max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
1,350
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.cosmos; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import static org.assertj.core.api.Assertions.assertThat; public class ConsistencyLevelTest { @Test(groups = { "unit" }, dataProvider = "expectedSerializationProvider") public void consistencyEnumToServiceExpectedFormat(ConsistencyLevel level, String expectedOverWireAsString) { assertThat(level.toString()).isEqualTo(expectedOverWireAsString); } @Test(groups = { "unit" }, dataProvider = "expectedSerializationProvider") public void consistencyEnumFromServiceExpectedFormat(ConsistencyLevel expectedConsistencyLevel, String overWireAsString) { assertThat(ConsistencyLevel.fromServiceSerializedFormat(overWireAsString)).isEqualTo(expectedConsistencyLevel); } @Test(groups = { "unit" }) public void consistencyEnumFromUnknownString() { assertThat(ConsistencyLevel.fromServiceSerializedFormat(null)).isNull(); assertThat(ConsistencyLevel.fromServiceSerializedFormat("xyz")).isNull(); assertThat(ConsistencyLevel.fromServiceSerializedFormat("session")).isNull(); } @DataProvider(name = "expectedSerializationProvider") private Object[][] expectedSerializationProvider() { return new Object[][]{ { ConsistencyLevel.SESSION, "Session" }, { ConsistencyLevel.STRONG, "Strong" }, { ConsistencyLevel.EVENTUAL, "Eventual" }, { ConsistencyLevel.CONSISTENT_PREFIX, "ConsistentPrefix" }, { ConsistencyLevel.BOUNDED_STALENESS, "BoundedStaleness" }, }; } }
736
19,438
/* * Copyright (c) 2020, <NAME> <<EMAIL>> * Copyright (c) 2021, <NAME> <<EMAIL>> * Copyright (c) 2021, <NAME> <<EMAIL>> * * SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <LibGUI/Frame.h> #include <LibGfx/Bitmap.h> #include <LibGfx/Filters/ColorBlindnessFilter.h> #include <LibGfx/Palette.h> namespace ThemeEditor { class MiniWidgetGallery; class PreviewWidget final : public GUI::Frame { C_OBJECT(PreviewWidget); public: virtual ~PreviewWidget() override; const Gfx::Palette& preview_palette() const { return m_preview_palette; } void set_preview_palette(const Gfx::Palette&); void set_theme_from_file(String const& path, int fd); void set_color_filter(OwnPtr<Gfx::ColorBlindnessFilter>); Function<void(String const&)> on_theme_load_from_file; private: explicit PreviewWidget(const Gfx::Palette&); void load_theme_bitmaps(); virtual void paint_event(GUI::PaintEvent&) override; virtual void second_paint_event(GUI::PaintEvent&) override; virtual void resize_event(GUI::ResizeEvent&) override; virtual void drop_event(GUI::DropEvent&) override; Gfx::Palette m_preview_palette; OwnPtr<Gfx::ColorBlindnessFilter> m_color_filter = nullptr; RefPtr<Gfx::Bitmap> m_active_window_icon; RefPtr<Gfx::Bitmap> m_inactive_window_icon; RefPtr<MiniWidgetGallery> m_gallery; RefPtr<Gfx::Bitmap> m_default_close_bitmap; RefPtr<Gfx::Bitmap> m_default_maximize_bitmap; RefPtr<Gfx::Bitmap> m_default_minimize_bitmap; RefPtr<Gfx::Bitmap> m_close_bitmap; RefPtr<Gfx::Bitmap> m_maximize_bitmap; RefPtr<Gfx::Bitmap> m_minimize_bitmap; String m_last_close_path; String m_last_maximize_path; String m_last_minimize_path; RefPtr<Gfx::Bitmap> m_active_window_shadow; RefPtr<Gfx::Bitmap> m_inactive_window_shadow; RefPtr<Gfx::Bitmap> m_menu_shadow; RefPtr<Gfx::Bitmap> m_taskbar_shadow; RefPtr<Gfx::Bitmap> m_tooltip_shadow; String m_last_active_window_shadow_path; String m_last_inactive_window_shadow_path; String m_last_menu_shadow_path; String m_last_taskbar_shadow_path; String m_last_tooltip_shadow_path; }; }
873
375
<reponame>Hengle/FbxExporter #pragma once #include "muSIMDConfig.h" namespace mu { #ifdef muEnableHalf void FloatToHalf(half *dst, const float *src, size_t num); void HalfToFloat(float *dst, const half *src, size_t num); #endif // muEnableHalf void InvertX(float3 *dst, size_t num); void InvertX(float4 *dst, size_t num); void InvertV(float2 *dst, size_t num); void Scale(float *dst, float s, size_t num); void Scale(float3 *dst, float s, size_t num); void Normalize(float3 *dst, size_t num); void Lerp(float *dst, const float *src1, const float *src2, size_t num, float w); void Lerp(float2 *dst, const float2 *src1, const float2 *src2, size_t num, float w); void Lerp(float3 *dst, const float3 *src1, const float3 *src2, size_t num, float w); void MinMax(const float3 *src, size_t num, float3& dst_min, float3& dst_max); void MinMax(const float2 *src, size_t num, float2& dst_min, float2& dst_max); bool NearEqual(const float *src1, const float *src2, size_t num, float eps = muEpsilon); bool NearEqual(const float2 *src1, const float2 *src2, size_t num, float eps = muEpsilon); bool NearEqual(const float3 *src1, const float3 *src2, size_t num, float eps = muEpsilon); bool NearEqual(const float4 *src1, const float4 *src2, size_t num, float eps = muEpsilon); void MulPoints(const float4x4& m, const float3 src[], float3 dst[], size_t num_data); void MulVectors(const float4x4& m, const float3 src[], float3 dst[], size_t num_data); int RayTrianglesIntersectionIndexed(float3 pos, float3 dir, const float3 *vertices, const int *indices, int num_triangles, int& tindex, float& distance); int RayTrianglesIntersectionFlattened(float3 pos, float3 dir, const float3 *vertices, int num_triangles, int& tindex, float& distance); int RayTrianglesIntersectionSoA(float3 pos, float3 dir, const float *v1x, const float *v1y, const float *v1z, const float *v2x, const float *v2y, const float *v2z, const float *v3x, const float *v3y, const float *v3z, int num_triangles, int& tindex, float& distance); int RayTrianglesIntersectionSoA(float3 pos, float3 dir, const float *v1x, const float *v1y, const float *v1z, const float *v2x, const float *v2y, const float *v2z, const float *v3x, const float *v3y, const float *v3z, int num_triangles, int& tindex, float& distance); bool PolyInside(const float px[], const float py[], int ngon, const float2 minp, const float2 maxp, const float2 pos); bool PolyInside(const float2 poly[], int ngon, const float2 minp, const float2 maxp, const float2 pos); bool PolyInside(const float2 poly[], int ngon, const float2 pos); void GenerateNormalsTriangleIndexed(float3 *dst, const float3 *vertices, const int *indices, int num_triangles, int num_vertices); void GenerateNormalsTriangleFlattened(float3 *dst, const float3 *vertices, const int *indices, int num_triangles, int num_vertices); void GenerateNormalsTriangleSoA(float3 *dst, const float *v1x, const float *v1y, const float *v1z, const float *v2x, const float *v2y, const float *v2z, const float *v3x, const float *v3y, const float *v3z, const int *indices, int num_triangles, int num_vertices); void GenerateTangentsTriangleIndexed(float4 *dst, const float3 *vertices, const float2 *uv, const float3 *normals, const int *indices, int num_triangles, int num_vertices); // vertices and uv must be flattened, * normals must not be flattened * void GenerateTangentsTriangleFlattened(float4 *dst, const float3 *vertices, const float2 *uv, const float3 *normals, const int *indices, int num_triangles, int num_vertices); void GenerateTangentsTriangleSoA(float4 *dst, const float *v1x, const float *v1y, const float *v1z, const float *v2x, const float *v2y, const float *v2z, const float *v3x, const float *v3y, const float *v3z, const float *u1x, const float *u1y, const float *u2x, const float *u2y, const float *u3x, const float *u3y, const float3 *normals, const int *indices, int num_triangles, int num_vertices); // ------------------------------------------------------------ // internal (for test) // ------------------------------------------------------------ #ifdef muEnableHalf void FloatToHalf_Generic(half *dst, const float *src, size_t num); void FloatToHalf_ISPC(half *dst, const float *src, size_t num); void HalfToFloat_Generic(float *dst, const half *src, size_t num); void HalfToFloat_ISPC(float *dst, const half *src, size_t num); #endif // muEnableHalf void InvertX_Generic(float3 *dst, size_t num); void InvertX_ISPC(float3 *dst, size_t num); void InvertX_Generic(float4 *dst, size_t num); void InvertX_ISPC(float4 *dst, size_t num); void Scale_Generic(float *dst, float s, size_t num); void Scale_Generic(float3 *dst, float s, size_t num); void Scale_ISPC(float *dst, float s, size_t num); void Scale_ISPC(float3 *dst, float s, size_t num); void Normalize_Generic(float3 *dst, size_t num); void Normalize_ISPC(float3 *dst, size_t num); void Lerp_Generic(float *dst, const float *src1, const float *src2, size_t num, float w); void Lerp_ISPC(float *dst, const float *src1, const float *src2, size_t num, float w); void MinMax_Generic(const float2 *src, size_t num, float2& dst_min, float2& dst_max); void MinMax_ISPC(const float2 *src, size_t num, float2& dst_min, float2& dst_max); void MinMax_Generic(const float3 *src, size_t num, float3& dst_min, float3& dst_max); void MinMax_ISPC(const float3 *src, size_t num, float3& dst_min, float3& dst_max); bool NearEqual_Generic(const float *src1, const float *src2, size_t num, float eps); bool NearEqual_ISPC(const float *src1, const float *src2, size_t num, float eps); void MulPoints_Generic(const float4x4& m, const float3 src[], float3 dst[], size_t num_data); void MulPoints_ISPC(const float4x4& m, const float3 src[], float3 dst[], size_t num_data); void MulVectors_Generic(const float4x4& m, const float3 src[], float3 dst[], size_t num_data); void MulVectors_ISPC(const float4x4& m, const float3 src[], float3 dst[], size_t num_data); int RayTrianglesIntersectionIndexed_Generic(float3 pos, float3 dir, const float3 *vertices, const int *indices, int num_triangles, int& tindex, float& distance); int RayTrianglesIntersectionIndexed_ISPC(float3 pos, float3 dir, const float3 *vertices, const int *indices, int num_triangles, int& tindex, float& distance); int RayTrianglesIntersectionFlattened_Generic(float3 pos, float3 dir, const float3 *vertices, int num_triangles, int& tindex, float& distance); int RayTrianglesIntersectionFlattened_ISPC(float3 pos, float3 dir, const float3 *vertices, int num_triangles, int& tindex, float& distance); int RayTrianglesIntersectionSoA_Generic(float3 pos, float3 dir, const float *v1x, const float *v1y, const float *v1z, const float *v2x, const float *v2y, const float *v2z, const float *v3x, const float *v3y, const float *v3z, int num_triangles, int& tindex, float& distance); int RayTrianglesIntersectionSoA_ISPC(float3 pos, float3 dir, const float *v1x, const float *v1y, const float *v1z, const float *v2x, const float *v2y, const float *v2z, const float *v3x, const float *v3y, const float *v3z, int num_triangles, int& tindex, float& distance); bool PolyInside_Generic(const float px[], const float py[], int ngon, const float2 minp, const float2 maxp, const float2 pos); bool PolyInside_ISPC(const float px[], const float py[], int ngon, const float2 minp, const float2 maxp, const float2 pos); bool PolyInside_Generic(const float2 poly[], int ngon, const float2 minp, const float2 maxp, const float2 pos); bool PolyInside_ISPC(const float2 poly[], int ngon, const float2 minp, const float2 maxp, const float2 pos); bool PolyInside_Generic(const float2 poly[], int ngon, const float2 pos); bool PolyInside_ISPC(const float2 poly[], int ngon, const float2 pos); void GenerateNormalsTriangleIndexed_Generic(float3 *dst, const float3 *vertices, const int *indices, int num_triangles, int num_vertices); void GenerateNormalsTriangleIndexed_ISPC(float3 *dst, const float3 *vertices, const int *indices, int num_triangles, int num_vertices); void GenerateNormalsTriangleFlattened_Generic(float3 *dst, const float3 *vertices, const int *indices, int num_triangles, int num_vertices); void GenerateNormalsTriangleFlattened_ISPC(float3 *dst, const float3 *vertices, const int *indices, int num_triangles, int num_vertices); void GenerateNormalsTriangleSoA_Generic(float3 *dst, const float *v1x, const float *v1y, const float *v1z, const float *v2x, const float *v2y, const float *v2z, const float *v3x, const float *v3y, const float *v3z, const int *indices, int num_triangles, int num_vertices); void GenerateNormalsTriangleSoA_ISPC(float3 *dst, const float *v1x, const float *v1y, const float *v1z, const float *v2x, const float *v2y, const float *v2z, const float *v3x, const float *v3y, const float *v3z, const int *indices, int num_triangles, int num_vertices); void GenerateTangentsTriangleIndexed_Generic(float4 *dst, const float3 *vertices, const float2 *uv, const float3 *normals, const int *indices, int num_triangles, int num_vertices); void GenerateTangentsTriangleIndexed_ISPC(float4 *dst, const float3 *vertices, const float2 *uv, const float3 *normals, const int *indices, int num_triangles, int num_vertices); void GenerateTangentsTriangleFlattened_Generic(float4 *dst, const float3 *vertices, const float2 *uv, const float3 *normals, const int *indices, int num_triangles, int num_vertices); void GenerateTangentsTriangleFlattened_ISPC(float4 *dst, const float3 *vertices, const float2 *uv, const float3 *normals, const int *indices, int num_triangles, int num_vertices); void GenerateTangentsTriangleSoA_Generic(float4 *dst, const float *v1x, const float *v1y, const float *v1z, const float *v2x, const float *v2y, const float *v2z, const float *v3x, const float *v3y, const float *v3z, const float *u1x, const float *u1y, const float *u2x, const float *u2y, const float *u3x, const float *u3y, const float3 *normals, const int *indices, int num_triangles, int num_vertices); void GenerateTangentsTriangleSoA_ISPC(float4 *dst, const float *v1x, const float *v1y, const float *v1z, const float *v2x, const float *v2y, const float *v2z, const float *v3x, const float *v3y, const float *v3z, const float *u1x, const float *u1y, const float *u2x, const float *u2y, const float *u3x, const float *u3y, const float3 *normals, const int *indices, int num_triangles, int num_vertices); } // namespace mu
4,108
678
<gh_stars>100-1000 #import "WBBaseViewController.h" @interface WBSettingViewController : WBBaseViewController @end
38
16,831
{ "transport": { "beacon": false, "xhrpost": false, "image": true }, "vars": { "account": "TEALIUM_ACCOUNT", "profile": "TEALIUM_PROFILE", "datasource": "TEALIUM_DATASOURCE", "visitor_id": "CLIENT_ID(AMP_ECID_GOOGLE,,_ga)" }, "requests": { "host": "https://collect.tealiumiq.com", "base": "${host}/event/?${tealium}&${dom1}&${dom2}&${datetime}&tealium_event=${tealium_event}&amp_version=${ampVersion}&amp_request_count=${requestCount}", "tealium": "tealium_account=${account}&tealium_profile=${profile}&tealium_datasource=${datasource}&tealium_visitor_id=${visitor_id}", "dom1": "url=${sourceUrl}&ampdoc_url=${ampdocUrl}&domain=${sourceHost}&pathname=${sourcePath}&amp_hostname=${ampdocHostname}&canonical_hostname=${canonicalHostname}", "dom2": "title=${title}&viewport_width=${availableScreenWidth}&viewport_height=${availableScreenHeight}", "datetime": "timestamp=${timestamp}&tz=${timezone}&lang=${browserLanguage}", "pageview": "${base}&referrer=${documentReferrer}&screen_size=${screenWidth}x${screenHeight}&content_load_ms=${contentLoadTime}&page_view_id=${pageViewId}", "event": "${base}&scroll_y=${scrollTop}&scroll_x=${scrollLeft}" }, "triggers": { "defaultPageview": { "on": "visible", "request": "pageview", "vars": { "tealium_event": "screen_view" } } } }
603
3,937
// Copyright (c) 2003-present, Jodd Team (http://jodd.org) // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. package jodd.joy; import jodd.util.ClassUtil; import jodd.util.SystemUtil; import javax.servlet.DispatcherType; import javax.servlet.FilterRegistration; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import java.util.EnumSet; import java.util.Objects; import static javax.servlet.DispatcherType.REQUEST; /** * Joy starts here. You can register this class it in several ways: * <ul> * <li>Add it in the web.xml</li> * <li>Make a subclass and annotate it with @WebListener</li> * <li>Register it explicitly (using embedded containers)</li> * </ul> */ public class JoyContextListener implements ServletContextListener { protected boolean decoraEnabled = false; protected String contextPath = "/*"; protected EnumSet<DispatcherType> madvocDispatcherTypes = EnumSet.of(REQUEST); /** * Alternative way for registering Joy listeners. * Sometimes servlet container does not allow adding new listener * from already added listener. This method therefore registers * the listener <i>before</i> container actually called the * callback methods. */ public static void registerInServletContext( final ServletContext servletContext, final Class<? extends JoyContextListener> joyContextListenerClass ) { try { final JoyContextListener joyContextListener = ClassUtil.newInstance(joyContextListenerClass); joyContextListener.createJoyAndInitServletContext(servletContext); } catch (final Exception e) { throw new JoyException(e); } servletContext.addListener(joyContextListenerClass); } @Override public void contextInitialized(final ServletContextEvent sce) { final ServletContext servletContext = sce.getServletContext(); createJoyAndInitServletContext(servletContext).start(servletContext); } private JoddJoy createJoyAndInitServletContext(final ServletContext servletContext) { JoddJoy joy = (JoddJoy) servletContext.getAttribute(JoddJoy.class.getName()); if (joy == null) { joy = createJoy(); configureServletContext(servletContext); } servletContext.setAttribute(JoddJoy.class.getName(), joy); return joy; } /** * Creates {@link JoddJoy}. This is a place where to configure the app. */ protected JoddJoy createJoy() { final JoddJoy joy = JoddJoy.get(); if (SystemUtil.info().isAtLeastJavaVersion(9)) { joy.withScanner(joyScanner -> joyScanner.scanClasspathOf(this.getClass())); } return joy; } /** * Enables Decora. */ protected void enableDecora() { decoraEnabled = true; } /** * Defines Madvoc servlet context. */ protected void setMadvocContextPath(final String context) { Objects.requireNonNull(context); this.contextPath = context; } /** * Defines enum set of dispatcher types for the filter. */ protected void mapMadvocFilterFor(final EnumSet<DispatcherType> dispatcherTypeEnumSet) { this.madvocDispatcherTypes = dispatcherTypeEnumSet; } /** * Configures servlet context. */ private void configureServletContext(final ServletContext servletContext) { servletContext.addListener(jodd.servlet.RequestContextListener.class); if (decoraEnabled) { final FilterRegistration filter = servletContext.addFilter("decora", jodd.decora.DecoraServletFilter.class); filter.addMappingForUrlPatterns(null, true, contextPath); } final FilterRegistration filter = servletContext.addFilter("madvoc", jodd.madvoc.MadvocServletFilter.class); filter.addMappingForUrlPatterns(madvocDispatcherTypes, true, contextPath); } @Override public void contextDestroyed(final ServletContextEvent sce) { JoddJoy.get().stop(); } }
1,560
406
<gh_stars>100-1000 /* * The MIT License (MIT) * * Copyright (c) 2007-2015 Broad Institute * * 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 org.broad.igv.sam; import org.broad.igv.feature.BasicFeature; import org.broad.igv.feature.Exon; import org.broad.igv.feature.LocusScore; import org.broad.igv.feature.Strand; import org.broad.igv.track.WindowFunction; import java.awt.*; import java.util.List; /** * Some alignment formats are parsed as Features. * <p/> * This is all getting rather circular, some refactoring is in order. * * @author jrobinso * @date Aug 5, 2010 */ public class FeatureWrappedAlignment implements Alignment { String readName; String chr; int start; int end; AlignmentBlockImpl[] blocks; Strand strand; public FeatureWrappedAlignment(BasicFeature f) { this.readName = f.getName(); this.chr = f.getChr(); this.start = f.getStart(); this.end = f.getEnd(); strand = f.getStrand(); if (f.getExonCount() > 0) { blocks = new AlignmentBlockImpl[f.getExonCount()]; int i = 0; for (Exon exon : f.getExons()) { int length = exon.getLength(); byte[] seq = new byte[length]; blocks[i] = new AlignmentBlockImpl(exon.getStart(), seq, seq); i++; } } } public String getReadName() { return readName; } public String getReadSequence() { return null; } public String getChromosome() { return chr; } public String getChr() { return chr; } @Override public String getContig() { return chr; } public int getAlignmentStart() { return start; } public boolean contains(double location) { return location >= start && location <= getEnd(); } public AlignmentBlock[] getAlignmentBlocks() { return blocks; } public AlignmentBlock[] getInsertions() { return null; } public String getCigarString() { return "*"; } public int getInferredInsertSize() { return 0; } public int getMappingQuality() { return 255; } public ReadMate getMate() { return null; } public boolean isProperPair() { return true; } public boolean isMapped() { return true; } public boolean isPaired() { return false; } public boolean isNegativeStrand() { return strand == Strand.NEGATIVE; } public boolean isDuplicate() { return false; } public float getScore() { return 1.0f; } public LocusScore copy() { return this; } public String getClipboardString(double location, int mouseX) { return getValueString(location, mouseX, (WindowFunction) null); } public String getValueString(double position, int mouseX, WindowFunction windowFunction) { return readName + "<br>Read length = " + (getEnd() - getStart()); } /** * @return the start */ public int getStart() { return start; } /** * @param start the start to set */ public void setStart(int start) { this.start = start; } /** * @return the end */ public int getEnd() { return end; } public int getAlignmentEnd() { return end; } /** * @param end the end to set */ public void setEnd(int end) { this.end = end; } public byte getBase(double position) { return 0; } public byte getPhred(double position) { return 0; } public String getSample() { return null; } public String getReadGroup() { return null; } public String getLibrary() { return null; } public Object getAttribute(String key) { return null; //To change body of implemented methods use File | Settings | File Templates. } public void setMateSequence(String sequence) { //To change body of implemented methods use File | Settings | File Templates. } public String getPairOrientation() { return null; //To change body of implemented methods use File | Settings | File Templates. } public boolean isSmallInsert() { return false; //To change body of implemented methods use File | Settings | File Templates. } public boolean isVendorFailedRead() { return false; //To change body of implemented methods use File | Settings | File Templates. } public Color getYcColor() { return null; } @Override public List<Gap> getGaps() { return null; } public boolean isFirstOfPair() { return false; } public boolean isSecondOfPair() { return false; } public Strand getFirstOfPairStrand() { return strand; } public Strand getSecondOfPairStrand() { return Strand.NONE; } public Strand getReadStrand() { return isNegativeStrand() ? Strand.NEGATIVE : Strand.POSITIVE; } @Override public void finish() { } @Override public boolean isPrimary() { return true; } @Override public boolean isSupplementary() { return false; } }
2,476
371
<filename>neural_networks/rnn_margin.py from __future__ import print_function import numpy as np import theano import theano.tensor as T import lasagne import cPickle import random from time import time import rnn_base as rnn from sparse_lstm import * class RNNMargin(rnn.RNNBase): ''' OPTIONS ------- balance: float, default 1, balance between the weight of false negative and false positive on the loss function. e.g. if balance = 1, both have the same weight, if balance = 0, only false negative have an impact, if balance = 2, false positive have twice as much weight as false negative. popularity_based: bool, default False, choose wether the target value of negatives depends on their popularity. if False, the target value of all negatives is 0 (versus 1 for the positives) if True, the target value of item i is min(1 - p_i, (1 - min_access) * p_i / min_access), where p_i = fraction of users who consumed that item. min_access: float in (0,1), default 0.05, parameter used in the formula for the target value of negatives in the popularity based case. Represent the minimum fraction of users that has access to any item. e.g. min_access=0.05 means that there is no item accessible by less than 5% of the users. n_targets: int or inf, default 1, number of items in the continuation of the sequence that will be used as positive target. ''' def __init__(self, loss_function="hinge", balance=1., popularity_based=False, min_access=0.05, n_targets=1, **kwargs): super(RNNMargin, self).__init__(**kwargs) self.balance = balance self.popularity_based = popularity_based self.min_access = min_access self.n_targets = n_targets if loss_function is None: loss_function = "hinge" self.loss_function_name = loss_function if loss_function == "hinge": self.loss_function = self._hinge_loss elif loss_function == "logit": self.loss_function = self._logit_loss elif loss_function == "logsig": self.loss_function = self._logsigmoid_loss else: raise ValueError('Unknown loss function') self.name = "RNN multi-targets" def _get_model_filename(self, epochs): '''Return the name of the file to save the current model ''' filename = "rnn_multitarget_"+self.loss_function_name+"_b"+str(self.balance) if self.popularity_based: filename += '_pb_ma'+str(self.min_access) return filename + "_" + self._common_filename(epochs) def _hinge_loss(self, predictions, targets, weights): return T.nnet.relu((predictions - targets) * weights).sum(axis=-1) def _logit_loss(self, predictions, targets, weights): return (T.nnet.sigmoid(predictions - targets) * weights).sum(axis=-1) def _logsigmoid_loss(self, predictions, targets, weights): return -T.log(T.nnet.sigmoid((targets - predictions) * weights)).sum(axis=-1) def _prepare_networks(self, n_items): ''' Prepares the building blocks of the RNN, but does not compile them: self.l_in : input layer self.l_mask : mask of the input layer self.target : target of the network self.l_out : output of the network self.cost : cost function ''' self.n_items = n_items # The input is composed of to parts : the on-hot encoding of the movie, and the features of the movie self.l_in = lasagne.layers.InputLayer(shape=(self.batch_size, self.max_length, self._input_size())) # The input is completed by a mask to inform the LSTM of the length of the sequence self.l_mask = lasagne.layers.InputLayer(shape=(self.batch_size, self.max_length)) # recurrent layer if not self.use_movies_features: l_recurrent = self.recurrent_layer(self.l_in, self.l_mask, true_input_size=self.n_items + self._n_optional_features(), only_return_final=True) else: l_recurrent = self.recurrent_layer(self.l_in, self.l_mask, true_input_size=None, only_return_final=True) # l_last_slice gets the last output of the recurrent layer l_last_slice = l_recurrent # l_last_slice = lasagne.layers.SliceLayer(l_recurrent, -1, 1) # Theano tensor for the targets target = T.fmatrix('multiple_target_output') target_weight = T.fmatrix('target_weight') self.exclude = T.fmatrix('excluded_items') self.theano_inputs = [self.l_in.input_var, self.l_mask.input_var, target, target_weight, self.exclude] # The sliced output is then passed through linear layer to obtain the right output size self.l_out = lasagne.layers.DenseLayer(l_last_slice, num_units=self.n_items, nonlinearity=None) # lasagne.layers.get_output produces a variable for the output of the net network_output = lasagne.layers.get_output(self.l_out) # loss function self.cost = self.loss_function(network_output, target, target_weight).mean() def _prepare_input(self, sequences): ''' Sequences is a list of [user_id, input_sequence, targets] ''' batch_size = len(sequences) # Shape return variables X = np.zeros((batch_size, self.max_length, self._input_size()), dtype=self._input_type) # input of the RNN mask = np.zeros((batch_size, self.max_length)) # mask of the input (to deal with sequences of different length) Y = np.zeros((batch_size, self.n_items), dtype=theano.config.floatX) weight = np.zeros((batch_size, self.n_items), dtype=theano.config.floatX) exclude = np.zeros((batch_size, self.n_items), dtype=theano.config.floatX) for i, sequence in enumerate(sequences): user_id, in_seq, target = sequence seq_features = np.array(map(lambda x: self._get_features(x, user_id), in_seq)) X[i, :len(in_seq), :] = seq_features # Copy sequences into X mask[i, :len(in_seq)] = 1 exclude[i, [j[0] for j in in_seq]] = 1 # compute weight for false positive w = self.balance * len(target) / (self.n_items - len(target) - len(in_seq)) weight[i,:] = w weight[i, [t[0] for t in target]] = -1 if self.interactions_are_unique: weight[i, [t[0] for t in in_seq]] = 0 Y[i, :] = self._default_target() Y[i, [t[0] for t in target]] = 1 if self.interactions_are_unique: Y[i, [t[0] for t in in_seq]] = 0 # weight *= 10e3 return (X, mask.astype(theano.config.floatX), Y, weight, exclude) def _default_target(self): if not hasattr(self, '__default_target'): if not self.popularity_based: self.__default_target = np.zeros(self.n_items) else: num_users = self.dataset.training_set.n_users view_prob = self.dataset.item_popularity / num_users self.__default_target = np.minimum(1 - view_prob, (1 - self.min_access) * view_prob / self.min_access) return self.__default_target
2,373
839
#include <hvpp/hypervisor.h> #include <hvpp/lib/driver.h> #include <hvpp/lib/assert.h> #include <hvpp/lib/log.h> #include <hvpp/lib/mm.h> #include <hvpp/lib/mp.h> #include "vmexit_custom.h" #include "device_custom.h" #include <cinttypes> using namespace ia32; using namespace hvpp; namespace driver { // // Create combined handler from these VM-exit handlers. // using vmexit_handler_t = vmexit_compositor_handler< vmexit_stats_handler, vmexit_dbgbreak_handler, vmexit_custom_handler >; static_assert(std::is_base_of_v<vmexit_handler, vmexit_handler_t>); vmexit_handler_t* vmexit_handler_ = nullptr; device_custom* device_ = nullptr; auto initialize() noexcept -> error_code_t { // // Create device instance. // device_ = new device_custom(); if (!device_) { destroy(); return make_error_code_t(std::errc::not_enough_memory); } // // Initialize device instance. // if (auto err = device_->create()) { destroy(); return err; } // // Create VM-exit handler instance. // vmexit_handler_ = new vmexit_handler_t(); if (!vmexit_handler_) { destroy(); return make_error_code_t(std::errc::not_enough_memory); } // // Assign the vmexit_dbgbreak_handler instance to the device. // device_->handler(std::get<vmexit_dbgbreak_handler>(vmexit_handler_->handlers)); // // Example: Enable tracing of I/O instructions. // std::get<vmexit_stats_handler>(vmexit_handler_->handlers) .trace_bitmap().set(int(vmx::exit_reason::execute_io_instruction)); // // Start the hypervisor. // if (auto err = hvpp::hypervisor::start(*vmexit_handler_)) { destroy(); return err; } // // Tell debugger we're started. // hvpp_info("Hypervisor started, current free memory: %" PRIu64 " MB", mm::hypervisor_allocator()->free_bytes() / 1024 / 1024); return {}; } void destroy() noexcept { // // Stop the hypervisor. // hvpp::hypervisor::stop(); // // Destroy VM-exit handler. // if (vmexit_handler_) { // // Print statistics into debugger. // std::get<vmexit_stats_handler>(vmexit_handler_->handlers).dump(); delete vmexit_handler_; } // // Destroy device. // if (device_) { delete device_; } hvpp_info("Hypervisor stopped"); } }
1,066
6,210
<reponame>chienfuchen32/cassandra<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.apache.cassandra.utils; import java.nio.ByteBuffer; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class ObjectSizesTest { @Test public void heapByteBuffer() { byte[] bytes = {0, 1, 2, 3, 4}; ByteBuffer buffer = ByteBuffer.wrap(bytes); long empty = ObjectSizes.sizeOfEmptyHeapByteBuffer(); long actual = ObjectSizes.measureDeep(buffer); assertThat(actual).isEqualTo(empty + ObjectSizes.sizeOfArray(bytes)); assertThat(ObjectSizes.sizeOnHeapOf(buffer)).isEqualTo(actual); } @Test public void shouldIgnoreArrayOverheadForSubBuffer() { byte[] bytes = {0, 1, 2, 3, 4}; ByteBuffer buffer = ByteBuffer.wrap(bytes); buffer.position(1); assertThat(ObjectSizes.sizeOnHeapOf(buffer)).isEqualTo(ObjectSizes.sizeOfEmptyHeapByteBuffer() + 4); } }
586
628
# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2019-06-27 20:29 from __future__ import unicode_literals from django.db import migrations import osf.utils.fields class Migration(migrations.Migration): dependencies = [ ('osf', '0187_remove_outdated_contributor_permissions'), ] operations = [ migrations.AddField( model_name='abstractnode', name='deleted', field=osf.utils.fields.NonNaiveDateTimeField(blank=True, null=True), ), migrations.AddField( model_name='basefilenode', name='deleted', field=osf.utils.fields.NonNaiveDateTimeField(blank=True, null=True), ), migrations.AddField( model_name='comment', name='deleted', field=osf.utils.fields.NonNaiveDateTimeField(blank=True, null=True), ), migrations.AddField( model_name='privatelink', name='deleted', field=osf.utils.fields.NonNaiveDateTimeField(blank=True, null=True), ), migrations.AddField( model_name='institution', name='deleted', field=osf.utils.fields.NonNaiveDateTimeField(blank=True, null=True), ), ]
604
515
<reponame>kraehlit/CTK /*========================================================================= Library: CTK Copyright (c) Kitware 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.txt Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================*/ #ifndef __ctkCheckablePushButton_h #define __ctkCheckablePushButton_h // CTK includes #include <ctkPimpl.h> #include "ctkPushButton.h" #include "ctkWidgetsExport.h" class ctkCheckablePushButtonPrivate; /// \ingroup Widgets /// Description /// ctkCheckablePushButton is a QPushButton with a checkbox. /// /// \warning The checkbox is drawn in place of the pushbuton icon, any icon /// will then be ignored. class CTK_WIDGETS_EXPORT ctkCheckablePushButton : public ctkPushButton { Q_OBJECT /// This property controls the location of the checkbox with regard to the text. /// Qt::AlignLeft|Qt::AlignVCenter by default Q_PROPERTY(Qt::Alignment indicatorAlignment READ indicatorAlignment WRITE setIndicatorAlignment) Q_PROPERTY(Qt::CheckState checkState READ checkState WRITE setCheckState NOTIFY checkStateChanged) Q_PROPERTY(bool checkBoxControlsButton READ checkBoxControlsButton WRITE setCheckBoxControlsButton) Q_PROPERTY(bool checkBoxControlsButtonToggleState READ checkBoxControlsButtonToggleState WRITE setCheckBoxControlsButtonToggleState) Q_PROPERTY(bool checkBoxUserCheckable READ isCheckBoxUserCheckable WRITE setCheckBoxUserCheckable) public: ctkCheckablePushButton(QWidget *parent = 0); ctkCheckablePushButton(const QString& text, QWidget *parent = 0); virtual ~ctkCheckablePushButton(); /// Set the alignment of the indicator (arrow) on the button, /// Qt::AlignLeft|Qt::AlignVCenter by default. void setIndicatorAlignment(Qt::Alignment indicatorAlignment); Qt::Alignment indicatorAlignment()const; /// Get checked state of the checkbox on the button. virtual Qt::CheckState checkState()const; /// Set checked state of the checkbox on the button. virtual void setCheckState(Qt::CheckState checkState); /// By default the checkbox is connected to the checkable property of the push button. /// You can change this behaviour by clearing the "checkBoxControlsButton" /// property. /// \note In checkBoxControlsButton mode, calling setCheckable() instead of /// setCheckState() may not refresh the button automatically. Use setCheckState() /// instead. /// \note You can automatically check the button when the user checks the /// checkbox by connecting the checkBoxToggled(bool) signal with the /// setChecked(bool) slot or by enabling "checkBoxControlsButtonToggleState" property. virtual bool checkBoxControlsButton()const; virtual void setCheckBoxControlsButton(bool b); /// If both checkBoxControlsButton and checkBoxControlsButtonToggleState /// are enabled then check state is synchronized with pushed state of the button /// (checking the checkbox also pushes down the button and releasing the button /// unchecks the checkbox). virtual bool checkBoxControlsButtonToggleState()const; virtual void setCheckBoxControlsButtonToggleState(bool b); /// The checkBoxUserCheckable property determines if the state of the /// checkbox can be changed interactively by the user by clicking on the /// checkbox. virtual bool isCheckBoxUserCheckable()const; virtual void setCheckBoxUserCheckable(bool b); Q_SIGNALS: /// Fired anytime the checkbox change of state void checkBoxToggled(bool); /// Fired anytime the checkbox change of state void checkStateChanged(Qt::CheckState newCheckState); protected: /// Reimplemented for internal reasons virtual void mousePressEvent(QMouseEvent* event); /// Reimplemented for internal reasons virtual bool hitButton(const QPoint & pos) const; /// Reimplemented for internal reasons void checkStateSet() override; /// Reimplemented for internal reasons void nextCheckState() override; private: Q_DECLARE_PRIVATE(ctkCheckablePushButton); Q_DISABLE_COPY(ctkCheckablePushButton); }; #endif
1,234
14,668
// Copyright 2021 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 ANDROID_WEBVIEW_BROWSER_COMPONENT_UPDATER_REGISTRATION_H_ #define ANDROID_WEBVIEW_BROWSER_COMPONENT_UPDATER_REGISTRATION_H_ #include "components/component_updater/android/component_loader_policy.h" namespace android_webview { // ComponentLoaderPolicies for component to load in an embedded WebView during // startup. component_updater::ComponentLoaderPolicyVector GetComponentLoaderPolicies(); } // namespace android_webview #endif // ANDROID_WEBVIEW_BROWSER_COMPONENT_UPDATER_REGISTRATION_H_
222
348
<gh_stars>100-1000 {"nom":"Saint-Méard","circ":"1ère circonscription","dpt":"Haute-Vienne","inscrits":280,"abs":108,"votants":172,"blancs":8,"nuls":1,"exp":163,"res":[{"nuance":"REM","nom":"Mme <NAME>","voix":47},{"nuance":"FI","nom":"Mme <NAME>","voix":24},{"nuance":"SOC","nom":"<NAME>","voix":23},{"nuance":"LR","nom":"Mme <NAME>","voix":23},{"nuance":"FN","nom":"Mme <NAME>","voix":18},{"nuance":"ECO","nom":"<NAME>","voix":13},{"nuance":"COM","nom":"<NAME>","voix":9},{"nuance":"DVG","nom":"<NAME>","voix":5},{"nuance":"DLF","nom":"Mme <NAME>","voix":1},{"nuance":"DIV","nom":"<NAME>","voix":0},{"nuance":"ECO","nom":"<NAME>","voix":0},{"nuance":"EXG","nom":"Mme <NAME>","voix":0}]}
279
3,401
# -*- coding: utf-8 -*- # website: http://30daydo.com # @Time : 2020/2/20 17:06 # @File : etf_info.py # 获取etf的成分股数据 # 重构 2021-01-21 import datetime import pymongo import re import requests import sys from parsel.selector import Selector from sqlalchemy.orm import sessionmaker from loguru import logger sys.path.append('..') from common.BaseService import BaseService from configure.settings import DBSelector from fund.etf_models import IndexObject, IndexObjectNew, Base TIMEOUT = 30 # 超时 class Fund(BaseService): def __init__(self, first_use=False): super(Fund, self).__init__(f'../log/{self.__class__.__name__}.log') self.first_use = first_use self.engine = self.get_engine() def get_engine(self): return DBSelector().get_engine('db_stock') def create_table(self): # 初始化数据库连接: Base.metadata.create_all(self.engine) # 创建表结构 def get_session(self): return sessionmaker(bind=self.engine) def get(self, url, retry=5, js=True): start = 0 while start < retry: try: response = self.session.get(url, headers=self.headers, verify=False) except Exception as e: self.logger.error(e) start += 1 else: if js: content = response.json() else: content = response.text return content if start == retry: self.logger.error('重试太多') return None class IndexSpider(Fund): def __init__(self, first_use=False): super(IndexSpider, self).__init__(first_use) if first_use: self.create_table() self.sess = self.get_session()() self.base_url = 'http://www.csindex.com.cn/zh-CN/indices/index-detail/{}' self.download_url = 'http://www.csindex.com.cn/uploads/file/autofile/cons/{}cons.xls' def basic_info(self): ''' 基本数据,没有仓位的 拿到的只是上证的数据, ??? 中证吧 :return: ''' r = requests.get(url='http://www.csindex.com.cn/zh-CN/search/indices?about=1', headers={'User-Agent': 'Molliza Firefox Chrome'}) response = Selector(text=r.text) table = response.xpath('//table[@class="table table-even table-bg tc p_table tablePage"]') index_list = table[0].xpath('.//tbody[@id="itemContainer"]/tr') for idx in index_list: code = idx.xpath('.//td[1]/a/text()').extract_first() detail_url = idx.xpath('.//td[1]/a/@href').extract_first() name = idx.xpath('.//td[2]/a/text()').extract_first() stock_count = idx.xpath('.//td[3]/text()').extract_first() price = idx.xpath('.//td[4]/text()').extract_first() month_ratio = idx.xpath('.//td[5]/text()').extract_first() month_ratio = month_ratio.replace('--', '') if len(month_ratio) == 0: month_ratio = 0 type_ = idx.xpath('.//td[6]/text()').extract_first() hot_pot = idx.xpath('.//td[7]/text()').extract_first() area = idx.xpath('.//td[8]/text()').extract_first() coin = idx.xpath('.//td[9]/text()').extract_first() specified = idx.xpath('.//td[10]/text()').extract_first() index_type = idx.xpath('.//td[11]/text()').extract_first() obj = IndexObject( 代码=code, 详细URL=detail_url, 指数名称=name, 股票数目=stock_count, 最新收盘=float(price), 一个月收益率=float(month_ratio), 资产类别=type_, 热点=hot_pot, 地区覆盖=area, 币种=coin, 定制=specified, 指数类别=index_type ) try: self.sess.add(obj) except Exception as e: logger.error(e) self.sess.rollback() else: self.sess.commit() def etf_detail_with_product_inuse(self): ''' 获取到所有的成分,不过没有权重 :return: ''' self.client = DBSelector().mongo() self.db = self.client['fund'] # self.doc = client['fund']['etf_info'] ret = self.sess.query(IndexObjectNew).all() sess = requests.Session() for i in ret: code = i.代码 name = i.指数名称 self.etf_detail_constituent_stock(sess, code, name) def full_market(self): ''' 勾选了 中证,上证,深证 :return: ''' total = 1797 # hard code page_size = 50 total_page = total // page_size + 1 url = 'http://www.csindex.com.cn/zh-CN/indices/index?page={}&page_size=50&by=asc&order=%E5%8F%91%E5%B8%83%E6%97%B6%E9%97%B4&data_type=json&class_1=1&class_2=2&class_3=3' for i in range(1, total_page + 1): r = requests.get(url.format(i), headers={'User-Agent': 'Molliza Firefox Chrome'}) ret = r.json() for item in ret.get('list'): index_id = item.get('index_id') index_code = item.get('index_code') index_sname = item.get('indx_sname') index_ename = item.get('index_ename') num = item.get('num') tclose = item.get('tclose') yld_1_mon = item.get('yld_1_mon') base_point = item.get('base_point') index_c_intro = item.get('index_c_intro') index_c_fullname = item.get('index_c_fullname') class_assets = item.get('class_assets') class_series = item.get('class_series') class_classify = item.get('class_classify') class_hot = item.get('class_hot') class_region = item.get('class_region') obj = IndexObjectNew( # id=index_id, 代码=index_code, 指数名称=index_sname, 指数英文名称=index_ename, 股票数目=num, 最新收盘=tclose, 一个月收益率=yld_1_mon, 基准点数=base_point, 指数介绍=index_c_intro, 指数全称=index_c_fullname, 资产类别=class_assets, 指数系列=class_series, 热点=class_hot, 地区覆盖=class_region, 指数类别=class_classify, 获取时间=datetime.datetime.now() ) try: self.sess.add(obj) except Exception as e: logger.error(e) self.sess.rollback() else: self.sess.commit() def download_excel_file(self, sess, code, name): s = sess.get(self.download_url.format(code), headers={'User-Agent': 'Molliza Firefox Chrome'},timeout=TIMEOUT) with open('../data/etf/{}_{}.xls'.format(code, name), 'wb') as f: f.write(s.content) def get_qz_page(self, sess, code): ''' 获取权重页面 :return: ''' # 获取权重 qz_url = 'http://www.csindex.com.cn/zh-CN/indices/index-detail/{}' s1 = sess.get(qz_url.format(code), headers={'User-Agent': 'Molliza Firefox Chrome'}) return Selector(text=s1.text) def parse_qz_data(self, resp, code, name): ''' 解析权重页面 :return: ''' logger.info(code) qz_stock_list = resp.xpath( '//div[@class="details_r fr"]//table[@class="table table-even table-bg p_table tc"]/tbody/tr') qz_list = [] for stock in qz_stock_list: s_code = stock.xpath('.//td[1]/text()').extract_first() s_name = stock.xpath('.//td[2]/text()').extract_first() s_area = stock.xpath('.//td[3]/text()').extract_first() s_qz = stock.xpath('.//td[4]/text()').extract_first() try: s_qz = float(s_qz) except: pass d = {} d['代码'] = s_code d['名称'] = s_name d['行业'] = s_area d['权重'] = s_qz qz_list.append(d) qz_dict = {} qz_dict['ETF代码'] = code qz_dict['ETF名称'] = name qz_dict['权重'] = qz_list return qz_dict def more_etf_product(self,resp): more_detail_url = resp.xpath('//div[@class="details_l fl"]/h2[@class="t_3 pr mb-10"]/a/@href').extract_first() r = requests.get(more_detail_url,headers={'User-Agent': 'Molliza Firefox Chrome'}) def etf_product_list(self, resp_selector): tables = resp_selector.xpath('//table[@class="table table-even table-bg p_table tc mb-20"]/tbody/tr') if len(tables) == 0: return [] product_list = [] for item in tables: product_list.append(item.xpath('.//td/text()').extract_first()) return product_list def store_product_list(self, code, name, products): if len(products) == 0: return [] return {'etf_code': code, 'etf_name': name, 'etf_product': products, 'crawltime': str(datetime.date.today())} def etf_detail_constituent_stock(self, sess, code, name): ''' 获取某个基金的权重数据 :param sess: :param code: :param name: :return: ''' self.download_excel_file(sess, code, name) resp = self.get_qz_page(sess, code) detail_data_json = self.parse_qz_data(resp, code, name) self.store_data(detail_data_json, collection_name='etf_quanzhong',key='ETF代码') product_list = self.etf_product_list(resp) if len(product_list)==5: product_list = self.store_product_list(code, name, product_list) self.store_data(product_list, collection_name='etf_product',key='etf_code') else: product_list = self.store_product_list(code, name, product_list) if product_list: self.store_data(product_list, collection_name='etf_product',key='etf_code') def store_data(self, detail_data_json, collection_name, key=''): try: if not self.db[collection_name].find_one({key: detail_data_json[key]}): self.db[collection_name].insert_one(detail_data_json) except Exception as e: logger.error(e) return False else: return True if __name__ == '__main__': app = IndexSpider(first_use=True) # app.basic_info() # app.full_market() app.etf_detail_with_product_inuse()
6,120
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.databoxedge.implementation; import com.azure.resourcemanager.databoxedge.fluent.models.OrderInner; import com.azure.resourcemanager.databoxedge.models.Address; import com.azure.resourcemanager.databoxedge.models.ContactDetails; import com.azure.resourcemanager.databoxedge.models.Order; import com.azure.resourcemanager.databoxedge.models.OrderStatus; import com.azure.resourcemanager.databoxedge.models.TrackingInfo; import java.util.Collections; import java.util.List; public final class OrderImpl implements Order { private OrderInner innerObject; private final com.azure.resourcemanager.databoxedge.DataBoxEdgeManager serviceManager; OrderImpl(OrderInner innerObject, com.azure.resourcemanager.databoxedge.DataBoxEdgeManager serviceManager) { this.innerObject = innerObject; this.serviceManager = serviceManager; } public String id() { return this.innerModel().id(); } public String name() { return this.innerModel().name(); } public String type() { return this.innerModel().type(); } public ContactDetails contactInformation() { return this.innerModel().contactInformation(); } public Address shippingAddress() { return this.innerModel().shippingAddress(); } public OrderStatus currentStatus() { return this.innerModel().currentStatus(); } public List<OrderStatus> orderHistory() { List<OrderStatus> inner = this.innerModel().orderHistory(); if (inner != null) { return Collections.unmodifiableList(inner); } else { return Collections.emptyList(); } } public String serialNumber() { return this.innerModel().serialNumber(); } public List<TrackingInfo> deliveryTrackingInfo() { List<TrackingInfo> inner = this.innerModel().deliveryTrackingInfo(); if (inner != null) { return Collections.unmodifiableList(inner); } else { return Collections.emptyList(); } } public List<TrackingInfo> returnTrackingInfo() { List<TrackingInfo> inner = this.innerModel().returnTrackingInfo(); if (inner != null) { return Collections.unmodifiableList(inner); } else { return Collections.emptyList(); } } public OrderInner innerModel() { return this.innerObject; } private com.azure.resourcemanager.databoxedge.DataBoxEdgeManager manager() { return this.serviceManager; } }
983
520
# Unless explicitly stated otherwise all files in this repository are licensed under the BSD-3-Clause License. # This product includes software developed at Datadog (https://www.datadoghq.com/). # Copyright 2015-Present Datadog, Inc # stdlib import json # datadog from datadog import api from datadog.dogshell.common import report_errors, report_warnings # TODO IS there a test ? class SearchClient(object): @classmethod def setup_parser(cls, subparsers): parser = subparsers.add_parser("search", help="search datadog") verb_parsers = parser.add_subparsers(title="Verbs", dest="verb") verb_parsers.required = True query_parser = verb_parsers.add_parser("query", help="Search datadog.") query_parser.add_argument("query", help="optionally faceted search query") query_parser.set_defaults(func=cls._query) @classmethod def _query(cls, args): api._timeout = args.timeout res = api.Infrastructure.search(q=args.query) report_warnings(res) report_errors(res) if format == "pretty": for facet, results in list(res["results"].items()): for idx, result in enumerate(results): if idx == 0: print("\n") print("%s\t%s" % (facet, result)) else: print("%s\t%s" % (" " * len(facet), result)) elif format == "raw": print(json.dumps(res)) else: for facet, results in list(res["results"].items()): for result in results: print("%s\t%s" % (facet, result))
742
314
<gh_stars>100-1000 // Copyright (c) 2011, <NAME> // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of the disruptor-- nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL FRANÇOIS SAINT-JACQUES BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef DISRUPTOR_SEQUENCER_H_ // NOLINT #define DISRUPTOR_SEQUENCER_H_ // NOLINT #include <vector> #include "batch_descriptor.h" #include "claim_strategy.h" #include "interface.h" #include "sequence_barrier.h" #include "wait_strategy.h" namespace rocketmq { // Coordinator for claiming sequences for access to a data structures while // tracking dependent {@link Sequence}s class Sequencer: public boost::noncopyable { public: // Construct a Sequencer with the selected strategies. // // @param buffer_size over which sequences are valid. // @param claim_strategy_option for those claiming sequences. // @param wait_strategy_option for those waiting on sequences. Sequencer(int buffer_size, ClaimStrategyOption claim_strategy_option, WaitStrategyOption wait_strategy_option) : buffer_size_(buffer_size), claim_strategy_(CreateClaimStrategy(claim_strategy_option, buffer_size_)), wait_strategy_(CreateWaitStrategy(wait_strategy_option)) { } ~Sequencer() { delete claim_strategy_; delete wait_strategy_; } // Set the sequences that will gate publishers to prevent the buffer // wrapping. // // @param sequences to be gated on. void set_gating_sequences( const std::vector<Sequence*>& sequences) { gating_sequences_ = sequences; } // Create a {@link SequenceBarrier} that gates on the cursor and a list of // {@link Sequence}s. // // @param sequences_to_track this barrier will track. // @return the barrier gated as required. ProcessingSequenceBarrier* NewBarrier( const std::vector<Sequence*>& sequences_to_track) { return new ProcessingSequenceBarrier(wait_strategy_, &cursor_, sequences_to_track); } // Create a new {@link BatchDescriptor} that is the minimum of the // requested size and the buffer_size. // // @param size for the new batch. // @return the new {@link BatchDescriptor}. BatchDescriptor* NewBatchDescriptor(const int& size) { return new BatchDescriptor(size<buffer_size_?size:buffer_size_); } // The capacity of the data structure to hold entries. // // @return capacity of the data structure. int buffer_size() { return buffer_size_; } // Get the value of the cursor indicating the published sequence. // // @return value of the cursor for events that have been published. int64_t GetCursor() { return cursor_.sequence(); } // Has the buffer capacity left to allocate another sequence. This is a // concurrent method so the response should only be taken as an indication // of available capacity. // // @return true if the buffer has the capacity to allocated another event. bool HasAvalaibleCapacity() { return claim_strategy_->HasAvalaibleCapacity(gating_sequences_); } // Claim the next event in sequence for publishing to the {@link RingBuffer}. // // @return the claimed sequence. int64_t Next() { return claim_strategy_->IncrementAndGet(gating_sequences_); } // Claim the next batch of sequence numbers for publishing. // // @param batch_descriptor to be updated for the batch range. // @return the updated batch_descriptor. BatchDescriptor* Next(BatchDescriptor* batch_descriptor) { int64_t sequence = claim_strategy_->IncrementAndGet(batch_descriptor->size(), gating_sequences_); batch_descriptor->set_end(sequence); return batch_descriptor; } // Claim a specific sequence when only one publisher is involved. // // @param sequence to be claimed. // @return sequence just claime. int64_t Claim(const int64_t& sequence) { claim_strategy_->SetSequence(sequence, gating_sequences_); return sequence; } // Publish an event and make it visible to {@link EventProcessor}s. // // @param sequence to be published. void Publish(const int64_t& sequence) { Publish(sequence, 1); } // Publish the batch of events in sequence. // // @param sequence to be published. void Publish(const BatchDescriptor& batch_descriptor) { Publish(batch_descriptor.end(), batch_descriptor.size()); } // Force the publication of a cursor sequence. // // Only use this method when forcing a sequence and you are sure only one // publisher exists. This will cause the cursor to advance to this // sequence. // // @param sequence to which is to be forced for publication. void ForcePublish(const int64_t& sequence) { cursor_.set_sequence(sequence); wait_strategy_->SignalAllWhenBlocking(); } // TODO(fsaintjacques): This was added to overcome // NoOpEventProcessor::GetSequence(), this is not a clean solution. Sequence* GetSequencePtr() { return &cursor_; } private: // Helpers void Publish(const int64_t& sequence, const int64_t& batch_size) { //LOG_DEBUG("publish sequence:%d", sequence); claim_strategy_->SerialisePublishing(sequence, cursor_, batch_size); cursor_.set_sequence(sequence); wait_strategy_->SignalAllWhenBlocking(); } // Members const int buffer_size_; PaddedSequence cursor_; std::vector<Sequence*> gating_sequences_; ClaimStrategyInterface* claim_strategy_; WaitStrategyInterface* wait_strategy_; }; }; // namespace rocketmq #endif // DISRUPTOR_RING_BUFFER_H_ NOLINT
2,540
1,144
<gh_stars>1000+ // Generated Model - DO NOT CHANGE package de.metas.handlingunits.model; import java.sql.ResultSet; import java.util.Properties; import javax.annotation.Nullable; /** Generated Model for EDI_M_HU_PI_Item_Product_Lookup_UPC_v * @author metasfresh (generated) */ @SuppressWarnings("unused") public class X_EDI_M_HU_PI_Item_Product_Lookup_UPC_v extends org.compiere.model.PO implements I_EDI_M_HU_PI_Item_Product_Lookup_UPC_v, org.compiere.model.I_Persistent { private static final long serialVersionUID = 1809833829L; /** Standard Constructor */ public X_EDI_M_HU_PI_Item_Product_Lookup_UPC_v (final Properties ctx, final int EDI_M_HU_PI_Item_Product_Lookup_UPC_v_ID, @Nullable final String trxName) { super (ctx, EDI_M_HU_PI_Item_Product_Lookup_UPC_v_ID, trxName); } /** Load Constructor */ public X_EDI_M_HU_PI_Item_Product_Lookup_UPC_v (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setM_HU_PI_Item_Product_ID (final int M_HU_PI_Item_Product_ID) { if (M_HU_PI_Item_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_PI_Item_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_PI_Item_Product_ID, M_HU_PI_Item_Product_ID); } @Override public int getM_HU_PI_Item_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_PI_Item_Product_ID); } @Override public void setUPC (final @Nullable java.lang.String UPC) { set_Value (COLUMNNAME_UPC, UPC); } @Override public java.lang.String getUPC() { return get_ValueAsString(COLUMNNAME_UPC); } }
762
348
<filename>docs/data/leg-t2/011/01101152.json {"nom":"Fontjoncouse","circ":"1ère circonscription","dpt":"Aude","inscrits":104,"abs":56,"votants":48,"blancs":7,"nuls":1,"exp":40,"res":[{"nuance":"REM","nom":"<NAME>","voix":31},{"nuance":"FN","nom":"<NAME>","voix":9}]}
108
343
<reponame>edamato/go-graphviz /* $Id$ $Revision$ */ /* vim:set shiftwidth=4 ts=8: */ /** * \brief A block structure defined over the variables * * A block structure defined over the variables such that each block contains * 1 or more variables, with the invariant that all constraints inside a block * are satisfied by keeping the variables fixed relative to one another * * Authors: * <NAME> <<EMAIL>> * * Copyright (C) 2005 Authors * * This version is released under the CPL (Common Public License) with * the Graphviz distribution. * A version is also available under the LGPL as part of the Adaptagrams * project: http://sourceforge.net/projects/adaptagrams. * If you make improvements or bug fixes to this code it would be much * appreciated if you could also contribute those changes back to the * Adaptagrams repository. */ #ifndef SEEN_REMOVEOVERLAP_BLOCKS_H #define SEEN_REMOVEOVERLAP_BLOCKS_H #ifdef RECTANGLE_OVERLAP_LOGGING #define LOGFILE "cRectangleOverlap.log" #endif #include <set> #include <list> class Block; class Variable; class Constraint; /** * A block structure defined over the variables such that each block contains * 1 or more variables, with the invariant that all constraints inside a block * are satisfied by keeping the variables fixed relative to one another */ class Blocks : public std::set<Block*> { public: Blocks(const int n, Variable *vs[]); ~Blocks(void); void mergeLeft(Block *r); void mergeRight(Block *l); void split(Block *b, Block *&l, Block *&r, Constraint *c); std::list<Variable*> *totalOrder(); void cleanup(); double cost(); private: void dfsVisit(Variable *v, std::list<Variable*> *order); void removeBlock(Block *doomed); Variable **vs; int nvs; }; extern long blockTimeCtr; #endif // SEEN_REMOVEOVERLAP_BLOCKS_H
561
1,457
// // S1Arpeggiator.hpp // AudioKitSynthOne // // Created by AudioKit Contributors on 3/06/19. // Copyright © 2019 AudioKit. All rights reserved. // #import "S1AudioUnit.h" #import "S1SeqNoteNumber.hpp" #include <vector> template<typename SeqNoteNumbers, typename NoteNumbers> struct Arpeggiator { Arpeggiator() = delete; static int up(SeqNoteNumbers &sequencerNotes, NoteNumbers &sequencerNotes2, const int heldNotesCount, const int arpOctaves, const int interval) { int index = 0; for (int octave = 0; octave < arpOctaves; octave++) { for (int i = 0; i < heldNotesCount; i++) { NoteNumber& note = sequencerNotes2[i]; const int nn = note.noteNumber + (octave * interval); const int velocity = note.velocity; SeqNoteNumber snn{nn, 1, velocity}; std::vector<SeqNoteNumber>::iterator it = sequencerNotes.begin() + index; sequencerNotes.insert(it, snn); ++index; } } return index; } static void down(SeqNoteNumbers &sequencerNotes, NoteNumbers &sequencerNotes2, const int heldNotesCount, const int arpOctaves, const int interval, const bool noTail, int index = 0) { for (int octave = arpOctaves - 1; octave >= 0; octave--) { for (int i = heldNotesCount - 1; i >= 0; i--) { const bool firstNote = (i == heldNotesCount - 1) && (octave == arpOctaves - 1); const bool lastNote = (i == 0) && (octave == 0); if ((firstNote || lastNote) && noTail) { continue; } NoteNumber& note = sequencerNotes2[i]; const int nn = note.noteNumber + (octave * interval); const int velocity = note.velocity; SeqNoteNumber snn{nn, 1, velocity}; std::vector<SeqNoteNumber>::iterator it = sequencerNotes.begin() + index; sequencerNotes.insert(it, snn); ++index; } } }; };
1,008
1,056
<filename>ide/css.editor/src/org/netbeans/modules/css/editor/module/ModulesPropertyDefinitionProvider.java /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.css.editor.module; import java.util.ArrayList; import java.util.Collection; import org.netbeans.modules.css.editor.module.spi.CssEditorModule; import org.netbeans.modules.css.lib.api.properties.PropertyDefinition; import org.netbeans.modules.css.lib.api.properties.PropertyDefinitionProvider; import org.openide.filesystems.FileObject; import org.openide.util.lookup.ServiceProvider; /** * * @author marekfukala */ @ServiceProvider(service=PropertyDefinitionProvider.class) public class ModulesPropertyDefinitionProvider implements PropertyDefinitionProvider { @Override public Collection<String> getPropertyNames(FileObject context) { Collection<String> all = new ArrayList<>(); for (CssEditorModule module : CssModuleSupport.getModules()) { all.addAll(module.getPropertyNames(context)); } return all; } @Override public PropertyDefinition getPropertyDefinition(String propertyName) { for (CssEditorModule module : CssModuleSupport.getModules()) { PropertyDefinition def = module.getPropertyDefinition(propertyName); if(def != null) { return def; } } return null; } }
673
323
<reponame>vkhodygo/parsl import argparse import os import pytest import parsl from parsl.app.app import bash_app import parsl.app.errors as pe from parsl.tests.configs.local_threads import config local_config = config @bash_app def command_not_found(stderr='std.err', stdout='std.out'): cmd_line = 'catdogcat' return cmd_line @bash_app def bash_misuse(stderr='std.err', stdout='std.out'): cmd_line = 'exit 15' return cmd_line @bash_app def div_0(stderr='std.err', stdout='std.out'): cmd_line = '$((5/0))' return cmd_line @bash_app def invalid_exit(stderr='std.err', stdout='std.out'): cmd_line = 'exit 3.141' return cmd_line @bash_app def not_executable(stderr='std.err', stdout='std.out'): cmd_line = '/dev/null' return cmd_line @bash_app def bad_format(stderr='std.err', stdout='std.out'): cmd_line = 'echo {0}' return cmd_line test_matrix = { div_0: { 'exit_code': 1 }, bash_misuse: { 'exit_code': 15 }, command_not_found: { 'exit_code': 127 }, invalid_exit: { 'exit_code': 128 }, not_executable: { 'exit_code': 126 } } whitelist = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'configs', '*threads*') # @pytest.mark.whitelist(whitelist, reason='broken in IPP') @pytest.mark.skip("Broke somewhere between PR #525 and PR #652") def test_bash_formatting(): f = bad_format() try: f.result() except Exception as e: print("Caught exception", e) assert isinstance( e, parsl.app.errors.AppBadFormatting), "Expected AppBadFormatting got : {0}".format(e) return True # @pytest.mark.whitelist(whitelist, reason='broken in IPP') @pytest.mark.skip("Broke somewhere between PR #525 and PR #652") def test_div_0(test_fn=div_0): err_code = test_matrix[test_fn]['exit_code'] f = test_fn() try: f.result() except Exception as e: print("Caught exception", e) assert e.exitcode == err_code, "{0} expected err_code:{1} but got {2}".format(test_fn.__name__, err_code, e.exitcode) print(os.listdir('.')) os.remove('std.err') os.remove('std.out') return True @pytest.mark.issue363 def test_bash_misuse(test_fn=bash_misuse): err_code = test_matrix[test_fn]['exit_code'] f = test_fn() try: f.result() except pe.BashExitFailure as e: print("Caught expected BashExitFailure", e) assert e.exitcode == err_code, "{0} expected err_code:{1} but got {2}".format(test_fn.__name__, err_code, e.exitcode) os.remove('std.err') os.remove('std.out') @pytest.mark.issue363 def test_command_not_found(test_fn=command_not_found): err_code = test_matrix[test_fn]['exit_code'] f = test_fn() try: f.result() except pe.BashExitFailure as e: print("Caught exception", e) assert e.exitcode == err_code, "{0} expected err_code:{1} but got {2}".format(test_fn.__name__, err_code, e.exitcode) os.remove('std.err') os.remove('std.out') return True @pytest.mark.skip('broken') def test_invalid_exit(test_fn=invalid_exit): err_code = test_matrix[test_fn]['exit_code'] f = test_fn() try: f.result() except Exception as e: print("Caught exception", e) assert e.exitcode == err_code, "{0} expected err_code:{1} but got {2}".format(test_fn.__name__, err_code, e.exitcode) os.remove('std.err') os.remove('std.out') return True @pytest.mark.issue363 def test_not_executable(test_fn=not_executable): err_code = test_matrix[test_fn]['exit_code'] f = test_fn() try: f.result() except Exception as e: print("Caught exception", e) assert e.exitcode == err_code, "{0} expected err_code:{1} but got {2}".format(test_fn.__name__, err_code, e.exitcode) os.remove('std.err') os.remove('std.out') return True def run_app(test_fn, err_code): f = test_fn() print(f) try: f.result() except Exception as e: print("Caught exception", e) assert e.exitcode == err_code, "{0} expected err_code:{1} but got {2}".format(test_fn.__name__, err_code, e.exitcode) os.remove('std.err') os.remove('std.out') return True if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("-d", "--debug", action='store_true', help="Count of apps to launch") args = parser.parse_args() print(test_bash_formatting()) exit(0) if args.debug: parsl.set_stream_logger() for test in test_matrix: try: run_app(test, test_matrix[test]['exit_code']) except AssertionError as e: print("Test {0:15} [FAILED]".format(test.__name__)) print("Caught error : {0}".format(e)) else: print("Test {0:15} [SUCCESS]".format(test.__name__))
3,232
2,220
import pytest from qstrader.utils.console import GREEN, BLUE, CYAN, string_colour @pytest.mark.parametrize( "text,colour,expected", [ ('green colour', GREEN, "\x1b[1;32mgreen colour\x1b[0m"), ('blue colour', BLUE, "\x1b[1;34mblue colour\x1b[0m"), ('cyan colour', CYAN, "\x1b[1;36mcyan colour\x1b[0m"), ] ) def test_string_colour(text, colour, expected): """ Tests that the string colourisation for the terminal console produces the correct values. """ assert string_colour(text, colour=colour) == expected
230
8,969
<reponame>domesticmouse/sdk // Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "vm/compiler/backend/inliner.h" #include "vm/compiler/backend/il.h" #include "vm/compiler/backend/il_printer.h" #include "vm/compiler/backend/il_test_helper.h" #include "vm/compiler/compiler_pass.h" #include "vm/object.h" #include "vm/unit_test.h" namespace dart { // Test that the redefinition for an inlined polymorphic function used with // multiple receiver cids does not have a concrete type. ISOLATE_UNIT_TEST_CASE(Inliner_PolyInliningRedefinition) { const char* kScript = R"( abstract class A { String toInline() { return "A"; } } class B extends A {} class C extends A { @override String toInline() { return "C";} } class D extends A {} testInlining(A arg) { arg.toInline(); } main() { for (var i = 0; i < 10; i++) { testInlining(B()); testInlining(C()); testInlining(D()); } } )"; const auto& root_library = Library::Handle(LoadTestScript(kScript)); const auto& function = Function::Handle(GetFunction(root_library, "testInlining")); Invoke(root_library, "main"); TestPipeline pipeline(function, CompilerPass::kJIT); FlowGraph* flow_graph = pipeline.RunPasses({ CompilerPass::kComputeSSA, CompilerPass::kApplyICData, CompilerPass::kTryOptimizePatterns, CompilerPass::kSetOuterInliningId, CompilerPass::kTypePropagation, CompilerPass::kApplyClassIds, CompilerPass::kInlining, }); auto entry = flow_graph->graph_entry()->normal_entry(); EXPECT(entry != nullptr); EXPECT(entry->initial_definitions()->length() == 1); EXPECT(entry->initial_definitions()->At(0)->IsParameter()); ParameterInstr* param = entry->initial_definitions()->At(0)->AsParameter(); // First we find the start of the prelude for the inlined instruction, // and also keep a reference to the LoadClassId instruction for later. LoadClassIdInstr* lcid = nullptr; BranchInstr* prelude = nullptr; ILMatcher cursor(flow_graph, entry); RELEASE_ASSERT(cursor.TryMatch( { {kMatchLoadClassId, &lcid}, {kMatchBranch, &prelude}, }, /*insert_before=*/kMoveGlob)); const Class& cls = Class::Handle( root_library.LookupLocalClass(String::Handle(Symbols::New(thread, "B")))); Definition* cid_B = flow_graph->GetConstant(Smi::Handle(Smi::New(cls.id()))); Instruction* current = prelude; // We walk false branches until we either reach a branch instruction that uses // B's cid for comparison to the value returned from the LCID instruction // above, or a default case if there was no branch instruction for B's cid. while (true) { EXPECT(current->IsBranch()); const ComparisonInstr* check = current->AsBranch()->comparison(); EXPECT(check->left()->definition() == lcid); if (check->right()->definition() == cid_B) break; current = current->SuccessorAt(1); // By following false paths, we should be walking a series of blocks that // looks like: // B#[target]:# // Branch if <check on class ID> // If we end up not finding a branch, then we're in a default case // that contains a class check. current = current->next(); if (!current->IsBranch()) { break; } } // If we found a branch that checks against the class ID, we follow the true // branch to a block that contains only a goto to the desired join block. if (current->IsBranch()) { current = current->SuccessorAt(0); } else { // We're in the default case, which will check the class ID to make sure // it's the one expected for the fallthrough. That check will be followed // by a goto to the desired join block. EXPECT(current->IsRedefinition()); const auto redef = current->AsRedefinition(); EXPECT(redef->value()->definition() == lcid); current = current->next(); EXPECT(current->IsCheckClassId()); EXPECT(current->AsCheckClassId()->value()->definition() == redef); } current = current->next(); EXPECT(current->IsGoto()); current = current->AsGoto()->successor(); // Now we should be at a block that starts like: // BY[join]:# pred(...) // vW <- Redefinition(vV) // // where vV is a reference to the function parameter (the receiver of // the inlined function). current = current->next(); EXPECT(current->IsRedefinition()); EXPECT(current->AsRedefinition()->value()->definition() == param); EXPECT(current->AsRedefinition()->Type()->ToCid() == kDynamicCid); } ISOLATE_UNIT_TEST_CASE(Inliner_TypedData_Regress7551) { const char* kScript = R"( import 'dart:typed_data'; setValue(Int32List list, int value) { list[0] = value; } main() { final list = Int32List(10); setValue(list, 0x1122334455); } )"; const auto& root_library = Library::Handle(LoadTestScript(kScript)); const auto& function = Function::Handle(GetFunction(root_library, "setValue")); Invoke(root_library, "main"); TestPipeline pipeline(function, CompilerPass::kJIT); FlowGraph* flow_graph = pipeline.RunPasses({ CompilerPass::kComputeSSA, CompilerPass::kApplyICData, CompilerPass::kTryOptimizePatterns, CompilerPass::kSetOuterInliningId, CompilerPass::kTypePropagation, CompilerPass::kApplyClassIds, CompilerPass::kInlining, }); auto entry = flow_graph->graph_entry()->normal_entry(); EXPECT(entry->initial_definitions()->length() == 2); EXPECT(entry->initial_definitions()->At(0)->IsParameter()); EXPECT(entry->initial_definitions()->At(1)->IsParameter()); ParameterInstr* list_param = entry->initial_definitions()->At(0)->AsParameter(); ParameterInstr* value_param = entry->initial_definitions()->At(1)->AsParameter(); ILMatcher cursor(flow_graph, entry); CheckArrayBoundInstr* bounds_check_instr = nullptr; UnboxInt32Instr* unbox_instr = nullptr; StoreIndexedInstr* store_instr = nullptr; RELEASE_ASSERT(cursor.TryMatch({ {kMoveGlob}, {kMatchAndMoveCheckArrayBound, &bounds_check_instr}, {kMatchAndMoveUnboxInt32, &unbox_instr}, {kMatchAndMoveStoreIndexed, &store_instr}, })); RELEASE_ASSERT(unbox_instr->InputAt(0)->definition() == value_param); RELEASE_ASSERT(store_instr->InputAt(0)->definition() == list_param); RELEASE_ASSERT(store_instr->InputAt(2)->definition() == unbox_instr); RELEASE_ASSERT(unbox_instr->is_truncating()); } #if defined(DART_PRECOMPILER) // Verifies that all calls are inlined in List.generate call // with a simple closure. ISOLATE_UNIT_TEST_CASE(Inliner_List_generate) { const char* kScript = R"( foo(n) => List<int>.generate(n, (int x) => x, growable: false); main() { foo(100); } )"; const auto& root_library = Library::Handle(LoadTestScript(kScript)); const auto& function = Function::Handle(GetFunction(root_library, "foo")); TestPipeline pipeline(function, CompilerPass::kAOT); FlowGraph* flow_graph = pipeline.RunPasses({}); auto entry = flow_graph->graph_entry()->normal_entry(); ILMatcher cursor(flow_graph, entry, /*trace=*/true, ParallelMovesHandling::kSkip); RELEASE_ASSERT(cursor.TryMatch({ kMoveGlob, kMatchAndMoveCreateArray, kMatchAndMoveUnboxInt64, kMatchAndMoveGoto, // Loop header kMatchAndMoveJoinEntry, kMatchAndMoveCheckStackOverflow, kMatchAndMoveBranchTrue, // Loop body kMatchAndMoveTargetEntry, kWordSize == 4 ? kMatchAndMoveBoxInt64 : kNop, kMatchAndMoveBoxInt64, kMatchAndMoveStoreIndexed, kMatchAndMoveBinaryInt64Op, kMatchAndMoveGoto, // Loop header once again kMatchAndMoveJoinEntry, kMatchAndMoveCheckStackOverflow, kMatchAndMoveBranchFalse, // After loop kMatchAndMoveTargetEntry, kMatchReturn, })); } #endif // defined(DART_PRECOMPILER) } // namespace dart
3,020
1,590
/* * Tests for Simd Library (http://ermig1979.github.io/Simd). * * Copyright (c) 2011-2018 <NAME>. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "Test/TestUtils.h" #include "Test/TestPerformance.h" #include "Test/TestData.h" namespace Test { namespace { struct Func { typedef void(*FuncPtr)(const uint8_t * value, size_t valueStride, size_t width, size_t height, const uint8_t * lo, size_t loStride, const uint8_t * hi, size_t hiStride, uint16_t weight, uint8_t * difference, size_t differenceStride); FuncPtr func; String description; Func(const FuncPtr & f, const String & d) : func(f), description(d) {} void Call(const View & value, const View & lo, const View & hi, uint16_t weight, const View & differenceSrc, View & differenceDst) const { Simd::Copy(differenceSrc, differenceDst); TEST_PERFORMANCE_TEST(description); func(value.data, value.stride, value.width, value.height, lo.data, lo.stride, hi.data, hi.stride, weight, differenceDst.data, differenceDst.stride); } }; } #define FUNC(function) Func(function, std::string(#function)) bool AddFeatureDifferenceAutoTest(int width, int height, uint16_t weight, const Func & f1, const Func & f2) { bool result = true; TEST_LOG_SS(Info, "Test " << f1.description << " & " << f2.description << " [" << width << ", " << height << "] (" << weight / 256 << "*256)."); View value(width, height, View::Gray8, NULL, TEST_ALIGN(width)); FillRandom(value); View lo(width, height, View::Gray8, NULL, TEST_ALIGN(width)); FillRandom(lo); View hi(width, height, View::Gray8, NULL, TEST_ALIGN(width)); FillRandom(hi); View differenceSrc(width, height, View::Gray8, NULL, TEST_ALIGN(width)); FillRandom(differenceSrc); View differenceDst1(width, height, View::Gray8, NULL, TEST_ALIGN(width)); View differenceDst2(width, height, View::Gray8, NULL, TEST_ALIGN(width)); TEST_EXECUTE_AT_LEAST_MIN_TIME(f1.Call(value, lo, hi, weight, differenceSrc, differenceDst1)); TEST_EXECUTE_AT_LEAST_MIN_TIME(f2.Call(value, lo, hi, weight, differenceSrc, differenceDst2)); result = result && Compare(differenceDst1, differenceDst2, 0, true, 32, 0); return result; } bool AddFeatureDifferenceAutoTest(const Func & f1, const Func & f2) { bool result = true; const uint16_t delta = 256 * 7; for (uint16_t weight = 0; weight < 4 && result; ++weight) { result = result && AddFeatureDifferenceAutoTest(W, H, weight*delta, f1, f2); result = result && AddFeatureDifferenceAutoTest(W + O, H - O, weight*delta, f1, f2); } return result; } bool AddFeatureDifferenceAutoTest() { bool result = true; result = result && AddFeatureDifferenceAutoTest(FUNC(Simd::Base::AddFeatureDifference), FUNC(SimdAddFeatureDifference)); #ifdef SIMD_SSE2_ENABLE if (Simd::Sse2::Enable && W >= Simd::Sse2::A) result = result && AddFeatureDifferenceAutoTest(FUNC(Simd::Sse2::AddFeatureDifference), FUNC(SimdAddFeatureDifference)); #endif #ifdef SIMD_AVX2_ENABLE if (Simd::Avx2::Enable && W >= Simd::Avx2::A) result = result && AddFeatureDifferenceAutoTest(FUNC(Simd::Avx2::AddFeatureDifference), FUNC(SimdAddFeatureDifference)); #endif #ifdef SIMD_AVX512BW_ENABLE if (Simd::Avx512bw::Enable) result = result && AddFeatureDifferenceAutoTest(FUNC(Simd::Avx512bw::AddFeatureDifference), FUNC(SimdAddFeatureDifference)); #endif #ifdef SIMD_VMX_ENABLE if (Simd::Vmx::Enable && W >= Simd::Vmx::A) result = result && AddFeatureDifferenceAutoTest(FUNC(Simd::Vmx::AddFeatureDifference), FUNC(SimdAddFeatureDifference)); #endif #ifdef SIMD_NEON_ENABLE if (Simd::Neon::Enable && W >= Simd::Neon::A) result = result && AddFeatureDifferenceAutoTest(FUNC(Simd::Neon::AddFeatureDifference), FUNC(SimdAddFeatureDifference)); #endif return result; } //----------------------------------------------------------------------- bool AddFeatureDifferenceDataTest(bool create, int width, int height, const Func & f) { bool result = true; Data data(f.description); TEST_LOG_SS(Info, (create ? "Create" : "Verify") << " test " << f.description << " [" << width << ", " << height << "]."); View value(width, height, View::Gray8, NULL, TEST_ALIGN(width)); View lo(width, height, View::Gray8, NULL, TEST_ALIGN(width)); View hi(width, height, View::Gray8, NULL, TEST_ALIGN(width)); View differenceSrc(width, height, View::Gray8, NULL, TEST_ALIGN(width)); View differenceDst1(width, height, View::Gray8, NULL, TEST_ALIGN(width)); View differenceDst2(width, height, View::Gray8, NULL, TEST_ALIGN(width)); const uint16_t weight = 256 * 7; if (create) { FillRandom(value); FillRandom(lo); FillRandom(hi); FillRandom(differenceSrc); TEST_SAVE(value); TEST_SAVE(lo); TEST_SAVE(hi); TEST_SAVE(differenceSrc); f.Call(value, lo, hi, weight, differenceSrc, differenceDst1); TEST_SAVE(differenceDst1); } else { TEST_LOAD(value); TEST_LOAD(lo); TEST_LOAD(hi); TEST_LOAD(differenceSrc); TEST_LOAD(differenceDst1); f.Call(value, lo, hi, weight, differenceSrc, differenceDst2); TEST_SAVE(differenceDst2); result = result && Compare(differenceDst1, differenceDst2, 0, true, 32, 0); } return result; } bool AddFeatureDifferenceDataTest(bool create) { bool result = true; result = result && AddFeatureDifferenceDataTest(create, DW, DH, FUNC(SimdAddFeatureDifference)); return result; } }
3,185
2,160
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import os import shutil import subprocess import sys from pex.pex_info import PexInfo from pex.testing import run_pex_command from pex.typing import TYPE_CHECKING from pex.variables import unzip_dir if TYPE_CHECKING: from typing import Any def test_layout_identification(tmpdir): # type: (Any) -> None pex_root = os.path.join(str(tmpdir), "pex_root") pex_file = os.path.join(str(tmpdir), "a.pex") run_pex_command( args=["-o", pex_file, "--pex-root", pex_root, "--runtime-pex-root", pex_root] ).assert_success() pex_hash = PexInfo.from_pex(pex_file).pex_hash assert pex_hash is not None expected_unzip_dir = unzip_dir(pex_root, pex_hash) assert not os.path.exists(expected_unzip_dir) subprocess.check_call(args=[pex_file, "-c", ""]) assert os.path.isdir(expected_unzip_dir) shutil.rmtree(expected_unzip_dir) os.chmod(pex_file, 0o644) subprocess.check_call(args=[sys.executable, pex_file, "-c", ""]) assert os.path.isdir(expected_unzip_dir)
455
1,024
<reponame>mmg-3/commafeed<filename>src/main/java/com/commafeed/backend/feed/FeedRefreshContext.java package com.commafeed.backend.feed; import java.util.List; import lombok.Getter; import lombok.Setter; import com.commafeed.backend.model.Feed; import com.commafeed.backend.model.FeedEntry; @Getter @Setter public class FeedRefreshContext { private Feed feed; private List<FeedEntry> entries; private boolean urgent; public FeedRefreshContext(Feed feed, boolean isUrgent) { this.feed = feed; this.urgent = isUrgent; } }
218
1,205
<reponame>iamreallyi9/cd #!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. import os from os.path import join as pjoin import wget from zipfile import ZipFile def get_model_from_url( url: str, local_path: str, is_zip: bool = False, path_root: str = "checkpoints" ) -> str: local_path = pjoin(path_root, local_path) if os.path.exists(local_path): print(f"Found cache {local_path}") return local_path # download local_path = local_path.rstrip(os.sep) download_path = local_path if not is_zip else f"{local_path}.zip" os.makedirs(os.path.dirname(download_path), exist_ok=True) if os.path.isfile(download_path): print(f"Found cache {download_path}") else: print(f"Dowloading {url} to {download_path} ...") wget.download(url, download_path) if is_zip: print(f"Unziping {download_path} to {local_path}") with ZipFile(download_path, 'r') as f: f.extractall(local_path) os.remove(download_path) return local_path
446
315
<filename>drybell/drybell_dask.py<gh_stars>100-1000 import logging import dask.dataframe as dd from snorkel.labeling.model import LabelModel from snorkel.labeling.apply.dask import DaskLFApplier from drybell_lfs import article_mentions_person, body_contains_fortune, person_in_db logging.basicConfig(level=logging.INFO) def main(data_path, output_path): # Read data logging.info(f"Reading data from {data_path}") data = dd.read_parquet(data_path) data = data.repartition(npartitions=2) # Build label matrix logging.info("Applying LFs") lfs = [article_mentions_person, body_contains_fortune, person_in_db] applier = DaskLFApplier(lfs) L = applier.apply(data) # Train label model logging.info("Training label model") label_model = LabelModel(cardinality=2) label_model.fit(L) # Generate training labels logging.info("Generating probabilistic labels") y_prob = label_model.predict_proba(L)[:, 1] data = data.reset_index().set_index("index") data_labeled = data.assign(y_prob=dd.from_array(y_prob)) dd.to_parquet(data_labeled, output_path) logging.info(f"Labels saved to {output_path}") if __name__ == "__main__": main("drybell/data/raw_data.parquet", "drybell/data/labeled_data.parquet")
493
892
{ "schema_version": "1.2.0", "id": "GHSA-pgw2-4cf2-2hqc", "modified": "2022-04-29T01:27:23Z", "published": "2022-04-29T01:27:23Z", "aliases": [ "CVE-2003-1039" ], "details": "Multiple buffer overflows in the mySAP.com architecture for SAP allow remote attackers to execute arbitrary code via a long HTTP Host header to (1) Message Server, (2) Web Dispatcher, or (3) Application Server.", "severity": [ ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2003-1039" }, { "type": "WEB", "url": "https://exchange.xforce.ibmcloud.com/vulnerabilities/15513" }, { "type": "WEB", "url": "http://www.phenoelit.de/stuff/Phenoelit20c3.pd" } ], "database_specific": { "cwe_ids": [ ], "severity": "HIGH", "github_reviewed": false } }
403
3,428
{"id":"02452","group":"easy-ham-1","checksum":{"type":"MD5","value":"22e8f668f27122f74442cd887a02be07"},"text":"From <EMAIL> Mon Dec 2 11:20:12 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: yyyy<EMAIL>.spamassassin.taint.org\nReceived: from localhost (jalapeno [127.0.0.1])\n\tby jmason.org (Postfix) with ESMTP id 54BAA16F75\n\tfor <jm@localhost>; Mon, 2 Dec 2002 11:15:52 +0000 (GMT)\nReceived: from jalapeno [127.0.0.1]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor jm@localhost (single-drop); Mon, 02 Dec 2002 11:15:52 +0000 (GMT)\nReceived: from egwn.net (ns2.egwn.net [192.168.3.11]) by\n dogma.slashnull.org (8.11.6/8.11.6) with ESMTP id gB23NI806040 for\n <<EMAIL>>; Mon, 2 Dec 2002 03:23:18 GMT\nReceived: from auth02.nl.egwn.net (localhost [127.0.0.1]) by egwn.net\n (8.11.6/8.11.6/EGWN) with ESMTP id gB23M3o00493; Mon, 2 Dec 2002 04:22:03\n +0100\nReceived: from mta7.pltn13.pbi.net (mta7.pltn13.pbi.net [64.164.98.8]) by\n egwn.net (8.11.6/8.11.6/EGWN) with ESMTP id gB23L5o31267 for\n <<EMAIL>>; Mon, 2 Dec 2002 04:21:05 +0100\nReceived: from eecs.berkeley.edu ([172.16.58.3]) by mta7.pltn13.pbi.net\n (iPlanet Messaging Server 5.1 (built May 7 2001)) with ESMTP id\n <<EMAIL>> for <EMAIL>;\n Sun, 01 Dec 2002 19:21:03 -0800 (PST)\nFrom: <NAME> <<EMAIL>>\nSubject: Re: alsa:bass and treble\nIn-Reply-To: <<EMAIL>>\nTo: [email protected]\nMessage-Id: <<EMAIL>>\nMIME-Version: 1.0\nContent-Type: text/plain; charset=us-ascii; format=flowed\nContent-Transfer-Encoding: 7BIT\nX-Accept-Language: en-us, en\nUser-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.2) Gecko/20021127\nReferences: <1038772033.1784.<EMAIL>>\nX-Mailscanner: Found to be clean, Found to be clean\nSender: rpm-zzzlist-<EMAIL>\nErrors-To: [email protected]\nX-Beenthere: [email protected]\nX-Mailman-Version: 2.0.11\nPrecedence: bulk\nReply-To: <EMAIL>\nList-Help: <mailto:<EMAIL>?subject=help>\nList-Post: <mailto:<EMAIL>>\nList-Subscribe: <http://lists.freshrpms.net/mailman/listinfo/rpm-zzzlist>,\n <mailto:<EMAIL>?subject=subscribe>\nList-Id: Freshrpms RPM discussion list <rpm-zzzlist.freshrpms.net>\nList-Unsubscribe: <http://lists.freshrpms.net/mailman/listinfo/rpm-zzzlist>,\n <mailto:<EMAIL>?subject=unsubscribe>\nList-Archive: <http://lists.freshrpms.net/pipermail/rpm-zzzlist/>\nX-Original-Date: Sun, 01 Dec 2002 19:21:03 -0800\nDate: Sun, 01 Dec 2002 19:21:03 -0800\n\nNova Nova wrote:\n> bass and treble settings do not seem to have any affect on the sound.\n\nLook around for a \"Tone\" toggle. Toggle it.\n\n\n_______________________________________________\nRPM-List mailing list <<EMAIL>>\nhttp://lists.freshrpms.net/mailman/listinfo/rpm-list\n\n\n"}
1,199
1,401
package com.github.jvmgo.instructions.stores; import com.github.jvmgo.instructions.base.Index8Instruction; import com.github.jvmgo.rtda.Frame; public class istore extends Index8Instruction { @Override public int getOpCode() { return 0x36; } @Override public void execute(Frame frame) { int val = frame.getOperandStack().popInt(); frame.getLocalVars().setInt(index, val); } }
169
1,244
#include <sys/stat.h> #include "syscall.h" int utimensat(int fd, const char *path, const struct timespec times[2], int flags) { return syscall(SYS_utimensat, fd, path, times, flags); }
73
995
package zemberek.core.quantization; import com.google.common.primitives.Ints; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Random; import zemberek.core.math.DoubleArrays; /** * This applies a k-means like algorithm to the data points for quantization. It randomly chooses * cluster centers form actual data. After that it re-assgins the mean value to the center of mass * of the cluster points. If a cluster has no data points, it assigns the mean value as (most * crowded-data-point-mean+mean)/2 it iterates 15 times to find the final mean values and uses them * as quatization points. */ public class KMeansQuantizer implements Quantizer { final int range; double data[]; double sorted[]; Map<Double, Integer> lookup = new HashMap<>(); private KMeansQuantizer(double[] data, int range, Map<Double, Integer> lookup) { this.data = data; this.range = range; this.lookup = lookup; this.sorted = data.clone(); Arrays.sort(sorted); } public static KMeansQuantizer generateFromRawData(float[] dataToQuantize, int bits) { return generateFromRawData(DoubleArrays.convert(dataToQuantize), bits); } /** * Creates a KMeansQuantizer with given histogram and bitsize. * * @param dataToQuantize input dataToQuantize to quantize. * @param bits quantization level amount in bits. There will be 2^bits level. * @return A Quantizer. */ public static KMeansQuantizer generateFromRawData(double[] dataToQuantize, int bits) { if (bits < 4 || bits > 24) { throw new IllegalArgumentException( "Bit count cannot be less than 4 or larger than 24" + bits); } int range = 1 << bits; Map<Double, Integer> lookup = new HashMap<>(); final int dataLength = dataToQuantize.length; if (range >= dataLength) { double[] means = new double[dataLength]; int i = 0; for (double v : dataToQuantize) { lookup.put(v, i); means[i] = v; i++; } return new KMeansQuantizer(means, dataLength, lookup); } return kMeans(dataToQuantize, range, 10); } private static KMeansQuantizer kMeans(double[] data, int clusterCount, int iterationCount) { double[] means = new double[clusterCount]; Map<Double, Integer> lookup = new HashMap<>(); int indexes[] = new int[data.length]; //initialization. means are placed using random data. MeanCount[] meanCounts = new MeanCount[clusterCount]; Random r = new Random(); for (int i = 0; i < clusterCount; i++) { means[i] = data[r.nextInt(data.length)]; meanCounts[i] = new MeanCount(i, 0); } for (int j = 0; j < iterationCount; j++) { // cluster points. for (int i = 0; i < data.length; i++) { int closestMeanIndex = -1; double m = Double.POSITIVE_INFINITY; for (int k = 0; k < means.length; k++) { double dif = Math.abs(data[i] - means[k]); if (dif < m) { m = dif; closestMeanIndex = k; } } indexes[i] = closestMeanIndex; meanCounts[closestMeanIndex].count++; } Arrays.sort(meanCounts); // update means for (int k = 0; k < means.length; k++) { int pointCount = 0; double meanTotal = 0; for (int i = 0; i < data.length; i++) { if (indexes[i] == k) { pointCount++; meanTotal += data[i]; } } // if there is no point in one cluster,reassign the mean value of the empty cluster to // (most crowded cluster mean + empty cluseter mean ) /2 if (pointCount > 0) { means[k] = meanTotal / pointCount; } else { double m = (means[k] + means[meanCounts[0].index]) / 2; means[k] = m; } } } int i = 0; // generate lookup for quantization. for (int index : indexes) { lookup.put(data[i++], index); } return new KMeansQuantizer(means, means.length, lookup); } public int getQuantizationIndex(double value) { if (!lookup.containsKey(value)) { throw new IllegalArgumentException( "cannot quantize value. Value does not exist in quantization lookup:" + value); } return lookup.get(value); } public double getQuantizedValue(double value) { return data[lookup.get(value)]; } public DoubleLookup getDequantizer() { return new DoubleLookup(data); } private static class MeanCount implements Comparable<MeanCount> { int index; int count; MeanCount(int index, int count) { this.index = index; this.count = count; } public int compareTo(MeanCount o) { return -Ints.compare(count, o.count); } } }
1,863
3,212
/* * 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.nifi.registry.serialization; import java.io.InputStream; import java.io.OutputStream; /** * Serializes and de-serializes objects. * This interface is designed to provide backward compatibility to different versioned serialization formats. * So that serialized data model and format can evolve overtime. */ public interface VersionedSerializer<T> { /** * Serialize the given object into the target output stream with the specified version format. * Implementation classes are responsible to serialize the version to the head of the serialized content, * so that it can be retrieved by {@link #readDataModelVersion(InputStream)} method efficiently * without reading the entire byte array. * * @param dataModelVersion the data model version * @param t the object to serialize * @param out the target output stream * @throws SerializationException thrown when serialization failed */ void serialize(int dataModelVersion, T t, OutputStream out) throws SerializationException; /** * Read data model version from the given InputStream. * <p> * Even if an implementation serializer was able to read a version, it does not necessary mean * the same serializers {@link #deserialize(InputStream)} method will be called. * For example, when the header structure has not been changed, the newer version of serializer may be able to * read older data model version. But deserialization should be done with the older serializer. * </p> * @param input the input stream to read version from * @return the read data model version * @throws SerializationException thrown when reading version failed */ int readDataModelVersion(InputStream input) throws SerializationException; /** * Deserializes the given InputStream back to an object of the given type. * * @param input the InputStream to deserialize, * the position of input is reset to the the beginning of the stream when this method is called * @return the deserialized object * @throws SerializationException thrown when deserialization failed */ T deserialize(InputStream input) throws SerializationException; }
829
453
#include "syscall.h" #include "sysfuncs.h" #include <kernel/interrupts/interrupts.h> #include <kernel/drivers/terminal/terminal.h> #include <kernel/drivers/pit/pit.h> #include <kernel/multitasking//tasks/task.h> #include <std/array_m.h> #define MAX_SYSCALLS 128 static int syscall_handler(register_state_t* regs); array_m* syscalls = {0}; void syscall_init() { printf_info("Syscalls init..."); interrupt_setup_callback(INT_VECTOR_SYSCALL, (int_callback_t)syscall_handler); syscalls = array_m_create(MAX_SYSCALLS); create_sysfuncs(); } bool syscall_is_setup() { //has the syscalls array been created? return (syscalls); } void syscall_add(void* syscall) { if (syscalls->size + 1 == MAX_SYSCALLS) { printf_err("Not installing syscall %d, too many in use!", syscalls->size); return; } array_m_insert(syscalls, syscall); } static int syscall_handler(register_state_t* regs) { //check requested syscall number //stored in eax if (!syscalls || regs->eax >= MAX_SYSCALLS) { printf_err("Syscall %d called but not defined", regs->eax); return -1; } //location of syscall funcptr int (*location)() = (int(*)())array_m_lookup(syscalls, regs->eax); //we don't know how many arguments the function wants. //so just push them all on the stack in correct order //the function will use whatever it wants, and we can just //pop it all back off afterwards int ret; asm volatile(" \ push %1; \ push %2; \ push %3; \ push %4; \ push %5; \ call *%6; \ pop %%ebx; \ pop %%ebx; \ pop %%ebx; \ pop %%ebx; \ pop %%ebx; \ " : "=a" (ret) : "r" (regs->edi), "r" (regs->esi), "r" (regs->edx), "r" (regs->ecx), "r" (regs->ebx), "r" (location)); regs->eax = ret; return ret; }
725
348
{"nom":"<NAME>","circ":"4ème circonscription","dpt":"Yvelines","inscrits":3078,"abs":1636,"votants":1442,"blancs":14,"nuls":6,"exp":1422,"res":[{"nuance":"REM","nom":"Mme <NAME>","voix":692},{"nuance":"LR","nom":"<NAME>","voix":297},{"nuance":"FI","nom":"Mme <NAME>","voix":114},{"nuance":"FN","nom":"Mme <NAME>","voix":96},{"nuance":"ECO","nom":"Mme <NAME>","voix":60},{"nuance":"SOC","nom":"Mme <NAME>","voix":47},{"nuance":"DVD","nom":"Mme <NAME>","voix":29},{"nuance":"DVD","nom":"M. <NAME>","voix":19},{"nuance":"DLF","nom":"Mme <NAME>","voix":19},{"nuance":"DIV","nom":"M. <NAME>","voix":12},{"nuance":"DVG","nom":"M. <NAME>","voix":11},{"nuance":"COM","nom":"M. <NAME>","voix":11},{"nuance":"DIV","nom":"M. <NAME>","voix":7},{"nuance":"EXG","nom":"<NAME>","voix":6},{"nuance":"DIV","nom":"Mme <NAME>","voix":2}]}
332
348
{"nom":"Algrange","circ":"8ème circonscription","dpt":"Moselle","inscrits":4395,"abs":2806,"votants":1589,"blancs":26,"nuls":2,"exp":1561,"res":[{"nuance":"FN","nom":"<NAME>","voix":379},{"nuance":"MDM","nom":"<NAME>","voix":369},{"nuance":"COM","nom":"M. <NAME>","voix":326},{"nuance":"SOC","nom":"Mme <NAME>","voix":189},{"nuance":"FI","nom":"M. <NAME>","voix":168},{"nuance":"LR","nom":"Mme <NAME>","voix":56},{"nuance":"ECO","nom":"M. <NAME>","voix":25},{"nuance":"DLF","nom":"Mme <NAME>","voix":14},{"nuance":"EXG","nom":"M. <NAME>","voix":11},{"nuance":"REG","nom":"M. <NAME>","voix":11},{"nuance":"DIV","nom":"M. <NAME>","voix":8},{"nuance":"EXG","nom":"Mme <NAME>","voix":5},{"nuance":"REG","nom":"Mme <NAME>","voix":0}]}
298
862
<reponame>harryfallows/atlasdb /* * (c) Copyright 2019 Palantir Technologies Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.palantir.lock.client; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.palantir.atlasdb.timelock.api.ConjureLockToken; import com.palantir.common.time.NanoTime; import com.palantir.lock.v2.LeaderTime; import com.palantir.lock.v2.LeadershipId; import com.palantir.lock.v2.Lease; import java.time.Duration; import java.util.UUID; import org.junit.Test; public class LeasedLockTokenTest { private static final ConjureLockToken LOCK_TOKEN = ConjureLockToken.of(UUID.randomUUID()); private static final LeadershipId LEADER_ID = LeadershipId.random(); private static final LeadershipId OTHER_LEADER_ID = LeadershipId.random(); private static final Duration LEASE_TIMEOUT = Duration.ofMillis(1234); private NanoTime currentTime = NanoTime.createForTests(123); @Test public void shouldCreateValidTokensUntilExpiry() { LeasedLockToken token = LeasedLockToken.of(LOCK_TOKEN, getLease()); assertThat(token.isValid(getIdentifiedTime())).isTrue(); advance(LEASE_TIMEOUT.minus(Duration.ofNanos(1))); assertThat(token.isValid(getIdentifiedTime())).isTrue(); } @Test public void shouldBeInvalidAfterExpiry() { LeasedLockToken token = LeasedLockToken.of(LOCK_TOKEN, getLease()); advance(LEASE_TIMEOUT); assertThat(token.isValid(getIdentifiedTime())).isFalse(); } @Test public void shouldBeInvalidAfterInvalidation() { LeasedLockToken token = LeasedLockToken.of(LOCK_TOKEN, getLease()); token.invalidate(); assertThat(token.isValid(getIdentifiedTime())).isFalse(); } @Test public void shouldBeInvalidAfterInvalidationAndExpiry() { LeasedLockToken token = LeasedLockToken.of(LOCK_TOKEN, getLease()); advance(LEASE_TIMEOUT); token.invalidate(); assertThat(token.isValid(getIdentifiedTime())).isFalse(); } @Test public void refreshShouldExtendValidity() { LeasedLockToken token = LeasedLockToken.of(LOCK_TOKEN, getLease()); advance(LEASE_TIMEOUT.minus(Duration.ofNanos(1))); assertValid(token); token.updateLease(getLease()); advance(LEASE_TIMEOUT.minus(Duration.ofNanos(1))); assertValid(token); } @Test public void refreshShouldExtendValidityOfExpiredToken() { LeasedLockToken token = LeasedLockToken.of(LOCK_TOKEN, getLease()); advance(LEASE_TIMEOUT); assertInvalid(token); token.updateLease(getLease()); assertExpiresExactlyAfter(token, LEASE_TIMEOUT); } @Test public void ignoreRefreshIfNewLeaseHasShorterLife() { LeasedLockToken token = LeasedLockToken.of(LOCK_TOKEN, getLease()); assertExpiresExactlyAfter(token, LEASE_TIMEOUT); token.updateLease(Lease.of(getIdentifiedTime(), LEASE_TIMEOUT.minus(Duration.ofNanos(123)))); assertExpiresExactlyAfter(token, LEASE_TIMEOUT); } @Test public void ignoreRefreshIfNewLeaseGoesBackInTime() { Lease oldLease = getLease(); advance(Duration.ofNanos(123)); LeasedLockToken token = LeasedLockToken.of(LOCK_TOKEN, getLease()); assertExpiresExactlyAfter(token, LEASE_TIMEOUT); token.updateLease(oldLease); assertExpiresExactlyAfter(token, LEASE_TIMEOUT); } @Test public void throwIfRefreshedWithDifferentLeaderId() { LeasedLockToken token = LeasedLockToken.of(LOCK_TOKEN, getLease()); Lease otherLease = Lease.of(LeaderTime.of(OTHER_LEADER_ID, currentTime), LEASE_TIMEOUT); assertThatThrownBy(() -> token.updateLease(otherLease)) .hasMessageStartingWith("Lock leases can only be refreshed by lease owners."); } private void advance(Duration duration) { currentTime = currentTime.plus(duration); } private Lease getLease() { return Lease.of(getIdentifiedTime(), LEASE_TIMEOUT); } private LeaderTime getIdentifiedTime() { return LeaderTime.of(LEADER_ID, currentTime); } private void assertExpiresExactlyAfter(LeasedLockToken token, Duration duration) { LeadershipId tokenLeaderId = token.getLease().leaderTime().id(); assertThat(token.isValid(LeaderTime.of(tokenLeaderId, currentTime.plus(duration.minus(Duration.ofNanos(1)))))) .isTrue(); assertThat(token.isValid(LeaderTime.of(tokenLeaderId, currentTime.plus(duration)))) .isFalse(); } private void assertValid(LeasedLockToken token) { assertThat(token.isValid(getIdentifiedTime())).isTrue(); } private void assertInvalid(LeasedLockToken token) { assertThat(token.isValid(getIdentifiedTime())).isFalse(); } }
2,029
984
//+--------------------------------------------------------------------------- // // Microsoft Windows // Copyright (c) Microsoft Corporation. All rights reserved. // // File: coml2api.h // // Contents: Structured storage, property sets, and related APIs. // //---------------------------------------------------------------------------- #if !defined(_COML2API_H_) #define _COML2API_H_ #ifdef _MSC_VER #pragma once #endif // _MSC_VER #include <apiset.h> #include <apisetcconv.h> #include <combaseapi.h> #include <objidl.h> #include <propidlbase.h> #pragma region Application and Games Family #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP | WINAPI_PARTITION_GAMES) // // Common typedefs for paramaters used in Storage API's, gleamed from storage.h // Also contains Storage error codes, which should be moved into the storage // idl files. // #define CWCSTORAGENAME 32 /* Storage instantiation modes */ #define STGM_DIRECT 0x00000000L #define STGM_TRANSACTED 0x00010000L #define STGM_SIMPLE 0x08000000L #define STGM_READ 0x00000000L #define STGM_WRITE 0x00000001L #define STGM_READWRITE 0x00000002L #define STGM_SHARE_DENY_NONE 0x00000040L #define STGM_SHARE_DENY_READ 0x00000030L #define STGM_SHARE_DENY_WRITE 0x00000020L #define STGM_SHARE_EXCLUSIVE 0x00000010L #define STGM_PRIORITY 0x00040000L #define STGM_DELETEONRELEASE 0x04000000L #if (WINVER >= 400) #define STGM_NOSCRATCH 0x00100000L #endif /* WINVER */ #define STGM_CREATE 0x00001000L #define STGM_CONVERT 0x00020000L #define STGM_FAILIFTHERE 0x00000000L #define STGM_NOSNAPSHOT 0x00200000L #if (_WIN32_WINNT >= 0x0500) #define STGM_DIRECT_SWMR 0x00400000L #endif typedef DWORD STGFMT; #define STGFMT_STORAGE 0 #define STGFMT_NATIVE 1 #define STGFMT_FILE 3 #define STGFMT_ANY 4 #define STGFMT_DOCFILE 5 #endif /* WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP | WINAPI_PARTITION_GAMES) */ #pragma endregion #pragma region Application Family #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) // This is a legacy define to allow old component to builds #define STGFMT_DOCUMENT 0 // Structured storage APIs _Check_return_ WINOLEAPI StgCreateDocfile( _In_opt_ _Null_terminated_ const WCHAR* pwcsName, _In_ DWORD grfMode, _Reserved_ DWORD reserved, _Outptr_ IStorage** ppstgOpen ); _Check_return_ WINOLEAPI StgCreateDocfileOnILockBytes( _In_ ILockBytes* plkbyt, _In_ DWORD grfMode, _In_ DWORD reserved, _Outptr_ IStorage** ppstgOpen ); _Check_return_ WINOLEAPI StgOpenStorage( _In_opt_ _Null_terminated_ const WCHAR* pwcsName, _In_opt_ IStorage* pstgPriority, _In_ DWORD grfMode, _In_opt_z_ SNB snbExclude, _In_ DWORD reserved, _Outptr_ IStorage** ppstgOpen ); _Check_return_ WINOLEAPI StgOpenStorageOnILockBytes( _In_ ILockBytes* plkbyt, _In_opt_ IStorage* pstgPriority, _In_ DWORD grfMode, _In_opt_z_ SNB snbExclude, _Reserved_ DWORD reserved, _Outptr_ IStorage** ppstgOpen ); _Check_return_ WINOLEAPI StgIsStorageFile( _In_ _Null_terminated_ const WCHAR* pwcsName ); _Check_return_ WINOLEAPI StgIsStorageILockBytes( _In_ ILockBytes* plkbyt ); _Check_return_ WINOLEAPI StgSetTimes( _In_ _Null_terminated_ const WCHAR* lpszName, _In_opt_ const FILETIME* pctime, _In_opt_ const FILETIME* patime, _In_opt_ const FILETIME* pmtime ); // STG initialization options for StgCreateStorageEx and StgOpenStorageEx #if _WIN32_WINNT == 0x500 #define STGOPTIONS_VERSION 1 #elif _WIN32_WINNT > 0x500 #define STGOPTIONS_VERSION 2 #else #define STGOPTIONS_VERSION 0 #endif typedef struct tagSTGOPTIONS { USHORT usVersion; // Versions 1 and 2 supported USHORT reserved; // must be 0 for padding ULONG ulSectorSize; // docfile header sector size (512) #if STGOPTIONS_VERSION >= 2 const WCHAR *pwcsTemplateFile; // version 2 or above #endif } STGOPTIONS; _Check_return_ WINOLEAPI StgCreateStorageEx( _In_opt_ _Null_terminated_ const WCHAR* pwcsName, _In_ DWORD grfMode, _In_ DWORD stgfmt, _In_ DWORD grfAttrs, _Inout_opt_ STGOPTIONS* pStgOptions, _In_opt_ PSECURITY_DESCRIPTOR pSecurityDescriptor, _In_ REFIID riid, _Outptr_ void** ppObjectOpen ); _Check_return_ WINOLEAPI StgOpenStorageEx( _In_ _Null_terminated_ const WCHAR* pwcsName, _In_ DWORD grfMode, _In_ DWORD stgfmt, _In_ DWORD grfAttrs, _Inout_opt_ STGOPTIONS* pStgOptions, _In_opt_ PSECURITY_DESCRIPTOR pSecurityDescriptor, _In_ REFIID riid, _Outptr_ void** ppObjectOpen ); #ifndef _STGCREATEPROPSTG_DEFINED_ _Check_return_ WINOLEAPI StgCreatePropStg( _In_ IUnknown* pUnk, _In_ REFFMTID fmtid, _In_ const CLSID* pclsid, _In_ DWORD grfFlags, _Reserved_ DWORD dwReserved, _Outptr_ IPropertyStorage** ppPropStg ); _Check_return_ WINOLEAPI StgOpenPropStg( _In_ IUnknown* pUnk, _In_ REFFMTID fmtid, _In_ DWORD grfFlags, _Reserved_ DWORD dwReserved, _Outptr_ IPropertyStorage** ppPropStg ); _Check_return_ WINOLEAPI StgCreatePropSetStg( _In_ IStorage* pStorage, _Reserved_ DWORD dwReserved, _Outptr_ IPropertySetStorage** ppPropSetStg ); #define CCH_MAX_PROPSTG_NAME 31 _Check_return_ WINOLEAPI FmtIdToPropStgName( _In_ const FMTID* pfmtid, _Out_writes_(CCH_MAX_PROPSTG_NAME+1) LPOLESTR oszName ); _Check_return_ WINOLEAPI PropStgNameToFmtId( _In_ const LPOLESTR oszName, _Out_ FMTID* pfmtid ); #endif // _STGCREATEPROPSTG_DEFINED_ // Helper functions WINOLEAPI ReadClassStg( _In_ LPSTORAGE pStg, _Out_ CLSID FAR * pclsid ); WINOLEAPI WriteClassStg( _In_ LPSTORAGE pStg, _In_ REFCLSID rclsid ); WINOLEAPI ReadClassStm( _In_ LPSTREAM pStm, _Out_ CLSID FAR * pclsid ); WINOLEAPI WriteClassStm( _In_ LPSTREAM pStm, _In_ REFCLSID rclsid ); // Storage utility APIs _Check_return_ WINOLEAPI GetHGlobalFromILockBytes( _In_ LPLOCKBYTES plkbyt, _Out_ HGLOBAL FAR * phglobal ); _Check_return_ WINOLEAPI CreateILockBytesOnHGlobal( _In_opt_ HGLOBAL hGlobal, _In_ BOOL fDeleteOnRelease, _Outptr_ LPLOCKBYTES FAR * pplkbyt ); // ConvertTo APIs WINOLEAPI GetConvertStg( _In_ LPSTORAGE pStg ); #endif /* WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) */ #pragma endregion #endif // __COML2API_H__
2,989
471
<reponame>nipun-gupta-e3183/jesque package net.greghaines.jesque.meta; import java.util.Arrays; import java.util.Date; import java.util.List; import net.greghaines.jesque.WorkerStatus; import net.greghaines.jesque.meta.WorkerInfo.State; import org.junit.Assert; import org.junit.Test; public class TestWorkerInfo { @Test public void testProperties() { final WorkerInfo wInfo = new WorkerInfo(); final String name = "foo"; wInfo.setName(name); Assert.assertEquals(name, wInfo.getName()); Assert.assertEquals(name, wInfo.toString()); final State state = State.IDLE; wInfo.setState(state); Assert.assertEquals(state, wInfo.getState()); final Date started = new Date(); wInfo.setStarted(started); Assert.assertEquals(started, wInfo.getStarted()); final Long processed = 3l; wInfo.setProcessed(processed); Assert.assertEquals(processed, wInfo.getProcessed()); final Long failed = 4l; wInfo.setFailed(failed); Assert.assertEquals(failed, wInfo.getFailed()); final String host = "bar"; wInfo.setHost(host); Assert.assertEquals(host, wInfo.getHost()); final String pid = "123"; wInfo.setPid(pid); Assert.assertEquals(pid, wInfo.getPid()); final List<String> queues = Arrays.asList("queue1", "queue2"); wInfo.setQueues(queues); Assert.assertEquals(queues, wInfo.getQueues()); final WorkerStatus status = new WorkerStatus(); wInfo.setStatus(status); Assert.assertEquals(status, wInfo.getStatus()); } @Test public void testCompareToEqualsHashCode() { final WorkerInfo wi1 = new WorkerInfo(); Assert.assertTrue(wi1.compareTo(null) > 0); Assert.assertFalse(wi1.equals(null)); Assert.assertTrue(wi1.equals(wi1)); final WorkerInfo wi2 = new WorkerInfo(); Assert.assertEquals(0, wi1.compareTo(wi2)); Assert.assertTrue(wi1.equals(wi2)); Assert.assertEquals(wi1.hashCode(), wi2.hashCode()); final WorkerStatus status1 = new WorkerStatus(); wi1.setStatus(status1); Assert.assertTrue(wi1.compareTo(wi2) > 0); Assert.assertFalse(wi1.equals(wi2)); wi2.setStatus(status1); Assert.assertEquals(0, wi1.compareTo(wi2)); Assert.assertTrue(wi1.equals(wi2)); Assert.assertEquals(wi1.hashCode(), wi2.hashCode()); wi1.setStatus(null); Assert.assertTrue(wi1.compareTo(wi2) < 0); Assert.assertFalse(wi1.equals(wi2)); wi1.setStatus(status1); final Date runAt1 = new Date(); status1.setRunAt(runAt1); Assert.assertEquals(0, wi1.compareTo(wi2)); Assert.assertTrue(wi1.equals(wi2)); Assert.assertEquals(wi1.hashCode(), wi2.hashCode()); final WorkerStatus status2 = new WorkerStatus(); wi2.setStatus(status2); Assert.assertTrue(wi1.compareTo(wi2) > 0); Assert.assertFalse(wi1.equals(wi2)); final Date runAt2 = new Date(runAt1.getTime() + 1000); status2.setRunAt(runAt2); Assert.assertTrue(wi1.compareTo(wi2) < 0); Assert.assertFalse(wi1.equals(wi2)); status1.setRunAt(null); Assert.assertTrue(wi1.compareTo(wi2) < 0); Assert.assertFalse(wi1.equals(wi2)); } }
1,545
862
package com.palantir.atlasdb.schema.stream.generated; import java.util.Arrays; import java.util.Collection; import java.util.EnumSet; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.SortedMap; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import java.util.function.BiFunction; import java.util.function.Supplier; import java.util.stream.Stream; import javax.annotation.Generated; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.MoreObjects; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Collections2; import com.google.common.collect.ComparisonChain; import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.google.common.collect.Multimaps; import com.google.common.collect.Sets; import com.google.common.hash.Hashing; import com.google.common.primitives.Bytes; import com.google.common.primitives.UnsignedBytes; import com.google.protobuf.InvalidProtocolBufferException; import com.palantir.atlasdb.compress.CompressionUtils; import com.palantir.atlasdb.encoding.PtBytes; import com.palantir.atlasdb.keyvalue.api.BatchColumnRangeSelection; import com.palantir.atlasdb.keyvalue.api.Cell; import com.palantir.atlasdb.keyvalue.api.ColumnRangeSelection; import com.palantir.atlasdb.keyvalue.api.ColumnRangeSelections; import com.palantir.atlasdb.keyvalue.api.ColumnSelection; import com.palantir.atlasdb.keyvalue.api.Namespace; import com.palantir.atlasdb.keyvalue.api.Prefix; import com.palantir.atlasdb.keyvalue.api.RangeRequest; import com.palantir.atlasdb.keyvalue.api.RowResult; import com.palantir.atlasdb.keyvalue.api.TableReference; import com.palantir.atlasdb.keyvalue.impl.Cells; import com.palantir.atlasdb.ptobject.EncodingUtils; import com.palantir.atlasdb.table.api.AtlasDbDynamicMutablePersistentTable; import com.palantir.atlasdb.table.api.AtlasDbMutablePersistentTable; import com.palantir.atlasdb.table.api.AtlasDbNamedMutableTable; import com.palantir.atlasdb.table.api.AtlasDbNamedPersistentSet; import com.palantir.atlasdb.table.api.ColumnValue; import com.palantir.atlasdb.table.api.TypedRowResult; import com.palantir.atlasdb.table.description.ColumnValueDescription.Compression; import com.palantir.atlasdb.table.description.ValueType; import com.palantir.atlasdb.table.generation.ColumnValues; import com.palantir.atlasdb.table.generation.Descending; import com.palantir.atlasdb.table.generation.NamedColumnValue; import com.palantir.atlasdb.transaction.api.AtlasDbConstraintCheckingMode; import com.palantir.atlasdb.transaction.api.ConstraintCheckingTransaction; import com.palantir.atlasdb.transaction.api.ImmutableGetRangesQuery; import com.palantir.atlasdb.transaction.api.Transaction; import com.palantir.common.base.AbortingVisitor; import com.palantir.common.base.AbortingVisitors; import com.palantir.common.base.BatchingVisitable; import com.palantir.common.base.BatchingVisitableView; import com.palantir.common.base.BatchingVisitables; import com.palantir.common.base.Throwables; import com.palantir.common.collect.IterableView; import com.palantir.common.persist.Persistable; import com.palantir.common.persist.Persistable.Hydrator; import com.palantir.common.persist.Persistables; import com.palantir.util.AssertUtils; import com.palantir.util.crypto.Sha256Hash; @Generated("com.palantir.atlasdb.table.description.render.TableRenderer") @SuppressWarnings({"all", "deprecation"}) public final class StreamTestStreamIdxTable implements AtlasDbDynamicMutablePersistentTable<StreamTestStreamIdxTable.StreamTestStreamIdxRow, StreamTestStreamIdxTable.StreamTestStreamIdxColumn, StreamTestStreamIdxTable.StreamTestStreamIdxColumnValue, StreamTestStreamIdxTable.StreamTestStreamIdxRowResult> { private final Transaction t; private final List<StreamTestStreamIdxTrigger> triggers; private final static String rawTableName = "stream_test_stream_idx"; private final TableReference tableRef; private final static ColumnSelection allColumns = ColumnSelection.all(); static StreamTestStreamIdxTable of(Transaction t, Namespace namespace) { return new StreamTestStreamIdxTable(t, namespace, ImmutableList.<StreamTestStreamIdxTrigger>of()); } static StreamTestStreamIdxTable of(Transaction t, Namespace namespace, StreamTestStreamIdxTrigger trigger, StreamTestStreamIdxTrigger... triggers) { return new StreamTestStreamIdxTable(t, namespace, ImmutableList.<StreamTestStreamIdxTrigger>builder().add(trigger).add(triggers).build()); } static StreamTestStreamIdxTable of(Transaction t, Namespace namespace, List<StreamTestStreamIdxTrigger> triggers) { return new StreamTestStreamIdxTable(t, namespace, triggers); } private StreamTestStreamIdxTable(Transaction t, Namespace namespace, List<StreamTestStreamIdxTrigger> triggers) { this.t = t; this.tableRef = TableReference.create(namespace, rawTableName); this.triggers = triggers; } public static String getRawTableName() { return rawTableName; } public TableReference getTableRef() { return tableRef; } public String getTableName() { return tableRef.getQualifiedName(); } public Namespace getNamespace() { return tableRef.getNamespace(); } /** * <pre> * StreamTestStreamIdxRow { * {@literal Long id}; * } * </pre> */ public static final class StreamTestStreamIdxRow implements Persistable, Comparable<StreamTestStreamIdxRow> { private final long id; public static StreamTestStreamIdxRow of(long id) { return new StreamTestStreamIdxRow(id); } private StreamTestStreamIdxRow(long id) { this.id = id; } public long getId() { return id; } public static Function<StreamTestStreamIdxRow, Long> getIdFun() { return new Function<StreamTestStreamIdxRow, Long>() { @Override public Long apply(StreamTestStreamIdxRow row) { return row.id; } }; } public static Function<Long, StreamTestStreamIdxRow> fromIdFun() { return new Function<Long, StreamTestStreamIdxRow>() { @Override public StreamTestStreamIdxRow apply(Long row) { return StreamTestStreamIdxRow.of(row); } }; } @Override public byte[] persistToBytes() { byte[] idBytes = EncodingUtils.encodeUnsignedVarLong(id); return EncodingUtils.add(idBytes); } public static final Hydrator<StreamTestStreamIdxRow> BYTES_HYDRATOR = new Hydrator<StreamTestStreamIdxRow>() { @Override public StreamTestStreamIdxRow hydrateFromBytes(byte[] __input) { int __index = 0; Long id = EncodingUtils.decodeUnsignedVarLong(__input, __index); __index += EncodingUtils.sizeOfUnsignedVarLong(id); return new StreamTestStreamIdxRow(id); } }; @Override public String toString() { return MoreObjects.toStringHelper(getClass().getSimpleName()) .add("id", id) .toString(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } StreamTestStreamIdxRow other = (StreamTestStreamIdxRow) obj; return Objects.equals(id, other.id); } @SuppressWarnings("ArrayHashCode") @Override public int hashCode() { return Objects.hashCode(id); } @Override public int compareTo(StreamTestStreamIdxRow o) { return ComparisonChain.start() .compare(this.id, o.id) .result(); } } /** * <pre> * StreamTestStreamIdxColumn { * {@literal byte[] reference}; * } * </pre> */ public static final class StreamTestStreamIdxColumn implements Persistable, Comparable<StreamTestStreamIdxColumn> { private final byte[] reference; public static StreamTestStreamIdxColumn of(byte[] reference) { return new StreamTestStreamIdxColumn(reference); } private StreamTestStreamIdxColumn(byte[] reference) { this.reference = reference; } public byte[] getReference() { return reference; } public static Function<StreamTestStreamIdxColumn, byte[]> getReferenceFun() { return new Function<StreamTestStreamIdxColumn, byte[]>() { @Override public byte[] apply(StreamTestStreamIdxColumn row) { return row.reference; } }; } public static Function<byte[], StreamTestStreamIdxColumn> fromReferenceFun() { return new Function<byte[], StreamTestStreamIdxColumn>() { @Override public StreamTestStreamIdxColumn apply(byte[] row) { return StreamTestStreamIdxColumn.of(row); } }; } @Override public byte[] persistToBytes() { byte[] referenceBytes = EncodingUtils.encodeSizedBytes(reference); return EncodingUtils.add(referenceBytes); } public static final Hydrator<StreamTestStreamIdxColumn> BYTES_HYDRATOR = new Hydrator<StreamTestStreamIdxColumn>() { @Override public StreamTestStreamIdxColumn hydrateFromBytes(byte[] __input) { int __index = 0; byte[] reference = EncodingUtils.decodeSizedBytes(__input, __index); __index += EncodingUtils.sizeOfSizedBytes(reference); return new StreamTestStreamIdxColumn(reference); } }; @Override public String toString() { return MoreObjects.toStringHelper(getClass().getSimpleName()) .add("reference", reference) .toString(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } StreamTestStreamIdxColumn other = (StreamTestStreamIdxColumn) obj; return Arrays.equals(reference, other.reference); } @SuppressWarnings("ArrayHashCode") @Override public int hashCode() { return Objects.hashCode(reference); } @Override public int compareTo(StreamTestStreamIdxColumn o) { return ComparisonChain.start() .compare(this.reference, o.reference, UnsignedBytes.lexicographicalComparator()) .result(); } } public interface StreamTestStreamIdxTrigger { public void putStreamTestStreamIdx(Multimap<StreamTestStreamIdxRow, ? extends StreamTestStreamIdxColumnValue> newRows); } /** * <pre> * Column name description { * {@literal byte[] reference}; * } * Column value description { * type: Long; * } * </pre> */ public static final class StreamTestStreamIdxColumnValue implements ColumnValue<Long> { private final StreamTestStreamIdxColumn columnName; private final Long value; public static StreamTestStreamIdxColumnValue of(StreamTestStreamIdxColumn columnName, Long value) { return new StreamTestStreamIdxColumnValue(columnName, value); } private StreamTestStreamIdxColumnValue(StreamTestStreamIdxColumn columnName, Long value) { this.columnName = columnName; this.value = value; } public StreamTestStreamIdxColumn getColumnName() { return columnName; } @Override public Long getValue() { return value; } @Override public byte[] persistColumnName() { return columnName.persistToBytes(); } @Override public byte[] persistValue() { byte[] bytes = EncodingUtils.encodeUnsignedVarLong(value); return CompressionUtils.compress(bytes, Compression.NONE); } public static Long hydrateValue(byte[] bytes) { bytes = CompressionUtils.decompress(bytes, Compression.NONE); return EncodingUtils.decodeUnsignedVarLong(bytes, 0); } public static Function<StreamTestStreamIdxColumnValue, StreamTestStreamIdxColumn> getColumnNameFun() { return new Function<StreamTestStreamIdxColumnValue, StreamTestStreamIdxColumn>() { @Override public StreamTestStreamIdxColumn apply(StreamTestStreamIdxColumnValue columnValue) { return columnValue.getColumnName(); } }; } public static Function<StreamTestStreamIdxColumnValue, Long> getValueFun() { return new Function<StreamTestStreamIdxColumnValue, Long>() { @Override public Long apply(StreamTestStreamIdxColumnValue columnValue) { return columnValue.getValue(); } }; } @Override public String toString() { return MoreObjects.toStringHelper(getClass().getSimpleName()) .add("ColumnName", this.columnName) .add("Value", this.value) .toString(); } } public static final class StreamTestStreamIdxRowResult implements TypedRowResult { private final StreamTestStreamIdxRow rowName; private final ImmutableSet<StreamTestStreamIdxColumnValue> columnValues; public static StreamTestStreamIdxRowResult of(RowResult<byte[]> rowResult) { StreamTestStreamIdxRow rowName = StreamTestStreamIdxRow.BYTES_HYDRATOR.hydrateFromBytes(rowResult.getRowName()); Set<StreamTestStreamIdxColumnValue> columnValues = Sets.newHashSetWithExpectedSize(rowResult.getColumns().size()); for (Entry<byte[], byte[]> e : rowResult.getColumns().entrySet()) { StreamTestStreamIdxColumn col = StreamTestStreamIdxColumn.BYTES_HYDRATOR.hydrateFromBytes(e.getKey()); Long value = StreamTestStreamIdxColumnValue.hydrateValue(e.getValue()); columnValues.add(StreamTestStreamIdxColumnValue.of(col, value)); } return new StreamTestStreamIdxRowResult(rowName, ImmutableSet.copyOf(columnValues)); } private StreamTestStreamIdxRowResult(StreamTestStreamIdxRow rowName, ImmutableSet<StreamTestStreamIdxColumnValue> columnValues) { this.rowName = rowName; this.columnValues = columnValues; } @Override public StreamTestStreamIdxRow getRowName() { return rowName; } public Set<StreamTestStreamIdxColumnValue> getColumnValues() { return columnValues; } public static Function<StreamTestStreamIdxRowResult, StreamTestStreamIdxRow> getRowNameFun() { return new Function<StreamTestStreamIdxRowResult, StreamTestStreamIdxRow>() { @Override public StreamTestStreamIdxRow apply(StreamTestStreamIdxRowResult rowResult) { return rowResult.rowName; } }; } public static Function<StreamTestStreamIdxRowResult, ImmutableSet<StreamTestStreamIdxColumnValue>> getColumnValuesFun() { return new Function<StreamTestStreamIdxRowResult, ImmutableSet<StreamTestStreamIdxColumnValue>>() { @Override public ImmutableSet<StreamTestStreamIdxColumnValue> apply(StreamTestStreamIdxRowResult rowResult) { return rowResult.columnValues; } }; } @Override public String toString() { return MoreObjects.toStringHelper(getClass().getSimpleName()) .add("RowName", getRowName()) .add("ColumnValues", getColumnValues()) .toString(); } } @Override public void delete(StreamTestStreamIdxRow row, StreamTestStreamIdxColumn column) { delete(ImmutableMultimap.of(row, column)); } @Override public void delete(Iterable<StreamTestStreamIdxRow> rows) { Multimap<StreamTestStreamIdxRow, StreamTestStreamIdxColumn> toRemove = HashMultimap.create(); Multimap<StreamTestStreamIdxRow, StreamTestStreamIdxColumnValue> result = getRowsMultimap(rows); for (Entry<StreamTestStreamIdxRow, StreamTestStreamIdxColumnValue> e : result.entries()) { toRemove.put(e.getKey(), e.getValue().getColumnName()); } delete(toRemove); } @Override public void delete(Multimap<StreamTestStreamIdxRow, StreamTestStreamIdxColumn> values) { t.delete(tableRef, ColumnValues.toCells(values)); } @Override public void put(StreamTestStreamIdxRow rowName, Iterable<StreamTestStreamIdxColumnValue> values) { put(ImmutableMultimap.<StreamTestStreamIdxRow, StreamTestStreamIdxColumnValue>builder().putAll(rowName, values).build()); } @Override public void put(StreamTestStreamIdxRow rowName, StreamTestStreamIdxColumnValue... values) { put(ImmutableMultimap.<StreamTestStreamIdxRow, StreamTestStreamIdxColumnValue>builder().putAll(rowName, values).build()); } @Override public void put(Multimap<StreamTestStreamIdxRow, ? extends StreamTestStreamIdxColumnValue> values) { t.useTable(tableRef, this); t.put(tableRef, ColumnValues.toCellValues(values)); for (StreamTestStreamIdxTrigger trigger : triggers) { trigger.putStreamTestStreamIdx(values); } } @Override public void touch(Multimap<StreamTestStreamIdxRow, StreamTestStreamIdxColumn> values) { Multimap<StreamTestStreamIdxRow, StreamTestStreamIdxColumnValue> currentValues = get(values); put(currentValues); Multimap<StreamTestStreamIdxRow, StreamTestStreamIdxColumn> toDelete = HashMultimap.create(values); for (Map.Entry<StreamTestStreamIdxRow, StreamTestStreamIdxColumnValue> e : currentValues.entries()) { toDelete.remove(e.getKey(), e.getValue().getColumnName()); } delete(toDelete); } public static ColumnSelection getColumnSelection(Collection<StreamTestStreamIdxColumn> cols) { return ColumnSelection.create(Collections2.transform(cols, Persistables.persistToBytesFunction())); } public static ColumnSelection getColumnSelection(StreamTestStreamIdxColumn... cols) { return getColumnSelection(Arrays.asList(cols)); } @Override public Multimap<StreamTestStreamIdxRow, StreamTestStreamIdxColumnValue> get(Multimap<StreamTestStreamIdxRow, StreamTestStreamIdxColumn> cells) { Set<Cell> rawCells = ColumnValues.toCells(cells); Map<Cell, byte[]> rawResults = t.get(tableRef, rawCells); Multimap<StreamTestStreamIdxRow, StreamTestStreamIdxColumnValue> rowMap = HashMultimap.create(); for (Entry<Cell, byte[]> e : rawResults.entrySet()) { if (e.getValue().length > 0) { StreamTestStreamIdxRow row = StreamTestStreamIdxRow.BYTES_HYDRATOR.hydrateFromBytes(e.getKey().getRowName()); StreamTestStreamIdxColumn col = StreamTestStreamIdxColumn.BYTES_HYDRATOR.hydrateFromBytes(e.getKey().getColumnName()); Long val = StreamTestStreamIdxColumnValue.hydrateValue(e.getValue()); rowMap.put(row, StreamTestStreamIdxColumnValue.of(col, val)); } } return rowMap; } @Override public List<StreamTestStreamIdxColumnValue> getRowColumns(StreamTestStreamIdxRow row) { return getRowColumns(row, allColumns); } @Override public List<StreamTestStreamIdxColumnValue> getRowColumns(StreamTestStreamIdxRow row, ColumnSelection columns) { byte[] bytes = row.persistToBytes(); RowResult<byte[]> rowResult = t.getRows(tableRef, ImmutableSet.of(bytes), columns).get(bytes); if (rowResult == null) { return ImmutableList.of(); } else { List<StreamTestStreamIdxColumnValue> ret = Lists.newArrayListWithCapacity(rowResult.getColumns().size()); for (Entry<byte[], byte[]> e : rowResult.getColumns().entrySet()) { StreamTestStreamIdxColumn col = StreamTestStreamIdxColumn.BYTES_HYDRATOR.hydrateFromBytes(e.getKey()); Long val = StreamTestStreamIdxColumnValue.hydrateValue(e.getValue()); ret.add(StreamTestStreamIdxColumnValue.of(col, val)); } return ret; } } @Override public Multimap<StreamTestStreamIdxRow, StreamTestStreamIdxColumnValue> getRowsMultimap(Iterable<StreamTestStreamIdxRow> rows) { return getRowsMultimapInternal(rows, allColumns); } @Override public Multimap<StreamTestStreamIdxRow, StreamTestStreamIdxColumnValue> getRowsMultimap(Iterable<StreamTestStreamIdxRow> rows, ColumnSelection columns) { return getRowsMultimapInternal(rows, columns); } private Multimap<StreamTestStreamIdxRow, StreamTestStreamIdxColumnValue> getRowsMultimapInternal(Iterable<StreamTestStreamIdxRow> rows, ColumnSelection columns) { SortedMap<byte[], RowResult<byte[]>> results = t.getRows(tableRef, Persistables.persistAll(rows), columns); return getRowMapFromRowResults(results.values()); } private static Multimap<StreamTestStreamIdxRow, StreamTestStreamIdxColumnValue> getRowMapFromRowResults(Collection<RowResult<byte[]>> rowResults) { Multimap<StreamTestStreamIdxRow, StreamTestStreamIdxColumnValue> rowMap = HashMultimap.create(); for (RowResult<byte[]> result : rowResults) { StreamTestStreamIdxRow row = StreamTestStreamIdxRow.BYTES_HYDRATOR.hydrateFromBytes(result.getRowName()); for (Entry<byte[], byte[]> e : result.getColumns().entrySet()) { StreamTestStreamIdxColumn col = StreamTestStreamIdxColumn.BYTES_HYDRATOR.hydrateFromBytes(e.getKey()); Long val = StreamTestStreamIdxColumnValue.hydrateValue(e.getValue()); rowMap.put(row, StreamTestStreamIdxColumnValue.of(col, val)); } } return rowMap; } @Override public Map<StreamTestStreamIdxRow, BatchingVisitable<StreamTestStreamIdxColumnValue>> getRowsColumnRange(Iterable<StreamTestStreamIdxRow> rows, BatchColumnRangeSelection columnRangeSelection) { Map<byte[], BatchingVisitable<Map.Entry<Cell, byte[]>>> results = t.getRowsColumnRange(tableRef, Persistables.persistAll(rows), columnRangeSelection); Map<StreamTestStreamIdxRow, BatchingVisitable<StreamTestStreamIdxColumnValue>> transformed = Maps.newHashMapWithExpectedSize(results.size()); for (Entry<byte[], BatchingVisitable<Map.Entry<Cell, byte[]>>> e : results.entrySet()) { StreamTestStreamIdxRow row = StreamTestStreamIdxRow.BYTES_HYDRATOR.hydrateFromBytes(e.getKey()); BatchingVisitable<StreamTestStreamIdxColumnValue> bv = BatchingVisitables.transform(e.getValue(), result -> { StreamTestStreamIdxColumn col = StreamTestStreamIdxColumn.BYTES_HYDRATOR.hydrateFromBytes(result.getKey().getColumnName()); Long val = StreamTestStreamIdxColumnValue.hydrateValue(result.getValue()); return StreamTestStreamIdxColumnValue.of(col, val); }); transformed.put(row, bv); } return transformed; } @Override public Iterator<Map.Entry<StreamTestStreamIdxRow, StreamTestStreamIdxColumnValue>> getRowsColumnRange(Iterable<StreamTestStreamIdxRow> rows, ColumnRangeSelection columnRangeSelection, int batchHint) { Iterator<Map.Entry<Cell, byte[]>> results = t.getRowsColumnRange(getTableRef(), Persistables.persistAll(rows), columnRangeSelection, batchHint); return Iterators.transform(results, e -> { StreamTestStreamIdxRow row = StreamTestStreamIdxRow.BYTES_HYDRATOR.hydrateFromBytes(e.getKey().getRowName()); StreamTestStreamIdxColumn col = StreamTestStreamIdxColumn.BYTES_HYDRATOR.hydrateFromBytes(e.getKey().getColumnName()); Long val = StreamTestStreamIdxColumnValue.hydrateValue(e.getValue()); StreamTestStreamIdxColumnValue colValue = StreamTestStreamIdxColumnValue.of(col, val); return Maps.immutableEntry(row, colValue); }); } @Override public Map<StreamTestStreamIdxRow, Iterator<StreamTestStreamIdxColumnValue>> getRowsColumnRangeIterator(Iterable<StreamTestStreamIdxRow> rows, BatchColumnRangeSelection columnRangeSelection) { Map<byte[], Iterator<Map.Entry<Cell, byte[]>>> results = t.getRowsColumnRangeIterator(tableRef, Persistables.persistAll(rows), columnRangeSelection); Map<StreamTestStreamIdxRow, Iterator<StreamTestStreamIdxColumnValue>> transformed = Maps.newHashMapWithExpectedSize(results.size()); for (Entry<byte[], Iterator<Map.Entry<Cell, byte[]>>> e : results.entrySet()) { StreamTestStreamIdxRow row = StreamTestStreamIdxRow.BYTES_HYDRATOR.hydrateFromBytes(e.getKey()); Iterator<StreamTestStreamIdxColumnValue> bv = Iterators.transform(e.getValue(), result -> { StreamTestStreamIdxColumn col = StreamTestStreamIdxColumn.BYTES_HYDRATOR.hydrateFromBytes(result.getKey().getColumnName()); Long val = StreamTestStreamIdxColumnValue.hydrateValue(result.getValue()); return StreamTestStreamIdxColumnValue.of(col, val); }); transformed.put(row, bv); } return transformed; } private ColumnSelection optimizeColumnSelection(ColumnSelection columns) { if (columns.allColumnsSelected()) { return allColumns; } return columns; } public BatchingVisitableView<StreamTestStreamIdxRowResult> getAllRowsUnordered() { return getAllRowsUnordered(allColumns); } public BatchingVisitableView<StreamTestStreamIdxRowResult> getAllRowsUnordered(ColumnSelection columns) { return BatchingVisitables.transform(t.getRange(tableRef, RangeRequest.builder() .retainColumns(optimizeColumnSelection(columns)).build()), new Function<RowResult<byte[]>, StreamTestStreamIdxRowResult>() { @Override public StreamTestStreamIdxRowResult apply(RowResult<byte[]> input) { return StreamTestStreamIdxRowResult.of(input); } }); } @Override public List<String> findConstraintFailures(Map<Cell, byte[]> writes, ConstraintCheckingTransaction transaction, AtlasDbConstraintCheckingMode constraintCheckingMode) { return ImmutableList.of(); } @Override public List<String> findConstraintFailuresNoRead(Map<Cell, byte[]> writes, AtlasDbConstraintCheckingMode constraintCheckingMode) { return ImmutableList.of(); } /** * This exists to avoid unused import warnings * {@link AbortingVisitor} * {@link AbortingVisitors} * {@link ArrayListMultimap} * {@link Arrays} * {@link AssertUtils} * {@link AtlasDbConstraintCheckingMode} * {@link AtlasDbDynamicMutablePersistentTable} * {@link AtlasDbMutablePersistentTable} * {@link AtlasDbNamedMutableTable} * {@link AtlasDbNamedPersistentSet} * {@link BatchColumnRangeSelection} * {@link BatchingVisitable} * {@link BatchingVisitableView} * {@link BatchingVisitables} * {@link BiFunction} * {@link Bytes} * {@link Callable} * {@link Cell} * {@link Cells} * {@link Collection} * {@link Collections2} * {@link ColumnRangeSelection} * {@link ColumnRangeSelections} * {@link ColumnSelection} * {@link ColumnValue} * {@link ColumnValues} * {@link ComparisonChain} * {@link Compression} * {@link CompressionUtils} * {@link ConstraintCheckingTransaction} * {@link Descending} * {@link EncodingUtils} * {@link Entry} * {@link EnumSet} * {@link Function} * {@link Generated} * {@link HashMultimap} * {@link HashSet} * {@link Hashing} * {@link Hydrator} * {@link ImmutableGetRangesQuery} * {@link ImmutableList} * {@link ImmutableMap} * {@link ImmutableMultimap} * {@link ImmutableSet} * {@link InvalidProtocolBufferException} * {@link IterableView} * {@link Iterables} * {@link Iterator} * {@link Iterators} * {@link Joiner} * {@link List} * {@link Lists} * {@link Map} * {@link Maps} * {@link MoreObjects} * {@link Multimap} * {@link Multimaps} * {@link NamedColumnValue} * {@link Namespace} * {@link Objects} * {@link Optional} * {@link Persistable} * {@link Persistables} * {@link Prefix} * {@link PtBytes} * {@link RangeRequest} * {@link RowResult} * {@link Set} * {@link Sets} * {@link Sha256Hash} * {@link SortedMap} * {@link Stream} * {@link Supplier} * {@link TableReference} * {@link Throwables} * {@link TimeUnit} * {@link Transaction} * {@link TypedRowResult} * {@link UUID} * {@link UnsignedBytes} * {@link ValueType} */ static String __CLASS_HASH = "UpLQoZwCK/Ov1pclyB+iSA=="; }
12,762
1,392
<filename>src/main/java/io/fabric8/maven/docker/access/VolumeCreateConfig.java package io.fabric8.maven.docker.access; import com.google.gson.JsonObject; import java.util.Map; import io.fabric8.maven.docker.util.JsonFactory; public class VolumeCreateConfig { private final JsonObject createConfig = new JsonObject(); public VolumeCreateConfig(String name) { add("Name", name); } public VolumeCreateConfig driver(String driver) { return add("Driver", driver); } public VolumeCreateConfig opts(Map<String, String> opts) { if (opts != null && opts.size() > 0) { add("DriverOpts", JsonFactory.newJsonObject(opts)); } return this; } public VolumeCreateConfig labels(Map<String,String> labels) { if (labels != null && labels.size() > 0) { add("Labels", JsonFactory.newJsonObject(labels)); } return this; } public String getName() { return createConfig.get("Name").getAsString(); } /** * Get JSON which is used for <em>creating</em> a volume * * @return string representation for JSON representing creating a volume */ public String toJson() { return createConfig.toString(); } // ======================================================================= private VolumeCreateConfig add(String name, JsonObject value) { if (value != null) { createConfig.add(name, value); } return this; } private VolumeCreateConfig add(String name, String value) { if (value != null) { createConfig.addProperty(name, value); } return this; } }
656
325
//aro-args -E #define REC_EMPTY #define REC_DEFER(op) op REC_EMPTY #define REC_0_HOOK() REC_0 #define REC_1 REC_DEFER(REC_0_HOOK)() REC_1
68
334
<reponame>suomitekai/fairing import pytest import random from kubeflow import fairing import httplib2 from google.cloud import storage GCS_PROJECT_ID = fairing.cloud.gcp.guess_project_name() TEST_GCS_BUCKET = '{}-fairing'.format(GCS_PROJECT_ID) @pytest.fixture def temp_gcs_prefix(): rnd_prefix = "fairing_test_assets_{}".format(random.randint(0, 10**9)) yield rnd_prefix # delete all blobs with that prefix storage_client = storage.Client() bucket = storage_client.get_bucket(TEST_GCS_BUCKET) for blob in bucket.list_blobs(prefix=rnd_prefix): print("deleting {}".format(blob.name)) blob.delete() @pytest.fixture def httpmock(): http = httplib2.Http() class HTTPMock: def __init__(self, *args, **kwargs): pass def request(self, *args, **kwargs): if args and len(args) >= 4: headers = args[3] or {} else: headers = kwargs.get('headers') or {} print( "HTTPMock url:{} user-agent:{}".format(args[0], headers.get('user-agent'))) return http.request(*args, **kwargs) return HTTPMock
528
2,151
<gh_stars>1000+ /* * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.graphics; public class PorterDuff { // these value must match their native equivalents. See SkXfermode.h public enum Mode { /** [0, 0] */ CLEAR (0), /** [Sa, Sc] */ SRC (1), /** [Da, Dc] */ DST (2), /** [Sa + (1 - Sa)*Da, Rc = Sc + (1 - Sa)*Dc] */ SRC_OVER (3), /** [Sa + (1 - Sa)*Da, Rc = Dc + (1 - Da)*Sc] */ DST_OVER (4), /** [Sa * Da, Sc * Da] */ SRC_IN (5), /** [Sa * Da, Sa * Dc] */ DST_IN (6), /** [Sa * (1 - Da), Sc * (1 - Da)] */ SRC_OUT (7), /** [Da * (1 - Sa), Dc * (1 - Sa)] */ DST_OUT (8), /** [Da, Sc * Da + (1 - Sa) * Dc] */ SRC_ATOP (9), /** [Sa, Sa * Dc + Sc * (1 - Da)] */ DST_ATOP (10), /** [Sa + Da - 2 * Sa * Da, Sc * (1 - Da) + (1 - Sa) * Dc] */ XOR (11), /** [Sa + Da - Sa*Da, Sc*(1 - Da) + Dc*(1 - Sa) + min(Sc, Dc)] */ DARKEN (16), /** [Sa + Da - Sa*Da, Sc*(1 - Da) + Dc*(1 - Sa) + max(Sc, Dc)] */ LIGHTEN (17), /** [Sa * Da, Sc * Dc] */ MULTIPLY (13), /** [Sa + Da - Sa * Da, Sc + Dc - Sc * Dc] */ SCREEN (14), /** Saturate(S + D) */ ADD (12), OVERLAY (15); Mode(int nativeInt) { this.nativeInt = nativeInt; } /** * @hide */ public final int nativeInt; } /** * @hide */ public static final int modeToInt(Mode mode) { return mode.nativeInt; } /** * @hide */ public static final Mode intToMode(int val) { switch (val) { default: case 0: return Mode.CLEAR; case 1: return Mode.SRC; case 2: return Mode.DST; case 3: return Mode.SRC_OVER; case 4: return Mode.DST_OVER; case 5: return Mode.SRC_IN; case 6: return Mode.DST_IN; case 7: return Mode.SRC_OUT; case 8: return Mode.DST_OUT; case 9: return Mode.SRC_ATOP; case 10: return Mode.DST_ATOP; case 11: return Mode.XOR; case 16: return Mode.DARKEN; case 17: return Mode.LIGHTEN; case 13: return Mode.MULTIPLY; case 14: return Mode.SCREEN; case 12: return Mode.ADD; case 15: return Mode.OVERLAY; } } }
1,663
5,169
{ "name": "CLUberClient", "version": "0.0.1", "summary": "Wrapper around NSURLSession to access the Uber REST API", "description": "This is a very simple iOS Objective-C wrapper around NSURLSession\nfor use in accessing the Uber RESTful API:\n\nhttps://developer.uber.com/docs/api-overview\n\nSo far the only calls implemented are:\n\n 1. List Products\n 2. Get time estimates\n\nAlthough simple, it's a nice starting point for someone getting\nstarted with the Uber API. It has a few niceties like handling\nthe auth token, localization request based on the user's current\nlocale, and automatically switching to the proper Uber API endpoint\nin China when needed.", "homepage": "https://github.com/cromulentlabs/CLUberClient", "license": "Apache License, Version 2.0", "authors": "<NAME>", "platforms": { "ios": "7.0" }, "source": { "git": "https://github.com/cromulentlabs/CLUberClient.git", "tag": "0.0.1" }, "source_files": "CLUberClient", "frameworks": "Foundation", "requires_arc": true }
341
488
/* * Test Name: fstat03 * * Test Description: * Verify that, fstat(2) returns -1 and sets errno to EBADF if the file * pointed to by file descriptor is not valid. * * Expected Result: * fstat() should fail with return value -1 and set expected errno. * * Algorithm: * Setup: * Setup signal handling. * Create temporary directory. * Pause for SIGUSR1 if option specified. * * Test: * Loop if the proper options are given. * Execute system call * Check return code, if system call failed (return=-1) * if errno set == expected errno * Issue sys call fails with expected return value and errno. * Otherwise, * Issue sys call fails with unexpected errno. * Otherwise, * Issue sys call returns unexpected value. * * Cleanup: * Print errno log and/or timing stats if options given * Delete the temporary directory(s)/file(s) created. * * Usage: <for command-line> * fstat03 [-c n] [-e] [-i n] [-I x] [-P x] [-t] * where, -c n : Run n copies concurrently. * -e : Turn on errno logging. * -i n : Execute test n times. * -I x : Execute test for x seconds. * -P x : Pause for x seconds between iterations. * -t : Turn on syscall timing. * * HISTORY * 07/2001 Ported by <NAME> * * RESTRICTIONS: * This test should be executed by 'non-super-user' only. * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <string.h> #include <signal.h> #include <sys/types.h> #include <sys/stat.h> #include "test.h" #include "usctest.h" #define FILE_MODE S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH #define TEST_FILE "testfile" char *TCID = "fstat03"; /* Test program identifier. */ int TST_TOTAL = 1; /* Total number of test cases. */ extern int Tst_count; /* Test Case counter for tst_* routines */ int exp_enos[] = { EBADF, 0 }; int fildes; /* testfile descriptor */ void setup(); /* Main setup function for the tests */ void cleanup(); /* cleanup function for the test */ int main(int ac, char **av) { struct stat stat_buf; /* stat structure buffer */ int lc; /* loop counter */ char *msg; /* message returned from parse_opts */ /* Parse standard options given to run the test. */ msg = parse_opts(ac, av, (option_t *) NULL, NULL); if (msg != (char *)NULL) { tst_brkm(TBROK, NULL, "OPTION PARSING ERROR - %s", msg); tst_exit(); } /* * Invoke setup function to create a testfile under temporary * directory. */ setup(); /* set the expected errnos... */ TEST_EXP_ENOS(exp_enos); /* Check looping state if -i option given */ for (lc = 0; TEST_LOOPING(lc); lc++) { /* Reset Tst_count in case we are looping. */ Tst_count = 0; /* * Call fstat(2) to get the status information * of a closed testfile pointed to by 'fd'. * verify that fstat fails with -1 return value and * sets appropriate errno. */ TEST(fstat(fildes, &stat_buf)); /* Check return code from fstat(2) */ if (TEST_RETURN == -1) { TEST_ERROR_LOG(TEST_ERRNO); if (TEST_ERRNO == EBADF) { tst_resm(TPASS, "fstat() fails with expected error EBADF"); } else { tst_resm(TFAIL|TTERRNO, "fstat() did not fail with EBADF"); } } else { tst_resm(TFAIL, "fstat() returned %ld, expected -1", TEST_RETURN); } } /* End for TEST_LOOPING */ /* * Invoke cleanup() to delete the test directory/file(s) created * in the setup(). */ cleanup(); /*NOTREACHED*/ return 0; } /* End main */ /* * void * setup(void) - performs all ONE TIME setup for this test. * Exit the test program on receipt of unexpected signals. * Create a temporary directory and change directory to it. * Create a testfile under temporary directory. * Close the testfile. */ void setup() { /* Capture unexpected signals */ tst_sig(NOFORK, DEF_HANDLER, cleanup); /* Pause if that option was specified */ TEST_PAUSE; /* Make a temp dir and cd to it */ tst_tmpdir(); /* Create a testfile under temporary directory */ fildes = open(TEST_FILE, O_RDWR | O_CREAT, 0666); if (fildes == -1) tst_brkm(TBROK|TERRNO, cleanup, "open(%s, O_RDWR|O_CREAT, 0666) failed", TEST_FILE); if (close(fildes) == -1) tst_brkm(TBROK|TERRNO, cleanup, "close(%s) failed", TEST_FILE); } /* End of setup */ /* * void * cleanup() - Performs all ONE TIME cleanup for this test at * completion or premature exit. * Print test timing stats and errno log if test executed with options. * Close the testfile if still opened. * Remove temporary directory and sub-directories/files under it * created during setup(). * Exit the test program with normal exit code. */ void cleanup() { /* * print timing stats if that option was specified. * print errno log if that option was specified. */ TEST_CLEANUP; /* Remove files and temporary directory created */ tst_rmdir(); /* exit with return code appropriate for results */ tst_exit(); } /* End cleanup() */
1,840
466
package com.gykj.zhumulangma.home.activity; import android.view.View; import androidx.databinding.DataBindingUtil; import androidx.lifecycle.ViewModelProvider; import androidx.recyclerview.widget.LinearLayoutManager; import com.alibaba.android.arouter.facade.annotation.Autowired; import com.alibaba.android.arouter.facade.annotation.Route; import com.blankj.utilcode.util.ResourceUtils; import com.chad.library.adapter.base.BaseQuickAdapter; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.gykj.zhumulangma.common.Constants; import com.gykj.zhumulangma.common.bean.ProvinceBean; import com.gykj.zhumulangma.common.databinding.CommonLayoutRefreshListBinding; import com.gykj.zhumulangma.common.event.KeyCode; import com.gykj.zhumulangma.common.mvvm.view.BaseMvvmActivity; import com.gykj.zhumulangma.common.mvvm.view.status.ListSkeleton; import com.gykj.zhumulangma.home.R; import com.gykj.zhumulangma.home.adapter.RadioAdapter; import com.gykj.zhumulangma.home.databinding.HomeLayoutRankBarCenterBinding; import com.gykj.zhumulangma.home.dialog.RadioProvincePopup; import com.gykj.zhumulangma.home.mvvm.ViewModelFactory; import com.gykj.zhumulangma.home.mvvm.viewmodel.RadioListViewModel; import com.jakewharton.rxbinding3.view.RxView; import com.kingja.loadsir.callback.Callback; import com.lxj.xpopup.XPopup; import com.lxj.xpopup.enums.PopupPosition; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; /** * Author: Thomas. * <br/>Date: 2019/8/14 10:21 * <br/>Email: <EMAIL> * <br/>Description:电台列表 */ @Route(path = Constants.Router.Home.F_RADIO_LIST) public class RadioListActivity extends BaseMvvmActivity<CommonLayoutRefreshListBinding, RadioListViewModel> implements BaseQuickAdapter.OnItemClickListener, RadioProvincePopup.onSelectedListener, RadioProvincePopup.onPopupDismissingListener { //本省台 public static final int LOCAL_PROVINCE = 999; //国家台 public static final int COUNTRY = 998; //省市台 public static final int PROVINCE = 997; //网络台 public static final int INTERNET = 996; //排行榜 public static final int RANK = 995; //当地城市台 public static final int LOCAL_CITY = 993; @Autowired(name = KeyCode.Home.CATEGORY) public int mType; @Autowired(name = KeyCode.Home.TITLE) public String mTitle; private RadioAdapter mRadioAdapter; private int mProvinceCode; private HomeLayoutRankBarCenterBinding mBarCenterBind; private List<ProvinceBean> mProvinceBeans; private RadioProvincePopup mProvincePopup; public RadioListActivity() { } @Override public int onBindLayout() { return R.layout.common_layout_refresh_list; } @Override public void initView() { super.initView(); String s = ResourceUtils.readAssets2String("province.json"); mProvinceBeans = new Gson().fromJson(s, new TypeToken<ArrayList<ProvinceBean>>() { }.getType()); mBinding.recyclerview.setLayoutManager(new LinearLayoutManager(this)); mBinding.recyclerview.setHasFixedSize(true); mRadioAdapter = new RadioAdapter(R.layout.home_item_radio_line); mRadioAdapter.bindToRecyclerView(mBinding.recyclerview); mRadioAdapter.setOnItemClickListener(this); mBarCenterBind.tvTitle.setText(mTitle); if (mType == PROVINCE) { mBarCenterBind.ivDown.setVisibility(View.VISIBLE); mBarCenterBind.tvTitle.setText(mProvinceBeans.get(0).getProvince_name()); } mProvincePopup = new RadioProvincePopup(this, this); mProvincePopup.setDismissingListener(this); } @Override public void initListener() { super.initListener(); if (mType == PROVINCE) { RxView.clicks(mBarCenterBind.getRoot()) .doOnSubscribe(this) .throttleFirst(1, TimeUnit.SECONDS).subscribe(unit -> switchProvince()); } } @Override public void initData() { mProvinceCode = mProvinceBeans.get(0).getProvince_code(); mViewModel.setProvinceCode(mProvinceCode); mViewModel.setType(mType); mViewModel.init(); } @Override public void onItemClick(BaseQuickAdapter adapter, View view, int position) { if (adapter == mRadioAdapter) { // mViewModel.playRadio(mRadioAdapter.getItem(position)); } } @Override public ViewModelProvider.Factory onBindViewModelFactory() { return ViewModelFactory.getInstance(getApplication()); } @Override public Integer[] onBindBarRightIcon() { if (mType == LOCAL_PROVINCE || mType == COUNTRY || mType == PROVINCE || mType == INTERNET || mType == RANK || mType == LOCAL_CITY) { return null; } return new Integer[]{R.drawable.ic_common_search}; } @Override public View onBindBarCenterCustome() { mBarCenterBind = DataBindingUtil.inflate(getLayoutInflater(), R.layout.home_layout_rank_bar_center, null, false); return mBarCenterBind.getRoot(); } @Override public SimpleBarStyle onBindBarCenterStyle() { return SimpleBarStyle.CENTER_CUSTOME; } @Override public void initViewObservable() { // mViewModel.getInitRadiosEvent().observe(this, radios -> mRadioAdapter.setNewData(radios)); } private void switchProvince() { if (mProvincePopup.isShow()) { mProvincePopup.dismiss(); } else { mBarCenterBind.ivDown.animate().rotation(180).setDuration(200); new XPopup.Builder(this).atView(mSimpleTitleBar).popupPosition(PopupPosition.Bottom).asCustom(mProvincePopup).show(); } } @Override public void onSelected(int province_code, String province_name) { if (mProvinceCode != province_code) { mProvinceCode = province_code; mBarCenterBind.tvTitle.setText(province_name); mViewModel.setProvinceCode(mProvinceCode); mViewModel.init(); } } @Override public void onDismissing() { mBarCenterBind.ivDown.animate().rotation(0).setDuration(200); } @Override public Callback getInitStatus() { return new ListSkeleton(); } }
2,588
3,964
<gh_stars>1000+ from stream_framework.feeds.aggregated_feed.base import AggregatedFeed from stream_framework.storage.redis.activity_storage import RedisActivityStorage from stream_framework.storage.redis.timeline_storage import RedisTimelineStorage from stream_framework.serializers.aggregated_activity_serializer import AggregatedActivitySerializer from stream_framework.serializers.activity_serializer import ActivitySerializer class RedisAggregatedFeed(AggregatedFeed): timeline_serializer = AggregatedActivitySerializer activity_serializer = ActivitySerializer timeline_storage_class = RedisTimelineStorage activity_storage_class = RedisActivityStorage
181
373
<reponame>iplo/Chain // 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. package org.chromium.content_public.browser; /** * The WebContents Java wrapper to allow communicating with the native WebContents object. */ public interface WebContents { /** * @return The navigation controller associated with this WebContents. */ NavigationController getNavigationController(); }
134
625
/** * Copyright (c) 2001, <NAME> * All rights reserved. * <br> * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * <br> * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form * must reproduce the above copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the distribution. * - Neither the name of jregex nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior * written permission. * <br> * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @version 1.2_01 */ package regexodus; import com.jtransc.annotation.JTranscInvisible; @JTranscInvisible public interface REFlags { /** * All the following options turned off, EXCEPT UNICODE. Unicode handling can be turned off with "-u" at the end * of a flag string, or by simply specifying only the flags you want in a bitmask, like * {@code (REFlags.IGNORE_CASE | REFlags.MULTILINE | REFlags.DOTALL)}. * <br> * This behavior changed between the 0.1.1 and 0.1.2 release. */ int DEFAULT = 16; /** * Pattern "a" matches both "a" and "A". * Corresponds to "i" in Perl notation. */ int IGNORE_CASE = 1 << 0; /** * Affects the behaviour of "^" and "$" tags. When switched off: * <ul> * <li> the "^" matches the beginning of the whole text;</li> * <li> the "$" matches the end of the whole text, or just before the '\n' or "\r\n" at the end of text.</li> * </ul> * When switched on: * <ul> * <li> the "^" additionally matches the line beginnings (that is just after the '\n');</li> * <li> the "$" additionally matches the line ends (that is just before "\r\n" or '\n');</li> * </ul> * Corresponds to "m" in Perl notation. */ int MULTILINE = 1 << 1; /** * Affects the behaviour of dot(".") tag. When switched off: * <ul> * <li> the dot matches any character but EOLs('\r','\n');</li> * </ul> * When switched on: * <ul> * <li> the dot matches any character, including EOLs.</li> * </ul> * This flag is sometimes referenced in regex tutorials as SINGLELINE, which confusingly seems opposite to MULTILINE, but in fact is orthogonal. * Corresponds to "s" in Perl notation. */ int DOTALL = 1 << 2; /** * Affects how the space characters are interpreted in the expression. When switched off: * <ul> * <li> the spaces are interpreted literally;</li> * </ul> * When switched on: * <ul> * <li> the spaces are ignored, allowing an expression to be slightly more readable.</li> * </ul> * Corresponds to "x" in Perl notation. */ int IGNORE_SPACES = 1 << 3; /** * Affects whether the predefined classes("\d","\s","\w",etc) in the expression are interpreted as belonging to Unicode. When switched off: * <ul> * <li> the predefined classes are interpreted as ASCII;</li> * </ul> * When switched on: * <ul> * <li> the predefined classes are interpreted as Unicode categories;</li> * </ul> * Defaults to switched on, unlike the others. When specifying a flags with an int, however, UNICODE doesn't get * added automatically, so if you add a flag and want UNICODE on as well, you should specify it, too. * <br> * Corresponds to "u" in Perl notation. */ int UNICODE = 1 << 4; /** * Turns on the compatibility with XML Schema regular expressions. * <br> * Corresponds to "X" in Perl notation. */ int XML_SCHEMA = 1 << 5; }
1,575
1,056
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.docker.editor.completion; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.stream.Collectors; import javax.swing.ImageIcon; import javax.swing.text.Document; import javax.swing.text.JTextComponent; import org.netbeans.api.annotations.common.NonNull; import org.netbeans.api.annotations.common.NullAllowed; import org.netbeans.api.annotations.common.StaticResource; import org.netbeans.api.editor.document.LineDocumentUtils; import org.netbeans.api.lexer.Token; import org.netbeans.api.lexer.TokenHierarchy; import org.netbeans.api.lexer.TokenSequence; import org.netbeans.editor.BaseDocument; import org.netbeans.modules.csl.api.CodeCompletionContext; import org.netbeans.modules.csl.api.CodeCompletionHandler2; import org.netbeans.modules.csl.api.CodeCompletionResult; import org.netbeans.modules.csl.api.CompletionProposal; import org.netbeans.modules.csl.api.Documentation; import org.netbeans.modules.csl.api.ElementHandle; import org.netbeans.modules.csl.api.ElementKind; import org.netbeans.modules.csl.api.Modifier; import org.netbeans.modules.csl.api.OffsetRange; import org.netbeans.modules.csl.api.ParameterInfo; import org.netbeans.modules.csl.spi.DefaultCompletionProposal; import org.netbeans.modules.csl.spi.DefaultCompletionResult; import org.netbeans.modules.csl.spi.ParserResult; import org.netbeans.modules.docker.editor.DockerfileResolver; import org.netbeans.modules.docker.editor.lexer.DockerfileTokenId; import org.netbeans.modules.docker.editor.parser.Command; import org.netbeans.modules.docker.editor.util.DocDownloader; import org.openide.filesystems.FileObject; import org.openide.util.*; /** * * @author <NAME> */ public final class DockerfileCompletion implements CodeCompletionHandler2 { @Override public CodeCompletionResult complete(CodeCompletionContext context) { switch (context.getQueryType()) { case COMPLETION: case ALL_COMPLETION: case DOCUMENTATION: return completeImpl(context); default: return null; } } @Override public String document(ParserResult info, ElementHandle element) { return Optional.ofNullable(documentElement(info, element, ()->false)) .map((doc)->doc.getContent()) .orElse(null); } @Override public ElementHandle resolveLink(String link, ElementHandle originalHandle) { if (originalHandle.getKind() == ElementKind.KEYWORD) { return Optional.ofNullable(Command.forHandle(originalHandle)) .map((cmd) -> cmd.getDocumentation(null)) .map((doc) -> doc.getUrl()) .map((url) -> { try { return url.toURI(); } catch (URISyntaxException e) { return null; } }) .map((uri) -> { try { return uri.resolve(new URI(link)); } catch (URISyntaxException e) { return null; } }) .map((uri) -> new DocHandle(uri)) .orElse(null); } return null; } @Override public Documentation documentElement( @NonNull final ParserResult info, @NonNull final ElementHandle element, @NonNull final Callable<Boolean> cancel) { switch (element.getKind()) { case KEYWORD: return Optional.ofNullable(Command.forHandle(element)) .map((cmd) -> cmd.getDocumentation(cancel)) .orElse(null); case OTHER: try { final URL url = ((DocHandle)element).getURI().toURL(); final Future<String> becomesContent = DocDownloader.download(url, cancel); String content = null; while (cancel.call() != Boolean.TRUE) { try { content = becomesContent.get(250, TimeUnit.MILLISECONDS); break; } catch (TimeoutException timeout) { //retry } } return content == null ? null : DocDownloader.parseSection(content, url); } catch (Exception e) { return null; } default: return null; } } @Override public String getPrefix(ParserResult info, int caretOffset, boolean upToOffset) { return null; } @Override public QueryType getAutoQuery(JTextComponent component, String typedText) { return QueryType.COMPLETION; } @Override public String resolveTemplateVariable(String variable, ParserResult info, int caretOffset, String name, Map parameters) { return null; } @Override public Set<String> getApplicableTemplates(Document doc, int selectionBegin, int selectionEnd) { return null; } @Override public ParameterInfo parameters(ParserResult info, int caretOffset, CompletionProposal proposal) { return ParameterInfo.NONE; } private CodeCompletionResult completeImpl(@NonNull final CodeCompletionContext ctx) { final BaseDocument doc = (BaseDocument) ctx.getParserResult().getSnapshot().getSource().getDocument(false); if (doc == null) { return CodeCompletionResult.NONE; } doc.readLock(); try { final int offset = ctx.getCaretOffset(); String prefix = ctx.getPrefix(); final int lineStart = LineDocumentUtils.getLineStart(doc, offset); int anchor = offset - (prefix == null ? 0 : prefix.length()); if (anchor == lineStart) { //commands code completion return commands(prefix, anchor, false); } final TokenSequence<DockerfileTokenId> seq = TokenHierarchy.get(doc).tokenSequence(DockerfileTokenId.language()); if (seq == null) { return CodeCompletionResult.NONE; } seq.move(Math.max(0,offset-1)); if (!seq.moveNext() && !seq.movePrevious()) { return CodeCompletionResult.NONE; } final Token<DockerfileTokenId> current = seq.token(); if (current != null && current.id() != DockerfileTokenId.WHITESPACE) { anchor = seq.offset(); prefix = current.text().toString().substring(0,offset-anchor); seq.movePrevious(); } else { anchor = offset; prefix = ""; //NOI18N } Token<DockerfileTokenId> prev; while ((prev = seq.token()) != null && prev.id() == DockerfileTokenId.WHITESPACE) { if (!seq.movePrevious()) { break; } } if (prev != null && prev.id() == DockerfileTokenId.ONBUILD && LineDocumentUtils.getLineStart(doc,seq.offset()) == LineDocumentUtils.getLineStart(doc,anchor)) { //Commands after onbuild return commands(prefix, anchor, true); } return CodeCompletionResult.NONE; } finally { doc.readUnlock(); } } @NonNull private static CodeCompletionResult commands( final String prefix, final int anchor, final boolean afterOnBuild) { final List<CompletionProposal> commands = Command.getCommandNames(prefix).stream() .map((name) -> Command.forName(name)) .filter((cmd) -> cmd != null && (!afterOnBuild || cmd.isOnBuildSupported())) .map((cmd) -> new CmdCompletionProposal(cmd, isUpcase(prefix), anchor)) .collect(Collectors.toList()); if (commands.isEmpty()) { return CodeCompletionResult.NONE; } final DefaultCompletionResult res = new DefaultCompletionResult(commands, false); res.setFilterable(false); return res; } private static boolean isUpcase(@NullAllowed CharSequence text) { if (text != null) { for (int i = 0; i < text.length(); i++) { if (Character.isLowerCase(text.charAt(i))) { return false; } } } return true; } private static final class CmdCompletionProposal extends DefaultCompletionProposal { @StaticResource private static final String DOCKER_ICON = "org/netbeans/modules/docker/editor/resources/docker.png"; //NOI18N private final Command cmd; private final boolean upperCase; CmdCompletionProposal( @NonNull final Command cmd, final boolean upcase, final int anchor) { this.cmd = cmd; this.upperCase = upcase; setKind(ElementKind.KEYWORD); setAnchorOffset(anchor); } @Override public ElementHandle getElement() { return cmd.toElementHandle(); } @Override public String getName() { return cmd.getName(); } @Override public ImageIcon getIcon() { return ImageUtilities.loadImageIcon(DOCKER_ICON, true); } @Override public String getInsertPrefix() { return String.format("%s ", //NOI18N upperCase ? getName() : getName().toLowerCase()); } } private static final class DocHandle implements ElementHandle { private final URI uri; DocHandle(@NonNull final URI uri) { Parameters.notNull("uri", uri); this.uri = uri; } @Override public FileObject getFileObject() { return null; } @Override public String getMimeType() { return DockerfileResolver.MIME_TYPE; } @Override public String getName() { return uri.toString(); } @Override public String getIn() { return null; } @Override public ElementKind getKind() { return ElementKind.OTHER; } @Override public Set<Modifier> getModifiers() { return Collections.emptySet(); } @Override public boolean signatureEquals(ElementHandle handle) { return getKind().equals(handle.getKind()) && getName().equals(handle.getName()); } @Override public OffsetRange getOffsetRange(ParserResult result) { return OffsetRange.NONE; } @NonNull URI getURI() { return uri; } } }
5,639
782
/* * Copyright (c) 2021, <NAME>. All Rights Reserved. * * This file is part of BoofCV (http://boofcv.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package boofcv.alg.video; import boofcv.abst.feature.associate.AssociateDescription2D; import boofcv.abst.feature.describe.DescribePointRadiusAngle; import boofcv.abst.tracker.PointTrack; import boofcv.abst.tracker.PointTracker; import boofcv.alg.geo.PerspectiveOps; import boofcv.alg.structure.EpipolarScore3D; import boofcv.factory.structure.ConfigSelectFrames3D; import boofcv.misc.BoofMiscOps; import boofcv.struct.calib.CameraPinholeBrown; import boofcv.struct.feature.AssociatedIndex; import boofcv.struct.feature.TupleDesc_F64; import boofcv.struct.geo.AssociatedPair; import boofcv.struct.image.ImageBase; import georegression.struct.point.Point2D_F64; import gnu.trove.impl.Constants; import gnu.trove.map.TLongIntMap; import gnu.trove.map.hash.TLongIntHashMap; import lombok.Getter; import lombok.Setter; import org.ddogleg.sorting.QuickSelect; import org.ddogleg.struct.*; import org.ejml.data.DMatrixRMaj; import org.jetbrains.annotations.Nullable; import java.io.PrintStream; import java.util.ArrayList; import java.util.List; import java.util.Set; import static java.util.Objects.requireNonNull; /** * Processes all the frames in a video sequence and decides which frames to keep for 3D reconstruction. The idea * here is that file size can be reduced significantly if redundant information is removed. * * Internally it works by having a key frame that the current frame is compared against. First it checks to see * if the image tracker shows any significant motion with its features. If not then this image is considered redundant. * Next it computes a homography without doing any robustness filtering, if that describes the relationship well * then there's no chance if it being 3d. Then if those tests are inconclusive it will robustly fit a homography * and fundamental matrix and compare their fit scores to decide if there's significant 3D structure. * * Instructions: * <ol> * <li>Provide: tracker, descriptor, associate, score3D</li> * <li>Invoke {@link #initialize(int, int)}</li> * <li>Pass each frame into {@link #next(ImageBase)}</li> * <li>Get results from {@link #getSelectedFrames()}</li> * </ol> * * @author <NAME> */ public class SelectFramesForReconstruction3D<T extends ImageBase<T>> implements VerbosePrint { // TODO Jump over frames which are destroyed by image glare // TODO Score frames based on an estimate of blur. Try to select in focus frames // TODO If way too many tracks have been dropped go back and select a new key frame that's in the past // TODO Plan a path that minimizes pointless jitter. Maybe a new algorithm completely. Local window? /** * Returns the configuration with tuning parameters used. Note that settings for inner classes, e.g. * association and model matchers, are ignored. While not elegant, this config design avoids duplicate * code and comments. */ public @Getter final ConfigSelectFrames3D config = new ConfigSelectFrames3D(); /** Output: Frames which have been selected to be saved. */ private @Getter final DogArray_I32 selectedFrames = new DogArray_I32(); /** Tracks features frame to frame */ @Getter @Setter @Nullable PointTracker<T> tracker; /** Descriptors of tracks */ final @Getter DescribePointRadiusAngle<T, TupleDesc_F64> descriptor; /** Associates tracks to each other using their descriptors */ @Getter @Setter @Nullable AssociateDescription2D<TupleDesc_F64> associate; @Getter @Setter @Nullable EpipolarScore3D scorer; /** Indexes of pairs which are considered to be inliers for the dominant model */ public @Getter final DogArray_I32 inlierIdx = new DogArray_I32(); //----------------------------- Access to intermediate results /** Estimated number of pixels that the image moved. If not computed it will be NaN */ private @Getter double frameMotion; /** If it considered that new image could be 3D relative to the keyframe */ private @Getter boolean considered3D; /** True if there are too few pairs with the key frame to reliably estimate scene structure */ private @Getter boolean sufficientFeaturePairs; /** Why it requested a frame be saved */ private @Getter Cause cause = Cause.UNKNOWN; //----------------------------- Internally used fields // Guessed intrinsic parameters CameraPinholeBrown cameraA = new CameraPinholeBrown(); CameraPinholeBrown cameraB = new CameraPinholeBrown(); DMatrixRMaj fundamental = new DMatrixRMaj(3, 3); // Number of frames currently processed int frameNumber; // Frame number of the key frame int keyFrameNumber; // If true the next frame processed will be a key frame boolean forceKeyFrame; // Expected shape of input images int width, height; // Storage for active tracks from the tracker @Getter final List<PointTrack> activeTracks = new ArrayList<>(); // Pairs of features between the current frame and key frame @Getter final DogArray<AssociatedPair> pairs = new DogArray<>(AssociatedPair::new); // Storage for key frame final Frame keyFrame; // Storage for the current frame being processed final Frame currentFrame; // Storage for distances between tracks in each frame final DogArray_F64 distances = new DogArray_F64(); @Nullable PrintStream verbose = null; public SelectFramesForReconstruction3D( DescribePointRadiusAngle<T, TupleDesc_F64> descriptor ) { this.descriptor = descriptor; this.keyFrame = new Frame(); this.currentFrame = new Frame(); } /** * Must be called first and initializes data structures * * @param width Image width * @param height Image height */ public void initialize( int width, int height ) { // Make sure everything has been properly configured BoofMiscOps.checkTrue(tracker != null, "You must assign tracker a value"); BoofMiscOps.checkTrue(associate != null, "You must assign associate a value"); BoofMiscOps.checkTrue(scorer != null, "You must assign scorer a value"); this.width = width; this.height = height; tracker.reset(); associate.initialize(width, height); forceKeyFrame = true; frameNumber = 0; selectedFrames.reset(); PerspectiveOps.createIntrinsic(width, height, 90, cameraA); PerspectiveOps.createIntrinsic(width, height, 90, cameraB); } /** * Process the next frame in the sequence * * @param image Image. All images are assumed to have the same shape * @return true if it decided to add a new keyframe. Might not be the current frame. */ public boolean next( T image ) { BoofMiscOps.checkEq(image.width, width, "Width does not match."); BoofMiscOps.checkEq(image.height, height, "Height does not match."); frameMotion = Double.NaN; considered3D = false; sufficientFeaturePairs = false; cause = Cause.UNKNOWN; performTracking(image); copyTrackResultsIntoCurrentFrame(image); boolean saveImage = false; escape: if (forceKeyFrame) { cause = Cause.FORCED; forceKeyFrame = false; saveImage = true; } else { createPairsWithKeyFrameTracking(keyFrame, currentFrame); if (pairs.size < config.minimumPairs) { cause = Cause.TRACKING_FAILURE; // Almost all tracks got dropped. Could have been caused by something like a temporary obstruction // or motion blur. Save the image and start tracking again saveImage = true; if (verbose != null) verbose.printf("Too few pairs. pairs.size=%d, key.size=%d current.size=%d\n", pairs.size, keyFrame.size(), currentFrame.size()); break escape; } // Note that there were enough feature pairs sufficientFeaturePairs = true; // Compute how much the frame moved frameMotion = computeFrameRelativeMotion(); double minMotionThresh = config.minTranslation.computeI(Math.max(width, height)); double maxMotionThresh = config.maxTranslation.computeI(Math.max(width, height)); if (verbose != null) verbose.printf("_ Motion: distance=%.1f min=%.1f max=%.1f\n", frameMotion, minMotionThresh, maxMotionThresh); if (frameMotion >= minMotionThresh) { if (frameMotion > maxMotionThresh) { cause = Cause.EXCESSIVE_MOTION; saveImage = true; } else if (!isSceneStatic()) { saveImage = isScene3D(); considered3D = saveImage; if (saveImage) { cause = Cause.TRANSLATION_3D; } else { saveImage = checkSkippedBadFrame(); } } } } if (verbose != null) verbose.println("saveImage=" + saveImage + " cause=" + cause); // Save the frame and make it the new keyframe if (saveImage) { keyFrameNumber = frameNumber; selectedFrames.add(frameNumber); keyFrame.setTo(currentFrame); requireNonNull(associate).setSource(keyFrame.locations, keyFrame.descriptions); if (verbose != null) verbose.printf("key_frame: total=%d / %d\n", selectedFrames.size, frameNumber); } frameNumber++; return saveImage; } /** * Retrieves the locations of tracks in the current frame which were visible in the key frame * * @param tracks (Output) Storage for track locations */ public void lookupKeyFrameTracksInCurrentFrame( DogArray<Point2D_F64> tracks ) { tracks.reset(); tracks.resize(pairs.size); for (int i = 0; i < pairs.size; i++) { tracks.get(i).setTo(pairs.get(i).p1); } } protected void performTracking( T frame ) { requireNonNull(tracker, "Need to specify tracker. Did you call initialize too?"); tracker.process(frame); tracker.spawnTracks(); tracker.getAllTracks(activeTracks); } /** * Copies results from image-to-image tracker into the 'currentFrame' */ protected void copyTrackResultsIntoCurrentFrame( T image ) { descriptor.setImage(image); // Compute the descriptor region size based in the input image size int featureRadius = config.featureRadius.computeI(Math.max(width, height)); // Extract feature and track information from the current frame currentFrame.reserve(activeTracks.size()); for (int i = 0; i < activeTracks.size(); i++) { PointTrack t = activeTracks.get(i); currentFrame.trackID_to_index.put(t.featureId, i); currentFrame.locations.grow().setTo(t.pixel); descriptor.process(t.pixel.x, t.pixel.y, 0.0, featureRadius, currentFrame.descriptions.grow()); } if (verbose != null) verbose.printf("current_frame: tracks=%4d frame=%d\n", activeTracks.size(), frameNumber); } /** * Create a set of image pairs between the key frame and the current frame. */ protected void createPairsWithKeyFrameTracking( Frame keyFrame, Frame current ) { pairs.reset(); pairs.reserve(keyFrame.size()); keyFrame.trackID_to_index.forEachEntry(( trackID, prevIdx ) -> { int currIdx = current.trackID_to_index.get(trackID); if (currIdx < 0) return true; AssociatedPair p = pairs.grow(); p.p1.setTo(current.locations.get(currIdx)); p.p2.setTo(keyFrame.locations.get(prevIdx)); return true; }); } /** * Checks to see if the scene is nearly identical by the number of features which have barely moved * * @return true if it's nearly static */ protected boolean isSceneStatic() { // count the number of features which have moved double tol = config.motionInlierPx*config.motionInlierPx; int moved = 0; for (int pairIdx = 0; pairIdx < pairs.size; pairIdx++) { AssociatedPair p = pairs.get(pairIdx); if (p.p1.distance2(p.p2) > tol) { moved++; } } // Compute the ratio of moved vs stationary double ratio = moved/(double)pairs.size; if (verbose != null) verbose.printf("_ Static: moved=%4d total=%d ratio=%f\n", moved, pairs.size, ratio); return ratio < config.thresholdQuick; } /** * Checks to see if the scene is 3D by comparing the inliers from fundamental matrix vs homography. * * @return true if 3D */ boolean isScene3D() { requireNonNull(scorer); scorer.process(cameraA, cameraB, keyFrame.size(), currentFrame.size(), pairs.toList(), fundamental, inlierIdx); return scorer.is3D(); } /** * If tracks are dropped and association does much better that can indicate there was some even (like glare) * which caused the tracks to drop but is now gone. In that case save this frame and skip over the bad stuff */ protected boolean checkSkippedBadFrame() { if (config.skipEvidenceRatio < 1.0) return false; requireNonNull(associate); // the source was set as the keyframe when it became the keyframe. Sometimes this saves computations. associate.setDestination(currentFrame.locations, currentFrame.descriptions); associate.associate(); FastAccess<AssociatedIndex> matches = associate.getMatches(); boolean skip = matches.size > pairs.size*config.skipEvidenceRatio; if (verbose != null) verbose.printf("_ Skip: associated=%d tracking=%d skip=%s\n", matches.size, pairs.size, skip); return skip; } /** * Has there been so much motion that we should save the image anyways? If too many frames are skipped * the reconstruction can be bad or incomplete */ protected double computeFrameRelativeMotion() { distances.reset(); distances.resize(pairs.size); for (int pairIdx = 0; pairIdx < pairs.size; pairIdx++) { distances.set(pairIdx, pairs.get(pairIdx).distance2()); } double distance2 = QuickSelect.select(distances.data, (int)(distances.size*0.9), distances.size); return Math.sqrt(distance2); } @Override public void setVerbose( @Nullable PrintStream out, @Nullable Set<String> configuration ) { this.verbose = BoofMiscOps.addPrefix(this, out); BoofMiscOps.verboseChildren(verbose, configuration, scorer); } /** Storage for feature and track information for a single image frame */ public class Frame { // Descriptions of features public final DogArray<TupleDesc_F64> descriptions = new DogArray<>(descriptor::createDescription); // Locations of features public final DogArray<Point2D_F64> locations = new DogArray<>(Point2D_F64::new); // Conversion from track ID to feature index public final TLongIntMap trackID_to_index = new TLongIntHashMap(Constants.DEFAULT_CAPACITY, Constants.DEFAULT_LOAD_FACTOR, -1, -1); public int size() { return descriptions.size; } public void reserve( int size ) { reset(); descriptions.reserve(size); locations.reserve(size); } public void reset() { descriptions.reset(); locations.reset(); trackID_to_index.clear(); } public void setTo( Frame frame ) { reserve(frame.size()); for (int i = 0; i < frame.size(); i++) { descriptions.grow().setTo(frame.descriptions.get(i)); locations.grow().setTo(frame.locations.get(i)); } frame.trackID_to_index.forEachEntry(( key, value ) -> { trackID_to_index.put(key, value); return true; }); } } /** * What caused to to request a frame be saved */ public enum Cause { FORCED, TRACKING_FAILURE, EXCESSIVE_MOTION, TRANSLATION_3D, UNKNOWN } }
5,005
2,903
<reponame>seamhhp/redis-manager<gh_stars>1000+ package com.newegg.ec.redis.util; import com.alibaba.fastjson.JSONObject; import java.util.Collections; import java.util.List; /** * @author kz37 * @date 2018/10/20 */ public class ListSortUtil { /** * List<List<String>> * @param sort 排序的List * @param index 根据内部List的下标值进行排序 */ public static void sortListListStringAsc(List<List<String>> sort, int index) { Collections.sort(sort, (l1, l2) -> { return compareDouble(l1.get(index),l2.get(index)); }); } public static void sortListListStringDesc(List<List<String>> sort, int index) { Collections.sort(sort, (l1, l2) -> { return -compareDouble(l1.get(index),l2.get(index)); }); } public static int compareDouble(Double d1, Double d2) { if(Double.compare(d1, d2) > 0) { return 1; } else if(Double.compare(d1, d2) < 0) { return -1; } else { return 0; } } public static int compareDouble(String s1, String s2) throws NumberFormatException{ Double d1 = Double.parseDouble(s1); Double d2 = Double.parseDouble(s2); return compareDouble(d1, d2); } public static void sortByKeyValueDesc(List<JSONObject> jsonObjectList, String key) { Collections.sort(jsonObjectList, (l1, l2) -> { return -compareDouble(l1.getString(key),l2.getString(key)); }); } }
715
9,516
/*! * Copyright (c) 2019 by Contributors * \file msg_queue.cc * \brief Message queue for DGL distributed training. */ #include <dmlc/logging.h> #include <cstring> #include "msg_queue.h" namespace dgl { namespace network { using std::string; MessageQueue::MessageQueue(int64_t queue_size, int num_producers) { CHECK_GE(queue_size, 0); CHECK_GE(num_producers, 0); queue_size_ = queue_size; free_size_ = queue_size; num_producers_ = num_producers; } STATUS MessageQueue::Add(Message msg, bool is_blocking) { // check if message is too long to fit into the queue if (msg.size > queue_size_) { LOG(WARNING) << "Message is larger than the queue."; return MSG_GT_SIZE; } if (msg.size <= 0) { LOG(WARNING) << "Message size (" << msg.size << ") is negative or zero."; return MSG_LE_ZERO; } std::unique_lock<std::mutex> lock(mutex_); if (finished_producers_.size() >= num_producers_) { return QUEUE_CLOSE; } if (msg.size > free_size_ && !is_blocking) { return QUEUE_FULL; } cond_not_full_.wait(lock, [&]() { return msg.size <= free_size_; }); // Add data pointer to queue queue_.push(msg); free_size_ -= msg.size; // not empty signal cond_not_empty_.notify_one(); return ADD_SUCCESS; } STATUS MessageQueue::Remove(Message* msg, bool is_blocking) { std::unique_lock<std::mutex> lock(mutex_); if (queue_.empty()) { if (!is_blocking) { return QUEUE_EMPTY; } if (finished_producers_.size() >= num_producers_) { return QUEUE_CLOSE; } } cond_not_empty_.wait(lock, [this] { return !queue_.empty() || exit_flag_.load(); }); if (finished_producers_.size() >= num_producers_ && queue_.empty()) { return QUEUE_CLOSE; } Message old_msg = queue_.front(); queue_.pop(); msg->data = old_msg.data; msg->size = old_msg.size; msg->receiver_id = old_msg.receiver_id; msg->deallocator = old_msg.deallocator; free_size_ += old_msg.size; cond_not_full_.notify_one(); return REMOVE_SUCCESS; } void MessageQueue::SignalFinished(int producer_id) { std::lock_guard<std::mutex> lock(mutex_); finished_producers_.insert(producer_id); // if all producers have finished, consumers should be // waken up to get this signal if (finished_producers_.size() >= num_producers_) { exit_flag_.store(true); cond_not_empty_.notify_all(); } } bool MessageQueue::Empty() const { std::lock_guard<std::mutex> lock(mutex_); return queue_.size() == 0; } bool MessageQueue::EmptyAndNoMoreAdd() const { std::lock_guard<std::mutex> lock(mutex_); return queue_.size() == 0 && finished_producers_.size() >= num_producers_; } } // namespace network } // namespace dgl
1,033
1,664
<reponame>likenamehaojie/Apache-Ambari-ZH /* * 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.ambari.server.orm.dao; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import org.apache.ambari.server.orm.RequiresSession; import org.apache.ambari.server.orm.entities.KerberosKeytabEntity; import org.apache.ambari.server.orm.entities.KerberosKeytabPrincipalEntity; import org.apache.commons.collections.CollectionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.Singleton; import com.google.inject.persist.Transactional; @Singleton public class KerberosKeytabDAO { private final static Logger LOG = LoggerFactory.getLogger(KerberosKeytabDAO.class); @Inject Provider<EntityManager> entityManagerProvider; @Inject KerberosKeytabPrincipalDAO kerberosKeytabPrincipalDAO; @Transactional public void create(KerberosKeytabEntity kerberosKeytabEntity) { entityManagerProvider.get().persist(kerberosKeytabEntity); } public void create(String keytabPath) { create(new KerberosKeytabEntity(keytabPath)); } @Transactional public KerberosKeytabEntity merge(KerberosKeytabEntity kerberosKeytabEntity) { return entityManagerProvider.get().merge(kerberosKeytabEntity); } @Transactional public void remove(KerberosKeytabEntity kerberosKeytabEntity) { if (kerberosKeytabEntity != null) { EntityManager entityManager = entityManagerProvider.get(); entityManager.remove(entityManager.merge(kerberosKeytabEntity)); } } public void remove(String keytabPath) { KerberosKeytabEntity kke = find(keytabPath); if (kke != null) { remove(kke); } } @Transactional public void refresh(KerberosKeytabEntity kerberosKeytabEntity) { entityManagerProvider.get().refresh(kerberosKeytabEntity); } @RequiresSession public KerberosKeytabEntity find(String keytabPath) { return entityManagerProvider.get().find(KerberosKeytabEntity.class, keytabPath); } @RequiresSession public List<KerberosKeytabEntity> findByPrincipalAndHost(String principalName, Long hostId) { if(hostId == null) { return findByPrincipalAndNullHost(principalName); } TypedQuery<KerberosKeytabEntity> query = entityManagerProvider.get(). createNamedQuery("KerberosKeytabEntity.findByPrincipalAndHost", KerberosKeytabEntity.class); query.setParameter("hostId", hostId); query.setParameter("principalName", principalName); List<KerberosKeytabEntity> result = query.getResultList(); if(result == null) { return Collections.emptyList(); } return result; } @RequiresSession public List<KerberosKeytabEntity> findByPrincipalAndNullHost(String principalName) { TypedQuery<KerberosKeytabEntity> query = entityManagerProvider.get(). createNamedQuery("KerberosKeytabEntity.findByPrincipalAndNullHost", KerberosKeytabEntity.class); query.setParameter("principalName", principalName); List<KerberosKeytabEntity> result = query.getResultList(); if(result == null) { return Collections.emptyList(); } return result; } @RequiresSession public List<KerberosKeytabEntity> findAll() { TypedQuery<KerberosKeytabEntity> query = entityManagerProvider.get(). createNamedQuery("KerberosKeytabEntity.findAll", KerberosKeytabEntity.class); List<KerberosKeytabEntity> result = query.getResultList(); if(result == null) { return Collections.emptyList(); } return result; } @RequiresSession public boolean exists(String keytabPath) { return find(keytabPath) != null; } @RequiresSession public boolean exists(KerberosKeytabEntity kerberosKeytabEntity) { return find(kerberosKeytabEntity.getKeytabPath()) != null; } public void remove(List<KerberosKeytabEntity> entities) { if (entities != null) { for (KerberosKeytabEntity entity : entities) { remove(entity); } } } /** * Determines if there are any references to the {@link KerberosKeytabEntity} before attemping * to remove it. If there are any references to it, the entity will be not be removed. * * @param kerberosKeytabEntity the entity * @return <code>true</code>, if the entity was remove; <code>false</code> otherwise */ public boolean removeIfNotReferenced(KerberosKeytabEntity kerberosKeytabEntity) { if (kerberosKeytabEntity != null) { if (CollectionUtils.isNotEmpty(kerberosKeytabEntity.getKerberosKeytabPrincipalEntities())) { ArrayList<String> ids = new ArrayList<>(); for (KerberosKeytabPrincipalEntity entity : kerberosKeytabEntity.getKerberosKeytabPrincipalEntities()) { Long id = entity.getKkpId(); if (id != null) { ids.add(String.valueOf(id)); } } LOG.debug(String.format("keytab entry for %s is still referenced by [%s]", kerberosKeytabEntity.getKeytabPath(), String.join(",", ids))); } else { LOG.debug(String.format("keytab entry for %s is no longer referenced. It will be removed.", kerberosKeytabEntity.getKeytabPath())); remove(kerberosKeytabEntity); return true; } } return false; } }
2,104
4,772
<reponame>fjacobs/spring-data-examples package example.repo; import example.model.Customer273; import java.util.List; import org.springframework.data.repository.CrudRepository; public interface Customer273Repository extends CrudRepository<Customer273, Long> { List<Customer273> findByLastName(String lastName); }
99
488
<reponame>maurizioabba/rose<gh_stars>100-1000 // 7.3.4c.cc asm("collectLookupResults i=9 i=9 j=14"); namespace A { int i; // line 6 } namespace B { int i; // line 9 int j; // line 10 namespace C { namespace D { using namespace A; int j; // line 14 int k; // line 15 int a = i; // B::i hides A::i } using namespace D; int k = 89; // no problem yet line 19 //ERROR(1): int l = k; // ambiguous: C::k or D::k line 20 int m = i; // B::i hides A::i line 21 int n = j; // D::j hides B::j line 22 } }
476
880
/** * Copyright 2019 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ch.qos.logback.classic; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertNotNull; import static junit.framework.Assert.assertNull; import static junit.framework.Assert.assertTrue; import static junit.framework.Assert.fail; import org.junit.Before; import org.junit.Test; import java.util.Map; import ch.qos.logback.classic.turbo.NOPTurboFilter; import ch.qos.logback.core.CoreConstants; import ch.qos.logback.core.rolling.helper.FileNamePattern; import ch.qos.logback.core.status.StatusManager; public class LoggerContextTest { LoggerContext lc; @Before public void setUp() throws Exception { lc = new LoggerContext(); lc.setName("x"); } @Test public void testRootGetLogger() { Logger root = lc.getLogger(Logger.ROOT_LOGGER_NAME); assertEquals(Level.DEBUG, root.getLevel()); assertEquals(Level.DEBUG, root.getEffectiveLevel()); } @Test public void testLoggerX() { Logger x = lc.getLogger("x"); assertNotNull(x); assertEquals("x", x.getName()); assertNull(x.getLevel()); assertEquals(Level.DEBUG, x.getEffectiveLevel()); } @Test public void testNull() { try { lc.getLogger((String) null); fail("null should cause an exception"); } catch (IllegalArgumentException e) { } } @Test public void testEmpty() { Logger empty = lc.getLogger(""); LoggerTestHelper.assertNameEquals(empty, ""); LoggerTestHelper.assertLevels(null, empty, Level.DEBUG); Logger dot = lc.getLogger("."); LoggerTestHelper.assertNameEquals(dot, "."); // LoggerTestHelper.assertNameEquals(dot.parent, ""); // LoggerTestHelper.assertNameEquals(dot.parent.parent, "root"); // assertNull(dot.parent.parent.parent); LoggerTestHelper.assertLevels(null, dot, Level.DEBUG); assertEquals(3, lc.getLoggerList().size()); } @Test public void testDotDot() { Logger dotdot = lc.getLogger(".."); assertEquals(4, lc.getLoggerList().size()); LoggerTestHelper.assertNameEquals(dotdot, ".."); // LoggerTestHelper.assertNameEquals(dotdot.parent, "."); // LoggerTestHelper.assertNameEquals(dotdot.parent.parent, ""); // LoggerTestHelper.assertNameEquals(dotdot.parent.parent.parent, "root"); } int instanceCount() { return lc.getLoggerList().size(); } @Test public void testLoggerXY() { assertEquals(1, lc.getLoggerList().size()); Logger xy = lc.getLogger("x.y"); assertEquals(3, instanceCount()); LoggerTestHelper.assertNameEquals(xy, "x.y"); LoggerTestHelper.assertLevels(null, xy, Level.DEBUG); Logger x = lc.getLogger("x"); assertEquals(3, instanceCount()); Logger xy2 = lc.getLogger("x.y"); assertEquals(xy, xy2); Logger x2 = lc.getLogger("x"); assertEquals(x, x2); assertEquals(3, instanceCount()); } @Test public void testLoggerMultipleChildren() { assertEquals(1, instanceCount()); Logger xy0 = lc.getLogger("x.y0"); LoggerTestHelper.assertNameEquals(xy0, "x.y0"); Logger xy1 = lc.getLogger("x.y1"); LoggerTestHelper.assertNameEquals(xy1, "x.y1"); LoggerTestHelper.assertLevels(null, xy0, Level.DEBUG); LoggerTestHelper.assertLevels(null, xy1, Level.DEBUG); assertEquals(4, instanceCount()); for (int i = 0; i < 100; i++) { Logger xy_i = lc.getLogger("x.y" + i); LoggerTestHelper.assertNameEquals(xy_i, "x.y" + i); LoggerTestHelper.assertLevels(null, xy_i, Level.DEBUG); } assertEquals(102, instanceCount()); } @Test public void testMultiLevel() { Logger wxyz = lc.getLogger("w.x.y.z"); LoggerTestHelper.assertNameEquals(wxyz, "w.x.y.z"); LoggerTestHelper.assertLevels(null, wxyz, Level.DEBUG); Logger wx = lc.getLogger("w.x"); wx.setLevel(Level.INFO); LoggerTestHelper.assertNameEquals(wx, "w.x"); LoggerTestHelper.assertLevels(Level.INFO, wx, Level.INFO); LoggerTestHelper.assertLevels(null, lc.getLogger("w.x.y"), Level.INFO); LoggerTestHelper.assertLevels(null, wxyz, Level.INFO); } @Test public void testStatusWithUnconfiguredContext() { Logger logger = lc.getLogger(LoggerContextTest.class); for (int i = 0; i < 3; i++) { logger.debug("test"); } logger = lc.getLogger("x.y.z"); for (int i = 0; i < 3; i++) { logger.debug("test"); } StatusManager sm = lc.getStatusManager(); assertTrue("StatusManager has recieved too many messages", sm.getCount() == 1); } @Test public void resetTest() { Logger root = lc.getLogger(Logger.ROOT_LOGGER_NAME); Logger a = lc.getLogger("a"); Logger ab = lc.getLogger("a.b"); ab.setLevel(Level.WARN); root.setLevel(Level.INFO); lc.reset(); assertEquals(Level.DEBUG, root.getEffectiveLevel()); assertTrue(root.isDebugEnabled()); assertEquals(Level.DEBUG, a.getEffectiveLevel()); assertEquals(Level.DEBUG, ab.getEffectiveLevel()); assertEquals(Level.DEBUG, root.getLevel()); assertNull(a.getLevel()); assertNull(ab.getLevel()); } // http://jira.qos.ch/browse/LBCLASSIC-89 @Test public void turboFilterStopOnReset() { NOPTurboFilter nopTF = new NOPTurboFilter(); nopTF.start(); lc.addTurboFilter(nopTF); assertTrue(nopTF.isStarted()); lc.reset(); assertFalse(nopTF.isStarted()); } @Test public void resetTest_LBCORE_104() { lc.putProperty("keyA", "valA"); lc.putObject("keyA", "valA"); assertEquals("valA", lc.getProperty("keyA")); assertEquals("valA", lc.getObject("keyA")); lc.reset(); assertNull(lc.getProperty("keyA")); assertNull(lc.getObject("keyA")); } @Test public void loggerNameEndingInDotOrDollarShouldWork() { { String loggerName = "toto.x."; Logger logger = lc.getLogger(loggerName); assertEquals(loggerName, logger.getName()); } { String loggerName = "toto.x$"; Logger logger = lc.getLogger(loggerName); assertEquals(loggerName, logger.getName()); } } @Test public void levelResetTest() { Logger root = lc.getLogger(Logger.ROOT_LOGGER_NAME); root.setLevel(Level.TRACE); assertTrue(root.isTraceEnabled()); lc.reset(); assertFalse(root.isTraceEnabled()); assertTrue(root.isDebugEnabled()); } @Test public void evaluatorMapPostReset() { lc.reset(); assertNotNull(lc.getObject(CoreConstants.EVALUATOR_MAP)); } @SuppressWarnings("unchecked") @Test public void collisionMapsPostReset() { lc.reset(); Map<String, String> fileCollisions = (Map<String, String>) lc.getObject(CoreConstants.FA_FILENAME_COLLISION_MAP); assertNotNull(fileCollisions); assertTrue(fileCollisions.isEmpty()); Map<String, FileNamePattern> filenamePatternCollisionMap = (Map<String, FileNamePattern>) lc.getObject(CoreConstants.RFA_FILENAME_PATTERN_COLLISION_MAP); assertNotNull(filenamePatternCollisionMap); assertTrue(filenamePatternCollisionMap.isEmpty()); } // http://jira.qos.ch/browse/LOGBACK-142 @Test public void concurrentModification() { final int runLen = 100; Thread thread = new Thread(new Runnable() { public void run() { for (int i = 0; i < runLen; i++) { lc.getLogger("a" + i); Thread.yield(); } } }); thread.start(); for (int i = 0; i < runLen; i++) { lc.putProperty("a" + i, "val"); Thread.yield(); } } }
3,181
2,960
#include <bits/stdc++.h> using namespace std; class Solution { public: void rotate(vector<int>& nums, int k) { k %= nums.size(); reverse(nums.begin(), nums.end() - k); reverse(nums.end() - k, nums.end()); reverse(nums.begin(), nums.end()); } };
134
22,040
<filename>spacy/tests/tokenizer/test_explain.py import pytest import re from spacy.util import get_lang_class from spacy.tokenizer import Tokenizer # Only include languages with no external dependencies # "is" seems to confuse importlib, so we're also excluding it for now # excluded: ja, ru, th, uk, vi, zh, is LANGUAGES = [ pytest.param("fr", marks=pytest.mark.slow()), pytest.param("af", marks=pytest.mark.slow()), pytest.param("ar", marks=pytest.mark.slow()), pytest.param("bg", marks=pytest.mark.slow()), "bn", pytest.param("ca", marks=pytest.mark.slow()), pytest.param("cs", marks=pytest.mark.slow()), pytest.param("da", marks=pytest.mark.slow()), pytest.param("de", marks=pytest.mark.slow()), "el", "en", pytest.param("es", marks=pytest.mark.slow()), pytest.param("et", marks=pytest.mark.slow()), pytest.param("fa", marks=pytest.mark.slow()), pytest.param("fi", marks=pytest.mark.slow()), "fr", pytest.param("ga", marks=pytest.mark.slow()), pytest.param("he", marks=pytest.mark.slow()), pytest.param("hi", marks=pytest.mark.slow()), pytest.param("hr", marks=pytest.mark.slow()), "hu", pytest.param("id", marks=pytest.mark.slow()), pytest.param("it", marks=pytest.mark.slow()), pytest.param("kn", marks=pytest.mark.slow()), pytest.param("lb", marks=pytest.mark.slow()), pytest.param("lt", marks=pytest.mark.slow()), pytest.param("lv", marks=pytest.mark.slow()), pytest.param("nb", marks=pytest.mark.slow()), pytest.param("nl", marks=pytest.mark.slow()), "pl", pytest.param("pt", marks=pytest.mark.slow()), pytest.param("ro", marks=pytest.mark.slow()), pytest.param("si", marks=pytest.mark.slow()), pytest.param("sk", marks=pytest.mark.slow()), pytest.param("sl", marks=pytest.mark.slow()), pytest.param("sq", marks=pytest.mark.slow()), pytest.param("sr", marks=pytest.mark.slow()), pytest.param("sv", marks=pytest.mark.slow()), pytest.param("ta", marks=pytest.mark.slow()), pytest.param("te", marks=pytest.mark.slow()), pytest.param("tl", marks=pytest.mark.slow()), pytest.param("tr", marks=pytest.mark.slow()), pytest.param("tt", marks=pytest.mark.slow()), pytest.param("ur", marks=pytest.mark.slow()), ] @pytest.mark.parametrize("lang", LANGUAGES) def test_tokenizer_explain(lang): tokenizer = get_lang_class(lang)().tokenizer examples = pytest.importorskip(f"spacy.lang.{lang}.examples") for sentence in examples.sentences: tokens = [t.text for t in tokenizer(sentence) if not t.is_space] debug_tokens = [t[1] for t in tokenizer.explain(sentence)] assert tokens == debug_tokens def test_tokenizer_explain_special_matcher(en_vocab): suffix_re = re.compile(r"[\.]$") infix_re = re.compile(r"[/]") rules = {"a.": [{"ORTH": "a."}]} tokenizer = Tokenizer( en_vocab, rules=rules, suffix_search=suffix_re.search, infix_finditer=infix_re.finditer, ) tokens = [t.text for t in tokenizer("a/a.")] explain_tokens = [t[1] for t in tokenizer.explain("a/a.")] assert tokens == explain_tokens
1,333
3,428
{"id":"00578","group":"easy-ham-2","checksum":{"type":"MD5","value":"9c1b9956370b439f73cb2073037661fb"},"text":"From <EMAIL> Wed Aug 7 00:10:34 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: y<EMAIL>.netnoteinc.com\nReceived: from localhost (localhost [127.0.0.1])\n\tby phobos.labs.netnoteinc.com (Postfix) with ESMTP id 967BA440A8\n\tfor <jm@localhost>; Tue, 6 Aug 2002 19:10:34 -0400 (EDT)\nReceived: from phobos [127.0.0.1]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor jm@localhost (single-drop); Wed, 07 Aug 2002 00:10:34 +0100 (IST)\nReceived: from usw-sf-list2.sourceforge.net (usw-sf-fw2.sourceforge.net\n [172.16.31.102]) by dogma.slashnull.org (8.11.6/8.11.6) with ESMTP id\n g76N8Fk23032 for <<EMAIL>>; Wed, 7 Aug 2002 00:08:15 +0100\nReceived: from usw-sf-list1-b.sourceforge.net ([10.3.1.13]\n helo=usw-sf-list1.sourceforge.net) by usw-sf-list2.sourceforge.net with\n esmtp (Exim 3.31-VA-mm2 #1 (Debian)) id 17cDEI-0001vP-00; Tue,\n 06 Aug 2002 15:55:06 -0700\nReceived: from med-core07.med.wayne.edu ([192.168.127.12]) by\n usw-sf-list1.sourceforge.net with esmtp (Exim 3.31-VA-mm2 #1 (Debian)) id\n 17cDDQ-000331-00 for <<EMAIL>>; Tue,\n 06 Aug 2002 15:54:12 -0700\nX-Mimeole: Produced By Microsoft Exchange V6.0.6249.0\nContent-Class: urn:content-classes:message\nMIME-Version: 1.0\nContent-Type: text/plain; charset=\"US-ASCII\"\nSubject: RE: [Razor-users] What's wrong with the Razor servers now?\nMessage-Id: <<EMAIL>>\nX-MS-Has-Attach: \nX-MS-Tnef-Correlator: \nThread-Topic: [Razor-users] What's wrong with the Razor servers now?\nThread-Index: AcI6NTHhdNlotwjiQEiUizLDYaWgngCdP1sAADxyGsA=\nFrom: \"<NAME>\" <<EMAIL>>\nTo: \"ML-razor-users\" <<EMAIL>>\nSender: <EMAIL>\nErrors-To: [email protected]\nX-Beenthere: <EMAIL>.net\nX-Mailman-Version: 2.0.9-sf.net\nPrecedence: bulk\nList-Help: <mailto:<EMAIL>?subject=help>\nList-Post: <mailto:<EMAIL>>\nList-Subscribe: <https://example.sourceforge.net/lists/listinfo/razor-users>,\n <mailto:<EMAIL>?subject=subscribe>\nList-Id: <razor-users.example.sourceforge.net>\nList-Unsubscribe: <https://example.sourceforge.net/lists/listinfo/razor-users>,\n <mailto:<EMAIL>?subject=unsubscribe>\nList-Archive: <http://www.geocrawler.com/redir-sf.php3?list=razor-users>\nX-Original-Date: Tue, 6 Aug 2002 18:54:04 -0400\nDate: Tue, 6 Aug 2002 18:54:04 -0400\nContent-Transfer-Encoding: 8bit\nX-MIME-Autoconverted: from quoted-printable to 8bit by dogma.slashnull.org\n id g76N8Fk23032\n\nI'm still seeing this. It reports to honor.cloudmark.com but checks\nagainst apt.cloudmark.com. What is the sync delay between these boxes?\n\n-----Original Message-----\nFrom: <NAME> \nSent: Monday, August 05, 2002 2:05 PM\nTo: ML-razor-users\nSubject: [Razor-users] What's wrong with the Razor servers now?\n\n\nI noticed a low count of razor'd spam messages. So after digging, if I\nrazor-report a message the diags say that it was accepted but if I turn\naround and run a check on the exact same message that was reported, then\nit doesn't find the sig and as such isn't spam.\n\n\n-------------------------------------------------------\nThis sf.net email is sponsored by:ThinkGeek\nWelcome to geek heaven.\nhttp://thinkgeek.com/sf _______________________________________________\nRazor-users mailing list\n<EMAIL>\nhttps://lists.sourceforge.net/lists/listinfo/razor-users\n\n\n-------------------------------------------------------\nThis sf.net email is sponsored by:ThinkGeek\nWelcome to geek heaven.\nhttp://thinkgeek.com/sf\n_______________________________________________\nRazor-users mailing list\n<EMAIL>\nhttps://lists.sourceforge.net/lists/listinfo/razor-users\n\n\n"}
1,432
578
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <folly/Function.h> #include <memory> #include "cachelib/navy/common/CompilerUtils.h" #include "cachelib/navy/common/Types.h" // Defines Job and JobScheduler (asynchronous executor). // // Job has a movable function returning JobExitCode: // - Done Job finished // - Reschedule Re-queue and retry again // // JobScheduler has the following members: // - enqueue(Job) Enqueues a job // - enqueueWithKey(Job, key) Enqueues a job with a key. Can be used to hash // jobs. // - finish() Waits for all the scheduled jobs to finish namespace facebook { namespace cachelib { namespace navy { enum class JobExitCode { Done, Reschedule, }; // Allow job to have movable captures using Job = folly::Function<JobExitCode()>; enum class JobType { Read, Write, Reclaim, Flush }; class JobScheduler { public: virtual ~JobScheduler() = default; // Uses @key to schedule job on one of available workers. Jobs can be // ordered by their key based on their enqueue order, if the scheduler // supports it. virtual void enqueueWithKey(Job job, folly::StringPiece name, JobType type, uint64_t key) = 0; // enqueue a job for execution. No ordering guarantees are made for these // jobs. virtual void enqueue(Job job, folly::StringPiece name, JobType type) = 0; // guarantees that all enqueued jobs are finished and blocks until then. virtual void finish() = 0; // visits each available counter for the visitor to take appropriate action. virtual void getCounters(const CounterVisitor& visitor) const = 0; }; // create a thread pool job scheduler that ensures ordering of requests by // key. This is the default job scheduler for use in Navy. std::unique_ptr<JobScheduler> createOrderedThreadPoolJobScheduler( uint32_t readerThreads, uint32_t writerThreads, uint32_t reqOrderShardPower); } // namespace navy } // namespace cachelib } // namespace facebook
918
454
package cn.vertxup.jet.api; import io.vertx.core.Future; import io.vertx.core.json.JsonObject; import io.vertx.tp.jet.cv.JtAddr; import io.vertx.up.annotations.Address; import io.vertx.up.annotations.Queue; import io.vertx.up.runtime.soul.UriAeon; /** * @author <a href="http://www.origin-x.cn">Lang</a> */ @Queue public class UriActor { @Address(JtAddr.Aeon.NEW_ROUTE) public Future<Boolean> createUri(final JsonObject body) { UriAeon.mountRoute(body); return Future.succeededFuture(Boolean.TRUE); } }
231
348
<reponame>chamberone/Leaflet.PixiOverlay<filename>docs/data/leg-t1/056/05606083.json {"nom":"Hennebont","circ":"6ème circonscription","dpt":"Morbihan","inscrits":11743,"abs":5544,"votants":6199,"blancs":96,"nuls":43,"exp":6060,"res":[{"nuance":"REM","nom":"<NAME>","voix":2509},{"nuance":"FI","nom":"<NAME>","voix":880},{"nuance":"DVG","nom":"<NAME>","voix":876},{"nuance":"FN","nom":"M. <NAME>","voix":489},{"nuance":"LR","nom":"Mme <NAME>","voix":464},{"nuance":"UDI","nom":"<NAME>","voix":377},{"nuance":"REG","nom":"<NAME>","voix":138},{"nuance":"DLF","nom":"M. <NAME>","voix":102},{"nuance":"EXG","nom":"Mme <NAME>","voix":90},{"nuance":"REG","nom":"M. <NAME>","voix":80},{"nuance":"DIV","nom":"<NAME>","voix":30},{"nuance":"DVD","nom":"<NAME>","voix":25}]}
311
9,472
<gh_stars>1000+ from .route import Route, RouteNotFoundException from .cmatcher import Matcher class Router: def __init__(self, matcher_factory=Matcher): self._routes = [] self.matcher_factory = matcher_factory def add_route(self, pattern, handler, method=None, methods=None): assert not(method and methods), "Cannot use method and methods" if method: methods = [method] if not methods: methods = [] methods = {m.upper() for m in methods} route = Route(pattern, handler, methods) self._routes.append(route) return route def get_matcher(self): return self.matcher_factory(self._routes)
291
2,329
package fields; public class Ya002 { static int j; // made static }
23
3,428
<filename>lib/node_modules/@stdlib/datasets/spam-assassin/data/easy-ham-1/00567.aa0b1a5ccd63ce58ca09389b7dd7a5aa.json {"id":"00567","group":"easy-ham-1","checksum":{"type":"MD5","value":"aa0b1a5ccd63ce58ca09389b7dd7a5aa"},"text":"From <EMAIL> Thu Sep 12 13:39:44 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: y<EMAIL>.spamassassin.taint.org\nReceived: from localhost (jalapeno [1172.16.31.10])\n\tby jmason.org (Postfix) with ESMTP id 23FC716F03\n\tfor <jm@localhost>; Thu, 12 Sep 2002 13:39:44 +0100 (IST)\nReceived: from jalapeno [127.0.0.1]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor jm@localhost (single-drop); Thu, 12 Sep 2002 13:39:44 +0100 (IST)\nReceived: from xent.com ([64.161.22.236]) by dogma.slashnull.org\n (8.11.6/8.11.6) with ESMTP id g8C1ZvC12173 for <<EMAIL>>;\n Thu, 12 Sep 2002 02:36:03 +0100\nReceived: from lair.xent.com (localhost [127.0.0.1]) by xent.com (Postfix)\n with ESMTP id 9EE5A294172; Wed, 11 Sep 2002 18:32:04 -0700 (PDT)\nDelivered-To: <EMAIL>int.<EMAIL>\nReceived: from homer.perfectpresence.com (unknown [209.123.207.194]) by\n xent.com (Postfix) with ESMTP id 9564429409A for <<EMAIL>>;\n Wed, 11 Sep 2002 18:31:20 -0700 (PDT)\nReceived: from adsl-157-233-109.jax.bellsouth.net ([66.157.233.109]\n helo=regina) by homer.perfectpresence.com with smtp (Exim 3.36 #1) id\n 17pIrX-0000gf-00; Wed, 11 Sep 2002 21:33:43 -0400\nFrom: \"<NAME>\" <<EMAIL>>\nTo: \"Tom\" <<EMAIL>>, <<EMAIL>>\nSubject: RE: Bush blew take two\nMessage-Id: <<EMAIL>>\nMIME-Version: 1.0\nContent-Type: text/plain; charset=\"US-ASCII\"\nContent-Transfer-Encoding: 7bit\nX-Priority: 3 (Normal)\nX-Msmail-Priority: Normal\nX-Mailer: Microsoft Outlook IMO, Build 9.0.2416 (9.0.2911.0)\nImportance: Normal\nIn-Reply-To: <<EMAIL>.<EMAIL>>\nX-Mimeole: Produced By Microsoft MimeOLE V5.50.4910.0300\nX-Antiabuse: This header was added to track abuse, please include it with\n any abuse report\nX-Antiabuse: Primary Hostname - homer.perfectpresence.com\nX-Antiabuse: Original Domain - xent.com\nX-Antiabuse: Originator/Caller UID/GID - [0 0] / [0 0]\nX-Antiabuse: Sender Address Domain - barrera.org\nSender: <EMAIL>\nErrors-To: <EMAIL>\nX-Beenthere: <EMAIL>\nX-Mailman-Version: 2.0.11\nPrecedence: bulk\nList-Help: <mailto:<EMAIL>?subject=help>\nList-Post: <mailto:<EMAIL>>\nList-Subscribe: <http://xent.com/mailman/listinfo/fork>, <mailto:<EMAIL>?subject=subscribe>\nList-Id: Friends of <NAME> <fork.xent.com>\nList-Unsubscribe: <http://xent.com/mailman/listinfo/fork>,\n <mailto:<EMAIL>?subject=unsubscribe>\nList-Archive: <http://xent.com/pipermail/fork/>\nDate: Wed, 11 Sep 2002 21:32:23 -0400\n\nyeshterday we f*cked up our gubernatorial election, too. results to be\ncontested by reno. same six districts that were sued in 2000 still came up\ngimpy.\n\ni suggested to jeb via e-mail we hold a run-off pinata party. hoist up a\npapier mache donkey and a papier mache elephant. first one to batted open\nwins.\n\n-----Original Message-----\nFrom: <EMAIL> [mailto:<EMAIL>]On Behalf Of Tom\nSent: Wednesday, September 11, 2002 9:16 PM\nTo: <EMAIL>\nSubject: Bush blew take two\n\n\nhttp://www.washingtonpost.com/wp-dyn/articles/A63543-2002Sep10.html\n\n\"MIAMI, Sept. 10 -- A two-gram rock of crack\ncocaine was found inside the shoe of Florida\nGov. <NAME>'s 25-year-old daughter by workers\nat the central Florida rehabilitation center\nwhere she is undergoing court-ordered drug\ntreatment, Orlando police said today.\n\n<NAME> was not arrested because witnesses\nwould not give sworn statements, but the\nincident is under investigation, according to\nOrlando police spokesman <NAME>.\"\n\nWow, the witnesses would not nark of a Bush girl in an era where there are\nno mare restrictions on being held without a cause?\n\nImagine that...\n\n-tom\n\n\n\n\n\n\n\n"}
1,495
363
package cn.sddman.download.activity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import com.xunlei.downloadlib.XLTaskHelper; import org.xutils.view.annotation.ContentView; import org.xutils.view.annotation.Event; import org.xutils.view.annotation.ViewInject; import cn.sddman.download.R; import cn.sddman.download.common.BaseActivity; import cn.sddman.download.common.Const; import cn.sddman.download.mvp.p.UrlDownLoadPresenter; import cn.sddman.download.mvp.p.UrlDownLoadPresenterImp; import cn.sddman.download.mvp.v.UrlDownLoadView; import cn.sddman.download.util.Util; @ContentView(R.layout.activity_url_download) public class UrlDownLoadActivity extends BaseActivity implements UrlDownLoadView{ @ViewInject(R.id.url_input) private EditText urlInput; private UrlDownLoadPresenter urlDownLoadPresenter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.setTopBarTitle(R.string.new_download); XLTaskHelper.init(getApplicationContext()); urlDownLoadPresenter=new UrlDownLoadPresenterImp(this); } @Event(value = R.id.start_download) private void startDownloadClick(View view) { urlDownLoadPresenter.startTask(urlInput.getText().toString().trim()); } @Override public void addTaskSuccess() { // Intent intent =new Intent(UrlDownLoadActivity.this,DownloadManagementActivity.class); // startActivity(intent); finish(); } @Override public void addTaskFail(String msg) { Util.alert(this,msg, Const.ERROR_ALERT); } }
606
369
// Copyright (c) 2017-2021, Mudita Sp. z.o.o. All rights reserved. // For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md #include "SwitchConfirmation.hpp" namespace app::manager { SwitchConfirmation::SwitchConfirmation(const ApplicationName &sender) : BaseMessage(MessageType::APMConfirmSwitch, sender) {} } // namespace app::manager
125
495
<reponame>marlon-br/media-for-mobile<filename>domain/src/test/java/org/m4m/domain/mediaComposer/AndroidMediaObjectFactoryFake.java /* * Copyright 2014-2016 Media for Mobile * * 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.m4m.domain.mediaComposer; import org.m4m.domain.dsl.Father; import org.m4m.domain.dsl.MediaSourceFather; import org.m4m.domain.graphics.IEglUtil; import org.m4m.domain.pipeline.IOnStopListener; import org.m4m.domain.AudioDecoder; import org.m4m.domain.AudioEffector; import org.m4m.domain.AudioEncoder; import org.m4m.domain.CameraSource; import org.m4m.domain.FileSegment; import org.m4m.domain.IAndroidMediaObjectFactory; import org.m4m.domain.IAudioContentRecognition; import org.m4m.domain.ICameraSource; import org.m4m.domain.ICaptureSource; import org.m4m.domain.IEffectorSurface; import org.m4m.domain.IEglContext; import org.m4m.domain.IFrameBuffer; import org.m4m.domain.IMediaExtractor; import org.m4m.domain.IMediaMuxer; import org.m4m.domain.IMicrophoneSource; import org.m4m.domain.IPreview; import org.m4m.domain.MediaFormat; import org.m4m.domain.MediaSource; import org.m4m.domain.MuxRender; import org.m4m.domain.ProgressTracker; import org.m4m.domain.Render; import org.m4m.domain.Resampler; import org.m4m.domain.VideoDecoder; import org.m4m.domain.VideoEffector; import org.m4m.domain.VideoEncoder; import org.m4m.domain.VideoTimeScaler; import java.io.FileDescriptor; import java.io.IOException; import java.util.Dictionary; import java.util.Hashtable; import static org.mockito.Mockito.mock; public class AndroidMediaObjectFactoryFake implements IAndroidMediaObjectFactory { private final Father create; private Dictionary<String, IMediaExtractor> mediaExtractors = new Hashtable<String, IMediaExtractor>(); private IMediaMuxer muxer; private Render sink; private VideoDecoder videoDecoder; private AudioDecoder audioDecoder; private VideoEncoder videoEncoder; private AudioEncoder audioEncoder; private Resampler resampler; private MediaSource mediaSource; private VideoEffector videoEffector; private ICameraSource cameraSource; private MediaFormat videoFormat; private IMicrophoneSource microphoneSource; private org.m4m.AudioFormat audioFormat; private IEglContext currentEglContext; private IFrameBuffer FB; private IPreview preview; private final IOnStopListener onStopListener; public AndroidMediaObjectFactoryFake(Father create) { this.create = create; onStopListener = new IOnStopListener() { @Override public void onStop() { } }; } public AndroidMediaObjectFactoryFake withMediaSource(MediaSource mediaSource) { this.mediaSource = mediaSource; return this; } public AndroidMediaObjectFactoryFake withVideoDecoder(VideoDecoder decoder) { this.videoDecoder = decoder; return this; } public AndroidMediaObjectFactoryFake withAudioDecoder(AudioDecoder decoder) { this.audioDecoder = decoder; return this; } public AndroidMediaObjectFactoryFake withVideoEncoder(VideoEncoder encoder) { this.videoEncoder = encoder; return this; } public void withVideoEffector(VideoEffector videoEffector) { this.videoEffector = videoEffector; } public void withCameraSource(CameraSource cameraSource) { this.cameraSource = cameraSource; } @Override public MediaSource createMediaSource(String fileName) throws IOException { if (null != mediaSource) { return mediaSource; } MediaSourceFather mediaSourceFather = create.mediaSource(); if (mediaExtractors.get(fileName) != null) mediaSourceFather.with(mediaExtractors.get(fileName)); return mediaSourceFather.withFilePath(fileName).construct(); } @Override public MediaSource createMediaSource(FileDescriptor fileDescriptor) throws IOException { if (null != mediaSource) { return mediaSource; } MediaSourceFather mediaSourceFather = create.mediaSource(); if (mediaExtractors.get(fileDescriptor) != null) mediaSourceFather.with(mediaExtractors.get(fileDescriptor)); return mediaSourceFather.withFileDescriptor(fileDescriptor).construct(); } @Override public MediaSource createMediaSource(org.m4m.Uri uri) throws IOException { if (null != mediaSource) { return mediaSource; } MediaSourceFather mediaSourceFather = create.mediaSource(); if (mediaExtractors.get(uri) != null) mediaSourceFather.with(mediaExtractors.get(uri)); return mediaSourceFather.withUri(uri).construct(); } @Override public VideoDecoder createVideoDecoder(MediaFormat format) { if (videoDecoder == null) videoDecoder = create.videoDecoder().construct(); return videoDecoder; } @Override public VideoEncoder createVideoEncoder() { if (videoEncoder == null) videoEncoder = create.videoEncoder().construct(); return videoEncoder; } @Override public AudioDecoder createAudioDecoder() { if (audioDecoder == null) audioDecoder = create.audioDecoder().construct(); return audioDecoder; } @Override public AudioEncoder createAudioEncoder(String mimeType) { if (audioEncoder == null) audioEncoder = create.audioEncoder().construct(); return audioEncoder; } @Override public Resampler createAudioResampler(org.m4m.AudioFormat audioFormat) { if (resampler == null) resampler = create.resampler().construct(); return resampler; } @Override public Render createSink(String fileName, int orientationHint, org.m4m.IProgressListener progressListener, ProgressTracker progressTracker) throws IOException { if (sink == null) { if (muxer == null) muxer = create.mediaMuxer().construct(); return new MuxRender(muxer, progressListener, progressTracker); } return sink; } @Override public Render createSink(org.m4m.StreamingParameters StreamingParams, org.m4m.IProgressListener progressListener, ProgressTracker progressTracker) { if (muxer == null) { muxer = create.mediaStreamer().construct(); } return new MuxRender(muxer, progressListener, progressTracker); } @Override public ICaptureSource createCaptureSource() { return null; } @Override public MediaFormat createVideoFormat(String mimeType, int width, int height) { if (videoFormat == null) { videoFormat = create.videoFormat().construct(); } return videoFormat; } public void withVideoFormat(org.m4m.VideoFormat videoFormat) { this.videoFormat = videoFormat; } @Override public MediaFormat createAudioFormat(String mimeType, int channelCount, int sampleRate) { if (audioFormat == null) { audioFormat = create.audioFormat().construct(); } return audioFormat; } public AndroidMediaObjectFactoryFake withAudioFormat(org.m4m.AudioFormat audioFormat) { this.audioFormat = audioFormat; return this; } @Override public VideoEffector createVideoEffector() { return videoEffector != null ? videoEffector : new VideoEffector(create.mediaCodec().construct(), this); } @Override public VideoTimeScaler createVideoTimeScaler(int timeScale, FileSegment segment) { return new VideoTimeScaler(create.mediaCodec().construct(), this, timeScale, segment); } @Override public IEffectorSurface createEffectorSurface() { return mock(IEffectorSurface.class); } @Override public IPreview createPreviewRender(Object glView, Object camera) { return mock(IPreview.class); } @Override public AudioEffector createAudioEffects() { return null; } @Override public ICameraSource createCameraSource() { if (cameraSource == null) { cameraSource = mock(ICameraSource.class); } return cameraSource; } @Override public IMicrophoneSource createMicrophoneSource() { if (microphoneSource == null) { microphoneSource = mock(IMicrophoneSource.class); } return microphoneSource; } public void withMicrophoneSource(IMicrophoneSource microphoneSource) { this.microphoneSource = microphoneSource; } @Override public IAudioContentRecognition createAudioContentRecognition() { return mock(IAudioContentRecognition.class); } @Override public IEglContext getCurrentEglContext() { return currentEglContext; } @Override public IEglUtil getEglUtil() { return mock(IEglUtil.class); } @Override public IFrameBuffer createFrameBuffer() { if (FB == null) { FB = mock(IFrameBuffer.class); } return FB; } public AndroidMediaObjectFactoryFake withAudioEncoder(AudioEncoder audioEncoder) { this.audioEncoder = audioEncoder; return this; } public void withCurrentEglContext(IEglContext eglContext) { this.currentEglContext = eglContext; } public void withFrameBuffer(IFrameBuffer fakeFB) { this.FB = fakeFB; } public AndroidMediaObjectFactoryFake withSink(Render render) { this.sink = render; return this; } }
3,714
2,107
/* NetHack 3.6 windefs.h $NHDT-Date: 1432512795 2015/05/25 00:13:15 $ $NHDT-Branch: master $:$NHDT-Revision: 1.7 $ */ /* Copyright (c) <NAME>, Naperville, Illinois, 1991,1992,1993. */ /* NetHack may be freely redistributed. See license for details. */ #include <exec/types.h> #include <exec/memory.h> #include <exec/io.h> #if !defined(_DCC) && !defined(__GNUC__) #include <dos.h> #endif #include <exec/alerts.h> #include <exec/devices.h> #include <exec/execbase.h> #include <devices/console.h> #include <devices/conunit.h> #include <graphics/gfxbase.h> #include <intuition/intuition.h> #include <intuition/intuitionbase.h> #include <libraries/gadtools.h> #include <libraries/dosextens.h> #include <libraries/asl.h> /* stddef.h is included in the precompiled version of hack.h . If we include * it here normally (through string.h) we'll get an "illegal typedef" later * on. This is the easiest way I can think of to fix it without messing * around with the rest of the #includes. --AMC */ #if defined(_DCC) && !defined(HACK_H) #define ptrdiff_t ptrdiff_t_ #define size_t size_t_ #define wchar_t wchar_t_ #endif #include <ctype.h> #undef strcmpi #include <string.h> #include <errno.h> #if defined(_DCC) && !defined(HACK_H) #undef ptrdiff_t #undef size_t #undef wchar_T #endif #ifdef IDCMP_CLOSEWINDOW #ifndef INTUI_NEW_LOOK #define INTUI_NEW_LOOK #endif #endif #ifndef HACK_H #include "hack.h" #endif #include "wintype.h" #include "winami.h" #include "func_tab.h" #ifndef CLIPPING CLIPPING must be defined for the AMIGA version #endif #undef LI #undef CO /*#define TOPL_GETLINE /* Don't use a window for getlin() */ /*#define WINDOW_YN /* Use a window for y/n questions */ #ifdef AZTEC_C #include <functions.h> #else #ifdef _DCC #include <clib/dos_protos.h> #include <clib/exec_protos.h> #include <clib/console_protos.h> #include <clib/layers_protos.h> #include <clib/diskfont_protos.h> #include <clib/gadtools_protos.h> #else #include <proto/dos.h> #include <proto/exec.h> #include <proto/console.h> #include <proto/layers.h> #include <proto/diskfont.h> #include <proto/gadtools.h> #include <proto/asl.h> #endif /* kludge - see amirip for why */ #undef red #undef green #undef blue #ifdef _DCC #include <clib/graphics_protos.h> #else #include <proto/graphics.h> #endif #ifdef _DCC #define __asm /* DICE doesn't like __asm */ #endif #ifndef __SASC_60 #undef index #define index strchr #endif #ifdef _DCC #include <clib/intuition_protos.h> #else #include <proto/intuition.h> #endif #endif #ifdef SHAREDLIB #include "NH:sys/amiga/lib/libmacs.h" #endif #ifdef INTUI_NEW_LOOK #include <utility/tagitem.h> #endif #define WINVERS_AMII (strcmp("amii", windowprocs.name) == 0) #define WINVERS_AMIV (strcmp("amitile", windowprocs.name) == 0) #define WINVERS_AMIT (strcmp("amitty", windowprocs.name) == 0) /* cw->data[x] contains 2 characters worth of special information. These * characters are stored at the offsets as described here. */ #define VATTR 0 /* Video attribute is in this slot */ #define SEL_ITEM 1 /* If this is a select item, slot is 1 else 0 */ #define SOFF 2 /* The string starts here. */ #undef NULL #define NULL 0L /* * Versions we need of various libraries. We can't use LIBRARY_VERSION * as defined in <exec/types.h> because some of the libraries we need * don't have that version number in the 1.2 ROM. */ #define LIBRARY_FONT_VERSION 34L #define LIBRARY_TILE_VERSION 37L /* These values are just sorta suggestions in use, but are minimum * requirements * in reality... */ #define WINDOWHEIGHT 192 #define SCREENHEIGHT 200 #define WIDTH 640 /* This character is a solid block (cursor) in Hack.font */ #define CURSOR_CHAR 0x90 #define FONTHEIGHT 8 #define FONTWIDTH 8 #define FONTBASELINE 8 #define MAPFTWIDTH 8 #define MAPFTHEIGHT 8 #define MAPFTBASELN 6 /* If Compiling with the "New Look", redefine these now */ #ifdef INTUI_NEW_LOOK #define NewWindow ExtNewWindow #define NewScreen ExtNewScreen #endif #define SIZEOF_DISKNAME 8 #define CSI '\x9b' #define NO_CHAR -1 #define RAWHELP 0x5F /* Rawkey code of the HELP key */ #define C_BLACK 0 #define C_WHITE 1 #define C_BROWN (WINVERS_AMIV ? 11 : 2) #define C_CYAN (WINVERS_AMIV ? 2 : 3) #define C_GREEN (WINVERS_AMIV ? 5 : 4) #define C_MAGENTA (WINVERS_AMIV ? 10 : 5) #define C_BLUE (WINVERS_AMIV ? 4 : 6) #define C_RED 7 #define C_ORANGE 3 #define C_GREY 6 #define C_LTGREEN 8 #define C_YELLOW 9 #define C_GREYBLUE 12 #define C_LTBROWN 13 #define C_LTGREY 14 #define C_PEACH 15 /* Structure describing tile files */ struct PDAT { long nplanes; /* Depth of images */ long pbytes; /* Bytes in a plane of data */ long across; /* Number of tiles across */ long down; /* Number of tiles down */ long npics; /* Number of pictures in this file */ long xsize; /* X-size of a tile */ long ysize; /* Y-size of a-tile */ }; #undef MAXCOLORS #define MAXCOLORS 256
1,937
5,169
<reponame>Ray0218/Specs { "name": "ImageSlideshow", "version": "0.2.3", "summary": "Image slideshow written in Swift with circular scrolling, timer and full screen viewer", "description": "Image slideshow is a Swift library providing customizable image slideshow with circular scrolling, timer and full screen viewer and extendable image source (AFNetworking image source available in AFURL subspec).", "homepage": "https://github.com/zvonicek/ImageSlideshow", "screenshots": "http://cl.ly/image/2v193I0G0h0Z/ImageSlideshow2.gif", "license": "MIT", "authors": { "<NAME>": "<EMAIL>" }, "source": { "git": "https://github.com/zvonicek/ImageSlideshow.git", "tag": "0.2.3" }, "social_media_url": "https://twitter.com/zvonicek", "platforms": { "ios": "8.0" }, "requires_arc": true, "default_subspecs": "Core", "subspecs": [ { "name": "Core", "source_files": "Pod/Classes/Core/**/*", "resource_bundles": { "ImageSlideshow": [ "Pod/Assets/*.png" ] } }, { "name": "AFURL", "dependencies": { "ImageSlideshow/Core": [ ], "AFNetworking": [ "~> 2.3" ] }, "source_files": "Pod/Classes/InputSources/AFURLSource.swift" } ] }
550
16,989
<gh_stars>1000+ // Copyright 2019 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.rules.cpp; import com.google.devtools.build.lib.actions.Artifact; import com.google.devtools.build.lib.collect.nestedset.NestedSet; import com.google.devtools.build.lib.util.Fingerprint; import javax.annotation.Nullable; /** Wrapper around a map of bitcode files for purposes of caching its fingerprint. */ final class BitcodeFiles { private final NestedSet<Artifact> files; @Nullable private volatile byte[] fingerprint = null; BitcodeFiles(NestedSet<Artifact> files) { this.files = files; } NestedSet<Artifact> getFiles() { return files; } void addToFingerprint(Fingerprint fp) { if (fingerprint == null) { synchronized (this) { if (fingerprint == null) { fingerprint = computeFingerprint(); } } } fp.addBytes(fingerprint); } private byte[] computeFingerprint() { Fingerprint fp = new Fingerprint(); for (Artifact path : files.toList()) { fp.addPath(path.getExecPath()); } return fp.digestAndReset(); } }
548
2,453
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 30 2020 21:18:12). // // Copyright (C) 1997-2019 <NAME>. // #import <IDEKit/IDETestReport_Base-Protocol.h> #import <IDEKit/NSObject-Protocol.h> @class NSArray, NSString; @protocol IDETestReport_TestGroup <NSObject, IDETestReport_Base> - (NSArray *)ide_sharedTests_mixedTests; - (NSArray *)ide_sharedTests_skippedTests; - (NSArray *)ide_sharedTests_failingTests; - (NSArray *)ide_sharedTests_passingTests; - (NSArray *)ide_sharedTests_testGroup_allTests; - (NSArray *)ide_sharedTests_testGroup_perfTests; @property(nonatomic, readonly) NSString *ide_testReport_testGroup_testTargetName; @property(nonatomic, readonly) NSString *ide_testReport_testGroup_groupName; @optional @property(nonatomic, readonly) double ide_testReport_testGroup_duration; @end
303
6,717
<filename>tools/AppInsights/src/core/contracts/PageViewData.h #ifndef PAGEVIEWDATA_H #define PAGEVIEWDATA_H #include "../common/Common.h" #include "../common/JsonWriter.h" #include "../common/Nullable.h" #include "../common/Serializer.h" #include "EventData.h" #include <map> #include <string> #include <vector> namespace ApplicationInsights { namespace core { class TELEMETRYCLIENT_API PageViewData : public EventData { private: std::wstring m_url; std::wstring m_duration; public: PageViewData(); PageViewData(std::wstring envelopeName, std::wstring dataType); virtual ~PageViewData(); const std::wstring& GetUrl() const { return m_url; } void SetUrl(const std::wstring& value) { m_url = value; } const std::wstring& GetDuration() const { return m_duration; } void SetDuration(const std::wstring& value) { m_duration = value; } virtual void Serialize(Serializer& serializer) const; }; } } #endif
349
3,937
// Copyright (c) 2003-present, Jodd Team (http://jodd.org) // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. package jodd.util; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; /** * Tests for {@link MultiComparator}. */ class MultiComparatorTest { @Test void testCompare_with_null_list() { // asserts assertThrows(NullPointerException.class, () -> new MultiComparator<>(null).compare(new Object(), new Object())); } @Test void testCompare_with_null_entry_in_list() { final List<Comparator<Object>> comparators = new ArrayList<>(); comparators.add((o1, o2) -> 0); comparators.add(null); // asserts assertThrows(NullPointerException.class, () -> new MultiComparator<>(comparators).compare(new Object(), new Object())); } @Test void testCompare_with_empty_in_list() { final List<Comparator<Object>> comparators = new ArrayList<>(); // asserts assertEquals(0, new MultiComparator<>(comparators).compare(new Object(), new Object())); } @Test void testCompare_with_expected_negative_value() { final List<Comparator<Object>> comparators = new ArrayList<>(); Stream.of(0, 0, 0).forEach(c -> comparators.add((o1, o2) -> c)); comparators.add((o1, o2) -> -77); // asserts assertEquals(-77, new MultiComparator<>(comparators).compare(new Object(), new Object())); } @Test void testCompare_with_expected_positive_value() { final List<Comparator<Object>> comparators = new ArrayList<>(); Stream.of(0, 0, 0).forEach(c -> comparators.add((o1, o2) -> c)); comparators.add((o1, o2) -> 23); // asserts assertEquals(23, new MultiComparator<>(comparators).compare(new Object(), new Object())); } }
1,018
6,989
#pragma once #include <util/generic/ptr.h> #include <util/stream/output.h> #include <util/system/atomic.h> #include <util/system/atomic_ops.h> namespace NNeh { class TStatCollector; /// NEH service workability statistics collector. /// /// Disabled by default, use `TServiceStat::ConfigureValidator` to set `maxContinuousErrors` /// different from zero. class TServiceStat: public TThrRefBase { public: static void ConfigureValidator(unsigned maxContinuousErrors, unsigned reSendValidatorPeriod) noexcept { AtomicSet(MaxContinuousErrors_, maxContinuousErrors); AtomicSet(ReSendValidatorPeriod_, reSendValidatorPeriod); } static bool Disabled() noexcept { return !AtomicGet(MaxContinuousErrors_); } enum EStatus { Ok, Fail, ReTry //time for sending request-validator to service }; EStatus GetStatus(); void DbgOut(IOutputStream&) const; protected: friend class TStatCollector; virtual void OnBegin(); virtual void OnSuccess(); virtual void OnCancel(); virtual void OnFail(); static TAtomic MaxContinuousErrors_; static TAtomic ReSendValidatorPeriod_; TAtomicCounter RequestsInProcess_; TAtomic LastContinuousErrors_ = 0; TAtomic SendValidatorCounter_ = 0; }; using TServiceStatRef = TIntrusivePtr<TServiceStat>; //thread safe (race protected) service stat updater class TStatCollector { public: TStatCollector(TServiceStatRef& ss) : SS_(ss) { ss->OnBegin(); } ~TStatCollector() { if (CanInformSS()) { SS_->OnFail(); } } void OnCancel() noexcept { if (CanInformSS()) { SS_->OnCancel(); } } void OnFail() noexcept { if (CanInformSS()) { SS_->OnFail(); } } void OnSuccess() noexcept { if (CanInformSS()) { SS_->OnSuccess(); } } private: inline bool CanInformSS() noexcept { return AtomicGet(CanInformSS_) && AtomicCas(&CanInformSS_, 0, 1); } TServiceStatRef SS_; TAtomic CanInformSS_ = 1; }; TServiceStatRef GetServiceStat(TStringBuf addr); }
1,157
10,225
package io.quarkus.it.spring.web; import org.springframework.stereotype.Service; @Service public class GreetingService { public Greeting greet(String message) { return new Greeting(message); } }
77
507
# terrascript/resource/newrelic.py # Automatically generated by tools/makecode.py (24-Sep-2021 15:22:33 UTC) # # For imports without namespace, e.g. # # >>> import terrascript.resource.newrelic # # instead of # # >>> import terrascript.resource.newrelic.newrelic # # This is only available for 'official' and 'partner' providers. from terrascript.resource.newrelic.newrelic import *
129
734
<filename>language-support/ts/typedoc.bzl # Copyright (c) 2021 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. # SPDX-License-Identifier: Apache-2.0 load("@os_info//:os_info.bzl", "is_windows") load("@build_environment//:configuration.bzl", "sdk_version") def ts_docs(pkg_name): "Macro for Typescript documentation generation with typedoc" native.genrule( name = "docs", srcs = native.glob(["**/*.ts"], exclude = ["**/*test.ts"]) + [":README.md"], tools = [ "@language_support_ts_deps//typedoc/bin:typedoc", "//bazel_tools/sh:mktgz", ], outs = [pkg_name + "-docs.tar.gz"], cmd = """ # NOTE: we need the --ignoreCompilerErrors flag because we get errors when tsc is trying to # resolve the imported packages. $(location @language_support_ts_deps//typedoc/bin:typedoc) --out docs --ignoreCompilerErrors --readme README.md --stripInternal $(SRCS) sed -i -e 's/0.0.0-SDKVERSION/{sdk_version}/' docs/**/*.html $(execpath //bazel_tools/sh:mktgz) $@ -h docs """, visibility = ["//visibility:public"], ) if not is_windows else None
515
790
<filename>tests/requests/__init__.py<gh_stars>100-1000 """ Tests for Django's various Request objects. """
36
434
<filename>aws-lambda-java-events-sdk-transformer/src/test/java/com/amazonaws/services/lambda/runtime/events/transformers/v1/dynamodb/DynamodbRecordTransformerTest.java package com.amazonaws.services.lambda.runtime.events.transformers.v1.dynamodb; import com.amazonaws.services.dynamodbv2.model.OperationType; import com.amazonaws.services.dynamodbv2.model.Record; import com.amazonaws.services.lambda.runtime.events.DynamodbEvent; import com.amazonaws.services.lambda.runtime.events.transformers.v1.DynamodbEventTransformer; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static com.amazonaws.services.lambda.runtime.events.transformers.v1.dynamodb.DynamodbIdentityTransformerTest.identity_event; import static com.amazonaws.services.lambda.runtime.events.transformers.v1.dynamodb.DynamodbIdentityTransformerTest.identity_v1; import static com.amazonaws.services.lambda.runtime.events.transformers.v1.dynamodb.DynamodbStreamRecordTransformerTest.streamRecord_event; import static com.amazonaws.services.lambda.runtime.events.transformers.v1.dynamodb.DynamodbStreamRecordTransformerTest.streamRecord_v1; public class DynamodbRecordTransformerTest { private static final String eventId = "2"; private static final String eventName = OperationType.MODIFY.toString(); private static final String eventVersion = "1.0"; private static final String eventSource = "aws:dynamodb"; private static final String awsRegion = "us-west-2"; //region Record_event public static final DynamodbEvent.DynamodbStreamRecord record_event = (DynamodbEvent.DynamodbStreamRecord) new DynamodbEvent.DynamodbStreamRecord() .withEventID(eventId) .withEventName(eventName) .withEventVersion(eventVersion) .withEventSource(eventSource) .withAwsRegion(awsRegion) .withDynamodb(streamRecord_event) .withUserIdentity(identity_event); //endregion //region Record_v1 public static final Record record_v1 = new Record() .withEventID(eventId) .withEventName(eventName) .withEventVersion(eventVersion) .withEventSource(eventSource) .withAwsRegion(awsRegion) .withDynamodb(streamRecord_v1) .withUserIdentity(identity_v1); //endregion @Test public void testToRecordV1() { Record convertedRecord = DynamodbRecordTransformer.toRecordV1(record_event); Assertions.assertEquals(record_v1, convertedRecord); } @Test public void testToRecordV1WhenUserIdentityIsNull() { DynamodbEvent.DynamodbStreamRecord record = record_event.clone(); record.setUserIdentity(null); Assertions.assertDoesNotThrow(() -> { com.amazonaws.services.lambda.runtime.events.transformers.v1.dynamodb.DynamodbRecordTransformer.toRecordV1(record); }); } }
1,242
868
<gh_stars>100-1000 // Copyright (C) 2019 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. // // General purpose random number generating methods. They are drop-in // replacements for `rand` / `rand_r`. // // CAUTION: NOTHING HERE SHOULD BE CONSIDERED CRYPTOGRAPHICALLY SECURE. FOR // CRYPTOGRAPHIC PURPOSE, USE OpenSSL INSTEAD. #ifndef FLARE_BASE_RANDOM_H_ #define FLARE_BASE_RANDOM_H_ #include <cstdint> #include <random> #include <type_traits> #include "flare/base/internal/annotation.h" namespace flare { namespace random { // Thread local random engine. // // `std::mt19937_64` performs equally well as `std::mt19937` on x86_64. So we // don't bother using `std::mt19937` for smaller types. // // We export this method into `gdt::random` (instead of keeping it in some // private namespace) so that people who randomly need an engine could directly // use this one, rather than declaring their own. inline std::mt19937_64& Engine() { // This could be quite tricky. // // Ideally we'd like to initialize the PRNG engine's internal state with raw // bits from `std::random_device`. However, per spec, the engine only accepts // a single number, or a `SeedSequence`, which is not satisfied by // `std::random-device`, in its constructor. In the meantime, by using // `std::seed_seq`, we potentially degrade our randomness. // // It would be the best if the Standard requires `std::random_device` to // satisfy `SeedSequence`, or (better yet), allows `std::mt19937` to accept a // `std::random_device`. // // More detailed discussion about the initialization of PRNG engine could be // found at: // // - https://stackoverflow.com/questions/15509270 // - http://www.pcg-random.org/posts/cpp-seeding-surprises.html // - https://www.reddit.com/r/cpp/comments/31857s // // Anyway, below is a more-or-less acceptable initialization, per the SO // answer linked above. FLARE_INTERNAL_TLS_MODEL thread_local auto engine = [] { std::random_device r; std::seed_seq seeds{r(), r(), r(), r(), r(), r(), r(), r()}; std::mt19937_64 engine(seeds); return engine; }(); return engine; } } // namespace random // Generate a random value of type `T`. `T` may not be floating point types. // // Returns: A random value in range [std::numeric_limits<T>::min(), // std::numeric_limits<T>::max()] (both inclusive). template <class T = std::uint64_t, class = std::enable_if_t<std::is_integral_v<T>>> T Random() { return random::Engine()(); } // Generate a random value in range [min, max] (inclusive) of type `T`. // // Values generated are distributed uniformly. // // `SimpleRandom` performs slightly better if multiple random values are needed. // @sa: //common/random/simple_random.h. template <class T> T Random(T min, T max) { using Distribution = std::conditional_t<std::is_floating_point_v<T>, std::uniform_real_distribution<T>, std::uniform_int_distribution<T>>; Distribution dist(min, max); // May NOT be `thread_local` as `min` / `max` // could be different across calls. return dist(random::Engine()); } // Shorthand for `Random(0, max)`. template <class T> T Random(T max) { return Random<T>(0, max); } } // namespace flare #endif // FLARE_BASE_RANDOM_H_
1,339
372
<filename>src/test/java/org/apache/sysds/test/functions/privacy/propagation/AppendPropagatorTest.java<gh_stars>100-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.apache.sysds.test.functions.privacy.propagation; import org.apache.sysds.runtime.instructions.cp.Data; import org.apache.sysds.runtime.instructions.cp.DoubleObject; import org.apache.sysds.runtime.instructions.cp.IntObject; import org.apache.sysds.runtime.instructions.cp.ListObject; import org.apache.sysds.runtime.instructions.cp.ScalarObject; import org.apache.sysds.runtime.matrix.data.MatrixBlock; import org.apache.sysds.runtime.meta.MatrixCharacteristics; import org.apache.sysds.runtime.privacy.PrivacyConstraint; import org.apache.sysds.runtime.privacy.PrivacyConstraint.PrivacyLevel; import org.apache.sysds.runtime.privacy.finegrained.DataRange; import org.apache.sysds.runtime.privacy.propagation.AppendPropagator; import org.apache.sysds.runtime.privacy.propagation.CBindPropagator; import org.apache.sysds.runtime.privacy.propagation.ListAppendPropagator; import org.apache.sysds.runtime.privacy.propagation.ListRemovePropagator; import org.apache.sysds.runtime.privacy.propagation.Propagator; import org.apache.sysds.runtime.privacy.propagation.PropagatorMultiReturn; import org.apache.sysds.runtime.privacy.propagation.RBindPropagator; import org.apache.sysds.test.AutomatedTestBase; import org.apache.sysds.test.TestConfiguration; import org.apache.sysds.test.TestUtils; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; public class AppendPropagatorTest extends AutomatedTestBase { private final static String TEST_DIR = "functions/privacy/"; private final static String TEST_NAME_RBIND = "RBindTest"; private final static String TEST_NAME_CBIND = "CBindTest"; private final static String TEST_NAME_STRING = "StringAppendTest"; private final static String TEST_NAME_LIST = "ListAppendTest"; private final static String TEST_CLASS_DIR = TEST_DIR + AppendPropagatorTest.class.getSimpleName() + "/"; @Override public void setUp() { TestUtils.clearAssertionInformation(); addTestConfiguration(TEST_NAME_RBIND, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME_RBIND, new String[] {"C"})); addTestConfiguration(TEST_NAME_CBIND, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME_CBIND, new String[] {"C"})); addTestConfiguration(TEST_NAME_STRING, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME_STRING, new String[] {"C"})); addTestConfiguration(TEST_NAME_LIST, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME_LIST, new String[] {"C"})); } @Test public void generalOnlyRBindPrivate1Test(){ generalOnlyRBindTest(new PrivacyConstraint(PrivacyLevel.Private), new PrivacyConstraint()); } @Test public void generalOnlyRBindPrivateAggregation1Test(){ generalOnlyRBindTest(new PrivacyConstraint(PrivacyLevel.PrivateAggregation), new PrivacyConstraint()); } @Test public void generalOnlyRBindNoneTest(){ generalOnlyRBindTest(new PrivacyConstraint(), new PrivacyConstraint()); } @Test public void generalOnlyRBindPrivate2Test(){ generalOnlyRBindTest(new PrivacyConstraint(), new PrivacyConstraint(PrivacyLevel.Private)); } @Test public void generalOnlyRBindPrivateAggregation2Test(){ generalOnlyRBindTest(new PrivacyConstraint(), new PrivacyConstraint(PrivacyLevel.PrivateAggregation)); } @Test public void generalOnlyRBindPrivatePrivateTest(){ generalOnlyRBindTest(new PrivacyConstraint(PrivacyLevel.Private), new PrivacyConstraint(PrivacyLevel.Private)); } @Test public void generalOnlyRBindPrivatePrivateAggregationTest(){ generalOnlyRBindTest(new PrivacyConstraint(PrivacyLevel.Private), new PrivacyConstraint(PrivacyLevel.PrivateAggregation)); } @Test public void generalOnlyCBindPrivate1Test(){ generalOnlyCBindTest(new PrivacyConstraint(PrivacyLevel.Private), new PrivacyConstraint()); } @Test public void generalOnlyCBindPrivateAggregation1Test(){ generalOnlyCBindTest(new PrivacyConstraint(PrivacyLevel.PrivateAggregation), new PrivacyConstraint()); } @Test public void generalOnlyCBindNoneTest(){ generalOnlyCBindTest(new PrivacyConstraint(), new PrivacyConstraint()); } @Test public void generalOnlyCBindPrivate2Test(){ generalOnlyCBindTest(new PrivacyConstraint(), new PrivacyConstraint(PrivacyLevel.Private)); } @Test public void generalOnlyCBindPrivateAggregation2Test(){ generalOnlyCBindTest(new PrivacyConstraint(), new PrivacyConstraint(PrivacyLevel.PrivateAggregation)); } @Test public void generalOnlyCBindPrivatePrivateTest(){ generalOnlyCBindTest(new PrivacyConstraint(PrivacyLevel.Private), new PrivacyConstraint(PrivacyLevel.Private)); } @Test public void generalOnlyCBindPrivatePrivateAggregationTest(){ generalOnlyCBindTest(new PrivacyConstraint(PrivacyLevel.Private), new PrivacyConstraint(PrivacyLevel.PrivateAggregation)); } @Test public void generalOnlyListAppendPrivate1Test(){ generalOnlyListAppendTest(new PrivacyConstraint(PrivacyLevel.Private), new PrivacyConstraint()); } @Test public void generalOnlyListAppendPrivateAggregation1Test(){ generalOnlyCBindTest(new PrivacyConstraint(PrivacyLevel.PrivateAggregation), new PrivacyConstraint()); } @Test public void generalOnlyListAppendNoneTest(){ generalOnlyListAppendTest(new PrivacyConstraint(), new PrivacyConstraint()); } @Test public void generalOnlyListAppendPrivate2Test(){ generalOnlyListAppendTest(new PrivacyConstraint(), new PrivacyConstraint(PrivacyLevel.Private)); } @Test public void generalOnlyListAppendPrivateAggregation2Test(){ generalOnlyListAppendTest(new PrivacyConstraint(), new PrivacyConstraint(PrivacyLevel.PrivateAggregation)); } @Test public void generalOnlyListAppendPrivatePrivateTest(){ generalOnlyListAppendTest(new PrivacyConstraint(PrivacyLevel.Private), new PrivacyConstraint(PrivacyLevel.Private)); } @Test public void generalOnlyListAppendPrivatePrivateAggregationTest(){ generalOnlyListAppendTest(new PrivacyConstraint(PrivacyLevel.Private), new PrivacyConstraint(PrivacyLevel.PrivateAggregation)); } @Test public void generalOnlyListRemoveAppendPrivate1Test(){ generalOnlyListRemoveAppendTest(new PrivacyConstraint(PrivacyLevel.Private), new PrivacyConstraint(), PrivacyLevel.Private, PrivacyLevel.Private); } @Test public void generalOnlyListRemoveAppendPrivateAggregation1Test(){ generalOnlyListRemoveAppendTest(new PrivacyConstraint(PrivacyLevel.PrivateAggregation), new PrivacyConstraint(), PrivacyLevel.PrivateAggregation, PrivacyLevel.PrivateAggregation); } @Test public void generalOnlyListRemoveAppendNoneTest(){ generalOnlyListRemoveAppendTest(new PrivacyConstraint(), new PrivacyConstraint(), PrivacyLevel.None, PrivacyLevel.None); } @Test public void generalOnlyListRemoveAppendPrivate2Test(){ generalOnlyListRemoveAppendTest(new PrivacyConstraint(), new PrivacyConstraint(PrivacyLevel.Private), PrivacyLevel.Private, PrivacyLevel.Private); } @Test public void generalOnlyListRemoveAppendPrivateAggregation2Test(){ generalOnlyListRemoveAppendTest(new PrivacyConstraint(), new PrivacyConstraint(PrivacyLevel.PrivateAggregation), PrivacyLevel.PrivateAggregation, PrivacyLevel.PrivateAggregation); } @Test public void generalOnlyListRemoveAppendPrivatePrivateTest(){ generalOnlyListRemoveAppendTest(new PrivacyConstraint(PrivacyLevel.Private), new PrivacyConstraint(PrivacyLevel.Private), PrivacyLevel.Private, PrivacyLevel.Private); } @Test public void generalOnlyListRemoveAppendPrivatePrivateAggregationTest(){ generalOnlyListRemoveAppendTest(new PrivacyConstraint(PrivacyLevel.Private), new PrivacyConstraint(PrivacyLevel.PrivateAggregation), PrivacyLevel.Private, PrivacyLevel.Private); } @Test public void finegrainedRBindPrivate1(){ PrivacyConstraint constraint1 = new PrivacyConstraint(); constraint1.getFineGrainedPrivacy().put(new DataRange(new long[]{1,0},new long[]{1,1}), PrivacyLevel.Private); PrivacyConstraint constraint2 = new PrivacyConstraint(); finegrainedRBindTest(constraint1, constraint2); } @Test public void finegrainedRBindPrivateAndPrivateAggregate1(){ PrivacyConstraint constraint1 = new PrivacyConstraint(); constraint1.getFineGrainedPrivacy().put(new DataRange(new long[]{1,0},new long[]{1,1}), PrivacyLevel.Private); constraint1.getFineGrainedPrivacy().put(new DataRange(new long[]{2,0},new long[]{3,1}), PrivacyLevel.PrivateAggregation); PrivacyConstraint constraint2 = new PrivacyConstraint(); finegrainedRBindTest(constraint1, constraint2); } @Test public void finegrainedRBindPrivate2(){ PrivacyConstraint constraint1 = new PrivacyConstraint(); PrivacyConstraint constraint2 = new PrivacyConstraint(); constraint2.getFineGrainedPrivacy().put(new DataRange(new long[]{1,0},new long[]{1,1}), PrivacyLevel.Private); finegrainedRBindTest(constraint1, constraint2); } @Test public void finegrainedRBindPrivateAndPrivateAggregate2(){ PrivacyConstraint constraint1 = new PrivacyConstraint(); PrivacyConstraint constraint2 = new PrivacyConstraint(); constraint2.getFineGrainedPrivacy().put(new DataRange(new long[]{1,0},new long[]{1,1}), PrivacyLevel.Private); constraint2.getFineGrainedPrivacy().put(new DataRange(new long[]{2,0},new long[]{3,1}), PrivacyLevel.PrivateAggregation); finegrainedRBindTest(constraint1, constraint2); } @Test public void finegrainedRBindPrivate12(){ PrivacyConstraint constraint1 = new PrivacyConstraint(); constraint1.getFineGrainedPrivacy().put(new DataRange(new long[]{1,0},new long[]{1,1}), PrivacyLevel.Private); PrivacyConstraint constraint2 = new PrivacyConstraint(); constraint2.getFineGrainedPrivacy().put(new DataRange(new long[]{1,0},new long[]{1,1}), PrivacyLevel.Private); finegrainedRBindTest(constraint1, constraint2); } @Test public void finegrainedRBindPrivateAndPrivateAggregate12(){ PrivacyConstraint constraint1 = new PrivacyConstraint(); constraint1.getFineGrainedPrivacy().put(new DataRange(new long[]{0,0},new long[]{0,1}), PrivacyLevel.Private); constraint1.getFineGrainedPrivacy().put(new DataRange(new long[]{2,0},new long[]{3,1}), PrivacyLevel.PrivateAggregation); PrivacyConstraint constraint2 = new PrivacyConstraint(); constraint2.getFineGrainedPrivacy().put(new DataRange(new long[]{0,0},new long[]{0,1}), PrivacyLevel.Private); constraint2.getFineGrainedPrivacy().put(new DataRange(new long[]{1,0},new long[]{2,0}), PrivacyLevel.PrivateAggregation); finegrainedRBindTest(constraint1, constraint2); } @Test public void finegrainedCBindPrivate1(){ PrivacyConstraint constraint1 = new PrivacyConstraint(); constraint1.getFineGrainedPrivacy().put(new DataRange(new long[]{1,0},new long[]{1,1}), PrivacyLevel.Private); PrivacyConstraint constraint2 = new PrivacyConstraint(); finegrainedCBindTest(constraint1, constraint2); } @Test public void finegrainedCBindPrivateAndPrivateAggregate1(){ PrivacyConstraint constraint1 = new PrivacyConstraint(); constraint1.getFineGrainedPrivacy().put(new DataRange(new long[]{1,0},new long[]{1,1}), PrivacyLevel.Private); constraint1.getFineGrainedPrivacy().put(new DataRange(new long[]{2,0},new long[]{3,1}), PrivacyLevel.PrivateAggregation); PrivacyConstraint constraint2 = new PrivacyConstraint(); finegrainedCBindTest(constraint1, constraint2); } @Test public void finegrainedCBindPrivate2(){ PrivacyConstraint constraint1 = new PrivacyConstraint(); PrivacyConstraint constraint2 = new PrivacyConstraint(); constraint2.getFineGrainedPrivacy().put(new DataRange(new long[]{1,0},new long[]{1,1}), PrivacyLevel.Private); finegrainedCBindTest(constraint1, constraint2); } @Test public void finegrainedCBindPrivateAndPrivateAggregate2(){ PrivacyConstraint constraint1 = new PrivacyConstraint(); PrivacyConstraint constraint2 = new PrivacyConstraint(); constraint2.getFineGrainedPrivacy().put(new DataRange(new long[]{1,0},new long[]{1,1}), PrivacyLevel.Private); constraint2.getFineGrainedPrivacy().put(new DataRange(new long[]{2,0},new long[]{3,1}), PrivacyLevel.PrivateAggregation); finegrainedCBindTest(constraint1, constraint2); } @Test public void finegrainedCBindPrivate12(){ PrivacyConstraint constraint1 = new PrivacyConstraint(); constraint1.getFineGrainedPrivacy().put(new DataRange(new long[]{1,0},new long[]{1,1}), PrivacyLevel.Private); PrivacyConstraint constraint2 = new PrivacyConstraint(); constraint2.getFineGrainedPrivacy().put(new DataRange(new long[]{1,0},new long[]{1,1}), PrivacyLevel.Private); finegrainedCBindTest(constraint1, constraint2); } @Test public void finegrainedCBindPrivateAndPrivateAggregate12(){ PrivacyConstraint constraint1 = new PrivacyConstraint(); constraint1.getFineGrainedPrivacy().put(new DataRange(new long[]{0,0},new long[]{0,1}), PrivacyLevel.Private); constraint1.getFineGrainedPrivacy().put(new DataRange(new long[]{2,0},new long[]{3,1}), PrivacyLevel.PrivateAggregation); PrivacyConstraint constraint2 = new PrivacyConstraint(); constraint2.getFineGrainedPrivacy().put(new DataRange(new long[]{0,0},new long[]{0,1}), PrivacyLevel.Private); constraint2.getFineGrainedPrivacy().put(new DataRange(new long[]{1,0},new long[]{2,0}), PrivacyLevel.PrivateAggregation); finegrainedCBindTest(constraint1, constraint2); } @Test public void finegrainedListAppendPrivate1(){ PrivacyConstraint constraint1 = new PrivacyConstraint(); constraint1.getFineGrainedPrivacy().put(new DataRange(new long[]{1},new long[]{2}), PrivacyLevel.Private); PrivacyConstraint constraint2 = new PrivacyConstraint(); finegrainedListAppendTest(constraint1, constraint2); } @Test public void finegrainedListAppendPrivateAndPrivateAggregate1(){ PrivacyConstraint constraint1 = new PrivacyConstraint(); constraint1.getFineGrainedPrivacy().put(new DataRange(new long[]{1},new long[]{2}), PrivacyLevel.Private); constraint1.getFineGrainedPrivacy().put(new DataRange(new long[]{3},new long[]{5}), PrivacyLevel.PrivateAggregation); PrivacyConstraint constraint2 = new PrivacyConstraint(); finegrainedListAppendTest(constraint1, constraint2); } @Test public void finegrainedListAppendPrivate2(){ PrivacyConstraint constraint1 = new PrivacyConstraint(); PrivacyConstraint constraint2 = new PrivacyConstraint(); constraint2.getFineGrainedPrivacy().put(new DataRange(new long[]{1},new long[]{2}), PrivacyLevel.Private); finegrainedListAppendTest(constraint1, constraint2); } @Test public void finegrainedListAppendPrivateAndPrivateAggregate2(){ PrivacyConstraint constraint1 = new PrivacyConstraint(); PrivacyConstraint constraint2 = new PrivacyConstraint(); constraint2.getFineGrainedPrivacy().put(new DataRange(new long[]{1},new long[]{2}), PrivacyLevel.Private); constraint2.getFineGrainedPrivacy().put(new DataRange(new long[]{3},new long[]{5}), PrivacyLevel.PrivateAggregation); finegrainedListAppendTest(constraint1, constraint2); } @Test public void finegrainedListAppendPrivate12(){ PrivacyConstraint constraint1 = new PrivacyConstraint(); constraint1.getFineGrainedPrivacy().put(new DataRange(new long[]{1},new long[]{2}), PrivacyLevel.Private); PrivacyConstraint constraint2 = new PrivacyConstraint(); constraint2.getFineGrainedPrivacy().put(new DataRange(new long[]{1},new long[]{4}), PrivacyLevel.Private); finegrainedListAppendTest(constraint1, constraint2); } @Test public void finegrainedListAppendPrivateAndPrivateAggregate12(){ PrivacyConstraint constraint1 = new PrivacyConstraint(); constraint1.getFineGrainedPrivacy().put(new DataRange(new long[]{0},new long[]{0}), PrivacyLevel.Private); constraint1.getFineGrainedPrivacy().put(new DataRange(new long[]{2},new long[]{3}), PrivacyLevel.PrivateAggregation); PrivacyConstraint constraint2 = new PrivacyConstraint(); constraint2.getFineGrainedPrivacy().put(new DataRange(new long[]{0},new long[]{1}), PrivacyLevel.Private); constraint2.getFineGrainedPrivacy().put(new DataRange(new long[]{3},new long[]{5}), PrivacyLevel.PrivateAggregation); finegrainedListAppendTest(constraint1, constraint2); } @Test public void testFunction(){ int dataLength = 9; List<Data> dataList = new ArrayList<>(); for ( int i = 0; i < dataLength; i++) dataList.add(new DoubleObject(i)); ListObject l = new ListObject(dataList); ListObject lCopy = l.copy(); int position = 4; ListObject output = l.remove(position); Assert.assertEquals(lCopy.getData(position), output.getData().get(0)); } @Test public void finegrainedListRemoveAppendNone1(){ PrivacyConstraint constraint1 = new PrivacyConstraint(); constraint1.getFineGrainedPrivacy().put(new DataRange(new long[]{1},new long[]{2}), PrivacyLevel.Private); PrivacyConstraint constraint2 = new PrivacyConstraint(); finegrainedListRemoveAppendTest(constraint1, constraint2, PrivacyLevel.None); } @Test public void finegrainedListRemoveAppendPrivate1(){ PrivacyConstraint constraint1 = new PrivacyConstraint(); constraint1.getFineGrainedPrivacy().put(new DataRange(new long[]{1},new long[]{6}), PrivacyLevel.Private); PrivacyConstraint constraint2 = new PrivacyConstraint(); finegrainedListRemoveAppendTest(constraint1, constraint2, PrivacyLevel.Private); } @Test public void finegrainedListRemoveAppendPrivate2(){ PrivacyConstraint constraint1 = new PrivacyConstraint(); constraint1.getFineGrainedPrivacy().put(new DataRange(new long[]{1},new long[]{6}), PrivacyLevel.Private); PrivacyConstraint constraint2 = new PrivacyConstraint(PrivacyLevel.PrivateAggregation); finegrainedListRemoveAppendTest(constraint1, constraint2, PrivacyLevel.Private); } @Test public void finegrainedListRemoveAppendPrivate3(){ PrivacyConstraint constraint1 = new PrivacyConstraint(PrivacyLevel.Private); constraint1.getFineGrainedPrivacy().put(new DataRange(new long[]{1},new long[]{6}), PrivacyLevel.PrivateAggregation); PrivacyConstraint constraint2 = new PrivacyConstraint(); finegrainedListRemoveAppendTest(constraint1, constraint2, PrivacyLevel.Private); } @Test public void finegrainedListRemoveAppendPrivate4(){ PrivacyConstraint constraint1 = new PrivacyConstraint(PrivacyLevel.PrivateAggregation); constraint1.getFineGrainedPrivacy().put(new DataRange(new long[]{4},new long[]{4}), PrivacyLevel.Private); PrivacyConstraint constraint2 = new PrivacyConstraint(); finegrainedListRemoveAppendTest(constraint1, constraint2, PrivacyLevel.Private, true); } @Test public void finegrainedListRemoveAppendPrivateAndPrivateAggregate1(){ PrivacyConstraint constraint1 = new PrivacyConstraint(); constraint1.getFineGrainedPrivacy().put(new DataRange(new long[]{1},new long[]{2}), PrivacyLevel.Private); constraint1.getFineGrainedPrivacy().put(new DataRange(new long[]{3},new long[]{5}), PrivacyLevel.PrivateAggregation); PrivacyConstraint constraint2 = new PrivacyConstraint(); finegrainedListRemoveAppendTest(constraint1, constraint2, PrivacyLevel.PrivateAggregation); } @Test public void finegrainedListRemoveAppendPrivateAggregate2(){ PrivacyConstraint constraint1 = new PrivacyConstraint(PrivacyLevel.PrivateAggregation); constraint1.getFineGrainedPrivacy().put(new DataRange(new long[]{5},new long[]{8}), PrivacyLevel.Private); PrivacyConstraint constraint2 = new PrivacyConstraint(); finegrainedListRemoveAppendTest(constraint1, constraint2, PrivacyLevel.PrivateAggregation); } @Test public void integrationRBindTestNoneNone(){ PrivacyConstraint pc1 = new PrivacyConstraint(PrivacyLevel.None); PrivacyConstraint pc2 = new PrivacyConstraint(PrivacyLevel.None); PrivacyConstraint pcExpected = new PrivacyConstraint(PrivacyLevel.None); integrationRBindTest(pc1, pc2, pcExpected); } @Test public void integrationRBindTestPrivateNone(){ PrivacyConstraint pc1 = new PrivacyConstraint(PrivacyLevel.Private); PrivacyConstraint pc2 = new PrivacyConstraint(PrivacyLevel.None); PrivacyConstraint pcExpected = new PrivacyConstraint(); pcExpected.getFineGrainedPrivacy().put(new DataRange(new long[]{0,0}, new long[]{19,9}), PrivacyLevel.Private); integrationRBindTest(pc1, pc2, pcExpected); } @Test public void integrationRBindTestPrivateAggregateNone(){ PrivacyConstraint pc1 = new PrivacyConstraint(PrivacyLevel.PrivateAggregation); PrivacyConstraint pc2 = new PrivacyConstraint(PrivacyLevel.None); PrivacyConstraint pcExpected = new PrivacyConstraint(); pcExpected.getFineGrainedPrivacy().put(new DataRange(new long[]{0,0}, new long[]{19,9}), PrivacyLevel.PrivateAggregation); integrationRBindTest(pc1, pc2, pcExpected); } @Test public void integrationRBindTestNonePrivateAggregate(){ PrivacyConstraint pc1 = new PrivacyConstraint(PrivacyLevel.None); PrivacyConstraint pc2 = new PrivacyConstraint(PrivacyLevel.PrivateAggregation); PrivacyConstraint pcExpected = new PrivacyConstraint(); pcExpected.getFineGrainedPrivacy().put(new DataRange(new long[]{20,0}, new long[]{49, 9}), PrivacyLevel.PrivateAggregation); integrationRBindTest(pc1, pc2, pcExpected); } @Test public void integrationRBindTestNonePrivate(){ PrivacyConstraint pc1 = new PrivacyConstraint(PrivacyLevel.None); PrivacyConstraint pc2 = new PrivacyConstraint(PrivacyLevel.Private); PrivacyConstraint pcExpected = new PrivacyConstraint(); pcExpected.getFineGrainedPrivacy().put(new DataRange(new long[]{20,0}, new long[]{49, 9}), PrivacyLevel.Private); integrationRBindTest(pc1, pc2, pcExpected); } @Test public void integrationFinegrainedRBindPrivate1(){ PrivacyConstraint constraint1 = new PrivacyConstraint(); constraint1.getFineGrainedPrivacy().put(new DataRange(new long[]{1,0},new long[]{1,1}), PrivacyLevel.Private); PrivacyConstraint constraint2 = new PrivacyConstraint(); integrationRBindTest(constraint1, constraint2, constraint1); } @Test public void integrationFinegrainedRBindPrivateAndPrivateAggregate1(){ PrivacyConstraint constraint1 = new PrivacyConstraint(); constraint1.getFineGrainedPrivacy().put(new DataRange(new long[]{1,0},new long[]{1,1}), PrivacyLevel.Private); constraint1.getFineGrainedPrivacy().put(new DataRange(new long[]{2,0},new long[]{3,1}), PrivacyLevel.PrivateAggregation); PrivacyConstraint constraint2 = new PrivacyConstraint(); integrationRBindTest(constraint1, constraint2, constraint1); } @Test public void integrationFinegrainedRBindPrivate2(){ PrivacyConstraint constraint1 = new PrivacyConstraint(); PrivacyConstraint constraint2 = new PrivacyConstraint(); constraint2.getFineGrainedPrivacy().put(new DataRange(new long[]{1,0},new long[]{1,1}), PrivacyLevel.Private); PrivacyConstraint pcExcepted = new PrivacyConstraint(); pcExcepted.getFineGrainedPrivacy().put(new DataRange(new long[]{21,0}, new long[]{21,1}), PrivacyLevel.Private); integrationRBindTest(constraint1, constraint2, pcExcepted); } @Test public void integrationFinegrainedRBindPrivateAndPrivateAggregate2(){ PrivacyConstraint constraint1 = new PrivacyConstraint(); PrivacyConstraint constraint2 = new PrivacyConstraint(); constraint2.getFineGrainedPrivacy().put(new DataRange(new long[]{1,0},new long[]{1,1}), PrivacyLevel.Private); constraint2.getFineGrainedPrivacy().put(new DataRange(new long[]{2,0},new long[]{3,1}), PrivacyLevel.PrivateAggregation); PrivacyConstraint pcExcepted = new PrivacyConstraint(); pcExcepted.getFineGrainedPrivacy().put(new DataRange(new long[]{21,0},new long[]{21,1}), PrivacyLevel.Private); pcExcepted.getFineGrainedPrivacy().put(new DataRange(new long[]{22,0}, new long[]{23,1}), PrivacyLevel.PrivateAggregation); integrationRBindTest(constraint1, constraint2, pcExcepted); } @Test public void integrationFinegrainedRBindPrivate12(){ PrivacyConstraint constraint1 = new PrivacyConstraint(); constraint1.getFineGrainedPrivacy().put(new DataRange(new long[]{1,0},new long[]{1,1}), PrivacyLevel.Private); PrivacyConstraint constraint2 = new PrivacyConstraint(); constraint2.getFineGrainedPrivacy().put(new DataRange(new long[]{1,0},new long[]{1,1}), PrivacyLevel.Private); PrivacyConstraint pcExpected = new PrivacyConstraint(); pcExpected.getFineGrainedPrivacy().put(new DataRange(new long[]{1,0},new long[]{1,1}), PrivacyLevel.Private); pcExpected.getFineGrainedPrivacy().put(new DataRange(new long[]{21,0},new long[]{21,1}), PrivacyLevel.Private); integrationRBindTest(constraint1, constraint2, pcExpected); } @Test public void integrationFinegrainedRBindPrivateAndPrivateAggregate12(){ PrivacyConstraint constraint1 = new PrivacyConstraint(); constraint1.getFineGrainedPrivacy().put(new DataRange(new long[]{0,0},new long[]{0,1}), PrivacyLevel.Private); constraint1.getFineGrainedPrivacy().put(new DataRange(new long[]{2,0},new long[]{3,1}), PrivacyLevel.PrivateAggregation); PrivacyConstraint constraint2 = new PrivacyConstraint(); constraint2.getFineGrainedPrivacy().put(new DataRange(new long[]{0,0},new long[]{0,1}), PrivacyLevel.Private); constraint2.getFineGrainedPrivacy().put(new DataRange(new long[]{1,0},new long[]{2,0}), PrivacyLevel.PrivateAggregation); PrivacyConstraint pcExpected = new PrivacyConstraint(); pcExpected.getFineGrainedPrivacy().put(new DataRange(new long[]{0,0},new long[]{0,1}), PrivacyLevel.Private); pcExpected.getFineGrainedPrivacy().put(new DataRange(new long[]{20,0},new long[]{20,1}), PrivacyLevel.Private); pcExpected.getFineGrainedPrivacy().put(new DataRange(new long[]{2,0}, new long[]{3,1}), PrivacyLevel.PrivateAggregation); pcExpected.getFineGrainedPrivacy().put(new DataRange(new long[]{21,0}, new long[]{22,0}), PrivacyLevel.PrivateAggregation); integrationRBindTest(constraint1, constraint2, pcExpected); } private void integrationRBindTest(PrivacyConstraint privacyConstraint1, PrivacyConstraint privacyConstraint2, PrivacyConstraint expectedOutput){ TestConfiguration config = getAndLoadTestConfiguration(TEST_NAME_RBIND); fullDMLScriptName = SCRIPT_DIR + TEST_DIR + config.getTestScript() + ".dml"; int rows1 = 20; int rows2 = 30; int cols = 10; double[][] A = getRandomMatrix(rows1, cols, -10, 10, 0.5, 1); double[][] B = getRandomMatrix(rows2, cols, -10, 10, 0.5, 1); writeInputMatrixWithMTD("A", A, false, new MatrixCharacteristics(rows1, cols), privacyConstraint1); writeInputMatrixWithMTD("B", B, false, new MatrixCharacteristics(rows2, cols), privacyConstraint2); programArgs = new String[]{"-nvargs", "A=" + input("A"), "B=" + input("B"), "C=" + output("C")}; runTest(true,false,null,-1); PrivacyConstraint outputConstraint = getPrivacyConstraintFromMetaData("C"); Assert.assertEquals(expectedOutput, outputConstraint); } @Test public void integrationCBindTestNoneNone(){ PrivacyConstraint pc1 = new PrivacyConstraint(PrivacyLevel.None); PrivacyConstraint pc2 = new PrivacyConstraint(PrivacyLevel.None); PrivacyConstraint pcExpected = new PrivacyConstraint(PrivacyLevel.None); integrationCBindTest(pc1, pc2, pcExpected); } @Test public void integrationCBindTestPrivateNone(){ PrivacyConstraint pc1 = new PrivacyConstraint(PrivacyLevel.Private); PrivacyConstraint pc2 = new PrivacyConstraint(PrivacyLevel.None); PrivacyConstraint pcExpected = new PrivacyConstraint(); pcExpected.getFineGrainedPrivacy().put(new DataRange(new long[]{0,0}, new long[]{9,19}), PrivacyLevel.Private); integrationCBindTest(pc1, pc2, pcExpected); } @Test public void integrationCBindTestPrivateAggregateNone(){ PrivacyConstraint pc1 = new PrivacyConstraint(PrivacyLevel.PrivateAggregation); PrivacyConstraint pc2 = new PrivacyConstraint(PrivacyLevel.None); PrivacyConstraint pcExpected = new PrivacyConstraint(); pcExpected.getFineGrainedPrivacy().put(new DataRange(new long[]{0,0}, new long[]{9,19}), PrivacyLevel.PrivateAggregation); integrationCBindTest(pc1, pc2, pcExpected); } @Test public void integrationCBindTestNonePrivateAggregate(){ PrivacyConstraint pc1 = new PrivacyConstraint(PrivacyLevel.None); PrivacyConstraint pc2 = new PrivacyConstraint(PrivacyLevel.PrivateAggregation); PrivacyConstraint pcExpected = new PrivacyConstraint(); pcExpected.getFineGrainedPrivacy().put(new DataRange(new long[]{0,20}, new long[]{9, 49}), PrivacyLevel.PrivateAggregation); integrationCBindTest(pc1, pc2, pcExpected); } @Test public void integrationCBindTestNonePrivate(){ PrivacyConstraint pc1 = new PrivacyConstraint(PrivacyLevel.None); PrivacyConstraint pc2 = new PrivacyConstraint(PrivacyLevel.Private); PrivacyConstraint pcExpected = new PrivacyConstraint(); pcExpected.getFineGrainedPrivacy().put(new DataRange(new long[]{0,20}, new long[]{9, 49}), PrivacyLevel.Private); integrationCBindTest(pc1, pc2, pcExpected); } @Test public void integrationFinegrainedCBindPrivate1(){ PrivacyConstraint constraint1 = new PrivacyConstraint(); constraint1.getFineGrainedPrivacy().put(new DataRange(new long[]{1,0},new long[]{1,1}), PrivacyLevel.Private); PrivacyConstraint constraint2 = new PrivacyConstraint(); integrationCBindTest(constraint1, constraint2, constraint1); } @Test public void integrationFinegrainedCBindPrivateAndPrivateAggregate1(){ PrivacyConstraint constraint1 = new PrivacyConstraint(); constraint1.getFineGrainedPrivacy().put(new DataRange(new long[]{1,0},new long[]{1,1}), PrivacyLevel.Private); constraint1.getFineGrainedPrivacy().put(new DataRange(new long[]{2,0},new long[]{3,1}), PrivacyLevel.PrivateAggregation); PrivacyConstraint constraint2 = new PrivacyConstraint(); integrationCBindTest(constraint1, constraint2, constraint1); } @Test public void integrationFinegrainedCBindPrivate2(){ PrivacyConstraint constraint1 = new PrivacyConstraint(); PrivacyConstraint constraint2 = new PrivacyConstraint(); constraint2.getFineGrainedPrivacy().put(new DataRange(new long[]{1,0},new long[]{1,1}), PrivacyLevel.Private); PrivacyConstraint pcExcepted = new PrivacyConstraint(); pcExcepted.getFineGrainedPrivacy().put(new DataRange(new long[]{1,20}, new long[]{1,21}), PrivacyLevel.Private); integrationCBindTest(constraint1, constraint2, pcExcepted); } @Test public void integrationFinegrainedCBindPrivateAndPrivateAggregate2(){ PrivacyConstraint constraint1 = new PrivacyConstraint(); PrivacyConstraint constraint2 = new PrivacyConstraint(); constraint2.getFineGrainedPrivacy().put(new DataRange(new long[]{1,0},new long[]{1,1}), PrivacyLevel.Private); constraint2.getFineGrainedPrivacy().put(new DataRange(new long[]{2,0},new long[]{3,1}), PrivacyLevel.PrivateAggregation); PrivacyConstraint pcExcepted = new PrivacyConstraint(); pcExcepted.getFineGrainedPrivacy().put(new DataRange(new long[]{1,20},new long[]{1,21}), PrivacyLevel.Private); pcExcepted.getFineGrainedPrivacy().put(new DataRange(new long[]{2,20}, new long[]{3,21}), PrivacyLevel.PrivateAggregation); integrationCBindTest(constraint1, constraint2, pcExcepted); } @Test public void integrationFinegrainedCBindPrivate12(){ PrivacyConstraint constraint1 = new PrivacyConstraint(); constraint1.getFineGrainedPrivacy().put(new DataRange(new long[]{1,0},new long[]{1,1}), PrivacyLevel.Private); PrivacyConstraint constraint2 = new PrivacyConstraint(); constraint2.getFineGrainedPrivacy().put(new DataRange(new long[]{1,0},new long[]{1,1}), PrivacyLevel.Private); PrivacyConstraint pcExpected = new PrivacyConstraint(); pcExpected.getFineGrainedPrivacy().put(new DataRange(new long[]{1,0},new long[]{1,1}), PrivacyLevel.Private); pcExpected.getFineGrainedPrivacy().put(new DataRange(new long[]{1,20},new long[]{1,21}), PrivacyLevel.Private); integrationCBindTest(constraint1, constraint2, pcExpected); } @Test public void integrationFinegrainedCBindPrivateAndPrivateAggregate12(){ PrivacyConstraint constraint1 = new PrivacyConstraint(); constraint1.getFineGrainedPrivacy().put(new DataRange(new long[]{0,0},new long[]{0,1}), PrivacyLevel.Private); constraint1.getFineGrainedPrivacy().put(new DataRange(new long[]{2,0},new long[]{3,1}), PrivacyLevel.PrivateAggregation); PrivacyConstraint constraint2 = new PrivacyConstraint(); constraint2.getFineGrainedPrivacy().put(new DataRange(new long[]{0,0},new long[]{0,1}), PrivacyLevel.Private); constraint2.getFineGrainedPrivacy().put(new DataRange(new long[]{1,0},new long[]{2,0}), PrivacyLevel.PrivateAggregation); PrivacyConstraint pcExpected = new PrivacyConstraint(); pcExpected.getFineGrainedPrivacy().put(new DataRange(new long[]{0,0},new long[]{0,1}), PrivacyLevel.Private); pcExpected.getFineGrainedPrivacy().put(new DataRange(new long[]{0,20},new long[]{0,21}), PrivacyLevel.Private); pcExpected.getFineGrainedPrivacy().put(new DataRange(new long[]{2,0}, new long[]{3,1}), PrivacyLevel.PrivateAggregation); pcExpected.getFineGrainedPrivacy().put(new DataRange(new long[]{1,20}, new long[]{2,20}), PrivacyLevel.PrivateAggregation); integrationCBindTest(constraint1, constraint2, pcExpected); } @Test public void integrationStringAppendTestNoneNone(){ PrivacyConstraint pc1 = new PrivacyConstraint(PrivacyLevel.None); PrivacyConstraint pc2 = new PrivacyConstraint(PrivacyLevel.None); integrationStringAppendTest(pc1, pc2, pc1); } @Test public void integrationStringAppendTestPrivateNone(){ PrivacyConstraint pc1 = new PrivacyConstraint(PrivacyLevel.Private); PrivacyConstraint pc2 = new PrivacyConstraint(PrivacyLevel.None); integrationStringAppendTest(pc1, pc2, pc1); } @Test public void integrationStringAppendTestPrivateAggregateNone(){ PrivacyConstraint pc1 = new PrivacyConstraint(PrivacyLevel.PrivateAggregation); PrivacyConstraint pc2 = new PrivacyConstraint(PrivacyLevel.None); integrationStringAppendTest(pc1, pc2, pc1); } @Test public void integrationStringAppendTestNonePrivateAggregate(){ PrivacyConstraint pc1 = new PrivacyConstraint(PrivacyLevel.None); PrivacyConstraint pc2 = new PrivacyConstraint(PrivacyLevel.PrivateAggregation); integrationStringAppendTest(pc1, pc2, pc2); } @Test public void integrationStringAppendTestNonePrivate(){ PrivacyConstraint pc1 = new PrivacyConstraint(PrivacyLevel.None); PrivacyConstraint pc2 = new PrivacyConstraint(PrivacyLevel.Private); integrationStringAppendTest(pc1, pc2, pc2); } @Ignore @Test public void integrationListAppendTestNoneNone(){ PrivacyConstraint pc1 = new PrivacyConstraint(PrivacyLevel.None); PrivacyConstraint pc2 = new PrivacyConstraint(PrivacyLevel.None); integrationListAppendTest(pc1, pc2, pc1); } @Ignore @Test public void integrationListAppendTestPrivateNone(){ PrivacyConstraint pc1 = new PrivacyConstraint(PrivacyLevel.Private); PrivacyConstraint pc2 = new PrivacyConstraint(PrivacyLevel.None); PrivacyConstraint pcExpected = new PrivacyConstraint(); pcExpected.getFineGrainedPrivacy().put(new DataRange(new long[]{0}, new long[]{0}), PrivacyLevel.Private); integrationListAppendTest(pc1, pc2, pcExpected); } @Ignore @Test public void integrationListAppendTestPrivateAggregateNone(){ PrivacyConstraint pc1 = new PrivacyConstraint(PrivacyLevel.PrivateAggregation); PrivacyConstraint pc2 = new PrivacyConstraint(PrivacyLevel.None); integrationListAppendTest(pc1, pc2, pc1); } @Ignore @Test public void integrationListAppendTestNonePrivateAggregate(){ PrivacyConstraint pc1 = new PrivacyConstraint(PrivacyLevel.None); PrivacyConstraint pc2 = new PrivacyConstraint(PrivacyLevel.PrivateAggregation); integrationListAppendTest(pc1, pc2, pc2); } @Ignore @Test public void integrationListAppendTestNonePrivate(){ PrivacyConstraint pc1 = new PrivacyConstraint(PrivacyLevel.None); PrivacyConstraint pc2 = new PrivacyConstraint(PrivacyLevel.Private); integrationListAppendTest(pc1, pc2, pc2); } private static void generalOnlyRBindTest(PrivacyConstraint constraint1, PrivacyConstraint constraint2){ int columns = 2; int rows1 = 4; int rows2 = 3; MatrixBlock inputMatrix1 = new MatrixBlock(rows1,columns,3); MatrixBlock inputMatrix2 = new MatrixBlock(rows2,columns,4); AppendPropagator propagator = new RBindPropagator(inputMatrix1, constraint1, inputMatrix2, constraint2); PrivacyConstraint mergedConstraint = propagator.propagate(); Assert.assertEquals(mergedConstraint.getPrivacyLevel(), PrivacyLevel.None); Map<DataRange, PrivacyLevel> firstHalfPrivacy = mergedConstraint.getFineGrainedPrivacy().getPrivacyLevel( new DataRange(new long[]{0,0}, new long[]{rows1-1,columns-1})); firstHalfPrivacy.forEach((range,level) -> Assert.assertEquals(constraint1.getPrivacyLevel(),level)); Map<DataRange, PrivacyLevel> secondHalfPrivacy = mergedConstraint.getFineGrainedPrivacy().getPrivacyLevel( new DataRange(new long[]{rows1,0}, new long[]{rows1+rows2-1,columns-1})); secondHalfPrivacy.forEach((range,level) -> Assert.assertEquals(constraint2.getPrivacyLevel(),level)); } private static void generalOnlyCBindTest(PrivacyConstraint constraint1, PrivacyConstraint constraint2){ int rows = 2; int columns1 = 4; int columns2 = 3; MatrixBlock inputMatrix1 = new MatrixBlock(rows,columns1,3); MatrixBlock inputMatrix2 = new MatrixBlock(rows,columns2,4); AppendPropagator propagator = new CBindPropagator(inputMatrix1, constraint1, inputMatrix2, constraint2); PrivacyConstraint mergedConstraint = propagator.propagate(); Assert.assertEquals(mergedConstraint.getPrivacyLevel(), PrivacyLevel.None); Map<DataRange, PrivacyLevel> firstHalfPrivacy = mergedConstraint.getFineGrainedPrivacy().getPrivacyLevel( new DataRange(new long[]{0,0}, new long[]{rows-1,columns1-1})); firstHalfPrivacy.forEach((range,level) -> Assert.assertEquals(constraint1.getPrivacyLevel(),level)); Map<DataRange, PrivacyLevel> secondHalfPrivacy = mergedConstraint.getFineGrainedPrivacy().getPrivacyLevel( new DataRange(new long[]{0,columns1}, new long[]{rows,columns1+columns2-1})); secondHalfPrivacy.forEach((range,level) -> Assert.assertEquals(constraint2.getPrivacyLevel(),level)); } private static void generalOnlyListAppendTest(PrivacyConstraint constraint1, PrivacyConstraint constraint2){ int length1 = 6; List<Data> dataList1 = Arrays.asList(new Data[length1]); ListObject input1 = new ListObject(dataList1); int length2 = 11; List<Data> dataList2 = Arrays.asList(new Data[length2]); ListObject input2 = new ListObject(dataList2); Propagator propagator = new ListAppendPropagator(input1, constraint1, input2, constraint2); PrivacyConstraint mergedConstraint = propagator.propagate(); Map<DataRange, PrivacyLevel> firstHalfPrivacy = mergedConstraint.getFineGrainedPrivacy().getPrivacyLevel( new DataRange(new long[]{0}, new long[]{length1-1}) ); firstHalfPrivacy.forEach((range,level) -> Assert.assertEquals(constraint1.getPrivacyLevel(),level)); Map<DataRange, PrivacyLevel> secondHalfPrivacy = mergedConstraint.getFineGrainedPrivacy().getPrivacyLevel( new DataRange(new long[length1], new long[]{length1+length2-1}) ); secondHalfPrivacy.forEach((range,level) -> Assert.assertEquals(constraint2.getPrivacyLevel(),level)); } private static void generalOnlyListRemoveAppendTest( PrivacyConstraint constraint1, PrivacyConstraint constraint2, PrivacyLevel expected1, PrivacyLevel expected2){ int dataLength = 9; List<Data> dataList = new ArrayList<>(); for ( int i = 0; i < dataLength; i++){ dataList.add(new DoubleObject(i)); } ListObject inputList = new ListObject(dataList); int removePositionInt = 5; ScalarObject removePosition = new IntObject(removePositionInt); PropagatorMultiReturn propagator = new ListRemovePropagator(inputList, constraint1, removePosition, constraint2); PrivacyConstraint[] mergedConstraints = propagator.propagate(); Assert.assertEquals(expected1, mergedConstraints[0].getPrivacyLevel()); Assert.assertEquals(expected2, mergedConstraints[1].getPrivacyLevel()); Assert.assertFalse("The first output constraint should have no fine-grained constraints", mergedConstraints[0].hasFineGrainedConstraints()); Assert.assertFalse("The second output constraint should have no fine-grained constraints", mergedConstraints[1].hasFineGrainedConstraints()); } private static void finegrainedRBindTest(PrivacyConstraint constraint1, PrivacyConstraint constraint2){ int columns = 2; int rows1 = 4; int rows2 = 3; MatrixBlock inputMatrix1 = new MatrixBlock(rows1,columns,3); MatrixBlock inputMatrix2 = new MatrixBlock(rows2,columns,4); AppendPropagator propagator = new RBindPropagator(inputMatrix1, constraint1, inputMatrix2, constraint2); PrivacyConstraint mergedConstraint = propagator.propagate(); Assert.assertEquals(mergedConstraint.getPrivacyLevel(), PrivacyLevel.None); Map<DataRange, PrivacyLevel> firstHalfPrivacy = mergedConstraint.getFineGrainedPrivacy().getPrivacyLevel( new DataRange(new long[]{0,0}, new long[]{rows1-1,columns-1})); constraint1.getFineGrainedPrivacy().getAllConstraintsList().forEach( constraint -> Assert.assertTrue("Merged constraint should contain same privacy levels as input 1", firstHalfPrivacy.containsValue(constraint.getValue())) ); Map<DataRange, PrivacyLevel> secondHalfPrivacy = mergedConstraint.getFineGrainedPrivacy().getPrivacyLevel( new DataRange(new long[]{rows1,0}, new long[]{rows1+rows2-1,columns-1})); constraint2.getFineGrainedPrivacy().getAllConstraintsList().forEach( constraint -> Assert.assertTrue("Merged constraint should contain same privacy levels as input 2", secondHalfPrivacy.containsValue(constraint.getValue())) ); } private static void finegrainedCBindTest(PrivacyConstraint constraint1, PrivacyConstraint constraint2){ int rows = 6; int columns1 = 4; int columns2 = 3; MatrixBlock inputMatrix1 = new MatrixBlock(rows,columns1,3); MatrixBlock inputMatrix2 = new MatrixBlock(rows,columns2,4); AppendPropagator propagator = new CBindPropagator(inputMatrix1, constraint1, inputMatrix2, constraint2); PrivacyConstraint mergedConstraint = propagator.propagate(); Assert.assertEquals(mergedConstraint.getPrivacyLevel(), PrivacyLevel.None); Map<DataRange, PrivacyLevel> firstHalfPrivacy = mergedConstraint.getFineGrainedPrivacy().getPrivacyLevel( new DataRange(new long[]{0,0}, new long[]{rows-1,columns1-1})); constraint1.getFineGrainedPrivacy().getAllConstraintsList().forEach( constraint -> Assert.assertTrue("Merged constraint should contain same privacy levels as input 1", firstHalfPrivacy.containsValue(constraint.getValue())) ); Map<DataRange, PrivacyLevel> secondHalfPrivacy = mergedConstraint.getFineGrainedPrivacy().getPrivacyLevel( new DataRange(new long[]{0,columns1}, new long[]{rows,columns1+columns2-1})); constraint2.getFineGrainedPrivacy().getAllConstraintsList().forEach( constraint -> Assert.assertTrue("Merged constraint should contain same privacy levels as input 2", secondHalfPrivacy.containsValue(constraint.getValue())) ); } private static void finegrainedListAppendTest(PrivacyConstraint constraint1, PrivacyConstraint constraint2){ int length1 = 6; List<Data> dataList1 = Arrays.asList(new Data[length1]); ListObject input1 = new ListObject(dataList1); int length2 = 11; List<Data> dataList2 = Arrays.asList(new Data[length2]); ListObject input2 = new ListObject(dataList2); Propagator propagator = new ListAppendPropagator(input1, constraint1, input2, constraint2); PrivacyConstraint mergedConstraint = propagator.propagate(); Assert.assertEquals(mergedConstraint.getPrivacyLevel(), PrivacyLevel.None); Map<DataRange, PrivacyLevel> firstHalfPrivacy = mergedConstraint.getFineGrainedPrivacy().getPrivacyLevel( new DataRange(new long[]{0}, new long[]{length1-1}) ); constraint1.getFineGrainedPrivacy().getAllConstraintsList().forEach( constraint -> Assert.assertTrue("Merged constraint should contain same privacy levels as input 1", firstHalfPrivacy.containsValue(constraint.getValue())) ); Map<DataRange, PrivacyLevel> secondHalfPrivacy = mergedConstraint.getFineGrainedPrivacy().getPrivacyLevel( new DataRange(new long[]{length1}, new long[]{length1+length2-1}) ); constraint2.getFineGrainedPrivacy().getAllConstraintsList().forEach( constraint -> Assert.assertTrue("Merged constraint should contain same privacy levels as input 2", secondHalfPrivacy.containsValue(constraint.getValue())) ); } private static void finegrainedListRemoveAppendTest( PrivacyConstraint constraint1, PrivacyConstraint constraint2, PrivacyLevel expectedOutput2){ finegrainedListRemoveAppendTest(constraint1, constraint2, expectedOutput2, false); } private static void finegrainedListRemoveAppendTest( PrivacyConstraint constraint1, PrivacyConstraint constraint2, PrivacyLevel expectedOutput2, boolean singleElementPrivacy){ int dataLength = 9; List<Data> dataList = new ArrayList<>(); for ( int i = 0; i < dataLength; i++){ dataList.add(new DoubleObject(i)); } ListObject inputList = new ListObject(dataList); int removePositionInt = 5; ScalarObject removePosition = new IntObject(removePositionInt); PropagatorMultiReturn propagator = new ListRemovePropagator(inputList, constraint1, removePosition, constraint2); PrivacyConstraint[] mergedConstraints = propagator.propagate(); if ( !singleElementPrivacy ){ Map<DataRange, PrivacyLevel> outputPrivacy = mergedConstraints[0].getFineGrainedPrivacy().getPrivacyLevel( new DataRange(new long[]{0}, new long[]{dataLength-1}) ); constraint1.getFineGrainedPrivacy().getAllConstraintsList().forEach( constraint -> Assert.assertTrue("Merged constraint should contain same privacy levels as input 1", outputPrivacy.containsValue(constraint.getValue())) ); } Assert.assertEquals(expectedOutput2, mergedConstraints[1].getPrivacyLevel()); Assert.assertFalse(mergedConstraints[1].hasFineGrainedConstraints()); } private void integrationCBindTest(PrivacyConstraint privacyConstraint1, PrivacyConstraint privacyConstraint2, PrivacyConstraint expectedOutput){ TestConfiguration config = getAndLoadTestConfiguration(TEST_NAME_CBIND); fullDMLScriptName = SCRIPT_DIR + TEST_DIR + config.getTestScript() + ".dml"; int cols1 = 20; int cols2 = 30; int rows = 10; double[][] A = getRandomMatrix(rows, cols1, -10, 10, 0.5, 1); double[][] B = getRandomMatrix(rows, cols2, -10, 10, 0.5, 1); writeInputMatrixWithMTD("A", A, false, new MatrixCharacteristics(rows, cols1), privacyConstraint1); writeInputMatrixWithMTD("B", B, false, new MatrixCharacteristics(rows, cols2), privacyConstraint2); programArgs = new String[]{"-nvargs", "A=" + input("A"), "B=" + input("B"), "C=" + output("C")}; runTest(true,false,null,-1); PrivacyConstraint outputConstraint = getPrivacyConstraintFromMetaData("C"); Assert.assertEquals(expectedOutput, outputConstraint); } private void integrationStringAppendTest(PrivacyConstraint privacyConstraint1, PrivacyConstraint privacyConstraint2, PrivacyConstraint expectedOutput){ TestConfiguration config = getAndLoadTestConfiguration(TEST_NAME_STRING); fullDMLScriptName = SCRIPT_DIR + TEST_DIR + config.getTestScript() + ".dml"; int cols = 1; int rows = 1; double[][] A = getRandomMatrix(rows, cols, -10, 10, 0.5, 1); double[][] B = getRandomMatrix(rows, cols, -10, 10, 0.5, 1); writeInputMatrixWithMTD("A", A, false, new MatrixCharacteristics(rows, cols), privacyConstraint1); writeInputMatrixWithMTD("B", B, false, new MatrixCharacteristics(rows, cols), privacyConstraint2); programArgs = new String[]{"-nvargs", "A=" + input("A"), "B=" + input("B"), "C=" + output("C")}; runTest(true,false,null,-1); PrivacyConstraint outputConstraint = getPrivacyConstraintFromMetaData("C"); Assert.assertEquals(expectedOutput, outputConstraint); } private void integrationListAppendTest(PrivacyConstraint privacyConstraint1, PrivacyConstraint privacyConstraint2, PrivacyConstraint expectedOutput){ TestConfiguration config = getAndLoadTestConfiguration(TEST_NAME_LIST); fullDMLScriptName = SCRIPT_DIR + TEST_DIR + config.getTestScript() + ".dml"; int cols = 1; int rows = 5; double[][] A = getRandomMatrix(rows, cols, -10, 10, 0.5, 1); double[][] B = getRandomMatrix(rows, cols, -10, 10, 0.5, 1); writeInputMatrixWithMTD("A", A, false, new MatrixCharacteristics(rows, cols), privacyConstraint1); writeInputMatrixWithMTD("B", B, false, new MatrixCharacteristics(rows, cols), privacyConstraint2); programArgs = new String[]{"-nvargs", "A=" + input("A"), "B=" + input("B"), "C=" + output("C")}; runTest(true,false,null,-1); PrivacyConstraint outputConstraint = getPrivacyConstraintFromMetaData("C"); Assert.assertEquals(expectedOutput, outputConstraint); } }
15,955
1,039
#if defined(SIMDE_TEST_BARE) int main(void) { int retval = EXIT_SUCCESS; fprintf(stdout, "1..%zu\n", (sizeof(test_suite_tests) / sizeof(test_suite_tests[0]))); for (size_t i = 0 ; i < (sizeof(test_suite_tests) / sizeof(test_suite_tests[0])) ; i++) { int res = test_suite_tests[i].func(); if (res != 0) { retval = EXIT_FAILURE; fprintf(stdout, "not ok %zu " HEDLEY_STRINGIFY(SIMDE_TEST_ARM_NEON_INSN) "/%s\n", i + 1, test_suite_tests[i].name); } else { fprintf(stdout, "ok %zu " HEDLEY_STRINGIFY(SIMDE_TEST_ARM_NEON_INSN) "/%s\n", i + 1, test_suite_tests[i].name); } } return retval; } #else #if defined(__cplusplus) static MunitSuite suite = { const_cast<char*>("/" HEDLEY_STRINGIFY(SIMDE_TEST_ARM_NEON_INSN)), test_suite_tests, NULL, 1, MUNIT_SUITE_OPTION_NONE }; #else static MunitSuite suite = { (char*) "/" HEDLEY_STRINGIFY(SIMDE_TEST_ARM_NEON_INSN), test_suite_tests, NULL, 1, MUNIT_SUITE_OPTION_NONE }; #endif HEDLEY_C_DECL MunitSuite* SIMDE_TEST_GENERATE_VARIANT_SYMBOL_CURRENT(HEDLEY_CONCAT(simde_test_arm_neon_get_suite_,SIMDE_TEST_ARM_NEON_INSN)) (void) { return &suite; } #endif
582
1,585
/* * Copyright (c) 2004-2005 The Trustees of Indiana University and Indiana * University Research and Technology * Corporation. All rights reserved. * Copyright (c) 2004-2005 The University of Tennessee and The University * of Tennessee Research Foundation. All rights * reserved. * Copyright (c) 2004-2005 High Performance Computing Center Stuttgart, * University of Stuttgart. All rights reserved. * Copyright (c) 2004-2005 The Regents of the University of California. * All rights reserved. * Copyright (c) 2011-2012 Cisco Systems, Inc. All rights reserved. * Copyright (c) 2015-2021 Research Organization for Information Science * and Technology (RIST). All rights reserved. * $COPYRIGHT$ * * Additional copyrights may follow * * $HEADER$ */ #include "ompi_config.h" #include "ompi/mpi/fortran/mpif-h/bindings.h" #include "ompi/mpi/fortran/base/constants.h" #if OMPI_BUILD_MPI_PROFILING #if OPAL_HAVE_WEAK_SYMBOLS #pragma weak PMPI_ALLTOALLV_INIT = ompi_alltoallv_init_f #pragma weak pmpi_alltoallv_init = ompi_alltoallv_init_f #pragma weak pmpi_alltoallv_init_ = ompi_alltoallv_init_f #pragma weak pmpi_alltoallv_init__ = ompi_alltoallv_init_f #pragma weak PMPI_Alltoallv_init_f = ompi_alltoallv_init_f #pragma weak PMPI_Alltoallv_init_f08 = ompi_alltoallv_init_f #else OMPI_GENERATE_F77_BINDINGS (PMPI_ALLTOALLV_INIT, pmpi_alltoallv_init, pmpi_alltoallv_init_, pmpi_alltoallv_init__, pompi_alltoallv_init_f, (char *sendbuf, MPI_Fint *sendcounts, MPI_Fint *sdispls, MPI_Fint *sendtype, char *recvbuf, MPI_Fint *recvcounts, MPI_Fint *rdispls, MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *info, MPI_Fint *request, MPI_Fint *ierr), (sendbuf, sendcounts, sdispls, sendtype, recvbuf, recvcounts, rdispls, recvtype, comm, info, request, ierr) ) #endif #endif #if OPAL_HAVE_WEAK_SYMBOLS #pragma weak MPI_ALLTOALLV_INIT = ompi_alltoallv_init_f #pragma weak mpi_alltoallv_init = ompi_alltoallv_init_f #pragma weak mpi_alltoallv_init_ = ompi_alltoallv_init_f #pragma weak mpi_alltoallv_init__ = ompi_alltoallv_init_f #pragma weak MPI_Alltoallv_init_f = ompi_alltoallv_init_f #pragma weak MPI_Alltoallv_init_f08 = ompi_alltoallv_init_f #else #if ! OMPI_BUILD_MPI_PROFILING OMPI_GENERATE_F77_BINDINGS (MPI_ALLTOALLV_INIT, mpi_alltoallv_init, mpi_alltoallv_init_, mpi_alltoallv_init__, ompi_alltoallv_init_f, (char *sendbuf, MPI_Fint *sendcounts, MPI_Fint *sdispls, MPI_Fint *sendtype, char *recvbuf, MPI_Fint *recvcounts, MPI_Fint *rdispls, MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *info, MPI_Fint *request, MPI_Fint *ierr), (sendbuf, sendcounts, sdispls, sendtype, recvbuf, recvcounts, rdispls, recvtype, comm, info, request, ierr) ) #else #define ompi_alltoallv_init_f pompi_alltoallv_init_f #endif #endif void ompi_alltoallv_init_f(char *sendbuf, MPI_Fint *sendcounts, MPI_Fint *sdispls, MPI_Fint *sendtype, char *recvbuf, MPI_Fint *recvcounts, MPI_Fint *rdispls, MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *info, MPI_Fint *request, MPI_Fint *ierr) { MPI_Comm c_comm; MPI_Datatype c_sendtype, c_recvtype; MPI_Info c_info; MPI_Request c_request; int size, c_ierr; OMPI_ARRAY_NAME_DECL(sendcounts); OMPI_ARRAY_NAME_DECL(sdispls); OMPI_ARRAY_NAME_DECL(recvcounts); OMPI_ARRAY_NAME_DECL(rdispls); c_comm = PMPI_Comm_f2c(*comm); c_sendtype = PMPI_Type_f2c(*sendtype); c_recvtype = PMPI_Type_f2c(*recvtype); c_info = PMPI_Info_f2c(*info); PMPI_Comm_size(c_comm, &size); OMPI_ARRAY_FINT_2_INT(sendcounts, size); OMPI_ARRAY_FINT_2_INT(sdispls, size); OMPI_ARRAY_FINT_2_INT(recvcounts, size); OMPI_ARRAY_FINT_2_INT(rdispls, size); sendbuf = (char *) OMPI_F2C_IN_PLACE(sendbuf); sendbuf = (char *) OMPI_F2C_BOTTOM(sendbuf); recvbuf = (char *) OMPI_F2C_BOTTOM(recvbuf); c_ierr = PMPI_Alltoallv_init(sendbuf, OMPI_ARRAY_NAME_CONVERT(sendcounts), OMPI_ARRAY_NAME_CONVERT(sdispls), c_sendtype, recvbuf, OMPI_ARRAY_NAME_CONVERT(recvcounts), OMPI_ARRAY_NAME_CONVERT(rdispls), c_recvtype, c_comm, c_info, &c_request); if (NULL != ierr) *ierr = OMPI_INT_2_FINT(c_ierr); if (MPI_SUCCESS == c_ierr) *request = PMPI_Request_c2f(c_request); OMPI_ARRAY_FINT_2_INT_CLEANUP(sendcounts); OMPI_ARRAY_FINT_2_INT_CLEANUP(sdispls); OMPI_ARRAY_FINT_2_INT_CLEANUP(recvcounts); OMPI_ARRAY_FINT_2_INT_CLEANUP(rdispls); }
2,830
3,073
<filename>clients/ios/Classes/NBSwipeableCell.h // // NBSwipeableCell.h // NewsBlur // // Created by <NAME> on 9/27/13. // Copyright (c) 2013 NewsBlur. All rights reserved. // #import "MCSwipeTableViewCell.h" @interface NBSwipeableCell : MCSwipeTableViewCell - (UIImage *)imageByApplyingAlpha:(UIImage *)image withAlpha:(CGFloat) alpha; @end
138
884
<filename>objectModel/TestData/Cdm/Relationship/TestCalculateRelationshipsOnResolvedEntities/ExpectedOutput/expectedResolvedExcSubManifestRels.json<gh_stars>100-1000 [ { "fromEntity": "C-resolved.cdm.json/C", "fromEntityAttribute": "CId", "toEntity": "D-resolved.cdm.json/D", "toEntityAttribute": "DId" } ]
148
9,657
from base.loss.adv_loss import adv from base.loss.coral import CORAL from base.loss.cos import cosine from base.loss.kl_js import kl_div, js from base.loss.mmd import MMD_loss from base.loss.mutual_info import Mine from base.loss.pair_dist import pairwise_dist __all__ = [ 'adv', 'CORAL', 'cosine', 'kl_div', 'js' 'MMD_loss', 'Mine', 'pairwise_dist' ]
161
3,142
# Copyright (C) 2021 Intel Corporation # # SPDX-License-Identifier: MIT import os import glob import requests import json from deepdiff import DeepDiff from .utils import config def test_check_objects_integrity(): with requests.Session() as session: session.auth = ('admin1', config.USER_PASS) for filename in glob.glob(os.path.join(config.ASSETS_DIR, '*.json')): with open(filename) as f: endpoint = os.path.basename(filename).rsplit('.')[0] response = session.get(config.get_api_url(endpoint, page_size='all')) json_objs = json.load(f) resp_objs = response.json() assert DeepDiff(json_objs, resp_objs, ignore_order=True, exclude_regex_paths="root\['results'\]\[\d+\]\['last_login'\]") == {}
364
2,151
<reponame>zipated/src // 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 <string.h> #include "base/command_line.h" #include "base/run_loop.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" #include "chrome/browser/dom_distiller/dom_distiller_service_factory.h" #include "chrome/browser/dom_distiller/tab_utils.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "components/dom_distiller/content/browser/distiller_javascript_utils.h" #include "components/dom_distiller/content/browser/web_contents_main_frame_observer.h" #include "components/dom_distiller/core/dom_distiller_service.h" #include "components/dom_distiller/core/dom_distiller_switches.h" #include "components/dom_distiller/core/task_tracker.h" #include "components/dom_distiller/core/url_constants.h" #include "components/dom_distiller/core/url_utils.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_observer.h" #include "content/public/common/isolated_world_ids.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/test_utils.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "testing/gtest/include/gtest/gtest.h" namespace dom_distiller { namespace { const char* kSimpleArticlePath = "/dom_distiller/simple_article.html"; } // namespace class DomDistillerTabUtilsBrowserTest : public InProcessBrowserTest { public: void SetUpOnMainThread() override { if (!DistillerJavaScriptWorldIdIsSet()) { SetDistillerJavaScriptWorldId(content::ISOLATED_WORLD_ID_CONTENT_END); } } void SetUpCommandLine(base::CommandLine* command_line) override { command_line->AppendSwitch(switches::kEnableDomDistiller); } }; // WebContentsMainFrameHelper is used to detect if a distilled page has // finished loading. This is done by checking how many times the title has // been set rather than using "DidFinishLoad" directly due to the content // being set by JavaScript. class WebContentsMainFrameHelper : public content::WebContentsObserver { public: WebContentsMainFrameHelper(content::WebContents* web_contents, const base::Closure& callback) : callback_(callback), title_set_count_(0), loaded_distiller_page_(false) { content::WebContentsObserver::Observe(web_contents); } void DidFinishLoad(content::RenderFrameHost* render_frame_host, const GURL& validated_url) override { if (!render_frame_host->GetParent() && validated_url.scheme() == kDomDistillerScheme) loaded_distiller_page_ = true; } void TitleWasSet(content::NavigationEntry* entry) override { // The title will be set twice on distilled pages; once for the placeholder // and once when the distillation has finished. Watch for the second time // as a signal that the JavaScript that sets the content has run. title_set_count_++; if (title_set_count_ >= 2 && loaded_distiller_page_) { callback_.Run(); } } private: base::Closure callback_; int title_set_count_; bool loaded_distiller_page_; }; // https://crbug.com/751730. #if defined(OS_CHROMEOS) || defined(OS_LINUX) #define MAYBE_TestSwapWebContents DISABLED_TestSwapWebContents #else #define MAYBE_TestSwapWebContents TestSwapWebContents #endif IN_PROC_BROWSER_TEST_F(DomDistillerTabUtilsBrowserTest, MAYBE_TestSwapWebContents) { ASSERT_TRUE(embedded_test_server()->Start()); content::WebContents* initial_web_contents = browser()->tab_strip_model()->GetActiveWebContents(); const GURL& article_url = embedded_test_server()->GetURL(kSimpleArticlePath); // This blocks until the navigation has completely finished. ui_test_utils::NavigateToURL(browser(), article_url); DistillCurrentPageAndView(initial_web_contents); // Wait until the new WebContents has fully navigated. content::WebContents* after_web_contents = browser()->tab_strip_model()->GetActiveWebContents(); ASSERT_TRUE(after_web_contents != NULL); base::RunLoop new_url_loaded_runner; std::unique_ptr<WebContentsMainFrameHelper> distilled_page_loaded( new WebContentsMainFrameHelper(after_web_contents, new_url_loaded_runner.QuitClosure())); new_url_loaded_runner.Run(); std::string page_title; content::ExecuteScriptAndGetValue(after_web_contents->GetMainFrame(), "document.title")->GetAsString(&page_title); // Verify the new URL is showing distilled content in a new WebContents. EXPECT_NE(initial_web_contents, after_web_contents); EXPECT_TRUE( after_web_contents->GetLastCommittedURL().SchemeIs(kDomDistillerScheme)); EXPECT_EQ("Test Page Title", page_title); } IN_PROC_BROWSER_TEST_F(DomDistillerTabUtilsBrowserTest, TestDistillIntoWebContents) { ASSERT_TRUE(embedded_test_server()->Start()); content::WebContents* source_web_contents = browser()->tab_strip_model()->GetActiveWebContents(); const GURL& article_url = embedded_test_server()->GetURL(kSimpleArticlePath); // This blocks until the navigation has completely finished. ui_test_utils::NavigateToURL(browser(), article_url); // Create destination WebContents. content::WebContents::CreateParams create_params( source_web_contents->GetBrowserContext()); std::unique_ptr<content::WebContents> destination_web_contents = content::WebContents::Create(create_params); content::WebContents* raw_destination_web_contents = destination_web_contents.get(); DCHECK(raw_destination_web_contents); browser()->tab_strip_model()->AppendWebContents( std::move(destination_web_contents), true); ASSERT_EQ(raw_destination_web_contents, browser()->tab_strip_model()->GetWebContentsAt(1)); DistillAndView(source_web_contents, raw_destination_web_contents); // Wait until the destination WebContents has fully navigated. base::RunLoop new_url_loaded_runner; std::unique_ptr<WebContentsMainFrameHelper> distilled_page_loaded( new WebContentsMainFrameHelper(raw_destination_web_contents, new_url_loaded_runner.QuitClosure())); new_url_loaded_runner.Run(); // Verify that the source WebContents is showing the original article. EXPECT_EQ(article_url, source_web_contents->GetLastCommittedURL()); std::string page_title; content::ExecuteScriptAndGetValue(source_web_contents->GetMainFrame(), "document.title")->GetAsString(&page_title); EXPECT_EQ("Test Page Title", page_title); // Verify the destination WebContents is showing distilled content. EXPECT_TRUE(raw_destination_web_contents->GetLastCommittedURL().SchemeIs( kDomDistillerScheme)); content::ExecuteScriptAndGetValue( raw_destination_web_contents->GetMainFrame(), "document.title") ->GetAsString(&page_title); EXPECT_EQ("Test Page Title", page_title); content::WebContentsDestroyedWatcher destroyed_watcher( raw_destination_web_contents); browser()->tab_strip_model()->CloseWebContentsAt(1, 0); destroyed_watcher.Wait(); } } // namespace dom_distiller
2,659
1,603
<reponame>bskim45/datahub package com.linkedin.metadata.kafka.hydrator; import com.fasterxml.jackson.databind.node.ObjectNode; import com.linkedin.datahub.graphql.types.common.mappers.util.MappingHelper; import com.linkedin.entity.EntityResponse; import com.linkedin.entity.EnvelopedAspectMap; import com.linkedin.identity.CorpUserInfo; import com.linkedin.metadata.key.CorpUserKey; import lombok.extern.slf4j.Slf4j; import static com.linkedin.metadata.Constants.*; @Slf4j public class CorpUserHydrator extends BaseHydrator { private static final String USER_NAME = "username"; private static final String NAME = "name"; @Override protected void hydrateFromEntityResponse(ObjectNode document, EntityResponse entityResponse) { EnvelopedAspectMap aspectMap = entityResponse.getAspects(); MappingHelper<ObjectNode> mappingHelper = new MappingHelper<>(aspectMap, document); mappingHelper.mapToResult(CORP_USER_INFO_ASPECT_NAME, (jsonNodes, dataMap) -> jsonNodes.put(NAME, new CorpUserInfo(dataMap).getDisplayName())); mappingHelper.mapToResult(CORP_USER_KEY_ASPECT_NAME, (jsonNodes, dataMap) -> jsonNodes.put(USER_NAME, new CorpUserKey(dataMap).getUsername())); } }
414
892
<gh_stars>100-1000 { "schema_version": "1.2.0", "id": "GHSA-87h8-h6wc-7xhj", "modified": "2022-05-01T01:50:30Z", "published": "2022-05-01T01:50:30Z", "aliases": [ "CVE-2005-0564" ], "details": "Stack-based buffer overflow in Microsoft Word 2000 and Word 2002, and Microsoft Works Suites 2000 through 2004, might allow remote attackers to execute arbitrary code via a .doc file with long font information.", "severity": [ ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2005-0564" }, { "type": "WEB", "url": "https://docs.microsoft.com/en-us/security-updates/securitybulletins/2005/ms05-035" }, { "type": "WEB", "url": "https://oval.cisecurity.org/repository/search/definition/oval%3Aorg.mitre.oval%3Adef%3A1190" }, { "type": "WEB", "url": "https://oval.cisecurity.org/repository/search/definition/oval%3Aorg.mitre.oval%3Adef%3A1331" }, { "type": "WEB", "url": "http://www.idefense.com/application/poi/display?id=281&type=vulnerabilities" }, { "type": "WEB", "url": "http://www.kb.cert.org/vuls/id/218621" }, { "type": "WEB", "url": "http://www.us-cert.gov/cas/techalerts/TA05-193A.html" } ], "database_specific": { "cwe_ids": [ ], "severity": "HIGH", "github_reviewed": false } }
666
318
<filename>serializer/test/Serializer/EnterpriseUserTest.java package Serializer; import com.bj58.enterprise.entity.SESUser; import com.bj58.spat.gaea.serializer.serializer.Serializer; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Service Platform Architecture Team (<EMAIL>) */ public class EnterpriseUserTest { @Test public void TestUser() throws Exception { SESUser user = new SESUser(); user.setUserID(1L); user.setState(1); Serializer serializer = new Serializer(); byte[] buffer = serializer.Serialize(user); assertNotNull(buffer); Object obj = serializer.Derialize(buffer, SimpleClass.class); Object expect = obj; assertNotNull(expect); } }
238
584
/* * Copyright 2012-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.data.repository.config; import java.util.Optional; import org.springframework.core.type.classreading.MetadataReaderFactory; import org.springframework.core.type.filter.TypeFilter; import org.springframework.data.repository.query.QueryLookupStrategy; import org.springframework.data.util.Streamable; import org.springframework.lang.Nullable; /** * Configuration information for a single repository instance. * * @author <NAME> * @author <NAME> */ public interface RepositoryConfiguration<T extends RepositoryConfigurationSource> { /** * Returns the base packages that the repository was scanned under. * * @return */ Streamable<String> getBasePackages(); /** * Returns the base packages to scan for repository implementations. * * @return * @since 2.0 */ Streamable<String> getImplementationBasePackages(); /** * Returns the interface name of the repository. * * @return */ String getRepositoryInterface(); /** * Returns the key to resolve a {@link QueryLookupStrategy} from eventually. * * @see QueryLookupStrategy.Key * @return */ Object getQueryLookupStrategyKey(); /** * Returns the location of the file containing Spring Data named queries. * * @return */ Optional<String> getNamedQueriesLocation(); /** * Returns the name of the repository base class to be used or {@literal null} if the store specific defaults shall be * applied. * * @return * @since 1.11 */ Optional<String> getRepositoryBaseClassName(); /** * Returns the name of the repository factory bean class to be used. * * @return */ String getRepositoryFactoryBeanClassName(); /** * Returns the source of the {@link RepositoryConfiguration}. * * @return */ @Nullable Object getSource(); /** * Returns the {@link RepositoryConfigurationSource} that backs the {@link RepositoryConfiguration}. * * @return */ T getConfigurationSource(); /** * Returns whether to initialize the repository proxy lazily. * * @return */ boolean isLazyInit(); /** * Returns whether the repository is the primary one for its type. * * @return {@literal true} whether the repository is the primary one for its type. * @since 2.3 */ boolean isPrimary(); /** * Returns the {@link TypeFilter}s to be used to exclude packages from repository scanning. * * @return */ Streamable<TypeFilter> getExcludeFilters(); /** * Returns the {@link ImplementationDetectionConfiguration} to be used for this repository. * * @param factory must not be {@literal null}. * @return will never be {@literal null}. * @since 2.1 */ ImplementationDetectionConfiguration toImplementationDetectionConfiguration(MetadataReaderFactory factory); /** * Returns the {@link ImplementationLookupConfiguration} for the given {@link MetadataReaderFactory}. * * @param factory must not be {@literal null}. * @return will never be {@literal null}. * @since 2.1 */ ImplementationLookupConfiguration toLookupConfiguration(MetadataReaderFactory factory); /** * Returns a human readable description of the repository interface declaration for error reporting purposes. * * @return can be {@literal null}. * @since 2.3 */ @Nullable String getResourceDescription(); }
1,112
5,169
{ "name": "SZNZotero", "version": "0.3.4", "summary": "Objective-C client for the Zotero API.", "homepage": "https://github.com/shazino/SZNZotero", "license": "MIT", "authors": { "shazino": "<EMAIL>" }, "social_media_url": "https://twitter.com/shazino", "source": { "git": "https://github.com/shazino/SZNZotero.git", "tag": "0.3.4" }, "source_files": "SZNZotero/*", "requires_arc": true, "platforms": { "ios": "6.0", "osx": "10.7" }, "ios": { "frameworks": "Security" }, "dependencies": { "AFOAuth1Client": [ "~> 1.0.0" ], "TBXML": [ "~> 1.5" ], "ISO8601DateFormatter": [ "~> 0.7" ] }, "prefix_header_contents": "#import <Availability.h>\n\n#if __IPHONE_OS_VERSION_MIN_REQUIRED\n #import <SystemConfiguration/SystemConfiguration.h>\n #import <MobileCoreServices/MobileCoreServices.h>\n #import <Security/Security.h>\n#else\n #import <SystemConfiguration/SystemConfiguration.h>\n #import <CoreServices/CoreServices.h>\n #import <Security/Security.h>\n#endif" }
475