max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
1,473
<filename>web/src/test/java/com/navercorp/pinpoint/web/task/RequestContextPropagatingTaskDecoratorTest.java /* * Copyright 2018 NAVER Corp. * * 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.navercorp.pinpoint.web.task; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.core.task.SimpleAsyncTaskExecutor; import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.RequestContextHolder; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; /** * @author <NAME> */ @RunWith(MockitoJUnitRunner.class) public class RequestContextPropagatingTaskDecoratorTest { private final RequestContextPropagatingTaskDecorator decorator = new RequestContextPropagatingTaskDecorator(); private final SimpleAsyncTaskExecutor executor = new SimpleAsyncTaskExecutor("Test-Worker-"); @Mock private RequestAttributes requestAttributes; @Before public void setup() { executor.setTaskDecorator(decorator); } @Test public void requestContextShouldBePropagated() throws InterruptedException { // Given final int testCount = 100; final CountDownLatch completeLatch = new CountDownLatch(testCount); final AtomicBoolean verifiedFlag = new AtomicBoolean(true); final TestWorker.Callback workerCallback = new TestWorker.Callback() { @Override public void onRun() { RequestAttributes actualRequestAttributes = RequestContextHolder.getRequestAttributes(); boolean verified = requestAttributes == actualRequestAttributes; verifiedFlag.compareAndSet(true, verified); } @Override public void onError() { // do nothing } }; // When RequestContextHolder.setRequestAttributes(requestAttributes); for (int i = 0; i < testCount; i++) { executor.execute(new TestWorker(completeLatch, workerCallback)); } completeLatch.await(5, TimeUnit.SECONDS); // Then boolean testVerified = verifiedFlag.get(); Assert.assertTrue("RequestContext has not been propagated", testVerified); } }
1,029
679
<filename>main/connectivity/inc/connectivity/TTableHelper.hxx<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. * *************************************************************/ #ifndef CONNECTIVITY_TABLEHELPER_HXX #define CONNECTIVITY_TABLEHELPER_HXX #include "connectivity/dbtoolsdllapi.hxx" #include "connectivity/sdbcx/VTable.hxx" #include "connectivity/sdbcx/VKey.hxx" #include "connectivity/StdTypeDefs.hxx" #include <comphelper/stl_types.hxx> #include <com/sun/star/sdb/tools/XTableRename.hpp> #include <com/sun/star/sdb/tools/XTableAlteration.hpp> #include <com/sun/star/sdb/tools/XKeyAlteration.hpp> #include <com/sun/star/sdb/tools/XIndexAlteration.hpp> namespace connectivity { typedef sal_Int32 OrdinalPosition; struct ColumnDesc { ::rtl::OUString sName; ::rtl::OUString aField6; ::rtl::OUString sField12; // REMARKS ::rtl::OUString sField13; sal_Int32 nField5 , nField7 , nField9 , nField11; OrdinalPosition nOrdinalPosition; ColumnDesc() {} ColumnDesc( const ::rtl::OUString& _rName , sal_Int32 _nField5 , const ::rtl::OUString& _aField6 , sal_Int32 _nField7 , sal_Int32 _nField9 , sal_Int32 _nField11 , const ::rtl::OUString& _sField12 , const ::rtl::OUString& _sField13 ,OrdinalPosition _nPosition ) :sName( _rName ) ,aField6(_aField6) ,sField12(_sField12) ,sField13(_sField13) ,nField5(_nField5) ,nField7(_nField7) ,nField9(_nField9) ,nField11(_nField11) ,nOrdinalPosition( _nPosition ) { } }; typedef connectivity::sdbcx::OTable OTable_TYPEDEF; OOO_DLLPUBLIC_DBTOOLS ::rtl::OUString getTypeString(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& xColProp); DECLARE_STL_USTRINGACCESS_MAP( sdbcx::TKeyProperties , TKeyMap); struct OTableHelperImpl; class OOO_DLLPUBLIC_DBTOOLS OTableHelper : public OTable_TYPEDEF { ::std::auto_ptr<OTableHelperImpl> m_pImpl; void refreshPrimaryKeys(TStringVector& _rKeys); void refreshForgeinKeys(TStringVector& _rKeys); protected: /** creates the column collection for the table @param _rNames The column names. */ virtual sdbcx::OCollection* createColumns(const TStringVector& _rNames) = 0; /** creates the key collection for the table @param _rNames The key names. */ virtual sdbcx::OCollection* createKeys(const TStringVector& _rNames) = 0; /** creates the index collection for the table @param _rNames The index names. */ virtual sdbcx::OCollection* createIndexes(const TStringVector& _rNames) = 0; /** this function is called upon disposing the component */ virtual void SAL_CALL disposing(); /** The default returns "RENAME TABLE " or "RENAME VIEW " depending on the type. * * \return The start of the rename statement. */ virtual ::rtl::OUString getRenameStart() const; virtual ~OTableHelper(); public: virtual void refreshColumns(); virtual void refreshKeys(); virtual void refreshIndexes(); const ColumnDesc* getColumnDescription(const ::rtl::OUString& _sName) const; public: OTableHelper( sdbcx::OCollection* _pTables, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _xConnection, sal_Bool _bCase); OTableHelper( sdbcx::OCollection* _pTables, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _xConnection, sal_Bool _bCase, const ::rtl::OUString& _Name, const ::rtl::OUString& _Type, const ::rtl::OUString& _Description = ::rtl::OUString(), const ::rtl::OUString& _SchemaName = ::rtl::OUString(), const ::rtl::OUString& _CatalogName = ::rtl::OUString() ); virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData> getMetaData() const; ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection> getConnection() const; virtual void SAL_CALL acquire() throw(); virtual void SAL_CALL release() throw(); // XRename virtual void SAL_CALL rename( const ::rtl::OUString& newName ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::container::ElementExistException, ::com::sun::star::uno::RuntimeException); // XAlterTable virtual void SAL_CALL alterColumnByIndex( sal_Int32 index, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& descriptor ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); // XNamed virtual ::rtl::OUString SAL_CALL getName() throw(::com::sun::star::uno::RuntimeException); // helper method to get key properties sdbcx::TKeyProperties getKeyProperties(const ::rtl::OUString& _sName) const; void addKey(const ::rtl::OUString& _sName,const sdbcx::TKeyProperties& _aKeyProperties); virtual ::rtl::OUString getTypeCreatePattern() const; ::com::sun::star::uno::Reference< ::com::sun::star::sdb::tools::XTableRename> getRenameService() const; ::com::sun::star::uno::Reference< ::com::sun::star::sdb::tools::XTableAlteration> getAlterService() const; ::com::sun::star::uno::Reference< ::com::sun::star::sdb::tools::XKeyAlteration> getKeyService() const; ::com::sun::star::uno::Reference< ::com::sun::star::sdb::tools::XIndexAlteration> getIndexService() const; }; } #endif // CONNECTIVITY_TABLEHELPER_HXX
2,578
1,590
<filename>specification/storsimple8000series/resource-manager/Microsoft.StorSimple/stable/2017-06-01/examples/ManagersGetPublicEncryptionKey.json { "parameters": { "subscriptionId": "d3ebfe71-b7a9-4c57-92b9-68a2afde4de5", "resourceGroupName": "ResourceGroupForSDKTest", "managerName": "ManagerForSDKTest1", "api-version": "2017-06-01" }, "responses": { "200": { "body": { "value": "<KEY> "valueCertificateThumbprint": "<KEY>", "encryptionAlgorithm": "AES256" } } } }
238
473
<reponame>ProjectVault/orp<filename>third-party/qemu-orp/include/exec/ram_addr.h /* * Declarations for cpu physical memory functions * * Copyright 2011 Red Hat, Inc. and/or its affiliates * * Authors: * <NAME> <<EMAIL>> * * This work is licensed under the terms of the GNU GPL, version 2 or * later. See the COPYING file in the top-level directory. * */ /* * This header is for use by exec.c and memory.c ONLY. Do not include it. * The functions declared here will be removed soon. */ #ifndef RAM_ADDR_H #define RAM_ADDR_H #ifndef CONFIG_USER_ONLY #include "hw/xen/xen.h" ram_addr_t qemu_ram_alloc_from_file(ram_addr_t size, MemoryRegion *mr, bool share, const char *mem_path, Error **errp); ram_addr_t qemu_ram_alloc_from_ptr(ram_addr_t size, void *host, MemoryRegion *mr, Error **errp); ram_addr_t qemu_ram_alloc(ram_addr_t size, MemoryRegion *mr, Error **errp); int qemu_get_ram_fd(ram_addr_t addr); void *qemu_get_ram_block_host_ptr(ram_addr_t addr); void *qemu_get_ram_ptr(ram_addr_t addr); void qemu_ram_free(ram_addr_t addr); void qemu_ram_free_from_ptr(ram_addr_t addr); static inline bool cpu_physical_memory_get_dirty(ram_addr_t start, ram_addr_t length, unsigned client) { unsigned long end, page, next; assert(client < DIRTY_MEMORY_NUM); end = TARGET_PAGE_ALIGN(start + length) >> TARGET_PAGE_BITS; page = start >> TARGET_PAGE_BITS; next = find_next_bit(ram_list.dirty_memory[client], end, page); return next < end; } static inline bool cpu_physical_memory_get_dirty_flag(ram_addr_t addr, unsigned client) { return cpu_physical_memory_get_dirty(addr, 1, client); } static inline bool cpu_physical_memory_is_clean(ram_addr_t addr) { bool vga = cpu_physical_memory_get_dirty_flag(addr, DIRTY_MEMORY_VGA); bool code = cpu_physical_memory_get_dirty_flag(addr, DIRTY_MEMORY_CODE); bool migration = cpu_physical_memory_get_dirty_flag(addr, DIRTY_MEMORY_MIGRATION); return !(vga && code && migration); } static inline void cpu_physical_memory_set_dirty_flag(ram_addr_t addr, unsigned client) { assert(client < DIRTY_MEMORY_NUM); set_bit(addr >> TARGET_PAGE_BITS, ram_list.dirty_memory[client]); } static inline void cpu_physical_memory_set_dirty_range_nocode(ram_addr_t start, ram_addr_t length) { unsigned long end, page; end = TARGET_PAGE_ALIGN(start + length) >> TARGET_PAGE_BITS; page = start >> TARGET_PAGE_BITS; bitmap_set(ram_list.dirty_memory[DIRTY_MEMORY_MIGRATION], page, end - page); bitmap_set(ram_list.dirty_memory[DIRTY_MEMORY_VGA], page, end - page); } static inline void cpu_physical_memory_set_dirty_range(ram_addr_t start, ram_addr_t length) { unsigned long end, page; end = TARGET_PAGE_ALIGN(start + length) >> TARGET_PAGE_BITS; page = start >> TARGET_PAGE_BITS; bitmap_set(ram_list.dirty_memory[DIRTY_MEMORY_MIGRATION], page, end - page); bitmap_set(ram_list.dirty_memory[DIRTY_MEMORY_VGA], page, end - page); bitmap_set(ram_list.dirty_memory[DIRTY_MEMORY_CODE], page, end - page); xen_modified_memory(start, length); } #if !defined(_WIN32) static inline void cpu_physical_memory_set_dirty_lebitmap(unsigned long *bitmap, ram_addr_t start, ram_addr_t pages) { unsigned long i, j; unsigned long page_number, c; hwaddr addr; ram_addr_t ram_addr; unsigned long len = (pages + HOST_LONG_BITS - 1) / HOST_LONG_BITS; unsigned long hpratio = getpagesize() / TARGET_PAGE_SIZE; unsigned long page = BIT_WORD(start >> TARGET_PAGE_BITS); /* start address is aligned at the start of a word? */ if ((((page * BITS_PER_LONG) << TARGET_PAGE_BITS) == start) && (hpratio == 1)) { long k; long nr = BITS_TO_LONGS(pages); for (k = 0; k < nr; k++) { if (bitmap[k]) { unsigned long temp = leul_to_cpu(bitmap[k]); ram_list.dirty_memory[DIRTY_MEMORY_MIGRATION][page + k] |= temp; ram_list.dirty_memory[DIRTY_MEMORY_VGA][page + k] |= temp; ram_list.dirty_memory[DIRTY_MEMORY_CODE][page + k] |= temp; } } xen_modified_memory(start, pages); } else { /* * bitmap-traveling is faster than memory-traveling (for addr...) * especially when most of the memory is not dirty. */ for (i = 0; i < len; i++) { if (bitmap[i] != 0) { c = leul_to_cpu(bitmap[i]); do { j = ctzl(c); c &= ~(1ul << j); page_number = (i * HOST_LONG_BITS + j) * hpratio; addr = page_number * TARGET_PAGE_SIZE; ram_addr = start + addr; cpu_physical_memory_set_dirty_range(ram_addr, TARGET_PAGE_SIZE * hpratio); } while (c != 0); } } } } #endif /* not _WIN32 */ static inline void cpu_physical_memory_clear_dirty_range(ram_addr_t start, ram_addr_t length, unsigned client) { unsigned long end, page; assert(client < DIRTY_MEMORY_NUM); end = TARGET_PAGE_ALIGN(start + length) >> TARGET_PAGE_BITS; page = start >> TARGET_PAGE_BITS; bitmap_clear(ram_list.dirty_memory[client], page, end - page); } void cpu_physical_memory_reset_dirty(ram_addr_t start, ram_addr_t length, unsigned client); #endif #endif
3,071
2,453
<reponame>haozhiyu1990/XVim2 // // Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 30 2020 21:18:12). // // Copyright (C) 1997-2019 <NAME>. // #import <DVTFoundation/DVTDiffContextOperation.h> @class DVTDiffDataSource; @interface DVTDiffContextThreeWayOperation : DVTDiffContextOperation { BOOL _ignoresLineEnds; DVTDiffDataSource *_ancestorDataSource; DVTDiffDataSource *_intermediateDataSource; } - (void).cxx_destruct; @property(retain, nonatomic) DVTDiffDataSource *intermediateDataSource; // @synthesize intermediateDataSource=_intermediateDataSource; @property(retain, nonatomic) DVTDiffDataSource *ancestorDataSource; // @synthesize ancestorDataSource=_ancestorDataSource; @property(nonatomic) BOOL ignoresLineEnds; // @synthesize ignoresLineEnds=_ignoresLineEnds; - (id)modifiedDescriptorIndexesForDiffDescriptors:(id)arg1; - (id)_diffDescriptorsByAddingUnmodified:(id)arg1; - (id)_diffContextForComparing:(id)arg1 with:(id)arg2; - (void)_buildDiffDescriptors; - (id)initWithContext:(id)arg1 lineRange:(struct _NSRange)arg2 isDeletion:(BOOL)arg3 shouldCommence:(CDUnknownBlockType)arg4 completion:(CDUnknownBlockType)arg5; @end
418
348
{"nom":"Jouy-le-Moutier","circ":"10ème circonscription","dpt":"Val-d'Oise","inscrits":10976,"abs":6883,"votants":4093,"blancs":240,"nuls":57,"exp":3796,"res":[{"nuance":"REM","nom":"<NAME>","voix":2091},{"nuance":"FI","nom":"Mme <NAME>","voix":1705}]}
106
374
/* * Copyright (C) 2021 by Intel Corporation * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ #include "gtest/gtest.h" #include <math.h> #include "optimisation_common.h" #include "single_sqrt_14.h" #include "single_sqrt_23.h" #include "single_sqrt_24.h" static float out_expected[16]; #ifdef _MSC_VER // Preferred VS2019 version 16.3 or higher __declspec(align(64)) static float in[16]; __declspec(align(64)) static float out[16]; #else static float in[16] __attribute__((aligned(64))); static float out[16] __attribute__((aligned(64))); #endif static void init_data() { for (size_t i = 0; i < 16; i++) { in[i] = i + 1.0f; out_expected[i] = sqrtf(in[i]); } } TEST(avx512_32, single_sqrt_24) { if (!supports_avx512_skx()) GTEST_SKIP_("AVX-512 not supported, skipping test"); init_data(); memset(out, 0, sizeof(out)); ASSERT_EQ(single_sqrt_24_check(in, out), true); for (int i = 0; i < 16; i++) { ASSERT_FLOAT_EQ(out[i], out_expected[i]); } ASSERT_EQ(single_sqrt_24_check(in, NULL), false); ASSERT_EQ(single_sqrt_24_check(NULL, out), false); } TEST(avx512_32, single_sqrt_23) { if (!supports_avx512_skx()) GTEST_SKIP_("AVX-512 not supported, skipping test"); init_data(); memset(out, 0, sizeof(out)); ASSERT_EQ(single_sqrt_23_check(in, out), true); for (int i = 0; i < 16; i++) { ASSERT_FLOAT_EQ(out[i], out_expected[i]); } ASSERT_EQ(single_sqrt_23_check(NULL, out), false); ASSERT_EQ(single_sqrt_23_check(in, NULL), false); } TEST(avx512_32, single_sqrt_14) { if (!supports_avx512_skx()) GTEST_SKIP_("AVX-512 not supported, skipping test"); init_data(); memset(out, 0, sizeof(out)); ASSERT_EQ(single_sqrt_14_check(in, out), true); for (int i = 0; i < 16; i++) { ASSERT_NEAR(out[i], out_expected[i], 0.001); } ASSERT_EQ(single_sqrt_14_check(NULL, out), false); ASSERT_EQ(single_sqrt_14_check(in, NULL), false); }
994
319
<reponame>SonNguyenMinh123/MinYoutube package com.shapps.mintubeapp; import android.content.Context; import android.os.Build; import android.view.MotionEvent; import android.view.View; import android.webkit.WebChromeClient; import android.webkit.WebView; import android.webkit.WebViewClient; import java.util.Map; /** * Created by shyam on 15/3/16. */ public class WebPlayer { static WebView player; Context context; public WebPlayer(Context context) { this.player = new WebView(context); this.context = context; } public void setupPlayer() { player.getSettings().setJavaScriptEnabled(true); // For debugging using chrome on PC if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { player.setWebContentsDebuggingEnabled(true); } player.setWebChromeClient(new WebChromeClient()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { player.getSettings().setMediaPlaybackRequiresUserGesture(false); } player.getSettings().setUserAgentString("Mozilla/5.0 (Windows NT 6.2; Win64; x64; rv:21.0.0) Gecko/20121011 Firefox/21.0.0"); //----------------------------To get Player Id------------------------------------------- player.addJavascriptInterface(new JavaScriptInterface((PlayerService) context), "Interface"); player.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { return true; } @Override public void onPageFinished(WebView view, String url) { PlayerService.addStateChangeListener(); } } ); } public static void loadScript(String s) { player.loadUrl(s); } public static WebView getPlayer() { return player; } public void destroy() { player.destroy(); } public void loadDataWithUrl(String baseUrl, String videoHTML, String mimeType, String encoding, String historyUrl) { player.loadDataWithBaseURL(baseUrl, videoHTML, mimeType, encoding, historyUrl); } }
1,084
4,268
<filename>src-input/duk_heap_alloc.c /* * duk_heap allocation and freeing. */ #include "duk_internal.h" #if defined(DUK_USE_ROM_STRINGS) /* Fixed seed value used with ROM strings. */ #define DUK__FIXED_HASH_SEED 0xabcd1234 #endif /* * Free a heap object. * * Free heap object and its internal (non-heap) pointers. Assumes that * caller has removed the object from heap allocated list or the string * intern table, and any weak references (which strings may have) have * been already dealt with. */ DUK_INTERNAL void duk_free_hobject(duk_heap *heap, duk_hobject *h) { DUK_ASSERT(heap != NULL); DUK_ASSERT(h != NULL); DUK_FREE(heap, DUK_HOBJECT_GET_PROPS(heap, h)); if (DUK_HOBJECT_IS_COMPFUNC(h)) { duk_hcompfunc *f = (duk_hcompfunc *) h; DUK_UNREF(f); /* Currently nothing to free; 'data' is a heap object */ } else if (DUK_HOBJECT_IS_NATFUNC(h)) { duk_hnatfunc *f = (duk_hnatfunc *) h; DUK_UNREF(f); /* Currently nothing to free */ } else if (DUK_HOBJECT_IS_THREAD(h)) { duk_hthread *t = (duk_hthread *) h; duk_activation *act; DUK_FREE(heap, t->valstack); /* Don't free h->resumer because it exists in the heap. * Callstack entries also contain function pointers which * are not freed for the same reason. They are decref * finalized and the targets are freed if necessary based * on their refcount (or reachability). */ for (act = t->callstack_curr; act != NULL;) { duk_activation *act_next; duk_catcher *cat; for (cat = act->cat; cat != NULL;) { duk_catcher *cat_next; cat_next = cat->parent; DUK_FREE(heap, (void *) cat); cat = cat_next; } act_next = act->parent; DUK_FREE(heap, (void *) act); act = act_next; } /* XXX: with 'caller' property the callstack would need * to be unwound to update the 'caller' properties of * functions in the callstack. */ } else if (DUK_HOBJECT_IS_BOUNDFUNC(h)) { duk_hboundfunc *f = (duk_hboundfunc *) (void *) h; DUK_FREE(heap, f->args); } DUK_FREE(heap, (void *) h); } DUK_INTERNAL void duk_free_hbuffer(duk_heap *heap, duk_hbuffer *h) { DUK_ASSERT(heap != NULL); DUK_ASSERT(h != NULL); if (DUK_HBUFFER_HAS_DYNAMIC(h) && !DUK_HBUFFER_HAS_EXTERNAL(h)) { duk_hbuffer_dynamic *g = (duk_hbuffer_dynamic *) h; DUK_DDD(DUK_DDDPRINT("free dynamic buffer %p", (void *) DUK_HBUFFER_DYNAMIC_GET_DATA_PTR(heap, g))); DUK_FREE(heap, DUK_HBUFFER_DYNAMIC_GET_DATA_PTR(heap, g)); } DUK_FREE(heap, (void *) h); } DUK_INTERNAL void duk_free_hstring(duk_heap *heap, duk_hstring *h) { DUK_ASSERT(heap != NULL); DUK_ASSERT(h != NULL); DUK_UNREF(heap); DUK_UNREF(h); #if defined(DUK_USE_HSTRING_EXTDATA) && defined(DUK_USE_EXTSTR_FREE) if (DUK_HSTRING_HAS_EXTDATA(h)) { DUK_DDD( DUK_DDDPRINT("free extstr: hstring %!O, extdata: %p", h, DUK_HSTRING_GET_EXTDATA((duk_hstring_external *) h))); DUK_USE_EXTSTR_FREE(heap->heap_udata, (const void *) DUK_HSTRING_GET_EXTDATA((duk_hstring_external *) h)); } #endif DUK_FREE(heap, (void *) h); } DUK_INTERNAL void duk_heap_free_heaphdr_raw(duk_heap *heap, duk_heaphdr *hdr) { DUK_ASSERT(heap); DUK_ASSERT(hdr); DUK_DDD(DUK_DDDPRINT("free heaphdr %p, htype %ld", (void *) hdr, (long) DUK_HEAPHDR_GET_TYPE(hdr))); switch (DUK_HEAPHDR_GET_TYPE(hdr)) { case DUK_HTYPE_STRING: duk_free_hstring(heap, (duk_hstring *) hdr); break; case DUK_HTYPE_OBJECT: duk_free_hobject(heap, (duk_hobject *) hdr); break; default: DUK_ASSERT(DUK_HEAPHDR_GET_TYPE(hdr) == DUK_HTYPE_BUFFER); duk_free_hbuffer(heap, (duk_hbuffer *) hdr); } } /* * Free the heap. * * Frees heap-related non-heap-tracked allocations such as the * string intern table; then frees the heap allocated objects; * and finally frees the heap structure itself. Reference counts * and GC markers are ignored (and not updated) in this process, * and finalizers won't be called. * * The heap pointer and heap object pointers must not be used * after this call. */ #if defined(DUK_USE_CACHE_ACTIVATION) DUK_LOCAL duk_size_t duk__heap_free_activation_freelist(duk_heap *heap) { duk_activation *act; duk_activation *act_next; duk_size_t count_act = 0; for (act = heap->activation_free; act != NULL;) { act_next = act->parent; DUK_FREE(heap, (void *) act); act = act_next; #if defined(DUK_USE_DEBUG) count_act++; #endif } heap->activation_free = NULL; /* needed when called from mark-and-sweep */ return count_act; } #endif /* DUK_USE_CACHE_ACTIVATION */ #if defined(DUK_USE_CACHE_CATCHER) DUK_LOCAL duk_size_t duk__heap_free_catcher_freelist(duk_heap *heap) { duk_catcher *cat; duk_catcher *cat_next; duk_size_t count_cat = 0; for (cat = heap->catcher_free; cat != NULL;) { cat_next = cat->parent; DUK_FREE(heap, (void *) cat); cat = cat_next; #if defined(DUK_USE_DEBUG) count_cat++; #endif } heap->catcher_free = NULL; /* needed when called from mark-and-sweep */ return count_cat; } #endif /* DUK_USE_CACHE_CATCHER */ DUK_INTERNAL void duk_heap_free_freelists(duk_heap *heap) { duk_size_t count_act = 0; duk_size_t count_cat = 0; #if defined(DUK_USE_CACHE_ACTIVATION) count_act = duk__heap_free_activation_freelist(heap); #endif #if defined(DUK_USE_CACHE_CATCHER) count_cat = duk__heap_free_catcher_freelist(heap); #endif DUK_UNREF(heap); DUK_UNREF(count_act); DUK_UNREF(count_cat); DUK_D( DUK_DPRINT("freed %ld activation freelist entries, %ld catcher freelist entries", (long) count_act, (long) count_cat)); } DUK_LOCAL void duk__free_allocated(duk_heap *heap) { duk_heaphdr *curr; duk_heaphdr *next; curr = heap->heap_allocated; while (curr) { /* We don't log or warn about freeing zero refcount objects * because they may happen with finalizer processing. */ DUK_DDD(DUK_DDDPRINT("FINALFREE (allocated): %!iO", (duk_heaphdr *) curr)); next = DUK_HEAPHDR_GET_NEXT(heap, curr); duk_heap_free_heaphdr_raw(heap, curr); curr = next; } } #if defined(DUK_USE_FINALIZER_SUPPORT) DUK_LOCAL void duk__free_finalize_list(duk_heap *heap) { duk_heaphdr *curr; duk_heaphdr *next; curr = heap->finalize_list; while (curr) { DUK_DDD(DUK_DDDPRINT("FINALFREE (finalize_list): %!iO", (duk_heaphdr *) curr)); next = DUK_HEAPHDR_GET_NEXT(heap, curr); duk_heap_free_heaphdr_raw(heap, curr); curr = next; } } #endif /* DUK_USE_FINALIZER_SUPPORT */ DUK_LOCAL void duk__free_stringtable(duk_heap *heap) { /* strings are only tracked by stringtable */ duk_heap_strtable_free(heap); } #if defined(DUK_USE_FINALIZER_SUPPORT) DUK_LOCAL void duk__free_run_finalizers(duk_heap *heap) { duk_heaphdr *curr; duk_uint_t round_no; duk_size_t count_all; duk_size_t count_finalized; duk_size_t curr_limit; DUK_ASSERT(heap != NULL); #if defined(DUK_USE_REFERENCE_COUNTING) DUK_ASSERT(heap->refzero_list == NULL); /* refzero not running -> must be empty */ #endif DUK_ASSERT(heap->finalize_list == NULL); /* mark-and-sweep last pass */ if (heap->heap_thread == NULL) { /* May happen when heap allocation fails right off. There * cannot be any finalizable objects in this case. */ DUK_D(DUK_DPRINT("no heap_thread in heap destruct, assume no finalizable objects")); return; } /* Prevent finalize_list processing and mark-and-sweep entirely. * Setting ms_running != 0 also prevents refzero handling from moving * objects away from the heap_allocated list. The flag name is a bit * misleading here. * * Use a distinct value for ms_running here (== 2) so that assertions * can detect this situation separate from the normal runtime * mark-and-sweep case. This allows better assertions (GH-2030). */ DUK_ASSERT(heap->pf_prevent_count == 0); DUK_ASSERT(heap->ms_running == 0); DUK_ASSERT(heap->ms_prevent_count == 0); heap->pf_prevent_count = 1; heap->ms_running = 2; /* Use distinguishable value. */ heap->ms_prevent_count = 1; /* Bump, because mark-and-sweep assumes it's bumped when ms_running is set. */ curr_limit = 0; /* suppress warning, not used */ for (round_no = 0;; round_no++) { curr = heap->heap_allocated; count_all = 0; count_finalized = 0; while (curr) { count_all++; if (DUK_HEAPHDR_IS_OBJECT(curr)) { /* Only objects in heap_allocated may have finalizers. Check that * the object itself has a _Finalizer property (own or inherited) * so that we don't execute finalizers for e.g. Proxy objects. */ DUK_ASSERT(curr != NULL); if (DUK_HOBJECT_HAS_FINALIZER_FAST(heap, (duk_hobject *) curr)) { if (!DUK_HEAPHDR_HAS_FINALIZED((duk_heaphdr *) curr)) { DUK_ASSERT( DUK_HEAP_HAS_FINALIZER_NORESCUE(heap)); /* maps to finalizer 2nd argument */ duk_heap_run_finalizer(heap, (duk_hobject *) curr); count_finalized++; } } } curr = DUK_HEAPHDR_GET_NEXT(heap, curr); } /* Each round of finalizer execution may spawn new finalizable objects * which is normal behavior for some applications. Allow multiple * rounds of finalization, but use a shrinking limit based on the * first round to detect the case where a runaway finalizer creates * an unbounded amount of new finalizable objects. Finalizer rescue * is not supported: the semantics are unclear because most of the * objects being finalized here are already reachable. The finalizer * is given a boolean to indicate that rescue is not possible. * * See discussion in: https://github.com/svaarala/duktape/pull/473 */ if (round_no == 0) { /* Cannot wrap: each object is at least 8 bytes so count is * at most 1/8 of that. */ curr_limit = count_all * 2; } else { curr_limit = (curr_limit * 3) / 4; /* Decrease by 25% every round */ } DUK_D(DUK_DPRINT("finalizer round %ld complete, %ld objects, tried to execute %ld finalizers, current limit is %ld", (long) round_no, (long) count_all, (long) count_finalized, (long) curr_limit)); if (count_finalized == 0) { DUK_D(DUK_DPRINT("no more finalizable objects, forced finalization finished")); break; } if (count_finalized >= curr_limit) { DUK_D(DUK_DPRINT("finalizer count above limit, potentially runaway finalizer; skip remaining finalizers")); break; } } DUK_ASSERT(heap->ms_running == 2); DUK_ASSERT(heap->pf_prevent_count == 1); heap->ms_running = 0; heap->pf_prevent_count = 0; } #endif /* DUK_USE_FINALIZER_SUPPORT */ DUK_INTERNAL void duk_heap_free(duk_heap *heap) { DUK_D(DUK_DPRINT("free heap: %p", (void *) heap)); #if defined(DUK_USE_DEBUG) duk_heap_strtable_dump(heap); #endif #if defined(DUK_USE_DEBUGGER_SUPPORT) /* Detach a debugger if attached (can be called multiple times) * safely. */ /* XXX: Add a flag to reject an attempt to re-attach? Otherwise * the detached callback may immediately reattach. */ duk_debug_do_detach(heap); #endif /* Execute finalizers before freeing the heap, even for reachable * objects. This gives finalizers the chance to free any native * resources like file handles, allocations made outside Duktape, * etc. This is quite tricky to get right, so that all finalizer * guarantees are honored. * * Run mark-and-sweep a few times just in case (unreachable object * finalizers run already here). The last round must rescue objects * from the previous round without running any more finalizers. This * ensures rescued objects get their FINALIZED flag cleared so that * their finalizer is called once more in forced finalization to * satisfy finalizer guarantees. However, we don't want to run any * more finalizers because that'd required one more loop, and so on. * * XXX: this perhaps requires an execution time limit. */ DUK_D(DUK_DPRINT("execute finalizers before freeing heap")); DUK_ASSERT(heap->pf_skip_finalizers == 0); DUK_D(DUK_DPRINT("forced gc #1 in heap destruction")); duk_heap_mark_and_sweep(heap, 0); DUK_D(DUK_DPRINT("forced gc #2 in heap destruction")); duk_heap_mark_and_sweep(heap, 0); DUK_D(DUK_DPRINT("forced gc #3 in heap destruction (don't run finalizers)")); heap->pf_skip_finalizers = 1; duk_heap_mark_and_sweep(heap, 0); /* Skip finalizers; queue finalizable objects to heap_allocated. */ /* There are never objects in refzero_list at this point, or at any * point beyond a DECREF (even a DECREF_NORZ). Since Duktape 2.1 * refzero_list processing is side effect free, so it is always * processed to completion by a DECREF initially triggering a zero * refcount. */ #if defined(DUK_USE_REFERENCE_COUNTING) DUK_ASSERT(heap->refzero_list == NULL); /* Always processed to completion inline. */ #endif #if defined(DUK_USE_FINALIZER_SUPPORT) DUK_ASSERT(heap->finalize_list == NULL); /* Last mark-and-sweep with skip_finalizers. */ #endif #if defined(DUK_USE_FINALIZER_SUPPORT) DUK_D(DUK_DPRINT("run finalizers for remaining finalizable objects")); DUK_HEAP_SET_FINALIZER_NORESCUE(heap); /* Rescue no longer supported. */ duk__free_run_finalizers(heap); #endif /* DUK_USE_FINALIZER_SUPPORT */ /* Note: heap->heap_thread, heap->curr_thread, and heap->heap_object * are on the heap allocated list. */ DUK_D(DUK_DPRINT("freeing temporary freelists")); duk_heap_free_freelists(heap); DUK_D(DUK_DPRINT("freeing heap_allocated of heap: %p", (void *) heap)); duk__free_allocated(heap); #if defined(DUK_USE_REFERENCE_COUNTING) DUK_ASSERT(heap->refzero_list == NULL); /* Always processed to completion inline. */ #endif #if defined(DUK_USE_FINALIZER_SUPPORT) DUK_D(DUK_DPRINT("freeing finalize_list of heap: %p", (void *) heap)); duk__free_finalize_list(heap); #endif DUK_D(DUK_DPRINT("freeing string table of heap: %p", (void *) heap)); duk__free_stringtable(heap); DUK_D(DUK_DPRINT("freeing heap structure: %p", (void *) heap)); heap->free_func(heap->heap_udata, heap); } /* * Allocate a heap. * * String table is initialized with built-in strings from genbuiltins.py, * either by dynamically creating the strings or by referring to ROM strings. */ #if defined(DUK_USE_ROM_STRINGS) DUK_LOCAL duk_bool_t duk__init_heap_strings(duk_heap *heap) { #if defined(DUK_USE_ASSERTIONS) duk_small_uint_t i; #endif DUK_UNREF(heap); /* With ROM-based strings, heap->strs[] and thr->strs[] are omitted * so nothing to initialize for strs[]. */ #if defined(DUK_USE_ASSERTIONS) for (i = 0; i < sizeof(duk_rom_strings_lookup) / sizeof(const duk_hstring *); i++) { const duk_hstring *h; duk_uint32_t hash; h = duk_rom_strings_lookup[i]; while (h != NULL) { hash = duk_heap_hashstring(heap, (const duk_uint8_t *) DUK_HSTRING_GET_DATA(h), DUK_HSTRING_GET_BYTELEN(h)); DUK_DD(DUK_DDPRINT("duk_rom_strings_lookup[%d] -> hash 0x%08lx, computed 0x%08lx", (int) i, (unsigned long) DUK_HSTRING_GET_HASH(h), (unsigned long) hash)); DUK_ASSERT(hash == (duk_uint32_t) DUK_HSTRING_GET_HASH(h)); h = (const duk_hstring *) h->hdr.h_next; } } #endif return 1; } #else /* DUK_USE_ROM_STRINGS */ DUK_LOCAL duk_bool_t duk__init_heap_strings(duk_heap *heap) { duk_bitdecoder_ctx bd_ctx; duk_bitdecoder_ctx *bd = &bd_ctx; /* convenience */ duk_small_uint_t i; duk_memzero(&bd_ctx, sizeof(bd_ctx)); bd->data = (const duk_uint8_t *) duk_strings_data; bd->length = (duk_size_t) DUK_STRDATA_DATA_LENGTH; for (i = 0; i < DUK_HEAP_NUM_STRINGS; i++) { duk_uint8_t tmp[DUK_STRDATA_MAX_STRLEN]; duk_small_uint_t len; duk_hstring *h; len = duk_bd_decode_bitpacked_string(bd, tmp); /* No need to length check string: it will never exceed even * the 16-bit length maximum. */ DUK_ASSERT(len <= 0xffffUL); DUK_DDD(DUK_DDDPRINT("intern built-in string %ld", (long) i)); h = duk_heap_strtable_intern(heap, tmp, len); if (!h) { goto failed; } DUK_ASSERT(!DUK_HEAPHDR_HAS_READONLY((duk_heaphdr *) h)); /* Special flags checks. Since these strings are always * reachable and a string cannot appear twice in the string * table, there's no need to check/set these flags elsewhere. * The 'internal' flag is set by string intern code. */ if (i == DUK_STRIDX_EVAL || i == DUK_STRIDX_LC_ARGUMENTS) { DUK_HSTRING_SET_EVAL_OR_ARGUMENTS(h); } if (i >= DUK_STRIDX_START_RESERVED && i < DUK_STRIDX_END_RESERVED) { DUK_HSTRING_SET_RESERVED_WORD(h); if (i >= DUK_STRIDX_START_STRICT_RESERVED) { DUK_HSTRING_SET_STRICT_RESERVED_WORD(h); } } DUK_DDD(DUK_DDDPRINT("interned: %!O", (duk_heaphdr *) h)); /* XXX: The incref macro takes a thread pointer but doesn't * use it right now. */ DUK_HSTRING_INCREF(_never_referenced_, h); #if defined(DUK_USE_HEAPPTR16) heap->strs16[i] = DUK_USE_HEAPPTR_ENC16(heap->heap_udata, (void *) h); #else heap->strs[i] = h; #endif } return 1; failed: return 0; } #endif /* DUK_USE_ROM_STRINGS */ DUK_LOCAL duk_bool_t duk__init_heap_thread(duk_heap *heap) { duk_hthread *thr; DUK_D(DUK_DPRINT("heap init: alloc heap thread")); thr = duk_hthread_alloc_unchecked(heap, DUK_HOBJECT_FLAG_EXTENSIBLE | DUK_HOBJECT_CLASS_AS_FLAGS(DUK_HOBJECT_CLASS_THREAD)); if (thr == NULL) { DUK_D(DUK_DPRINT("failed to alloc heap_thread")); return 0; } thr->state = DUK_HTHREAD_STATE_INACTIVE; #if defined(DUK_USE_ROM_STRINGS) /* No strs[] pointer. */ #else /* DUK_USE_ROM_STRINGS */ #if defined(DUK_USE_HEAPPTR16) thr->strs16 = heap->strs16; #else thr->strs = heap->strs; #endif #endif /* DUK_USE_ROM_STRINGS */ heap->heap_thread = thr; DUK_HTHREAD_INCREF(thr, thr); /* Note: first argument not really used */ /* 'thr' is now reachable */ DUK_D(DUK_DPRINT("heap init: init heap thread stacks")); if (!duk_hthread_init_stacks(heap, thr)) { return 0; } /* XXX: this may now fail, and is not handled correctly */ duk_hthread_create_builtin_objects(thr); /* default prototype */ DUK_HOBJECT_SET_PROTOTYPE_INIT_INCREF(thr, (duk_hobject *) thr, thr->builtins[DUK_BIDX_THREAD_PROTOTYPE]); return 1; } #if defined(DUK_USE_DEBUG) #define DUK__DUMPSZ(t) \ do { \ DUK_D(DUK_DPRINT("" #t "=%ld", (long) sizeof(t))); \ } while (0) /* These is not 100% because format would need to be non-portable "long long". * Also print out as doubles to catch cases where the "long" type is not wide * enough; the limits will then not be printed accurately but the magnitude * will be correct. */ #define DUK__DUMPLM_SIGNED_RAW(t, a, b) \ do { \ DUK_D(DUK_DPRINT(t "=[%ld,%ld]=[%lf,%lf]", (long) (a), (long) (b), (double) (a), (double) (b))); \ } while (0) #define DUK__DUMPLM_UNSIGNED_RAW(t, a, b) \ do { \ DUK_D(DUK_DPRINT(t "=[%lu,%lu]=[%lf,%lf]", (unsigned long) (a), (unsigned long) (b), (double) (a), (double) (b))); \ } while (0) #define DUK__DUMPLM_SIGNED(t) \ do { \ DUK__DUMPLM_SIGNED_RAW("DUK_" #t "_{MIN,MAX}", DUK_##t##_MIN, DUK_##t##_MAX); \ } while (0) #define DUK__DUMPLM_UNSIGNED(t) \ do { \ DUK__DUMPLM_UNSIGNED_RAW("DUK_" #t "_{MIN,MAX}", DUK_##t##_MIN, DUK_##t##_MAX); \ } while (0) DUK_LOCAL void duk__dump_type_sizes(void) { DUK_D(DUK_DPRINT("sizeof()")); /* basic platform types */ DUK__DUMPSZ(char); DUK__DUMPSZ(short); DUK__DUMPSZ(int); DUK__DUMPSZ(long); DUK__DUMPSZ(double); DUK__DUMPSZ(void *); DUK__DUMPSZ(size_t); /* basic types from duk_config.h */ DUK__DUMPSZ(duk_uint8_t); DUK__DUMPSZ(duk_int8_t); DUK__DUMPSZ(duk_uint16_t); DUK__DUMPSZ(duk_int16_t); DUK__DUMPSZ(duk_uint32_t); DUK__DUMPSZ(duk_int32_t); DUK__DUMPSZ(duk_uint64_t); DUK__DUMPSZ(duk_int64_t); DUK__DUMPSZ(duk_uint_least8_t); DUK__DUMPSZ(duk_int_least8_t); DUK__DUMPSZ(duk_uint_least16_t); DUK__DUMPSZ(duk_int_least16_t); DUK__DUMPSZ(duk_uint_least32_t); DUK__DUMPSZ(duk_int_least32_t); #if defined(DUK_USE_64BIT_OPS) DUK__DUMPSZ(duk_uint_least64_t); DUK__DUMPSZ(duk_int_least64_t); #endif DUK__DUMPSZ(duk_uint_fast8_t); DUK__DUMPSZ(duk_int_fast8_t); DUK__DUMPSZ(duk_uint_fast16_t); DUK__DUMPSZ(duk_int_fast16_t); DUK__DUMPSZ(duk_uint_fast32_t); DUK__DUMPSZ(duk_int_fast32_t); #if defined(DUK_USE_64BIT_OPS) DUK__DUMPSZ(duk_uint_fast64_t); DUK__DUMPSZ(duk_int_fast64_t); #endif DUK__DUMPSZ(duk_uintptr_t); DUK__DUMPSZ(duk_intptr_t); DUK__DUMPSZ(duk_uintmax_t); DUK__DUMPSZ(duk_intmax_t); DUK__DUMPSZ(duk_double_t); /* important chosen base types */ DUK__DUMPSZ(duk_int_t); DUK__DUMPSZ(duk_uint_t); DUK__DUMPSZ(duk_int_fast_t); DUK__DUMPSZ(duk_uint_fast_t); DUK__DUMPSZ(duk_small_int_t); DUK__DUMPSZ(duk_small_uint_t); DUK__DUMPSZ(duk_small_int_fast_t); DUK__DUMPSZ(duk_small_uint_fast_t); /* some derived types */ DUK__DUMPSZ(duk_codepoint_t); DUK__DUMPSZ(duk_ucodepoint_t); DUK__DUMPSZ(duk_idx_t); DUK__DUMPSZ(duk_errcode_t); DUK__DUMPSZ(duk_uarridx_t); /* tval */ DUK__DUMPSZ(duk_double_union); DUK__DUMPSZ(duk_tval); /* structs from duk_forwdecl.h */ DUK__DUMPSZ(duk_jmpbuf); /* just one 'int' for C++ exceptions */ DUK__DUMPSZ(duk_heaphdr); DUK__DUMPSZ(duk_heaphdr_string); DUK__DUMPSZ(duk_hstring); DUK__DUMPSZ(duk_hstring_external); DUK__DUMPSZ(duk_hobject); DUK__DUMPSZ(duk_harray); DUK__DUMPSZ(duk_hcompfunc); DUK__DUMPSZ(duk_hnatfunc); DUK__DUMPSZ(duk_hdecenv); DUK__DUMPSZ(duk_hobjenv); DUK__DUMPSZ(duk_hthread); #if defined(DUK_USE_BUFFEROBJECT_SUPPORT) DUK__DUMPSZ(duk_hbufobj); #endif DUK__DUMPSZ(duk_hproxy); DUK__DUMPSZ(duk_hbuffer); DUK__DUMPSZ(duk_hbuffer_fixed); DUK__DUMPSZ(duk_hbuffer_dynamic); DUK__DUMPSZ(duk_hbuffer_external); DUK__DUMPSZ(duk_propaccessor); DUK__DUMPSZ(duk_propvalue); DUK__DUMPSZ(duk_propdesc); DUK__DUMPSZ(duk_heap); DUK__DUMPSZ(duk_activation); DUK__DUMPSZ(duk_catcher); DUK__DUMPSZ(duk_strcache_entry); DUK__DUMPSZ(duk_litcache_entry); DUK__DUMPSZ(duk_ljstate); DUK__DUMPSZ(duk_fixedbuffer); DUK__DUMPSZ(duk_bitdecoder_ctx); DUK__DUMPSZ(duk_bitencoder_ctx); DUK__DUMPSZ(duk_token); DUK__DUMPSZ(duk_re_token); DUK__DUMPSZ(duk_lexer_point); DUK__DUMPSZ(duk_lexer_ctx); DUK__DUMPSZ(duk_compiler_instr); DUK__DUMPSZ(duk_compiler_func); DUK__DUMPSZ(duk_compiler_ctx); DUK__DUMPSZ(duk_re_matcher_ctx); DUK__DUMPSZ(duk_re_compiler_ctx); } DUK_LOCAL void duk__dump_type_limits(void) { DUK_D(DUK_DPRINT("limits")); /* basic types */ DUK__DUMPLM_SIGNED(INT8); DUK__DUMPLM_UNSIGNED(UINT8); DUK__DUMPLM_SIGNED(INT_FAST8); DUK__DUMPLM_UNSIGNED(UINT_FAST8); DUK__DUMPLM_SIGNED(INT_LEAST8); DUK__DUMPLM_UNSIGNED(UINT_LEAST8); DUK__DUMPLM_SIGNED(INT16); DUK__DUMPLM_UNSIGNED(UINT16); DUK__DUMPLM_SIGNED(INT_FAST16); DUK__DUMPLM_UNSIGNED(UINT_FAST16); DUK__DUMPLM_SIGNED(INT_LEAST16); DUK__DUMPLM_UNSIGNED(UINT_LEAST16); DUK__DUMPLM_SIGNED(INT32); DUK__DUMPLM_UNSIGNED(UINT32); DUK__DUMPLM_SIGNED(INT_FAST32); DUK__DUMPLM_UNSIGNED(UINT_FAST32); DUK__DUMPLM_SIGNED(INT_LEAST32); DUK__DUMPLM_UNSIGNED(UINT_LEAST32); #if defined(DUK_USE_64BIT_OPS) DUK__DUMPLM_SIGNED(INT64); DUK__DUMPLM_UNSIGNED(UINT64); DUK__DUMPLM_SIGNED(INT_FAST64); DUK__DUMPLM_UNSIGNED(UINT_FAST64); DUK__DUMPLM_SIGNED(INT_LEAST64); DUK__DUMPLM_UNSIGNED(UINT_LEAST64); #endif DUK__DUMPLM_SIGNED(INTPTR); DUK__DUMPLM_UNSIGNED(UINTPTR); DUK__DUMPLM_SIGNED(INTMAX); DUK__DUMPLM_UNSIGNED(UINTMAX); /* derived types */ DUK__DUMPLM_SIGNED(INT); DUK__DUMPLM_UNSIGNED(UINT); DUK__DUMPLM_SIGNED(INT_FAST); DUK__DUMPLM_UNSIGNED(UINT_FAST); DUK__DUMPLM_SIGNED(SMALL_INT); DUK__DUMPLM_UNSIGNED(SMALL_UINT); DUK__DUMPLM_SIGNED(SMALL_INT_FAST); DUK__DUMPLM_UNSIGNED(SMALL_UINT_FAST); } DUK_LOCAL void duk__dump_misc_options(void) { DUK_D(DUK_DPRINT("DUK_VERSION: %ld", (long) DUK_VERSION)); DUK_D(DUK_DPRINT("DUK_GIT_DESCRIBE: %s", DUK_GIT_DESCRIBE)); DUK_D(DUK_DPRINT("OS string: %s", DUK_USE_OS_STRING)); DUK_D(DUK_DPRINT("architecture string: %s", DUK_USE_ARCH_STRING)); DUK_D(DUK_DPRINT("compiler string: %s", DUK_USE_COMPILER_STRING)); DUK_D(DUK_DPRINT("debug level: %ld", (long) DUK_USE_DEBUG_LEVEL)); #if defined(DUK_USE_PACKED_TVAL) DUK_D(DUK_DPRINT("DUK_USE_PACKED_TVAL: yes")); #else DUK_D(DUK_DPRINT("DUK_USE_PACKED_TVAL: no")); #endif #if defined(DUK_USE_VARIADIC_MACROS) DUK_D(DUK_DPRINT("DUK_USE_VARIADIC_MACROS: yes")); #else DUK_D(DUK_DPRINT("DUK_USE_VARIADIC_MACROS: no")); #endif #if defined(DUK_USE_INTEGER_LE) DUK_D(DUK_DPRINT("integer endianness: little")); #elif defined(DUK_USE_INTEGER_ME) DUK_D(DUK_DPRINT("integer endianness: mixed")); #elif defined(DUK_USE_INTEGER_BE) DUK_D(DUK_DPRINT("integer endianness: big")); #else DUK_D(DUK_DPRINT("integer endianness: ???")); #endif #if defined(DUK_USE_DOUBLE_LE) DUK_D(DUK_DPRINT("IEEE double endianness: little")); #elif defined(DUK_USE_DOUBLE_ME) DUK_D(DUK_DPRINT("IEEE double endianness: mixed")); #elif defined(DUK_USE_DOUBLE_BE) DUK_D(DUK_DPRINT("IEEE double endianness: big")); #else DUK_D(DUK_DPRINT("IEEE double endianness: ???")); #endif } #endif /* DUK_USE_DEBUG */ DUK_INTERNAL duk_heap *duk_heap_alloc(duk_alloc_function alloc_func, duk_realloc_function realloc_func, duk_free_function free_func, void *heap_udata, duk_fatal_function fatal_func) { duk_heap *res = NULL; duk_uint32_t st_initsize; DUK_D(DUK_DPRINT("allocate heap")); /* * Random config sanity asserts */ DUK_ASSERT(DUK_USE_STRTAB_MINSIZE >= 64); DUK_ASSERT((DUK_HTYPE_STRING & 0x01U) == 0); DUK_ASSERT((DUK_HTYPE_BUFFER & 0x01U) == 0); DUK_ASSERT((DUK_HTYPE_OBJECT & 0x01U) == 1); /* DUK_HEAPHDR_IS_OBJECT() relies ont his. */ /* * Debug dump type sizes */ #if defined(DUK_USE_DEBUG) duk__dump_misc_options(); duk__dump_type_sizes(); duk__dump_type_limits(); #endif /* * If selftests enabled, run them as early as possible. */ #if defined(DUK_USE_SELF_TESTS) DUK_D(DUK_DPRINT("run self tests")); if (duk_selftest_run_tests(alloc_func, realloc_func, free_func, heap_udata) > 0) { fatal_func(heap_udata, "self test(s) failed"); } DUK_D(DUK_DPRINT("self tests passed")); #endif /* * Important assert-like checks that should be enabled even * when assertions are otherwise not enabled. */ #if defined(DUK_USE_EXEC_REGCONST_OPTIMIZE) /* Can't check sizeof() using preprocessor so explicit check. * This will be optimized away in practice; unfortunately a * warning is generated on some compilers as a result. */ #if defined(DUK_USE_PACKED_TVAL) if (sizeof(duk_tval) != 8) { #else if (sizeof(duk_tval) != 16) { #endif fatal_func(heap_udata, "sizeof(duk_tval) not 8 or 16, cannot use DUK_USE_EXEC_REGCONST_OPTIMIZE option"); } #endif /* DUK_USE_EXEC_REGCONST_OPTIMIZE */ /* * Computed values (e.g. INFINITY) */ #if defined(DUK_USE_COMPUTED_NAN) do { /* Workaround for some exotic platforms where NAN is missing * and the expression (0.0 / 0.0) does NOT result in a NaN. * Such platforms use the global 'duk_computed_nan' which must * be initialized at runtime. Use 'volatile' to ensure that * the compiler will actually do the computation and not try * to do constant folding which might result in the original * problem. */ volatile double dbl1 = 0.0; volatile double dbl2 = 0.0; duk_computed_nan = dbl1 / dbl2; } while (0); #endif #if defined(DUK_USE_COMPUTED_INFINITY) do { /* Similar workaround for INFINITY. */ volatile double dbl1 = 1.0; volatile double dbl2 = 0.0; duk_computed_infinity = dbl1 / dbl2; } while (0); #endif /* * Allocate heap struct * * Use a raw call, all macros expect the heap to be initialized */ #if defined(DUK_USE_INJECT_HEAP_ALLOC_ERROR) && (DUK_USE_INJECT_HEAP_ALLOC_ERROR == 1) goto failed; #endif DUK_D(DUK_DPRINT("alloc duk_heap object")); res = (duk_heap *) alloc_func(heap_udata, sizeof(duk_heap)); if (!res) { goto failed; } /* * Zero the struct, and start initializing roughly in order */ duk_memzero(res, sizeof(*res)); #if defined(DUK_USE_ASSERTIONS) res->heap_initializing = 1; #endif /* explicit NULL inits */ #if defined(DUK_USE_EXPLICIT_NULL_INIT) res->heap_udata = NULL; res->heap_allocated = NULL; #if defined(DUK_USE_REFERENCE_COUNTING) res->refzero_list = NULL; #endif #if defined(DUK_USE_FINALIZER_SUPPORT) res->finalize_list = NULL; #if defined(DUK_USE_ASSERTIONS) res->currently_finalizing = NULL; #endif #endif #if defined(DUK_USE_CACHE_ACTIVATION) res->activation_free = NULL; #endif #if defined(DUK_USE_CACHE_CATCHER) res->catcher_free = NULL; #endif res->heap_thread = NULL; res->curr_thread = NULL; res->heap_object = NULL; #if defined(DUK_USE_STRTAB_PTRCOMP) res->strtable16 = NULL; #else res->strtable = NULL; #endif #if defined(DUK_USE_ROM_STRINGS) /* no res->strs[] */ #else /* DUK_USE_ROM_STRINGS */ #if defined(DUK_USE_HEAPPTR16) /* res->strs16[] is zeroed and zero decodes to NULL, so no NULL inits. */ #else { duk_small_uint_t i; for (i = 0; i < DUK_HEAP_NUM_STRINGS; i++) { res->strs[i] = NULL; } } #endif #endif /* DUK_USE_ROM_STRINGS */ #if defined(DUK_USE_DEBUGGER_SUPPORT) res->dbg_read_cb = NULL; res->dbg_write_cb = NULL; res->dbg_peek_cb = NULL; res->dbg_read_flush_cb = NULL; res->dbg_write_flush_cb = NULL; res->dbg_request_cb = NULL; res->dbg_udata = NULL; res->dbg_pause_act = NULL; #endif #endif /* DUK_USE_EXPLICIT_NULL_INIT */ res->alloc_func = alloc_func; res->realloc_func = realloc_func; res->free_func = free_func; res->heap_udata = heap_udata; res->fatal_func = fatal_func; /* XXX: for now there's a pointer packing zero assumption, i.e. * NULL <=> compressed pointer 0. If this is removed, may need * to precompute e.g. null16 here. */ /* res->ms_trigger_counter == 0 -> now causes immediate GC; which is OK */ /* Prevent mark-and-sweep and finalizer execution until heap is completely * initialized. */ DUK_ASSERT(res->ms_prevent_count == 0); DUK_ASSERT(res->pf_prevent_count == 0); res->ms_prevent_count = 1; res->pf_prevent_count = 1; DUK_ASSERT(res->ms_running == 0); res->call_recursion_depth = 0; res->call_recursion_limit = DUK_USE_NATIVE_CALL_RECLIMIT; /* XXX: use the pointer as a seed for now: mix in time at least */ /* The casts through duk_uintptr_t is to avoid the following GCC warning: * * warning: cast from pointer to integer of different size [-Wpointer-to-int-cast] * * This still generates a /Wp64 warning on VS2010 when compiling for x86. */ #if defined(DUK_USE_ROM_STRINGS) /* XXX: make a common DUK_USE_ option, and allow custom fixed seed? */ DUK_D(DUK_DPRINT("using rom strings, force heap hash_seed to fixed value 0x%08lx", (long) DUK__FIXED_HASH_SEED)); res->hash_seed = (duk_uint32_t) DUK__FIXED_HASH_SEED; #else /* DUK_USE_ROM_STRINGS */ res->hash_seed = (duk_uint32_t) (duk_uintptr_t) res; #if !defined(DUK_USE_STRHASH_DENSE) res->hash_seed ^= 5381; /* Bernstein hash init value is normally 5381; XOR it in in case pointer low bits are 0 */ #endif #endif /* DUK_USE_ROM_STRINGS */ #if defined(DUK_USE_EXPLICIT_NULL_INIT) res->lj.jmpbuf_ptr = NULL; #endif DUK_ASSERT(res->lj.type == DUK_LJ_TYPE_UNKNOWN); /* zero */ DUK_ASSERT(res->lj.iserror == 0); DUK_TVAL_SET_UNDEFINED(&res->lj.value1); DUK_TVAL_SET_UNDEFINED(&res->lj.value2); DUK_ASSERT_LJSTATE_UNSET(res); /* * Init stringtable: fixed variant */ st_initsize = DUK_USE_STRTAB_MINSIZE; #if defined(DUK_USE_STRTAB_PTRCOMP) res->strtable16 = (duk_uint16_t *) alloc_func(heap_udata, sizeof(duk_uint16_t) * st_initsize); if (res->strtable16 == NULL) { goto failed; } #else res->strtable = (duk_hstring **) alloc_func(heap_udata, sizeof(duk_hstring *) * st_initsize); if (res->strtable == NULL) { goto failed; } #endif res->st_size = st_initsize; res->st_mask = st_initsize - 1; #if (DUK_USE_STRTAB_MINSIZE != DUK_USE_STRTAB_MAXSIZE) DUK_ASSERT(res->st_count == 0); #endif #if defined(DUK_USE_STRTAB_PTRCOMP) /* zero assumption */ duk_memzero(res->strtable16, sizeof(duk_uint16_t) * st_initsize); #else #if defined(DUK_USE_EXPLICIT_NULL_INIT) { duk_uint32_t i; for (i = 0; i < st_initsize; i++) { res->strtable[i] = NULL; } } #else duk_memzero(res->strtable, sizeof(duk_hstring *) * st_initsize); #endif /* DUK_USE_EXPLICIT_NULL_INIT */ #endif /* DUK_USE_STRTAB_PTRCOMP */ /* * Init stringcache */ #if defined(DUK_USE_EXPLICIT_NULL_INIT) { duk_uint_t i; for (i = 0; i < DUK_HEAP_STRCACHE_SIZE; i++) { res->strcache[i].h = NULL; } } #endif /* * Init litcache */ #if defined(DUK_USE_LITCACHE_SIZE) DUK_ASSERT(DUK_USE_LITCACHE_SIZE > 0); DUK_ASSERT(DUK_IS_POWER_OF_TWO((duk_uint_t) DUK_USE_LITCACHE_SIZE)); #if defined(DUK_USE_EXPLICIT_NULL_INIT) { duk_uint_t i; for (i = 0; i < DUK_USE_LITCACHE_SIZE; i++) { res->litcache[i].addr = NULL; res->litcache[i].h = NULL; } } #endif #endif /* DUK_USE_LITCACHE_SIZE */ /* XXX: error handling is incomplete. It would be cleanest if * there was a setjmp catchpoint, so that all init code could * freely throw errors. If that were the case, the return code * passing here could be removed. */ /* * Init built-in strings */ #if defined(DUK_USE_INJECT_HEAP_ALLOC_ERROR) && (DUK_USE_INJECT_HEAP_ALLOC_ERROR == 2) goto failed; #endif DUK_D(DUK_DPRINT("heap init: initialize heap strings")); if (!duk__init_heap_strings(res)) { goto failed; } /* * Init the heap thread */ #if defined(DUK_USE_INJECT_HEAP_ALLOC_ERROR) && (DUK_USE_INJECT_HEAP_ALLOC_ERROR == 3) goto failed; #endif DUK_D(DUK_DPRINT("heap init: initialize heap thread")); if (!duk__init_heap_thread(res)) { goto failed; } /* * Init the heap object */ #if defined(DUK_USE_INJECT_HEAP_ALLOC_ERROR) && (DUK_USE_INJECT_HEAP_ALLOC_ERROR == 4) goto failed; #endif DUK_D(DUK_DPRINT("heap init: initialize heap object")); DUK_ASSERT(res->heap_thread != NULL); res->heap_object = duk_hobject_alloc_unchecked(res, DUK_HOBJECT_FLAG_EXTENSIBLE | DUK_HOBJECT_FLAG_FASTREFS | DUK_HOBJECT_CLASS_AS_FLAGS(DUK_HOBJECT_CLASS_OBJECT)); if (res->heap_object == NULL) { goto failed; } DUK_HOBJECT_INCREF(res->heap_thread, res->heap_object); /* * Odds and ends depending on the heap thread */ #if !defined(DUK_USE_GET_RANDOM_DOUBLE) #if defined(DUK_USE_PREFER_SIZE) || !defined(DUK_USE_64BIT_OPS) res->rnd_state = (duk_uint32_t) duk_time_get_ecmascript_time(res->heap_thread); duk_util_tinyrandom_prepare_seed(res->heap_thread); #else res->rnd_state[0] = (duk_uint64_t) duk_time_get_ecmascript_time(res->heap_thread); DUK_ASSERT(res->rnd_state[1] == 0); /* Not filled here, filled in by seed preparation. */ #if 0 /* Manual test values matching misc/xoroshiro128plus_test.c. */ res->rnd_state[0] = DUK_U64_CONSTANT(0xdeadbeef12345678); res->rnd_state[1] = DUK_U64_CONSTANT(0xcafed00d12345678); #endif duk_util_tinyrandom_prepare_seed(res->heap_thread); /* Mix in heap pointer: this ensures that if two Duktape heaps are * created on the same millisecond, they get a different PRNG * sequence (unless e.g. virtual memory addresses cause also the * heap object pointer to be the same). */ { duk_uint64_t tmp_u64; tmp_u64 = 0; duk_memcpy((void *) &tmp_u64, (const void *) &res, (size_t) (sizeof(void *) >= sizeof(duk_uint64_t) ? sizeof(duk_uint64_t) : sizeof(void *))); res->rnd_state[1] ^= tmp_u64; } do { duk_small_uint_t i; for (i = 0; i < 10; i++) { /* Throw away a few initial random numbers just in * case. Probably unnecessary due to SplitMix64 * preparation. */ (void) duk_util_tinyrandom_get_double(res->heap_thread); } } while (0); #endif #endif /* * Allow finalizer and mark-and-sweep processing. */ DUK_D(DUK_DPRINT("heap init: allow finalizer/mark-and-sweep processing")); DUK_ASSERT(res->ms_prevent_count == 1); DUK_ASSERT(res->pf_prevent_count == 1); res->ms_prevent_count = 0; res->pf_prevent_count = 0; DUK_ASSERT(res->ms_running == 0); #if defined(DUK_USE_ASSERTIONS) res->heap_initializing = 0; #endif /* * All done. */ DUK_D(DUK_DPRINT("allocated heap: %p", (void *) res)); return res; failed: DUK_D(DUK_DPRINT("heap allocation failed")); if (res != NULL) { /* Assumes that allocated pointers and alloc funcs are valid * if res exists. */ DUK_ASSERT(res->ms_prevent_count == 1); DUK_ASSERT(res->pf_prevent_count == 1); DUK_ASSERT(res->ms_running == 0); if (res->heap_thread != NULL) { res->ms_prevent_count = 0; res->pf_prevent_count = 0; } #if defined(DUK_USE_ASSERTIONS) res->heap_initializing = 0; #endif DUK_ASSERT(res->alloc_func != NULL); DUK_ASSERT(res->realloc_func != NULL); DUK_ASSERT(res->free_func != NULL); duk_heap_free(res); } return NULL; }
16,431
828
/* * Copyright 2002-2010 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 * * 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 net.hasor.db.dialect; import net.hasor.db.metadata.ColumnDef; import net.hasor.db.metadata.TableDef; import java.util.Set; /** * SQL 方言 * @version : 2020-10-31 * @author 赵永春 (<EMAIL>) */ public interface SqlDialect { /** Cannot be used as a key for column names. when column name is key words, Generate SQL using Qualifier warp it. */ public Set<String> keywords(); public String leftQualifier(); public String rightQualifier(); /** 生成 form 后面的表名 */ public String tableName(boolean useQualifier, TableDef tableDef); /** 生成 where 中用到的条件名(包括 group by、order by) */ public String columnName(boolean useQualifier, TableDef tableDef, ColumnDef columnDef); }
429
1,623
#include <fstream> #include <memory> #include <pangolin/image/typed_image.h> namespace pangolin { #pragma pack(push, 1) struct packed12bit_image_header { char magic[4]; char fmt[16]; size_t w, h; }; #pragma pack(pop) void SavePacked12bit(const Image<uint8_t>& image, const pangolin::PixelFormat& fmt, std::ostream& out) { if (fmt.bpp != 16) { throw std::runtime_error("packed12bit currently only supported with 16bit input image"); } const size_t dest_pitch = (image.w*12)/ 8 + ((image.w*12) % 8 > 0? 1 : 0); const size_t dest_size = image.h*dest_pitch; std::unique_ptr<uint8_t[]> output_buffer(new uint8_t[dest_size]); for(size_t r=0; r<image.h; ++r) { uint8_t* pout = output_buffer.get() + r*dest_pitch; uint16_t* pin = (uint16_t*)(image.ptr + r*image.pitch); const uint16_t* pin_end = (uint16_t*)(image.ptr + (r+1)*image.pitch); while(pin < pin_end) { uint32_t val = (*(pin++) & 0x00000FFF); val |= uint32_t(*(pin++) & 0x00000FFF) << 12; *(pout++) = uint8_t( val & 0x000000FF); *(pout++) = uint8_t((val & 0x0000FF00) >> 8); *(pout++) = uint8_t((val & 0x00FF0000) >> 16); } } packed12bit_image_header header; static_assert (sizeof(header.magic) == 4, "[bug]"); memcpy(header.magic, "P12B", 4); memset(header.fmt, '\0', sizeof(header.fmt)); memcpy(header.fmt, fmt.format.c_str(), std::min(sizeof(header.fmt), fmt.format.size()) ); header.w = image.w; header.h = image.h; out.write((char*)&header, sizeof(header)); out.write((char*)output_buffer.get(), dest_size); } TypedImage LoadPacked12bit(std::istream& in) { // Read in header, uncompressed packed12bit_image_header header; in.read((char*)&header, sizeof(header)); TypedImage img(header.w, header.h, PixelFormatFromString(header.fmt)); if (img.fmt.bpp != 16) { throw std::runtime_error("packed12bit currently only supported with 16bit input image"); } const size_t input_pitch = (img.w*12)/ 8 + ((img.w*12) % 8 > 0? 1 : 0); const size_t input_size = img.h*input_pitch; std::unique_ptr<uint8_t[]> input_buffer(new uint8_t[input_size]); in.read((char*)input_buffer.get(), input_size); for(size_t r=0; r<img.h; ++r) { uint16_t* pout = (uint16_t*)(img.ptr + r*img.pitch); uint8_t* pin = input_buffer.get() + r*input_pitch; const uint8_t* pin_end = input_buffer.get() + (r+1)*input_pitch; while(pin < pin_end) { uint32_t val = *(pin++); val |= uint32_t(*(pin++)) << 8; val |= uint32_t(*(pin++)) << 16; *(pout++) = uint16_t( val & 0x000FFF); *(pout++) = uint16_t((val & 0xFFF000) >> 12); } } return img; } }
1,283
1,062
// // Generated by class-dump 3.5b1 (64 bit) (Debug version compiled Dec 3 2019 19:59:57). // // Copyright (C) 1997-2019 <NAME>. // #import "NSObject-Protocol.h" @class CALayer, StackController; @protocol StackDelegate <NSObject> @optional - (void)stackController:(StackController *)arg1 willRemoveLayerForItem:(id)arg2; - (void)stackController:(StackController *)arg1 willDisplayLayer:(CALayer *)arg2 forItem:(id)arg3; - (void)stackController:(StackController *)arg1 willStackLayer:(CALayer *)arg2 forItem:(id)arg3; - (void)stackController:(StackController *)arg1 dataLoadTimedOutInLayer:(CALayer *)arg2 forItem:(id)arg3; - (void)stackControllerDidStopAnimatingLayers:(StackController *)arg1; - (void)stackControllerWillStartAnimatingLayers:(StackController *)arg1; - (void)stackControllerDidStopStackingLayers:(StackController *)arg1; - (void)stackControllerWillStartStackingLayers:(StackController *)arg1; @end
297
2,539
<filename>CPP/7zip/UI/FileManager/SettingsPageRes.h #define IDD_SETTINGS 2500 #define IDD_SETTINGS_2 12500 #define IDX_SETTINGS_SHOW_DOTS 2501 #define IDX_SETTINGS_SHOW_REAL_FILE_ICONS 2502 #define IDX_SETTINGS_SHOW_SYSTEM_MENU 2503 #define IDX_SETTINGS_FULL_ROW 2504 #define IDX_SETTINGS_SHOW_GRID 2505 #define IDX_SETTINGS_SINGLE_CLICK 2506 #define IDX_SETTINGS_ALTERNATIVE_SELECTION 2507 #define IDX_SETTINGS_LARGE_PAGES 2508 #define IDX_SETTINGS_WANT_ARC_HISTORY 2509 #define IDX_SETTINGS_WANT_PATH_HISTORY 2510 #define IDX_SETTINGS_WANT_COPY_HISTORY 2511 #define IDX_SETTINGS_WANT_FOLDER_HISTORY 2512 #define IDX_SETTINGS_LOWERCASE_HASHES 2513
391
323
/* * Copyright (c) 2011-2021 Contributors to the Eclipse Foundation * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 * which is available at https://www.apache.org/licenses/LICENSE-2.0. * * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 */ package io.vertx.pgclient; import io.vertx.core.AbstractVerticle; import io.vertx.core.DeploymentOptions; import io.vertx.core.Future; import io.vertx.core.Promise; import io.vertx.core.Vertx; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import io.vertx.sqlclient.PoolOptions; import io.vertx.sqlclient.SqlConnection; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.util.concurrent.atomic.AtomicReference; @RunWith(VertxUnitRunner.class) public class SharedPoolTest extends PgTestBase { private static final String COUNT_CONNECTIONS_QUERY = "SELECT count(*) FROM pg_stat_activity WHERE application_name LIKE '%vertx%'"; Vertx vertx; @Before public void setup() throws Exception { super.setup(); vertx = Vertx.vertx(); } @After public void tearDown(TestContext ctx) { vertx.close(ctx.asyncAssertSuccess()); } @Test public void testUseSamePool(TestContext ctx) { int maxSize = 8; int instances = maxSize * 4; vertx.deployVerticle(() -> new AbstractVerticle() { PgPool pool; @Override public void start() { pool = PgPool.pool(vertx, options, new PoolOptions().setMaxSize(maxSize).setShared(true)); pool .query("SELECT pg_sleep(0.5);SELECT count(*) FROM pg_stat_activity WHERE application_name LIKE '%vertx%'") .execute(ctx.asyncAssertSuccess(rows -> { ctx.assertTrue(rows.next().iterator().next().getInteger(0) <= maxSize); })); } }, new DeploymentOptions().setInstances(instances), ctx.asyncAssertSuccess()); } @Test public void testCloseAutomatically(TestContext ctx) { int maxSize = 8; int instances = maxSize * 4; Async latch = ctx.async(instances); AtomicReference<String> deployment = new AtomicReference<>(); Async async = ctx.async(); vertx.deployVerticle(() -> new AbstractVerticle() { PgPool pool; @Override public void start() { pool = PgPool.pool(vertx, options, new PoolOptions().setMaxSize(maxSize).setShared(true)); pool .query("SELECT 1") .execute(ctx.asyncAssertSuccess(res -> latch.countDown())); } }, new DeploymentOptions().setInstances(instances), ctx.asyncAssertSuccess(deployment::set)); latch.awaitSuccess(20_000); vertx.undeploy(deployment.get()) .compose(v -> PgConnection.connect(vertx, options)) .compose(conn -> waitUntilConnCountIs(conn, 10, 1) ).onComplete(ctx.asyncAssertSuccess(v -> async.complete())); } private Future<Void> waitUntilConnCountIs(SqlConnection conn, int remaining, int expectedCount) { if (remaining > 0) { return conn.query(COUNT_CONNECTIONS_QUERY).execute().compose(res -> { int num = res.iterator().next().getInteger(0); if (num == expectedCount) { return Future.succeededFuture(); } else { return waitUntilConnCountIs(conn, remaining - 1, expectedCount); } }); } else { return Future.failedFuture("Could not count"); } } @Test public void testPartialClose(TestContext ctx) { int maxSize = 8; int instances = maxSize * 4; Async async = ctx.async(); vertx.deployVerticle(new AbstractVerticle() { PgPool pool; @Override public void start() { pool = PgPool.pool(vertx, options, new PoolOptions().setMaxSize(maxSize).setShared(true)); vertx.deployVerticle(() -> new AbstractVerticle() { @Override public void start(Promise<Void> startPromise) { PgPool pool = PgPool.pool(vertx, options, new PoolOptions().setMaxSize(maxSize).setShared(true)); pool.query("SELECT 1").execute() .<Void>mapEmpty() .onComplete(startPromise); } }, new DeploymentOptions().setInstances(instances), ctx.asyncAssertSuccess(id -> { pool .query(COUNT_CONNECTIONS_QUERY) .execute(ctx.asyncAssertSuccess(res1 -> { int num1 = res1.iterator().next().getInteger(0); ctx.assertTrue(num1 <= maxSize); vertx.undeploy(id) .compose(v -> pool.query(COUNT_CONNECTIONS_QUERY).execute()) .onComplete(ctx.asyncAssertSuccess(res2 -> { int num2 = res1.iterator().next().getInteger(0); ctx.assertEquals(num1, num2); async.complete(); })); })); })); } }); } }
2,058
619
{ "Library": "led", "Description": "LED library", "Sensor Class": { "Led": { "Name": "Light-emitting Diode (LED)", "Description": "UPM module for the LED (or other similar light-emitting diodes). An LED is a p-n junction semiconductor which emits light in response to voltage. The longer wire of an LED connects to the positive seat (anode); the shorter wire connects to the negative seat (cathode). The flat side of the bulb corresponds to the cathode, while the rounded side corresponds to the anode.", "Aliases": ["Grove - LED"], "Categories": ["led"], "Connections": ["gpio"], "Project Type": ["prototyping", "industrial"], "Manufacturers": ["seeed", "dfrobot", "sparkfun", "adafruit", "generic"], "Kits": ["gsk"], "Image": "led.jpg", "Examples": { "Java": ["LED_Example.java"], "Python": ["led.py"], "Node.js": ["led.js"], "C++": ["led.cxx"], "C": ["led.c"] }, "Urls" : { "Product Pages": ["http://wiki.seeed.cc/Grove-LED_Socket_Kit/"], "Schematics": ["https://github.com/SeeedDocument/Grove-LED_Socket_Kit/raw/master/res/Grove-LED_v1.3_Schematics.zip"] } } } }
675
623
<gh_stars>100-1000 //////////////////////////////////////////////////////////////////////////////////////////////////////// // Part of Injectable Generic Camera System // Copyright(c) 2017, <NAME> // All rights reserved. // https://github.com/FransBouma/InjectableGenericCameraSystem // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met : // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and / or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //////////////////////////////////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "CameraManipulator.h" #include "GameConstants.h" #include "InterceptorHelper.h" #include "Globals.h" #include "OverlayConsole.h" using namespace DirectX; using namespace std; extern "C" { LPBYTE g_cameraStructAddress = nullptr; LPBYTE g_cameraCutsceneStructAddress = nullptr; LPBYTE g_timestopStructAddress = nullptr; LPBYTE g_gamespeedStructAddress = nullptr; LPBYTE g_dofStructAddress = nullptr; LPBYTE g_todStructAddress = nullptr; LPBYTE g_weatherStructAddress = nullptr; } namespace IGCS::GameSpecific::CameraManipulator { static float _originalQuaternion[4]; static float _originalCutsceneQuaternion[4]; static float _originalCoords[3]; static float _originalCutsceneCoords[3]; static float _originalFov; static float _originalCutsceneFov; static int _originalToD=12; static int _originalWeatherA = 0; static float _originalWeatherIntensity=1.0f; void getSettingsFromGameState() { Settings& currentSettings = Globals::instance().settings(); if (nullptr != g_dofStructAddress) { float* apertureInMemory = reinterpret_cast<float*>(g_dofStructAddress + DOF_APERTURE_IN_STRUCT_OFFSET); currentSettings.dofAperture = *apertureInMemory; float* focusDistanceInMemory = reinterpret_cast<float*>(g_dofStructAddress + DOF_FOCUS_DISTANCE_IN_STRUCT_OFFSET); currentSettings.dofDistance = *focusDistanceInMemory; float* focalLengthInMemory = reinterpret_cast<float*>(g_dofStructAddress + DOF_FOCAL_LENGTH_IN_STRUCT_OFFSET); currentSettings.dofFocalLength = *focalLengthInMemory; } if (nullptr != g_todStructAddress) { int* todInMemory = reinterpret_cast<int*>(g_todStructAddress + TOD_IN_STRUCT_OFFSET); int currentTodInSeconds = (*todInMemory); currentSettings.todHour = currentTodInSeconds / 3600; currentSettings.todMinute = (currentTodInSeconds - (currentSettings.todHour * 3600)) / 60; } if (nullptr != g_weatherStructAddress) { int* weatherInMemory = reinterpret_cast<int*>(g_weatherStructAddress + WEATHER_DIRECT_IN_STRUCT_OFFSET); currentSettings.weatherA = weatherInMemory[0]; currentSettings.weatherB = weatherInMemory[2]; // 3 values, 0 and 2 are 2 weathers you can blend. 1 is transition effect float* weatherIntensityInMemory = reinterpret_cast<float*>(g_weatherStructAddress + WEATHER_INTENSITY_IN_STRUCT_OFFSET); currentSettings.weatherIntensity = *weatherIntensityInMemory; } } void applySettingsToGameState() { Settings& currentSettings = Globals::instance().settings(); if (nullptr != g_dofStructAddress) { float* apertureInMemory = reinterpret_cast<float*>(g_dofStructAddress + DOF_APERTURE_IN_STRUCT_OFFSET); *apertureInMemory = currentSettings.dofAperture; float* focusDistanceInMemory = reinterpret_cast<float*>(g_dofStructAddress + DOF_FOCUS_DISTANCE_IN_STRUCT_OFFSET); *focusDistanceInMemory = currentSettings.dofDistance; float* focalLengthInMemory = reinterpret_cast<float*>(g_dofStructAddress + DOF_FOCAL_LENGTH_IN_STRUCT_OFFSET); *focalLengthInMemory = currentSettings.dofFocalLength; } if (g_cameraEnabled) { if (nullptr != g_todStructAddress) { int todInSeconds = ((currentSettings.todHour % 24) * 3600) + ((currentSettings.todMinute % 60) * 60); int* todInMemory = reinterpret_cast<int*>(g_todStructAddress + TOD_IN_STRUCT_OFFSET); *todInMemory = todInSeconds; } writeWeatherValue(currentSettings.weatherA, currentSettings.weatherB, currentSettings.weatherIntensity); } } // newValue: 1 == time should be frozen, 0 == normal gameplay // returns true if the game was stopped by this call, false if the game was either already stopped or the state didn't change. bool setTimeStopValue(byte newValue) { if (nullptr == g_timestopStructAddress) { return false; } byte* timestopAddress = (g_timestopStructAddress + TIMESTOP_IN_STRUCT_OFFSET); bool toReturn = *timestopAddress == (byte)0 && (newValue == (byte)1); *timestopAddress = newValue; return toReturn; } // Resets the FOV to the one it got when we enabled the camera void resetFoV() { float* fovInMemory = nullptr; if (isCameraFound()) { fovInMemory = reinterpret_cast<float*>(g_cameraStructAddress + FOV_IN_STRUCT_OFFSET); *fovInMemory = _originalFov; } if (isCutsceneCameraFound()) { fovInMemory = reinterpret_cast<float*>(g_cameraCutsceneStructAddress + FOV_CUTSCENE_IN_STRUCT_OFFSET); *fovInMemory = _originalCutsceneFov; } } // changes the FoV with the specified amount void changeFoV(float amount) { // fov is in focal length, so the higher the number the more zoomed in, hence the negation of the value. float* fovInMemory = nullptr; if (isCameraFound()) { fovInMemory = reinterpret_cast<float*>(g_cameraStructAddress + FOV_IN_STRUCT_OFFSET); *fovInMemory -= amount; } if (isCutsceneCameraFound()) { fovInMemory = reinterpret_cast<float*>(g_cameraCutsceneStructAddress + FOV_CUTSCENE_IN_STRUCT_OFFSET); *fovInMemory -= amount; } } XMFLOAT3 getCurrentCameraCoords() { float* coordsInMemory = reinterpret_cast<float*>(g_cameraStructAddress + COORDS_IN_STRUCT_OFFSET); return XMFLOAT3(coordsInMemory[0], coordsInMemory[1], coordsInMemory[2]); } XMFLOAT3 getCurrentCutsceneCameraCoords() { float* coordsInMemory = reinterpret_cast<float*>(g_cameraCutsceneStructAddress + COORDS_CUTSCENE_IN_STRUCT_OFFSET); return XMFLOAT3(coordsInMemory[0], coordsInMemory[1], coordsInMemory[2]); } // newLookQuaternion: newly calculated quaternion of camera view space. Can be used to construct a 4x4 matrix if the game uses a matrix instead of a quaternion // newCoords are the new coordinates for the camera in worldspace. void writeNewCameraValuesToGameData(XMFLOAT3 newCoords, XMVECTOR newLookQuaternion, bool cutsceneCamera) { float* coordsInMemory = nullptr; float* quaternionInMemory = nullptr; if (cutsceneCamera) { if (nullptr == g_cameraCutsceneStructAddress) { return; } coordsInMemory = reinterpret_cast<float*>(g_cameraCutsceneStructAddress + COORDS_CUTSCENE_IN_STRUCT_OFFSET); quaternionInMemory = reinterpret_cast<float*>(g_cameraCutsceneStructAddress + QUATERNION_CUTSCENE_IN_STRUCT_OFFSET); } else { if (nullptr == g_cameraStructAddress) { return; } coordsInMemory = reinterpret_cast<float*>(g_cameraStructAddress + COORDS_IN_STRUCT_OFFSET); quaternionInMemory = reinterpret_cast<float*>(g_cameraStructAddress + QUATERNION_IN_STRUCT_OFFSET); } if (nullptr==coordsInMemory) { return; } if (nullptr == quaternionInMemory) { return; } coordsInMemory[0] = newCoords.x; coordsInMemory[1] = newCoords.y; coordsInMemory[2] = newCoords.z; XMFLOAT4 qAsFloat4; XMStoreFloat4(&qAsFloat4, newLookQuaternion); quaternionInMemory[0] = qAsFloat4.x; quaternionInMemory[1] = qAsFloat4.y; quaternionInMemory[2] = qAsFloat4.z; quaternionInMemory[3] = qAsFloat4.w; } bool isCameraFound() { return nullptr != g_cameraStructAddress; } bool isCutsceneCameraFound() { return nullptr != g_cameraCutsceneStructAddress; } void displayCameraStructAddress() { OverlayConsole::instance().logDebug("Camera struct address: %p", (void*)g_cameraStructAddress); } // should restore the camera values in the camera structures to the cached values. This assures the free camera is always enabled at the original camera location. void restoreOriginalValuesAfterCameraDisable() { float* coordsInMemory = nullptr; float* quaternionInMemory = nullptr; float* fovInMemory = nullptr; if (isCameraFound()) { coordsInMemory = reinterpret_cast<float*>(g_cameraStructAddress + COORDS_IN_STRUCT_OFFSET); memcpy(coordsInMemory, _originalCoords, 3 * sizeof(float)); quaternionInMemory = reinterpret_cast<float*>(g_cameraStructAddress + QUATERNION_IN_STRUCT_OFFSET); memcpy(quaternionInMemory, _originalQuaternion, 4 * sizeof(float)); fovInMemory = reinterpret_cast<float*>(g_cameraStructAddress + FOV_IN_STRUCT_OFFSET); *fovInMemory = _originalFov; } if (isCutsceneCameraFound()) { coordsInMemory = reinterpret_cast<float*>(g_cameraCutsceneStructAddress + COORDS_CUTSCENE_IN_STRUCT_OFFSET); memcpy(coordsInMemory, _originalCutsceneCoords, 3 * sizeof(float)); quaternionInMemory = reinterpret_cast<float*>(g_cameraCutsceneStructAddress + QUATERNION_CUTSCENE_IN_STRUCT_OFFSET); memcpy(quaternionInMemory, _originalCutsceneQuaternion, 4 * sizeof(float)); fovInMemory = reinterpret_cast<float*>(g_cameraCutsceneStructAddress + FOV_CUTSCENE_IN_STRUCT_OFFSET); *fovInMemory = _originalCutsceneFov; } if (nullptr != g_todStructAddress) { int* todInMemory = reinterpret_cast<int*>(g_todStructAddress + TOD_IN_STRUCT_OFFSET); *todInMemory = _originalToD; } // restore weathers all with weather A writeWeatherValue(_originalWeatherA, _originalWeatherA, _originalWeatherIntensity); // in theory we should reset the cutscene camera pointer to null as it could be the next time the user enables it, it might be somewhere else and the interception // hasn't ran yet. This is such an edge case that we leave it for now, as otherwise the camera can't be enabled twice when the game is paused. } void cacheOriginalValuesBeforeCameraEnable() { float* coordsInMemory = nullptr; float* quaternionInMemory = nullptr; float* fovInMemory = nullptr; if (isCameraFound()) { coordsInMemory = reinterpret_cast<float*>(g_cameraStructAddress + COORDS_IN_STRUCT_OFFSET); memcpy(_originalCoords, coordsInMemory, 3 * sizeof(float)); quaternionInMemory = reinterpret_cast<float*>(g_cameraStructAddress + QUATERNION_IN_STRUCT_OFFSET); memcpy(_originalQuaternion, quaternionInMemory, 4 * sizeof(float)); fovInMemory = reinterpret_cast<float*>(g_cameraStructAddress + FOV_IN_STRUCT_OFFSET); _originalFov = *fovInMemory; } if (isCutsceneCameraFound()) { coordsInMemory = reinterpret_cast<float*>(g_cameraCutsceneStructAddress + COORDS_CUTSCENE_IN_STRUCT_OFFSET); memcpy(_originalCutsceneCoords, coordsInMemory, 3 * sizeof(float)); quaternionInMemory = reinterpret_cast<float*>(g_cameraCutsceneStructAddress + QUATERNION_CUTSCENE_IN_STRUCT_OFFSET); memcpy(_originalCutsceneQuaternion, quaternionInMemory, 4 * sizeof(float)); fovInMemory = reinterpret_cast<float*>(g_cameraCutsceneStructAddress + FOV_CUTSCENE_IN_STRUCT_OFFSET); _originalCutsceneFov = *fovInMemory; } if (nullptr != g_todStructAddress) { int* todInMemory = reinterpret_cast<int*>(g_todStructAddress + TOD_IN_STRUCT_OFFSET); _originalToD = *todInMemory; } if (nullptr != g_weatherStructAddress) { int* weatherInMemory = reinterpret_cast<int*>(g_weatherStructAddress + WEATHER_DIRECT_IN_STRUCT_OFFSET); _originalWeatherA = weatherInMemory[0]; float* weatherIntensityInMemory = reinterpret_cast<float*>(g_weatherStructAddress + WEATHER_INTENSITY_IN_STRUCT_OFFSET); _originalWeatherIntensity = *weatherIntensityInMemory; } } void writeWeatherValue(int newWeatherValueA, int newWeatherValueB, float newWeatherIntensity) { if (nullptr != g_weatherStructAddress) { int* weatherInMemory = reinterpret_cast<int*>(g_weatherStructAddress + WEATHER_DIRECT_IN_STRUCT_OFFSET); weatherInMemory[0] = (newWeatherValueA % 5); weatherInMemory[2] = (newWeatherValueB % 5); weatherInMemory[1] = (newWeatherValueB % 5); // load the intermediate weather last float* weatherIntensityInMemory = reinterpret_cast<float*>(g_weatherStructAddress + WEATHER_INTENSITY_IN_STRUCT_OFFSET); *weatherIntensityInMemory = newWeatherIntensity < 0.0f ? 1.0f : newWeatherIntensity; } } }
4,678
384
<reponame>xuzhao9/benchmark<gh_stars>100-1000 """ Compute the benchmark score given a frozen score configuration and current benchmark data. """ import argparse import json import math import yaml import sys import os from torchbenchmark.score.compute_score import TorchBenchScore if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--score_version", choices=['v0', 'v1'], default="v1", help="which version of score to use - choose from v0 or v1") parser.add_argument("--benchmark_data_file", help="pytest-benchmark json file with current benchmark data") parser.add_argument("--benchmark_data_dir", help="directory containing multiple .json files for each of which to compute a score") parser.add_argument("--relative", action='store_true', help="use the first json file in benchmark data dir instead of the reference yaml") parser.add_argument("--output-norm-only", action='store_true', help="use the benchmark data file specified to output reference norm yaml") args = parser.parse_args() if args.benchmark_data_file is None and args.benchmark_data_dir is None: parser.print_help(sys.stderr) raise ValueError("Invalid command-line arguments. You must specify a data file or a data dir.") files = [] benchmark_data = [] scores = [] if args.benchmark_data_file is not None: with open(args.benchmark_data_file) as data_file: data = json.load(data_file) files.append(args.benchmark_data_file) benchmark_data.append(data) elif args.benchmark_data_dir is not None: for f in sorted(os.listdir(args.benchmark_data_dir)): path = os.path.join(args.benchmark_data_dir, f) if os.path.isfile(path) and os.path.splitext(path)[1] == '.json': with open(path) as data_file: data = json.load(data_file) files.append(f) benchmark_data.append(data) if args.output_norm_only: score_config = TorchBenchScore(ref_data=benchmark_data[0], version=args.score_version) print(yaml.dump(score_config.get_norm(benchmark_data[0]))) exit(0) if args.relative: score_config = TorchBenchScore(ref_data=benchmark_data[0], version=args.score_version) else: score_config = TorchBenchScore(version=args.score_version) results = [] for fname, data in zip(files, benchmark_data): result = {} score = score_config.compute_score(data) result["file"] = fname result["pytorch_version"] = data['machine_info']['pytorch_version'] result["score"] = score results.append(result) print(json.dumps(results, indent=4))
1,099
9,724
#if __EMSCRIPTEN__ #include <stdint.h> #endif #include <string.h> int memcmp(const void *vl, const void *vr, size_t n) { const unsigned char *l=vl, *r=vr; // XXX EMSCRIPTEN: add an optimized version. #if !defined(EMSCRIPTEN_OPTIMIZE_FOR_OZ) && !__has_feature(address_sanitizer) // If we have enough bytes, and everything is aligned, loop on words instead // of single bytes. if (n >= 4 && !((((uintptr_t)l) & 3) | (((uintptr_t)r) & 3))) { while (n >= 4) { if (*((uint32_t *)l) != *((uint32_t *)r)) { // Go to the single-byte loop to find the specific byte. break; } l += 4; r += 4; n -= 4; } } #endif #if defined(EMSCRIPTEN_OPTIMIZE_FOR_OZ) #pragma clang loop unroll(disable) #endif for (; n && *l == *r; n--, l++, r++); return n ? *l-*r : 0; }
349
14,668
<filename>chromeos/services/bluetooth_config/device_conversion_util.cc // 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. #include "chromeos/services/bluetooth_config/device_conversion_util.h" #include <bitset> #include "base/strings/utf_string_conversions.h" #include "device/bluetooth/bluetooth_common.h" #include "device/bluetooth/bluetooth_device.h" #include "device/bluetooth/string_util_icu.h" namespace chromeos { namespace bluetooth_config { namespace { // Returns the DeviceType associated with |device|. Note that BluetoothDevice // expresses more granularity than Bluetooth system UI, so some similar device // types return the same DeviceType value (e.g., both PHONE and MODEM return // the kPhone type). mojom::DeviceType ComputeDeviceType(const device::BluetoothDevice* device) { switch (device->GetDeviceType()) { case device::BluetoothDeviceType::UNKNOWN: return mojom::DeviceType::kUnknown; case device::BluetoothDeviceType::COMPUTER: return mojom::DeviceType::kComputer; case device::BluetoothDeviceType::PHONE: FALLTHROUGH; case device::BluetoothDeviceType::MODEM: return mojom::DeviceType::kPhone; case device::BluetoothDeviceType::AUDIO: FALLTHROUGH; case device::BluetoothDeviceType::CAR_AUDIO: return mojom::DeviceType::kHeadset; case device::BluetoothDeviceType::VIDEO: return mojom::DeviceType::kVideoCamera; case device::BluetoothDeviceType::PERIPHERAL: FALLTHROUGH; case device::BluetoothDeviceType::JOYSTICK: FALLTHROUGH; case device::BluetoothDeviceType::GAMEPAD: return mojom::DeviceType::kGameController; case device::BluetoothDeviceType::KEYBOARD: FALLTHROUGH; case device::BluetoothDeviceType::KEYBOARD_MOUSE_COMBO: return mojom::DeviceType::kKeyboard; case device::BluetoothDeviceType::MOUSE: return mojom::DeviceType::kMouse; case device::BluetoothDeviceType::TABLET: return mojom::DeviceType::kTablet; } } mojom::AudioOutputCapability ComputeAudioOutputCapability( const device::BluetoothDevice* device) { // For a device to provide audio output capabilities, both the "rendering" and // "audio" bits of the Bluetooth class must be set. See // https://crbug.com/1058451 for details. static constexpr int kRenderingBitPosition = 18; static constexpr int kAudioBitPosition = 21; const std::bitset<32> bluetooth_class_bitset(device->GetBluetoothClass()); if (bluetooth_class_bitset.test(kRenderingBitPosition) && bluetooth_class_bitset.test(kAudioBitPosition)) { return mojom::AudioOutputCapability::kCapableOfAudioOutput; } return mojom::AudioOutputCapability::kNotCapableOfAudioOutput; } mojom::BatteryPropertiesPtr ComputeBatteryInfoForBatteryType( const device::BluetoothDevice* device, device::BluetoothDevice::BatteryType battery_type) { const absl::optional<device::BluetoothDevice::BatteryInfo> battery_info = device->GetBatteryInfo(battery_type); if (!battery_info || !battery_info->percentage.has_value()) return nullptr; return mojom::BatteryProperties::New(battery_info->percentage.value()); } mojom::DeviceBatteryInfoPtr ComputeBatteryInfo( const device::BluetoothDevice* device) { // Only provide battery information for devices that are connected. if (!device->IsConnected()) return nullptr; mojom::BatteryPropertiesPtr default_battery = ComputeBatteryInfoForBatteryType( device, device::BluetoothDevice::BatteryType::kDefault); mojom::BatteryPropertiesPtr left_bud_battery = ComputeBatteryInfoForBatteryType( device, device::BluetoothDevice::BatteryType::kLeftBudTrueWireless); mojom::BatteryPropertiesPtr right_bud_battery = ComputeBatteryInfoForBatteryType( device, device::BluetoothDevice::BatteryType::kRightBudTrueWireless); mojom::BatteryPropertiesPtr case_battery = ComputeBatteryInfoForBatteryType( device, device::BluetoothDevice::BatteryType::kCaseTrueWireless); if (!default_battery && !left_bud_battery && !right_bud_battery && !case_battery) { return nullptr; } mojom::DeviceBatteryInfoPtr device_battery_info = mojom::DeviceBatteryInfo::New(); if (default_battery) device_battery_info->default_properties = std::move(default_battery); if (left_bud_battery) device_battery_info->left_bud_info = std::move(left_bud_battery); if (right_bud_battery) device_battery_info->right_bud_info = std::move(right_bud_battery); if (case_battery) device_battery_info->case_info = std::move(case_battery); return device_battery_info; } mojom::DeviceConnectionState ComputeConnectionState( const device::BluetoothDevice* device) { if (device->IsConnected()) return mojom::DeviceConnectionState::kConnected; if (device->IsConnecting()) return mojom::DeviceConnectionState::kConnecting; return mojom::DeviceConnectionState::kNotConnected; } std::u16string ComputeDeviceName(const device::BluetoothDevice* device) { absl::optional<std::string> name = device->GetName(); if (name && device::HasGraphicCharacter(name.value())) return device->GetNameForDisplay(); return base::UTF8ToUTF16(device->GetAddress()); } } // namespace mojom::BluetoothDevicePropertiesPtr GenerateBluetoothDeviceMojoProperties( const device::BluetoothDevice* device) { auto properties = mojom::BluetoothDeviceProperties::New(); properties->id = device->GetIdentifier(); properties->address = device->GetAddress(); properties->public_name = ComputeDeviceName(device); properties->device_type = ComputeDeviceType(device); properties->audio_capability = ComputeAudioOutputCapability(device); properties->battery_info = ComputeBatteryInfo(device); properties->connection_state = ComputeConnectionState(device); properties->is_blocked_by_policy = device->IsBlockedByPolicy(); return properties; } } // namespace bluetooth_config } // namespace chromeos
2,021
3,145
// // ViewController.h // macOS // // Created by <NAME> on 23/06/2016. // Copyright © 2012-2016, JSONModel contributors. MIT licensed. // @import Cocoa; @interface ViewController : NSViewController @end
69
6,989
<filename>linux-4.14.90-dev/linux-4.14.90/include/uapi/linux/atm_eni.h /* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* atm_eni.h - Driver-specific declarations of the ENI driver (for use by driver-specific utilities) */ /* Written 1995-2000 by <NAME>, EPFL LRC/ICA */ #ifndef LINUX_ATM_ENI_H #define LINUX_ATM_ENI_H #include <linux/atmioc.h> struct eni_multipliers { int tx,rx; /* values are in percent and must be > 100 */ }; #define ENI_MEMDUMP _IOW('a',ATMIOC_SARPRV,struct atmif_sioc) /* printk memory map */ #define ENI_SETMULT _IOW('a',ATMIOC_SARPRV+7,struct atmif_sioc) /* set buffer multipliers */ #endif
328
309
# Copyright (c) 2014 Hewlett-Packard Development Company, L.P. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from oslo_serialization import jsonutils import requests from six.moves import http_client as http from glance.tests.functional.v2 import metadef_base class TestMetadefResourceTypes(metadef_base.MetadefFunctionalTestBase): def setUp(self): super(TestMetadefResourceTypes, self).setUp() self.cleanup() self.api_server.deployment_flavor = 'noauth' self.start_servers(**self.__dict__.copy()) def test_metadef_resource_types_lifecycle(self): # Namespace should not exist path = self._url('/v2/metadefs/namespaces/MyNamespace') response = requests.get(path, headers=self._headers()) self.assertEqual(http.NOT_FOUND, response.status_code) # Create a namespace path = self._url('/v2/metadefs/namespaces') headers = self._headers({'content-type': 'application/json'}) namespace_name = 'MyNamespace' data = jsonutils.dumps({ "namespace": namespace_name, "display_name": "My User Friendly Namespace", "description": "My description", "visibility": "public", "protected": False, "owner": "The Test Owner" }) response = requests.post(path, headers=headers, data=data) self.assertEqual(http.CREATED, response.status_code) # Resource type should not exist path = self._url('/v2/metadefs/namespaces/%s/resource_types' % (namespace_name)) response = requests.get(path, headers=self._headers()) metadef_resource_type = jsonutils.loads(response.text) self.assertEqual( 0, len(metadef_resource_type['resource_type_associations'])) # Create a resource type path = self._url('/v2/metadefs/namespaces/MyNamespace/resource_types') headers = self._headers({'content-type': 'application/json'}) metadef_resource_type_name = "resource_type1" data = jsonutils.dumps( { "name": "resource_type1", "prefix": "hw_", "properties_target": "image", } ) response = requests.post(path, headers=headers, data=data) self.assertEqual(http.CREATED, response.status_code) # Attempt to insert a duplicate response = requests.post(path, headers=headers, data=data) self.assertEqual(http.CONFLICT, response.status_code) # Get the metadef resource type created above path = self._url('/v2/metadefs/namespaces/%s/resource_types' % (namespace_name)) response = requests.get(path, headers=self._headers()) self.assertEqual(http.OK, response.status_code) metadef_resource_type = jsonutils.loads(response.text) self.assertEqual( "resource_type1", metadef_resource_type['resource_type_associations'][0]['name']) # Returned resource type should match the created resource type resource_type = jsonutils.loads(response.text) checked_keys = set([ u'name', u'prefix', u'properties_target', u'created_at', u'updated_at' ]) self.assertEqual( set(resource_type['resource_type_associations'][0].keys()), checked_keys) expected_metadef_resource_types = { "name": metadef_resource_type_name, "prefix": "hw_", "properties_target": "image", } # Simple key values checked_values = set([ u'name', u'prefix', u'properties_target', ]) for key, value in expected_metadef_resource_types.items(): if(key in checked_values): self.assertEqual( resource_type['resource_type_associations'][0][key], value, key) # Deassociate of metadef resource type resource_type1 path = self._url('/v2/metadefs/namespaces/%s/resource_types/%s' % (namespace_name, metadef_resource_type_name)) response = requests.delete(path, headers=self._headers()) self.assertEqual(http.NO_CONTENT, response.status_code) # resource_type1 should not exist path = self._url('/v2/metadefs/namespaces/%s/resource_types' % (namespace_name)) response = requests.get(path, headers=self._headers()) metadef_resource_type = jsonutils.loads(response.text) self.assertEqual( 0, len(metadef_resource_type['resource_type_associations'])) def _create_resource_type(self, namespaces): resource_types = [] for namespace in namespaces: headers = self._headers({'X-Tenant-Id': namespace['owner']}) data = { "name": "resource_type_of_%s" % (namespace['namespace']), "prefix": "hw_", "properties_target": "image" } path = self._url('/v2/metadefs/namespaces/%s/resource_types' % (namespace['namespace'])) response = requests.post(path, headers=headers, json=data) self.assertEqual(http.CREATED, response.status_code) rs_type = response.json() resource_type = dict() resource_type[namespace['namespace']] = rs_type['name'] resource_types.append(resource_type) return resource_types def test_role_base_metadef_resource_types_lifecycle(self): # Create public and private namespaces for tenant1 and tenant2 path = self._url('/v2/metadefs/namespaces') headers = self._headers({'content-type': 'application/json'}) tenant1_namespaces = [] tenant2_namespaces = [] for tenant in [self.tenant1, self.tenant2]: headers['X-Tenant-Id'] = tenant for visibility in ['public', 'private']: namespace_data = { "namespace": "%s_%s_namespace" % (tenant, visibility), "display_name": "My User Friendly Namespace", "description": "My description", "visibility": visibility, "owner": tenant } namespace = self.create_namespace(path, headers, namespace_data) self.assertNamespacesEqual(namespace, namespace_data) if tenant == self.tenant1: tenant1_namespaces.append(namespace) else: tenant2_namespaces.append(namespace) # Create a resource type for each namespace created above tenant1_resource_types = self._create_resource_type( tenant1_namespaces) tenant2_resource_types = self._create_resource_type( tenant2_namespaces) def _check_resource_type_access(namespaces, tenant): headers = self._headers({'X-Tenant-Id': tenant, 'X-Roles': 'reader,member'}) for namespace in namespaces: path = self._url('/v2/metadefs/namespaces/%s/resource_types' % (namespace['namespace'])) response = requests.get(path, headers=headers) if namespace['visibility'] == 'public': self.assertEqual(http.OK, response.status_code) else: self.assertEqual(http.NOT_FOUND, response.status_code) def _check_resource_types(tenant, total_rs_types): # Resource types are visible across tenants for all users path = self._url('/v2/metadefs/resource_types') headers = self._headers({'X-Tenant-Id': tenant, 'X-Roles': 'reader,member'}) response = requests.get(path, headers=headers) self.assertEqual(http.OK, response.status_code) metadef_resource_type = response.json() # The resource types list count should be same as the total # resource types created across the tenants. self.assertEqual( sorted(x['name'] for x in metadef_resource_type['resource_types']), sorted(value for x in total_rs_types for key, value in x.items())) # Check Tenant 1 can access resource types of all public namespace # and cannot access resource type of private namespace of Tenant 2 _check_resource_type_access(tenant2_namespaces, self.tenant1) # Check Tenant 2 can access public namespace and cannot access private # namespace of Tenant 1 _check_resource_type_access(tenant1_namespaces, self.tenant2) # List all resource type irrespective of namespace & tenant are # accessible non admin roles total_resource_types = tenant1_resource_types + tenant2_resource_types _check_resource_types(self.tenant1, total_resource_types) _check_resource_types(self.tenant2, total_resource_types) # Disassociate resource type should not be allowed to non admin role for resource_type in total_resource_types: for namespace, rs_type in resource_type.items(): path = \ self._url('/v2/metadefs/namespaces/%s/resource_types/%s' % (namespace, rs_type)) response = requests.delete( path, headers=self._headers({ 'X-Roles': 'reader,member', 'X-Tenant-Id': namespace.split('_')[0] })) self.assertEqual(http.FORBIDDEN, response.status_code) # Disassociate of all metadef resource types headers = self._headers() for resource_type in total_resource_types: for namespace, rs_type in resource_type.items(): path = \ self._url('/v2/metadefs/namespaces/%s/resource_types/%s' % (namespace, rs_type)) response = requests.delete(path, headers=headers) self.assertEqual(http.NO_CONTENT, response.status_code) # Disassociated resource type should not be exist # When the specified resource type is not associated with given # namespace then it returns empty list in response instead of # raising not found error path = self._url( '/v2/metadefs/namespaces/%s/resource_types' % namespace) response = requests.get(path, headers=headers) metadef_resource_type = response.json() self.assertEqual( [], metadef_resource_type['resource_type_associations'])
5,306
488
<reponame>maurizioabba/rose /* * * Copyright (c) International Business Machines Corp., 2001 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See * the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* * NAME * statfs02.c * * DESCRIPTION * Testcase to check that statfs(2) sets errno correctly. * * ALGORITHM * 1. Use a component of the pathname, which is not a directory * in the "path" parameter to statfs(). Expect ENOTDIR * 2. Pass a filename which doesn't exist, and expect ENOENT. * 3. Pass a pathname which is more than MAXNAMLEN, and expect * ENAMETOOLONG. * 4. Pass a pointer to the pathname outside the address space of * the process, and expect EFAULT. * 5. Pass a pointer to the buf paramter outside the address space * of the process, and expect EFAULT. * * USAGE: <for command-line> * statfs02 [-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 * NONE * */ #include <sys/types.h> #include <sys/statfs.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/vfs.h> #include <sys/mman.h> #include <errno.h> #include "test.h" #include "usctest.h" char *TCID = "statfs02"; int fileHandle = 0; extern int Tst_count; int exp_enos[] = { ENOTDIR, ENOENT, ENAMETOOLONG, #if !defined(UCLINUX) EFAULT, 0 #endif }; char *bad_addr = 0; char bad_file[] = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstmnopqrstuvwxyzabcdefghijklmnopqrstmnopqrstuvwxyzabcdefghijklmnopqrstmnopqrstuvwxyzabcdefghijklmnopqrstmnopqrstuvwxyzabcdefghijklmnopqrstmnopqrstuvwxyzabcdefghijklmnopqrstmnopqrstuvwxyz"; char good_dir[100] = "testdir"; char fname[30] = "testfile"; struct statfs fsbuf; char fname1[30]; struct test_case_t { char *path; struct statfs *buf; int error; } TC[] = { /* path has a component which is not a directory - ENOTDIR */ { fname1, &fsbuf, ENOTDIR}, /* path does not exist - ENOENT */ { good_dir, &fsbuf, ENOENT}, /* path is too long - ENAMETOOLONG */ { bad_file, &fsbuf, ENAMETOOLONG}, #ifndef UCLINUX /* Skip since uClinux does not implement memory protection */ /* path is an invalid address - EFAULT */ { (char *)-1, &fsbuf, EFAULT}, /* buf is an invalid address - EFAULT */ { fname, (struct statfs *)-1, EFAULT} #endif }; int TST_TOTAL = sizeof(TC) / sizeof(*TC); void setup(void); void cleanup(void); int main(int ac, char **av) { int lc; /* loop counter */ char *msg; /* message returned from parse_opts */ int i; /* parse standard options */ if ((msg = parse_opts(ac, av, (option_t *) NULL, NULL)) != (char *)NULL) { tst_brkm(TBROK, tst_exit, "OPTION PARSING ERROR - %s", msg); /*NOTREACHED*/} setup(); /* set up 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; /* loop through the test cases */ for (i = 0; i < TST_TOTAL; i++) { TEST(statfs(TC[i].path, TC[i].buf)); if (TEST_RETURN != -1) { tst_resm(TFAIL, "call succeeded unexpectedly"); continue; } TEST_ERROR_LOG(TEST_ERRNO); if (TEST_ERRNO == TC[i].error) { tst_resm(TPASS, "expected failure - " "errno = %d : %s", TEST_ERRNO, strerror(TEST_ERRNO)); } else { tst_resm(TFAIL, "unexpected error - %d : %s - " "expected %d", TEST_ERRNO, strerror(TEST_ERRNO), TC[i].error); } } } cleanup(); /*NOTREACHED*/ return 0; } /* * setup() - performs all ONE TIME setup for this test. */ void setup() { /* capture signals */ tst_sig(NOFORK, DEF_HANDLER, cleanup); /* Pause if that option was specified */ TEST_PAUSE; /* make a temporary directory and cd to it */ tst_tmpdir(); sprintf(fname+strlen(fname), ".%d", getpid()); if ((fileHandle = creat(fname, 0444)) == -1) { tst_resm(TFAIL, "creat(2) FAILED to creat temp file"); } sprintf(fname1, "%s/%s", fname, fname); sprintf(good_dir+strlen(good_dir), ".statfs.%d", getpid()); #if !defined(UCLINUX) bad_addr = mmap(0, 1, PROT_NONE, MAP_PRIVATE_EXCEPT_UCLINUX | MAP_ANONYMOUS, 0, 0); if (bad_addr == MAP_FAILED) { tst_brkm(TBROK, cleanup, "mmap failed"); } TC[3].path = bad_addr; #endif } /* * cleanup() - performs all ONE TIME cleanup for this test at * completion or premature exit. */ void cleanup() { /* * print timing stats if that option was specified. * print errno log if that option was specified. */ close(fileHandle); TEST_CLEANUP; /* delete the test directory created in setup() */ tst_rmdir(); /* exit with return code appropriate for results */ tst_exit(); }
2,253
937
<reponame>HaoZhang95/PythonAndMachineLearning<gh_stars>100-1000 """ 服务器端包含服务器程序+框架 服务器程序比如flask中的GunXX和django使用的uwsgi这两个斗志服务器程序,用来通过WSGI协议链接不同的Web框架 框架就是符合WSGI协议的web代码,通过服务器程序来对外提供高性能的web服务 默认的flask和django中的app.run只是简单的服务器程序,性能只是用来开发测试,线上的产品则需要专业的服务器软件来支持 """ """ 序列化是指将计算机中的数据结构转换为可用于传输的格式:xml,json等,django响应的时候,从数据库读取数据模型对象,然后 通过一个空列表append添加多个字典对象进去,然后jsonresponse将这个列表序列化成json格式的字符串 反序列化就是用户请求的参数为json,进行request.body.decode()成json_str然后进行json.loads()把json转换为字典对象的过程 序列化: 模型对象 --> python字典,用于输出发,返回给前端使用的 反序列化: 前段数据 --> 经过验证 --> python字典,用于输入 序列化器:帮助进行序列化和反序列化 django rest framework(DRF)主要帮我们做了:就是序列化和反序列化,具体的就是不需要手动的append一个个字段 使用这个rest framework框架的serialize方法就可以把ORM对象转化为一个json,省去自己创建空列表,一个个append添加字典的字段 """ """ Serializer(instance=None, data=empty, **kwarg) 用于序列化时,将模**型类对象**传入instance参数 用于反序列化时,将要被反序列化的数据传入data参数 除了instance和data参数外,在构造Serializer对象时,还可通过context参数额外添加数据 """
1,216
372
/* * 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. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.compute.model; /** * gRPC config to access the SDS server. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Compute Engine API. For a detailed explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class GrpcServiceConfig extends com.google.api.client.json.GenericJson { /** * The call credentials to access the SDS server. * The value may be {@code null}. */ @com.google.api.client.util.Key private CallCredentials callCredentials; /** * The channel credentials to access the SDS server. * The value may be {@code null}. */ @com.google.api.client.util.Key private ChannelCredentials channelCredentials; /** * The target URI of the SDS server. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String targetUri; /** * The call credentials to access the SDS server. * @return value or {@code null} for none */ public CallCredentials getCallCredentials() { return callCredentials; } /** * The call credentials to access the SDS server. * @param callCredentials callCredentials or {@code null} for none */ public GrpcServiceConfig setCallCredentials(CallCredentials callCredentials) { this.callCredentials = callCredentials; return this; } /** * The channel credentials to access the SDS server. * @return value or {@code null} for none */ public ChannelCredentials getChannelCredentials() { return channelCredentials; } /** * The channel credentials to access the SDS server. * @param channelCredentials channelCredentials or {@code null} for none */ public GrpcServiceConfig setChannelCredentials(ChannelCredentials channelCredentials) { this.channelCredentials = channelCredentials; return this; } /** * The target URI of the SDS server. * @return value or {@code null} for none */ public java.lang.String getTargetUri() { return targetUri; } /** * The target URI of the SDS server. * @param targetUri targetUri or {@code null} for none */ public GrpcServiceConfig setTargetUri(java.lang.String targetUri) { this.targetUri = targetUri; return this; } @Override public GrpcServiceConfig set(String fieldName, Object value) { return (GrpcServiceConfig) super.set(fieldName, value); } @Override public GrpcServiceConfig clone() { return (GrpcServiceConfig) super.clone(); } }
1,085
4,036
// src1.cpp template<class A> class template_class; template_class<char> *x;
30
315
<reponame>g-r-a-n-t/py-libp2p from libp2p.crypto.keys import KeyPair, PrivateKey from libp2p.network.connection.raw_connection_interface import IRawConnection from libp2p.peer.id import ID from libp2p.security.secure_conn_interface import ISecureConn from libp2p.security.secure_transport_interface import ISecureTransport from libp2p.typing import TProtocol from .patterns import IPattern, PatternXX PROTOCOL_ID = TProtocol("/noise") class Transport(ISecureTransport): libp2p_privkey: PrivateKey noise_privkey: PrivateKey local_peer: ID early_data: bytes with_noise_pipes: bool # NOTE: Implementations that support Noise Pipes must decide whether to use # an XX or IK handshake based on whether they possess a cached static # Noise key for the remote peer. # TODO: A storage of seen noise static keys for pattern IK? def __init__( self, libp2p_keypair: KeyPair, noise_privkey: PrivateKey = None, early_data: bytes = None, with_noise_pipes: bool = False, ) -> None: self.libp2p_privkey = libp2p_keypair.private_key self.noise_privkey = noise_privkey self.local_peer = ID.from_pubkey(libp2p_keypair.public_key) self.early_data = early_data self.with_noise_pipes = with_noise_pipes if self.with_noise_pipes: raise NotImplementedError def get_pattern(self) -> IPattern: if self.with_noise_pipes: raise NotImplementedError else: return PatternXX( self.local_peer, self.libp2p_privkey, self.noise_privkey, self.early_data, ) async def secure_inbound(self, conn: IRawConnection) -> ISecureConn: pattern = self.get_pattern() return await pattern.handshake_inbound(conn) async def secure_outbound(self, conn: IRawConnection, peer_id: ID) -> ISecureConn: pattern = self.get_pattern() return await pattern.handshake_outbound(conn, peer_id)
876
2,329
package iri; import java.lang.reflect.Constructor; import java.lang.reflect.Method; public class JLCGetConstructors2 extends FormattingHelper { public JLCGetConstructors2() { } // not in original public JLCGetConstructors2(String s) { } @SuppressWarnings("rawtypes") public String run() throws Exception { Method m = Class.class.getMethod("getConstructors"); Constructor[] o = (Constructor[]) m.invoke(JLCGetConstructors2.class); // Method m2 = (Method) m.invoke(JLCGetDecMethod.class, "foo", new Class[] { String.class, Integer.TYPE }); return format(o); } public static void main(String[] argv) throws Exception { System.out.println(new JLCGetConstructors2().run()); } }
234
1,716
<reponame>hlemorvan/jimfs /* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.jimfs; import static com.google.common.jimfs.TestUtils.bytes; import static com.google.common.jimfs.TestUtils.regularFile; import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.fail; import com.google.common.util.concurrent.Runnables; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Tests for {@link JimfsOutputStream}. * * @author <NAME> */ @RunWith(JUnit4.class) public class JimfsOutputStreamTest { @Test public void testWrite_singleByte() throws IOException { JimfsOutputStream out = newOutputStream(false); out.write(1); out.write(2); out.write(3); assertStoreContains(out, 1, 2, 3); } @Test public void testWrite_wholeArray() throws IOException { JimfsOutputStream out = newOutputStream(false); out.write(new byte[] {1, 2, 3, 4}); assertStoreContains(out, 1, 2, 3, 4); } @Test public void testWrite_partialArray() throws IOException { JimfsOutputStream out = newOutputStream(false); out.write(new byte[] {1, 2, 3, 4, 5, 6}, 1, 3); assertStoreContains(out, 2, 3, 4); } @Test public void testWrite_partialArray_invalidInput() throws IOException { JimfsOutputStream out = newOutputStream(false); try { out.write(new byte[3], -1, 1); fail(); } catch (IndexOutOfBoundsException expected) { } try { out.write(new byte[3], 0, 4); fail(); } catch (IndexOutOfBoundsException expected) { } try { out.write(new byte[3], 1, 3); fail(); } catch (IndexOutOfBoundsException expected) { } } @Test public void testWrite_singleByte_appendMode() throws IOException { JimfsOutputStream out = newOutputStream(true); addBytesToStore(out, 9, 8, 7); out.write(1); out.write(2); out.write(3); assertStoreContains(out, 9, 8, 7, 1, 2, 3); } @Test public void testWrite_wholeArray_appendMode() throws IOException { JimfsOutputStream out = newOutputStream(true); addBytesToStore(out, 9, 8, 7); out.write(new byte[] {1, 2, 3, 4}); assertStoreContains(out, 9, 8, 7, 1, 2, 3, 4); } @Test public void testWrite_partialArray_appendMode() throws IOException { JimfsOutputStream out = newOutputStream(true); addBytesToStore(out, 9, 8, 7); out.write(new byte[] {1, 2, 3, 4, 5, 6}, 1, 3); assertStoreContains(out, 9, 8, 7, 2, 3, 4); } @Test public void testWrite_singleByte_overwriting() throws IOException { JimfsOutputStream out = newOutputStream(false); addBytesToStore(out, 9, 8, 7, 6, 5, 4, 3); out.write(1); out.write(2); out.write(3); assertStoreContains(out, 1, 2, 3, 6, 5, 4, 3); } @Test public void testWrite_wholeArray_overwriting() throws IOException { JimfsOutputStream out = newOutputStream(false); addBytesToStore(out, 9, 8, 7, 6, 5, 4, 3); out.write(new byte[] {1, 2, 3, 4}); assertStoreContains(out, 1, 2, 3, 4, 5, 4, 3); } @Test public void testWrite_partialArray_overwriting() throws IOException { JimfsOutputStream out = newOutputStream(false); addBytesToStore(out, 9, 8, 7, 6, 5, 4, 3); out.write(new byte[] {1, 2, 3, 4, 5, 6}, 1, 3); assertStoreContains(out, 2, 3, 4, 6, 5, 4, 3); } @Test public void testClosedOutputStream_throwsException() throws IOException { JimfsOutputStream out = newOutputStream(false); out.close(); try { out.write(1); fail(); } catch (IOException expected) { } try { out.write(new byte[3]); fail(); } catch (IOException expected) { } try { out.write(new byte[10], 1, 3); fail(); } catch (IOException expected) { } out.close(); // does nothing } @Test public void testClosedOutputStream_doesNotThrowOnFlush() throws IOException { JimfsOutputStream out = newOutputStream(false); out.close(); out.flush(); // does nothing try (JimfsOutputStream out2 = newOutputStream(false); BufferedOutputStream bout = new BufferedOutputStream(out2); OutputStreamWriter writer = new OutputStreamWriter(bout, UTF_8)) { /* * This specific scenario is why flush() shouldn't throw when the stream is already closed. * Nesting try-with-resources like this will cause close() to be called on the * BufferedOutputStream multiple times. Each time, BufferedOutputStream will first call * out2.flush(), then call out2.close(). If out2.flush() throws when the stream is already * closed, the second flush() will throw an exception. Prior to JDK8, this exception would be * swallowed and ignored completely; in JDK8, the exception is thrown from close(). */ } } private static JimfsOutputStream newOutputStream(boolean append) { RegularFile file = regularFile(0); return new JimfsOutputStream(file, append, new FileSystemState(Runnables.doNothing())); } @SuppressWarnings("GuardedByChecker") private static void addBytesToStore(JimfsOutputStream out, int... bytes) throws IOException { RegularFile file = out.file; long pos = file.sizeWithoutLocking(); for (int b : bytes) { file.write(pos++, (byte) b); } } @SuppressWarnings("GuardedByChecker") private static void assertStoreContains(JimfsOutputStream out, int... bytes) { byte[] actualBytes = new byte[bytes.length]; out.file.read(0, actualBytes, 0, actualBytes.length); assertArrayEquals(bytes(bytes), actualBytes); } }
2,286
15,577
<filename>src/Functions/MultiMatchAllIndicesImpl.h #pragma once #include <base/types.h> #include <Columns/ColumnString.h> #include <DataTypes/DataTypesNumber.h> #include "Regexps.h" #if !defined(ARCADIA_BUILD) # include "config_functions.h" # include <Common/config.h> #endif #if USE_HYPERSCAN # include <hs.h> #else # include "MatchImpl.h" #endif namespace DB { namespace ErrorCodes { extern const int HYPERSCAN_CANNOT_SCAN_TEXT; extern const int CANNOT_ALLOCATE_MEMORY; extern const int NOT_IMPLEMENTED; extern const int TOO_MANY_BYTES; } template <typename Name, typename Type, bool MultiSearchDistance> struct MultiMatchAllIndicesImpl { using ResultType = Type; static constexpr bool is_using_hyperscan = true; /// Variable for understanding, if we used offsets for the output, most /// likely to determine whether the function returns ColumnVector of ColumnArray. static constexpr bool is_column_array = true; static constexpr auto name = Name::name; static auto getReturnType() { return std::make_shared<DataTypeArray>(std::make_shared<DataTypeUInt64>()); } static void vectorConstant( const ColumnString::Chars & haystack_data, const ColumnString::Offsets & haystack_offsets, const std::vector<StringRef> & needles, PaddedPODArray<Type> & res, PaddedPODArray<UInt64> & offsets) { vectorConstant(haystack_data, haystack_offsets, needles, res, offsets, std::nullopt); } static void vectorConstant( const ColumnString::Chars & haystack_data, const ColumnString::Offsets & haystack_offsets, const std::vector<StringRef> & needles, PaddedPODArray<Type> & res, PaddedPODArray<UInt64> & offsets, [[maybe_unused]] std::optional<UInt32> edit_distance) { offsets.resize(haystack_offsets.size()); #if USE_HYPERSCAN const auto & hyperscan_regex = MultiRegexps::get</*SaveIndices=*/true, MultiSearchDistance>(needles, edit_distance); hs_scratch_t * scratch = nullptr; hs_error_t err = hs_clone_scratch(hyperscan_regex->getScratch(), &scratch); if (err != HS_SUCCESS) throw Exception("Could not clone scratch space for hyperscan", ErrorCodes::CANNOT_ALLOCATE_MEMORY); MultiRegexps::ScratchPtr smart_scratch(scratch); auto on_match = [](unsigned int id, unsigned long long /* from */, // NOLINT unsigned long long /* to */, // NOLINT unsigned int /* flags */, void * context) -> int { static_cast<PaddedPODArray<Type>*>(context)->push_back(id); return 0; }; const size_t haystack_offsets_size = haystack_offsets.size(); UInt64 offset = 0; for (size_t i = 0; i < haystack_offsets_size; ++i) { UInt64 length = haystack_offsets[i] - offset - 1; /// Hyperscan restriction. if (length > std::numeric_limits<UInt32>::max()) throw Exception("Too long string to search", ErrorCodes::TOO_MANY_BYTES); /// Scan, check, update the offsets array and the offset of haystack. err = hs_scan( hyperscan_regex->getDB(), reinterpret_cast<const char *>(haystack_data.data()) + offset, length, 0, smart_scratch.get(), on_match, &res); if (err != HS_SUCCESS) throw Exception("Failed to scan with hyperscan", ErrorCodes::HYPERSCAN_CANNOT_SCAN_TEXT); offsets[i] = res.size(); offset = haystack_offsets[i]; } #else (void)haystack_data; (void)haystack_offsets; (void)needles; (void)res; (void)offsets; throw Exception( "multi-search all indices is not implemented when hyperscan is off (is it x86 processor?)", ErrorCodes::NOT_IMPLEMENTED); #endif // USE_HYPERSCAN } }; }
1,847
22,688
<filename>modules/planning/scenarios/stop_sign/unprotected/stop_sign_unprotected_scenario.cc /****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/scenarios/stop_sign/unprotected/stop_sign_unprotected_scenario.h" #include "cyber/common/log.h" #include "modules/perception/proto/perception_obstacle.pb.h" #include "modules/planning/common/frame.h" #include "modules/planning/common/planning_context.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/proto/planning_config.pb.h" #include "modules/planning/scenarios/stop_sign/unprotected/stage_creep.h" #include "modules/planning/scenarios/stop_sign/unprotected/stage_intersection_cruise.h" #include "modules/planning/scenarios/stop_sign/unprotected/stage_pre_stop.h" #include "modules/planning/scenarios/stop_sign/unprotected/stage_stop.h" namespace apollo { namespace planning { namespace scenario { namespace stop_sign { using apollo::hdmap::HDMapUtil; using apollo::hdmap::StopSignInfo; using apollo::hdmap::StopSignInfoConstPtr; using StopSignLaneVehicles = std::unordered_map<std::string, std::vector<std::string>>; apollo::common::util::Factory< ScenarioConfig::StageType, Stage, Stage* (*)(const ScenarioConfig::StageConfig& stage_config, const std::shared_ptr<DependencyInjector>& injector)> StopSignUnprotectedScenario::s_stage_factory_; void StopSignUnprotectedScenario::Init() { if (init_) { return; } Scenario::Init(); if (!GetScenarioConfig()) { AERROR << "fail to get scenario specific config"; return; } const std::string stop_sign_overlap_id = injector_->planning_context() ->planning_status() .stop_sign() .current_stop_sign_overlap_id(); if (stop_sign_overlap_id.empty()) { AERROR << "Could not find stop sign"; return; } hdmap::StopSignInfoConstPtr stop_sign = HDMapUtil::BaseMap().GetStopSignById( hdmap::MakeMapId(stop_sign_overlap_id)); if (!stop_sign) { AERROR << "Could not find stop sign: " << stop_sign_overlap_id; return; } context_.current_stop_sign_overlap_id = stop_sign_overlap_id; context_.watch_vehicles.clear(); GetAssociatedLanes(*stop_sign); init_ = true; } void StopSignUnprotectedScenario::RegisterStages() { if (!s_stage_factory_.Empty()) { s_stage_factory_.Clear(); } s_stage_factory_.Register( ScenarioConfig::STOP_SIGN_UNPROTECTED_PRE_STOP, [](const ScenarioConfig::StageConfig& config, const std::shared_ptr<DependencyInjector>& injector) -> Stage* { return new StopSignUnprotectedStagePreStop(config, injector); }); s_stage_factory_.Register( ScenarioConfig::STOP_SIGN_UNPROTECTED_STOP, [](const ScenarioConfig::StageConfig& config, const std::shared_ptr<DependencyInjector>& injector) -> Stage* { return new StopSignUnprotectedStageStop(config, injector); }); s_stage_factory_.Register( ScenarioConfig::STOP_SIGN_UNPROTECTED_CREEP, [](const ScenarioConfig::StageConfig& config, const std::shared_ptr<DependencyInjector>& injector) -> Stage* { return new StopSignUnprotectedStageCreep(config, injector); }); s_stage_factory_.Register( ScenarioConfig::STOP_SIGN_UNPROTECTED_INTERSECTION_CRUISE, [](const ScenarioConfig::StageConfig& config, const std::shared_ptr<DependencyInjector>& injector) -> Stage* { return new StopSignUnprotectedStageIntersectionCruise(config, injector); }); } std::unique_ptr<Stage> StopSignUnprotectedScenario::CreateStage( const ScenarioConfig::StageConfig& stage_config, const std::shared_ptr<DependencyInjector>& injector) { if (s_stage_factory_.Empty()) { RegisterStages(); } auto ptr = s_stage_factory_.CreateObjectOrNull(stage_config.stage_type(), stage_config, injector); if (ptr) { ptr->SetContext(&context_); } return ptr; } /* * read scenario specific configs and set in context_ for stages to read */ bool StopSignUnprotectedScenario::GetScenarioConfig() { if (!config_.has_stop_sign_unprotected_config()) { AERROR << "miss scenario specific config"; return false; } context_.scenario_config.CopyFrom(config_.stop_sign_unprotected_config()); return true; } /* * get all the lanes associated/guarded by a stop sign */ int StopSignUnprotectedScenario::GetAssociatedLanes( const StopSignInfo& stop_sign_info) { context_.associated_lanes.clear(); std::vector<StopSignInfoConstPtr> associated_stop_signs; HDMapUtil::BaseMap().GetStopSignAssociatedStopSigns(stop_sign_info.id(), &associated_stop_signs); for (const auto stop_sign : associated_stop_signs) { if (stop_sign == nullptr) { continue; } const auto& associated_lane_ids = stop_sign->OverlapLaneIds(); for (const auto& lane_id : associated_lane_ids) { const auto lane = HDMapUtil::BaseMap().GetLaneById(lane_id); if (lane == nullptr) { continue; } for (const auto& stop_sign_overlap : lane->stop_signs()) { auto over_lap_info = stop_sign_overlap->GetObjectOverlapInfo(stop_sign.get()->id()); if (over_lap_info != nullptr) { context_.associated_lanes.push_back( std::make_pair(lane, stop_sign_overlap)); ADEBUG << "stop_sign: " << stop_sign_info.id().id() << "; associated_lane: " << lane_id.id() << "; associated_stop_sign: " << stop_sign.get()->id().id(); } } } } return 0; } } // namespace stop_sign } // namespace scenario } // namespace planning } // namespace apollo
2,530
5,169
{ "name": "SomeFramework", "version": "0.1.3", "summary": "SomeFramework. Private pod to add this framework to any project.", "description": "This is a private cocoapod framework for Sample Purpose.", "homepage": "https://github.com", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "sahajbhaikanhaiya": "<EMAIL>" }, "source": { "http": "https://bitbucket.org/sahajbhaikanhaiya/swfframeworkzip/raw/7f2ac35f30d45d2aee6101c53a6ae966d72f3555/SomeFramework.framework.zip" }, "platforms": { "ios": "9.0" }, "frameworks": "SomeFramework", "vendored_frameworks": "SomeFramework.framework", "dependencies": { "Alamofire": [ "~> 4.5" ], "CryptoSwift": [ ] } }
319
30,023
"""deCONZ number platform tests.""" from unittest.mock import patch import pytest from homeassistant.components.number import ( ATTR_VALUE, DOMAIN as NUMBER_DOMAIN, SERVICE_SET_VALUE, ) from homeassistant.const import ATTR_ENTITY_ID, STATE_UNAVAILABLE from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.helpers.entity import EntityCategory from .test_gateway import ( DECONZ_WEB_REQUEST, mock_deconz_put_request, setup_deconz_integration, ) async def test_no_number_entities(hass, aioclient_mock): """Test that no sensors in deconz results in no number entities.""" await setup_deconz_integration(hass, aioclient_mock) assert len(hass.states.async_all()) == 0 TEST_DATA = [ ( # Presence sensor - delay configuration { "name": "Presence sensor", "type": "ZHAPresence", "state": {"dark": False, "presence": False}, "config": { "delay": 0, "on": True, "reachable": True, "temperature": 10, }, "uniqueid": "00:00:00:00:00:00:00:00-00", }, { "entity_count": 3, "device_count": 3, "entity_id": "number.presence_sensor_delay", "unique_id": "00:00:00:00:00:00:00:00-delay", "state": "0", "entity_category": EntityCategory.CONFIG, "attributes": { "min": 0, "max": 65535, "step": 1, "mode": "auto", "friendly_name": "Presence sensor Delay", }, "websocket_event": {"config": {"delay": 10}}, "next_state": "10", "supported_service_value": 111, "supported_service_response": {"delay": 111}, "unsupported_service_value": 0.1, "unsupported_service_response": {"delay": 0}, "out_of_range_service_value": 66666, }, ) ] @pytest.mark.parametrize("sensor_data, expected", TEST_DATA) async def test_number_entities( hass, aioclient_mock, mock_deconz_websocket, sensor_data, expected ): """Test successful creation of number entities.""" ent_reg = er.async_get(hass) dev_reg = dr.async_get(hass) with patch.dict(DECONZ_WEB_REQUEST, {"sensors": {"0": sensor_data}}): config_entry = await setup_deconz_integration(hass, aioclient_mock) assert len(hass.states.async_all()) == expected["entity_count"] # Verify state data entity = hass.states.get(expected["entity_id"]) assert entity.state == expected["state"] assert entity.attributes == expected["attributes"] # Verify entity registry data ent_reg_entry = ent_reg.async_get(expected["entity_id"]) assert ent_reg_entry.entity_category is expected["entity_category"] assert ent_reg_entry.unique_id == expected["unique_id"] # Verify device registry data assert ( len(dr.async_entries_for_config_entry(dev_reg, config_entry.entry_id)) == expected["device_count"] ) # Change state event_changed_sensor = { "t": "event", "e": "changed", "r": "sensors", "id": "0", "config": {"delay": 10}, } await mock_deconz_websocket(data=event_changed_sensor) await hass.async_block_till_done() assert hass.states.get(expected["entity_id"]).state == expected["next_state"] # Verify service calls mock_deconz_put_request(aioclient_mock, config_entry.data, "/sensors/0/config") # Service set supported value await hass.services.async_call( NUMBER_DOMAIN, SERVICE_SET_VALUE, { ATTR_ENTITY_ID: expected["entity_id"], ATTR_VALUE: expected["supported_service_value"], }, blocking=True, ) assert aioclient_mock.mock_calls[1][2] == expected["supported_service_response"] # Service set float value await hass.services.async_call( NUMBER_DOMAIN, SERVICE_SET_VALUE, { ATTR_ENTITY_ID: expected["entity_id"], ATTR_VALUE: expected["unsupported_service_value"], }, blocking=True, ) assert aioclient_mock.mock_calls[2][2] == expected["unsupported_service_response"] # Service set value beyond the supported range with pytest.raises(ValueError): await hass.services.async_call( NUMBER_DOMAIN, SERVICE_SET_VALUE, { ATTR_ENTITY_ID: expected["entity_id"], ATTR_VALUE: expected["out_of_range_service_value"], }, blocking=True, ) # Unload entry await hass.config_entries.async_unload(config_entry.entry_id) assert hass.states.get(expected["entity_id"]).state == STATE_UNAVAILABLE # Remove entry await hass.config_entries.async_remove(config_entry.entry_id) await hass.async_block_till_done() assert len(hass.states.async_all()) == 0
2,290
709
<gh_stars>100-1000 package com.olacabs.jackhammer.service; import com.google.inject.Inject; import com.google.inject.name.Named; import com.olacabs.jackhammer.common.Constants; import com.olacabs.jackhammer.db.*; import com.olacabs.jackhammer.enums.Severities; import com.olacabs.jackhammer.models.*; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import java.util.ArrayList; import java.util.List; @Slf4j public abstract class AbstractDataService<T extends AbstractModel> { @Inject @Named(Constants.USER_DAO_JDBI) protected UserDAO userDAOJdbi; @Inject @Named(Constants.ROLE_DAO_JDBI) protected RoleDAO roleDAOJdbi; @Inject @Named(Constants.GROUP_USER_DAO) private GroupUserDAO groupUserDAO; @Inject @Named(Constants.GROUP_ROLE_DAO) private GroupRoleDAO groupRoleDAO; @Inject @Named(Constants.TASK_DAO) private TaskDAO taskDAO; @Inject @Named(Constants.ROLE_USER_DAO) private RoleUserDAO roleUserDAO; @Inject @Named(Constants.ROLE_TASK_DAO) private RoleTaskDAO roleTaskDAO; @Inject @Named(Constants.OWNER_TYPE_DAO) private OwnerTypeDAO ownerTypeDAO; @Inject @Named(Constants.SCAN_TYPE_DAO) private ScanTypeDAO scanTypeDAO; @Inject protected PagedResponse paginationRecords; public abstract PagedResponse<T> getAllRecords(T model); public abstract T createRecord(T model); public abstract T fetchRecordByname(T model); public abstract T fetchRecordById(long id); public abstract void updateRecord(T model); public abstract void deleteRecord(long id); public void setCRUDPermissions(PagedResponse<T> pagedResponse, T model, Task task) { List<Task> childTasks = taskDAO.getChildTasks(task.getId()); List<RoleTask> roleTasks = getRoleTasks(model.getUser().getId()); setCurrentUserTasks(pagedResponse, roleTasks, childTasks); } public List<RoleTask> getRoleTasks(long userId) { List<RoleTask> roleTaskList; List<RoleTask> roleTasList = new ArrayList(); List<RoleUser> roleUserList = roleUserDAO.findByUserId(userId); List<GroupUser> groupUserList = groupUserDAO.findByUserId(userId); for (GroupUser groupUser : groupUserList) { List<GroupRole> groupRoleList = groupRoleDAO.findByGroupId(groupUser.getGroupId()); for (GroupRole groupRole : groupRoleList) { roleTaskList = roleTaskDAO.findByRoleId(groupRole.getRoleId()); roleTasList.addAll(roleTaskList); } } for (RoleUser roleUser : roleUserList) { roleTaskList = roleTaskDAO.findByRoleId(roleUser.getRoleId()); roleTasList.addAll(roleTaskList); } return roleTasList; } public void setOwnerAndScanType(PagedResponse<T> pagedResponse, T model) { OwnerType ownerType = null; ScanType scanType = null; if (model.getOwnerTypeId() != 0) ownerType = ownerTypeDAO.get(model.getOwnerTypeId()); if (model.getScanTypeId() != 0) scanType = scanTypeDAO.findScanTypeById(model.getScanTypeId()); pagedResponse.setOwnerType(ownerType); pagedResponse.setScanType(scanType); } public SeverityCount fetchSeverityCountValues(List<SeverityCountChart> severityCountCharts) { SeverityCount severityCount = new SeverityCount(); long totalCount = 0; for (SeverityCountChart severityCountChart : severityCountCharts) { totalCount += severityCountChart.getCount(); switch (Severities.valueOf(severityCountChart.getSeverity().toUpperCase())) { case CRITICAL: severityCount.setCriticalCount(severityCountChart.getCount()); break; case HIGH: severityCount.setHighCount(severityCountChart.getCount()); break; case MEDIUM: severityCount.setMediumCount(severityCountChart.getCount()); break; case LOW: severityCount.setLowCount(severityCountChart.getCount()); break; case INFO: severityCount.setInfoCount(severityCountChart.getCount()); break; default: log.info("Invalid severity {} {}", severityCountChart.getSeverity()); } } severityCount.setTotalCount(totalCount); return severityCount; } public Task getCurrentTask(String taskName, long ownerTypeId) { return taskDAO.getCurrentTask(taskName, ownerTypeId); } public List<Task> getChildTasks(String taskName, long ownerTypeId) { Task task = taskDAO.getCurrentTask(taskName, ownerTypeId); return taskDAO.getChildTasks(task.getId()); } private void setCurrentUserTasks(PagedResponse pagedResponse, List<RoleTask> roleTasks, List<Task> childTasks) { for (RoleTask roleTask : roleTasks) { final Task task = taskDAO.getTask(roleTask.getTaskId()); Boolean taskAssigned = false; for (Task eachTask : childTasks) { if (eachTask.getId() == task.getId()) { taskAssigned = true; break; } } if (taskAssigned) { if (StringUtils.equals(task.getName(), Constants.CREATE)) pagedResponse.setCreateAllowed(true); if (StringUtils.equals(task.getName(), Constants.READ)) pagedResponse.setReadAllowed(true); if (StringUtils.equals(task.getName(), Constants.UPDATE)) pagedResponse.setUpdateAllowed(true); if (StringUtils.equals(task.getName(), Constants.DELETE)) pagedResponse.setDeleteAllowed(true); } } } public Boolean isCorporateRequest(long ownerTypeId) { return getOwnerType(ownerTypeId).getName().contains(Constants.CORPORATE); } public Boolean isGroupRequest(long ownerTypeId) { return getOwnerType(ownerTypeId).getName().contains(Constants.TEAM); } public Boolean isPersonalRequest(long ownerTypeId) { return getOwnerType(ownerTypeId).getName().contains(Constants.PERSONAL); } private OwnerType getOwnerType(long ownerTypeId) { return ownerTypeDAO.get(ownerTypeId); } }
2,865
1,350
<filename>sdk/dataprotection/azure-resourcemanager-dataprotection/src/samples/java/com/azure/resourcemanager/dataprotection/generated/BackupInstancesTriggerRestoreSamples.java // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.dataprotection.generated; import com.azure.core.util.Context; import com.azure.resourcemanager.dataprotection.models.AzureBackupRecoveryPointBasedRestoreRequest; import com.azure.resourcemanager.dataprotection.models.AzureBackupRestoreRequest; import com.azure.resourcemanager.dataprotection.models.Datasource; import com.azure.resourcemanager.dataprotection.models.DatasourceSet; import com.azure.resourcemanager.dataprotection.models.RecoveryOption; import com.azure.resourcemanager.dataprotection.models.RestoreFilesTargetInfo; import com.azure.resourcemanager.dataprotection.models.RestoreTargetInfo; import com.azure.resourcemanager.dataprotection.models.RestoreTargetLocationType; import com.azure.resourcemanager.dataprotection.models.SecretStoreBasedAuthCredentials; import com.azure.resourcemanager.dataprotection.models.SecretStoreResource; import com.azure.resourcemanager.dataprotection.models.SecretStoreType; import com.azure.resourcemanager.dataprotection.models.SourceDataStoreType; import com.azure.resourcemanager.dataprotection.models.TargetDetails; /** Samples for BackupInstances TriggerRestore. */ public final class BackupInstancesTriggerRestoreSamples { /* * x-ms-original-file: specification/dataprotection/resource-manager/Microsoft.DataProtection/stable/2021-07-01/examples/BackupInstanceOperations/TriggerRestoreAsFiles.json */ /** * Sample code: Trigger Restore As Files. * * @param manager Entry point to DataProtectionManager. */ public static void triggerRestoreAsFiles(com.azure.resourcemanager.dataprotection.DataProtectionManager manager) { manager .backupInstances() .triggerRestore( "PrivatePreviewVault1", "000pikumar", "testInstance1", new AzureBackupRecoveryPointBasedRestoreRequest() .withRestoreTargetInfo( new RestoreFilesTargetInfo() .withRecoveryOption(RecoveryOption.FAIL_IF_EXISTS) .withRestoreLocation("southeastasia") .withTargetDetails( new TargetDetails() .withFilePrefix("restoredblob") .withRestoreTargetLocationType(RestoreTargetLocationType.AZURE_BLOBS) .withUrl("https://teststorage.blob.core.windows.net/restoretest"))) .withSourceDataStoreType(SourceDataStoreType.VAULT_STORE) .withRecoveryPointId("hardcodedRP"), Context.NONE); } /* * x-ms-original-file: specification/dataprotection/resource-manager/Microsoft.DataProtection/stable/2021-07-01/examples/BackupInstanceOperations/TriggerRestoreWithRehydration.json */ /** * Sample code: Trigger Restore With Rehydration. * * @param manager Entry point to DataProtectionManager. */ public static void triggerRestoreWithRehydration( com.azure.resourcemanager.dataprotection.DataProtectionManager manager) { manager .backupInstances() .triggerRestore( "PratikPrivatePreviewVault1", "000pikumar", "testInstance1", new AzureBackupRestoreRequest() .withRestoreTargetInfo( new RestoreTargetInfo() .withRecoveryOption(RecoveryOption.FAIL_IF_EXISTS) .withRestoreLocation("southeastasia") .withDatasourceInfo( new Datasource() .withDatasourceType("OssDB") .withObjectType("Datasource") .withResourceId( "/subscriptions/f75d8d8b-6735-4697-82e1-1a7a3ff0d5d4/resourceGroups/viveksipgtest/providers/Microsoft.DBforPostgreSQL/servers/viveksipgtest/databases/testdb") .withResourceLocation("") .withResourceName("testdb") .withResourceType("Microsoft.DBforPostgreSQL/servers/databases") .withResourceUri("")) .withDatasourceSetInfo( new DatasourceSet() .withDatasourceType("OssDB") .withObjectType("DatasourceSet") .withResourceId( "/subscriptions/f75d8d8b-6735-4697-82e1-1a7a3ff0d5d4/resourceGroups/viveksipgtest/providers/Microsoft.DBforPostgreSQL/servers/viveksipgtest") .withResourceLocation("") .withResourceName("viveksipgtest") .withResourceType("Microsoft.DBforPostgreSQL/servers") .withResourceUri(""))) .withSourceDataStoreType(SourceDataStoreType.VAULT_STORE), Context.NONE); } /* * x-ms-original-file: specification/dataprotection/resource-manager/Microsoft.DataProtection/stable/2021-07-01/examples/BackupInstanceOperations/TriggerRestore.json */ /** * Sample code: Trigger Restore. * * @param manager Entry point to DataProtectionManager. */ public static void triggerRestore(com.azure.resourcemanager.dataprotection.DataProtectionManager manager) { manager .backupInstances() .triggerRestore( "PratikPrivatePreviewVault1", "000pikumar", "testInstance1", new AzureBackupRecoveryPointBasedRestoreRequest() .withRestoreTargetInfo( new RestoreTargetInfo() .withRecoveryOption(RecoveryOption.FAIL_IF_EXISTS) .withRestoreLocation("southeastasia") .withDatasourceInfo( new Datasource() .withDatasourceType("OssDB") .withObjectType("Datasource") .withResourceId( "/subscriptions/f75d8d8b-6735-4697-82e1-1a7a3ff0d5d4/resourceGroups/viveksipgtest/providers/Microsoft.DBforPostgreSQL/servers/viveksipgtest/databases/testdb") .withResourceLocation("") .withResourceName("testdb") .withResourceType("Microsoft.DBforPostgreSQL/servers/databases") .withResourceUri("")) .withDatasourceSetInfo( new DatasourceSet() .withDatasourceType("OssDB") .withObjectType("DatasourceSet") .withResourceId( "/subscriptions/f75d8d8b-6735-4697-82e1-1a7a3ff0d5d4/resourceGroups/viveksipgtest/providers/Microsoft.DBforPostgreSQL/servers/viveksipgtest") .withResourceLocation("") .withResourceName("viveksipgtest") .withResourceType("Microsoft.DBforPostgreSQL/servers") .withResourceUri("")) .withDatasourceAuthCredentials( new SecretStoreBasedAuthCredentials() .withSecretStoreResource( new SecretStoreResource() .withUri("https://samplevault.vault.azure.net/secrets/credentials") .withSecretStoreType(SecretStoreType.AZURE_KEY_VAULT)))) .withSourceDataStoreType(SourceDataStoreType.VAULT_STORE) .withRecoveryPointId("hardcodedRP"), Context.NONE); } }
4,520
323
<filename>dreamplace/ops/place_io/src/BinMap.cpp<gh_stars>100-1000 /************************************************************************* > File Name: BinMap.cpp > Author: <NAME> > Mail: <EMAIL> > Created Time: Tue 23 Jun 2015 08:57:40 PM CDT ************************************************************************/ #include "BinMap.h" DREAMPLACE_BEGIN_NAMESPACE BinMap& BinMap::set(BinType type, BinMap::index_type xNum, BinMap::index_type yNum) { m_dimension[kX] = xNum; m_dimension[kY] = yNum; m_vBin.resize(xNum*yNum); // only set bin indices // bin coordinates are set outside since layout information is not known index_type id2DX = 0; index_type id2DY = 0; for (index_type id1D = 0, id1De = m_vBin.size(); id1D < id1De; ++id1D) { Bin& bin = m_vBin.at(id1D); bin.setType(type); bin.setIndex1D(id1D); bin.setIndex2D(kX, id2DX) .setIndex2D(kY, id2DY); id2DX += 1; if (id2DX == m_dimension[kX]) { id2DX = 0; id2DY += 1; } } return *this; } BinMap& BinMap::resetBinDemand() { for (BinMap1DIterator it = begin1D(), ite = end1D(); it != ite; ++it) { it->setDemand(0); it->setPinDemand(0); } return *this; } DREAMPLACE_END_NAMESPACE
626
568
package com.fincatto.documentofiscal.cte300.classes.nota; import com.fincatto.documentofiscal.DFBase; import org.simpleframework.xml.Element; import org.simpleframework.xml.ElementList; import org.simpleframework.xml.Namespace; import org.simpleframework.xml.Root; import java.util.List; /** * @author Caio * @info Dados da cobrança do CT-e */ @Root(name = "cobr") @Namespace(reference = "http://www.portalfiscal.inf.br/cte") public class CTeNotaInfoCTeNormalCobranca extends DFBase { private static final long serialVersionUID = 3613541664304195294L; @Element(name = "fat", required = false) private CTeNotaInfoCTeNormalCobrancaFatura fatura; @ElementList(entry = "dup", inline = true, required = false) private List<CTeNotaInfoCTeNormalCobrancaDuplicata> duplicata; public CTeNotaInfoCTeNormalCobranca() { this.fatura = null; this.duplicata = null; } public CTeNotaInfoCTeNormalCobrancaFatura getFatura() { return this.fatura; } /** * Dados da fatura */ public void setFatura(final CTeNotaInfoCTeNormalCobrancaFatura fatura) { this.fatura = fatura; } public List<CTeNotaInfoCTeNormalCobrancaDuplicata> getDuplicata() { return this.duplicata; } /** * Dados das duplicatas */ public void setDuplicata(final List<CTeNotaInfoCTeNormalCobrancaDuplicata> duplicata) { this.duplicata = duplicata; } }
664
765
<gh_stars>100-1000 /* * Copyright (c) 2021 <NAME> * Copyright (c) 2019 Arm Limited * All rights reserved. * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Copyright (c) 2003-2005 The Regents of The University of Michigan * 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 copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "base/stats/storage.hh" #include <cmath> namespace gem5 { GEM5_DEPRECATED_NAMESPACE(Stats, statistics); namespace statistics { void DistStor::sample(Counter val, int number) { assert(bucket_size > 0); if (val < min_track) underflow += number; else if (val > max_track) overflow += number; else { cvec[std::floor((val - min_track) / bucket_size)] += number; } if (val < min_val) min_val = val; if (val > max_val) max_val = val; sum += val * number; squares += val * val * number; samples += number; } void HistStor::growOut() { int size = cvec.size(); int zero = size / 2; // round down! int top_half = zero + (size - zero + 1) / 2; // round up! int bottom_half = (size - zero) / 2; // round down! // grow down int low_pair = zero - 1; for (int i = zero - 1; i >= bottom_half; i--) { cvec[i] = cvec[low_pair]; if (low_pair - 1 >= 0) cvec[i] += cvec[low_pair - 1]; low_pair -= 2; } assert(low_pair == 0 || low_pair == -1 || low_pair == -2); for (int i = bottom_half - 1; i >= 0; i--) cvec[i] = Counter(); // grow up int high_pair = zero; for (int i = zero; i < top_half; i++) { cvec[i] = cvec[high_pair]; if (high_pair + 1 < size) cvec[i] += cvec[high_pair + 1]; high_pair += 2; } assert(high_pair == size || high_pair == size + 1); for (int i = top_half; i < size; i++) cvec[i] = Counter(); max_bucket *= 2; min_bucket *= 2; bucket_size *= 2; } void HistStor::growDown() { const int size = cvec.size(); const int zero = size / 2; // round down! const bool even = ((size - 1) % 2) == 0; // Make sure that zero becomes the lower bound of the middle bucket. On // an even number of buckets the last bucket does not change its lower // bound, therefore it does not need to absorb any other bucket int pair = size - 1; if (even) { pair--; } for (int i = pair; i >= zero; --i) { cvec[i] = cvec[pair]; if (pair - 1 >= 0) cvec[i] += cvec[pair - 1]; pair -= 2; } for (int i = zero - 1; i >= 0; i--) cvec[i] = Counter(); // Double the range by using the negative of the lower bound of the last // bucket as the new lower bound of the first bucket min_bucket = -max_bucket; // A special case must be handled when there is an odd number of // buckets so that zero is kept as the lower bound of the middle bucket if (!even) { min_bucket -= bucket_size; max_bucket -= bucket_size; } // Only update the bucket size once the range has been updated bucket_size *= 2; } void HistStor::growUp() { int size = cvec.size(); int half = (size + 1) / 2; // round up! int pair = 0; for (int i = 0; i < half; i++) { cvec[i] = cvec[pair]; if (pair + 1 < size) cvec[i] += cvec[pair + 1]; pair += 2; } assert(pair == size || pair == size + 1); for (int i = half; i < size; i++) cvec[i] = Counter(); max_bucket *= 2; bucket_size *= 2; } void HistStor::sample(Counter val, int number) { assert(min_bucket < max_bucket); if (val < min_bucket) { if (min_bucket == 0) growDown(); while (val < min_bucket) growOut(); } else if (val >= max_bucket + bucket_size) { if (min_bucket == 0) { while (val >= max_bucket + bucket_size) growUp(); } else { while (val >= max_bucket + bucket_size) growOut(); } } assert(bucket_size > 0); size_type index = (int64_t)std::floor((val - min_bucket) / bucket_size); assert(index < size()); cvec[index] += number; sum += val * number; squares += val * val * number; logs += std::log(val) * number; samples += number; } void HistStor::add(HistStor *hs) { int b_size = hs->size(); assert(size() == b_size); assert(min_bucket == hs->min_bucket); sum += hs->sum; logs += hs->logs; squares += hs->squares; samples += hs->samples; while (bucket_size > hs->bucket_size) hs->growUp(); while (bucket_size < hs->bucket_size) growUp(); for (uint32_t i = 0; i < b_size; i++) cvec[i] += hs->cvec[i]; } } // namespace statistics } // namespace gem5
2,598
511
<gh_stars>100-1000 /**************************************************************************** * * Copyright 2019 Samsung Electronics All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific * language governing permissions and limitations under the License. * ****************************************************************************/ // Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef _SSL_PORT_H_ #define _SSL_PORT_H_ #include <string.h> #include <stdlib.h> #include <stdio.h> #ifdef __cplusplus extern "C" { #endif #define ssl_mem_zalloc(s) zalloc(s) #define ssl_mem_malloc(s) malloc(s) #define ssl_mem_free(p) free(p) #define ssl_memcpy memcpy #define ssl_strlen strlen #ifdef CONFIG_SMP #define ssl_speed_up_enter() rtc_clk_cpu_freq_set(RTC_CPU_FREQ_160M) #define ssl_speed_up_exit() rtc_clk_cpu_freq_set(RTC_CPU_FREQ_80M) #else #define ssl_speed_up_enter() #define ssl_speed_up_exit() #endif #define SSL_DEBUG_LOG printf #endif
605
1,144
<gh_stars>1000+ /* * (C) Copyright 2016 * <NAME>, DENX Software Engineering, <EMAIL>. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc. */ #ifndef _SWUPDATE_SSL_H #define _SWUPDATE_SSL_H /* * openSSL is not mandatory * Let compile when openSSL is not activated */ #if defined(CONFIG_HASH_VERIFY) || defined(CONFIG_ENCRYPTED_IMAGES) #include <openssl/bio.h> #include <openssl/objects.h> #include <openssl/err.h> #include <openssl/x509.h> #include <openssl/x509v3.h> #include <openssl/pem.h> #include <openssl/evp.h> #include <openssl/hmac.h> #include <openssl/aes.h> #ifdef CONFIG_SIGALG_CMS #if defined(LIBRESSL_VERSION_NUMBER) #error "LibreSSL does not support CMS, please select RSA PKCS" #else #include <openssl/cms.h> #endif #endif #include <openssl/opensslv.h> struct swupdate_digest { EVP_PKEY *pkey; /* this is used for RSA key */ X509_STORE *certs; /* this is used if CMS is set */ EVP_MD_CTX *ctx; #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER) EVP_CIPHER_CTX ctxdec; #else EVP_CIPHER_CTX *ctxdec; #endif }; #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER) #define SSL_GET_CTXDEC(dgst) &dgst->ctxdec #else #define SSL_GET_CTXDEC(dgst) dgst->ctxdec #endif /* * This just initialize globally the openSSL * library * It must be called just once */ #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER) #define swupdate_crypto_init() { \ do { \ CRYPTO_malloc_init(); \ OpenSSL_add_all_algorithms(); \ } while (0); \ } #else #define swupdate_crypto_init() #endif #else #define swupdate_crypto_init() #define AES_BLOCK_SIZE 16 #endif #if defined(CONFIG_HASH_VERIFY) int swupdate_dgst_init(struct swupdate_cfg *sw, const char *keyfile); struct swupdate_digest *swupdate_HASH_init(void); int swupdate_HASH_update(struct swupdate_digest *dgst, unsigned char *buf, size_t len); int swupdate_HASH_final(struct swupdate_digest *dgst, unsigned char *md_value, unsigned int *md_len); void swupdate_HASH_cleanup(struct swupdate_digest *dgst); int swupdate_verify_file(struct swupdate_digest *dgst, const char *sigfile, const char *file); int swupdate_HASH_compare(unsigned char *hash1, unsigned char *hash2); #else #define swupdate_dgst_init(sw, keyfile) ( 0 ) #define swupdate_HASH_init(p) ( NULL ) #define swupdate_verify_file(dgst, sigfile, file) ( 0 ) #define swupdate_HASH_update(p, buf, len) #define swupdate_HASH_final(p, result, len) #define swupdate_HASH_cleanup(sw) #define swupdate_HASH_compare(hash1,hash2) (0) #endif #ifdef CONFIG_ENCRYPTED_IMAGES struct swupdate_digest *swupdate_DECRYPT_init(unsigned char *key, unsigned char *iv); int swupdate_DECRYPT_update(struct swupdate_digest *dgst, unsigned char *buf, int *outlen, unsigned char *cryptbuf, int inlen); int swupdate_DECRYPT_final(struct swupdate_digest *dgst, unsigned char *buf, int *outlen); void swupdate_DECRYPT_cleanup(struct swupdate_digest *dgst); #else /* * Note: macro for swupdate_DECRYPT_init is * just to avoid compiler warnings */ #define swupdate_DECRYPT_init(key, iv) (((key != NULL) | (ivt != NULL)) ? NULL : NULL) #define swupdate_DECRYPT_update(p, buf, len, cbuf, inlen) (-1) #define swupdate_DECRYPT_final(p, buf, len) (-1) #define swupdate_DECRYPT_cleanup(p) #endif #endif
1,469
348
<filename>docs/data/leg-t2/067/06706492.json<gh_stars>100-1000 {"nom":"Traenheim","circ":"6ème circonscription","dpt":"Bas-Rhin","inscrits":556,"abs":277,"votants":279,"blancs":11,"nuls":5,"exp":263,"res":[{"nuance":"LR","nom":"<NAME>","voix":164},{"nuance":"MDM","nom":"<NAME>","voix":99}]}
121
334
<filename>Telespot/Telespot/Library/EChart/EColumnDataModel.h<gh_stars>100-1000 // // EColumnDataModel.h // EChart // // Created by <NAME> on 13-12-12. // Copyright (c) 2013 <NAME>. All rights reserved. // #import <Foundation/Foundation.h> @interface EColumnDataModel : NSObject @property (strong, nonatomic) NSString *label; @property (nonatomic) float value; @property (nonatomic) NSInteger index; @property (nonatomic, strong) NSString *unit; - (id)initWithLabel:(NSString *)label value:(float)vaule index:(NSInteger)index unit:(NSString *)unit; @end
237
457
<filename>TestScripts/C Tests/DataTests.h //Copyright (c) 2013-2018 United States Government as represented by the Administrator of the //National Aeronautics and Space Administration. All Rights Reserved. #ifndef DATATESTS_H #define DATATESTS_H #include "Test.h" #include "xplaneConnect.h" int testDATA() { // Initialize int i, j; // Iterator const char* drefs[100] = { "sim/aircraft/parts/acf_gear_deploy" }; float* data[100]; // array for result of getDREFs int sizes[100]; float DATA[4][9]; // Array for sendDATA XPCSocket sock = openUDP(IP); // Setup for (int i = 0; i < 100; ++i) { data[i] = (float*)malloc(40 * sizeof(float)); sizes[i] = 40; } for (i = 0; i < 4; i++) { for (j = 0; j < 9; j++) { data[i][j] = -998; } } DATA[0][0] = 14; // Gear DATA[0][1] = 1; DATA[0][2] = 0; // Execution sendDATA(sock, DATA, 1); int result = getDREFs(sock, drefs, data, 1, sizes); // Close closeUDP(sock); // Tests if (result < 0)// Request 1 value { return -1; } if (sizes[0] != 10) { return -2; } if (*data[0] != data[0][1]) { return -3; } return 0; } #endif
494
627
<filename>include/mock/fpsensor_detect_mock.h /* Copyright 2020 The Chromium OS 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 __MOCK_FPSENSOR_DETECT_MOCK_H #define __MOCK_FPSENSOR_DETECT_MOCK_H #include "fpsensor_detect.h" struct mock_ctrl_fpsensor_detect { enum fp_sensor_type get_fp_sensor_type_return; enum fp_transport_type get_fp_transport_type_return; }; #define MOCK_CTRL_DEFAULT_FPSENSOR_DETECT { \ .get_fp_sensor_type_return = FP_SENSOR_TYPE_UNKNOWN, \ .get_fp_transport_type_return = FP_TRANSPORT_TYPE_UNKNOWN, \ } extern struct mock_ctrl_fpsensor_detect mock_ctrl_fpsensor_detect; #endif /* __MOCK_FPSENSOR_DETECT_MOCK_H */
308
2,461
/* * Copyright 2013-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.cloud.kubernetes.client.config; import io.kubernetes.client.openapi.apis.CoreV1Api; import org.springframework.cloud.kubernetes.commons.KubernetesClientProperties; import org.springframework.cloud.kubernetes.commons.KubernetesNamespaceProvider; import org.springframework.cloud.kubernetes.commons.config.ConfigMapConfigProperties; import org.springframework.cloud.kubernetes.commons.config.ConfigMapPropertySourceLocator; import org.springframework.cloud.kubernetes.commons.config.NamespaceResolutionFailedException; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.MapPropertySource; import org.springframework.util.StringUtils; /** * @author <NAME> * @author <NAME> */ public class KubernetesClientConfigMapPropertySourceLocator extends ConfigMapPropertySourceLocator { private final CoreV1Api coreV1Api; private final KubernetesClientProperties kubernetesClientProperties; private final KubernetesNamespaceProvider kubernetesNamespaceProvider; /** * This constructor is deprecated. Its usage might cause unexpected behavior when * looking for different properties. For example, in general, if a namespace is not * provided, we might look it up via other means: different documented environment * variables or from a kubernetes client itself. Using this constructor might not * reflect that. */ @Deprecated public KubernetesClientConfigMapPropertySourceLocator(CoreV1Api coreV1Api, ConfigMapConfigProperties properties, KubernetesClientProperties kubernetesClientProperties) { super(properties); this.coreV1Api = coreV1Api; this.kubernetesClientProperties = kubernetesClientProperties; this.kubernetesNamespaceProvider = null; } public KubernetesClientConfigMapPropertySourceLocator(CoreV1Api coreV1Api, ConfigMapConfigProperties properties, KubernetesNamespaceProvider kubernetesNamespaceProvider) { super(properties); this.coreV1Api = coreV1Api; this.kubernetesNamespaceProvider = kubernetesNamespaceProvider; this.kubernetesClientProperties = null; } @Override protected MapPropertySource getMapPropertySource(String name, ConfigMapConfigProperties.NormalizedSource normalizedSource, String configurationTarget, ConfigurableEnvironment environment) { String namespace; String normalizedNamespace = normalizedSource.getNamespace(); if (StringUtils.hasText(normalizedNamespace)) { namespace = normalizedNamespace; } else if (kubernetesClientProperties != null) { if (StringUtils.hasText(kubernetesClientProperties.getNamespace())) { namespace = kubernetesClientProperties.getNamespace(); } else { throw new NamespaceResolutionFailedException( "could not resolve namespace in normalized source or KubernetesClientProperties"); } } else { namespace = KubernetesClientConfigUtils.getApplicationNamespace(normalizedNamespace, "Config Map", kubernetesNamespaceProvider); } return new KubernetesClientConfigMapPropertySource(coreV1Api, name, namespace, environment, normalizedSource.getPrefix(), normalizedSource.isIncludeProfileSpecificSources(), this.properties.isFailFast()); } }
1,135
827
/* * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH * under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. Camunda licenses this file to you under the Apache License, * Version 2.0; you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.camunda.bpm.example.test; import static org.junit.Assert.assertEquals; import org.camunda.bpm.engine.HistoryService; import org.camunda.bpm.engine.RepositoryService; import org.camunda.bpm.engine.RuntimeService; import org.camunda.bpm.engine.history.HistoricProcessInstance; import org.camunda.bpm.engine.test.Deployment; import org.camunda.bpm.engine.test.ProcessEngineRule; import org.camunda.bpm.model.bpmn.BpmnModelInstance; import org.camunda.bpm.model.bpmn.instance.Process; import org.camunda.bpm.model.bpmn.instance.camunda.CamundaProperties; import org.camunda.bpm.model.bpmn.instance.camunda.CamundaProperty; import org.junit.Before; import org.junit.Rule; import org.junit.Test; /** * Test Bpmn Parse listener as process engine plugin and * parse extension properties on bpmn element * * @author kristin.polenz * */ public class PerProcessVariableHistoryLevelTest { @Rule public ProcessEngineRule processEngineRule = new ProcessEngineRule("camunda-per-process.cfg.xml"); protected RepositoryService repositoryService; protected RuntimeService runtimeService; protected HistoryService historyService; @Before public void getEngineServices() { repositoryService = processEngineRule.getRepositoryService(); runtimeService = processEngineRule.getRuntimeService(); historyService = processEngineRule.getHistoryService(); } @Test @Deployment(resources = { "process-history-none.bpmn" }) public void testProcessHistoryNone() { runtimeService.startProcessInstanceByKey("process-history-none"); // assert that no history was written assertEquals(0, historyService.createHistoricProcessInstanceQuery().count()); assertEquals(0, historyService.createHistoricActivityInstanceQuery().count()); assertEquals(0, historyService.createHistoricVariableInstanceQuery().count()); } @Test @Deployment(resources = { "process-history-activity.bpmn" }) public void testProcessHistoryActivity() { runtimeService.startProcessInstanceByKey("process-history-activity"); // assert that only activity history was written assertEquals(1, historyService.createHistoricProcessInstanceQuery().count()); assertEquals(3, historyService.createHistoricActivityInstanceQuery().count()); assertEquals(0, historyService.createHistoricVariableInstanceQuery().count()); } @Test @Deployment(resources = { "process-history-full.bpmn" }) public void testProcessHistoryFull() { runtimeService.startProcessInstanceByKey("process-history-full"); // assert that full history was written assertEquals(1, historyService.createHistoricProcessInstanceQuery().count()); assertEquals(3, historyService.createHistoricActivityInstanceQuery().count()); assertEquals(4, historyService.createHistoricVariableInstanceQuery().count()); } @Test @Deployment(resources = { "process-history-custom-variable.bpmn" }) public void testProcessHistoryCustomVariable() { runtimeService.startProcessInstanceByKey("process-history-custom-variable"); // assert that full history was written assertEquals(1, historyService.createHistoricProcessInstanceQuery().count()); assertEquals(3, historyService.createHistoricActivityInstanceQuery().count()); assertEquals(2, historyService.createHistoricVariableInstanceQuery().count()); } @Test @Deployment(resources = {"process-history-full.bpmn"}) public void testChangeHistoryLevelByRedeploying() { runtimeService.startProcessInstanceByKey("process-history-full"); // assert that full history was written assertEquals(1, historyService.createHistoricProcessInstanceQuery().count()); assertEquals(3, historyService.createHistoricActivityInstanceQuery().count()); assertEquals(4, historyService.createHistoricVariableInstanceQuery().count()); // delete history entries for (HistoricProcessInstance processInstance : historyService.createHistoricProcessInstanceQuery().list()) { historyService.deleteHistoricProcessInstance(processInstance.getId()); } // redeploy process definition with history level none String processDefinitionId = repositoryService.createProcessDefinitionQuery().singleResult().getId(); BpmnModelInstance modelInstance = repositoryService.getBpmnModelInstance(processDefinitionId); Process process = (Process) modelInstance.getDefinitions().getUniqueChildElementByType(Process.class); CamundaProperties camundaProperties = process.getExtensionElements().getElementsQuery().filterByType(CamundaProperties.class).singleResult(); for (CamundaProperty camundaProperty : camundaProperties.getCamundaProperties()) { if (camundaProperty.getCamundaName().equals("history")) { camundaProperty.setCamundaValue("none"); } } repositoryService.createDeployment().addModelInstance("process.bpmn", modelInstance).deploy(); // start instance with new process definition runtimeService.startProcessInstanceByKey("process-history-full"); // assert that no new history was written assertEquals(0, historyService.createHistoricProcessInstanceQuery().count()); assertEquals(0, historyService.createHistoricActivityInstanceQuery().count()); assertEquals(0, historyService.createHistoricVariableInstanceQuery().count()); } }
1,702
394
<reponame>CoeOmnichannel/LaunchNavigator-OS /* * LN_LaunchNavigator Library * * Copyright (c) 2018 <NAME> (http://github.com/dpa99c) * Copyright (c) 2018 Working Edge Ltd. (http://www.workingedge.co.uk) * * 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. * */ #import <MapKit/MapKit.h> #import <CoreLocation/CoreLocation.h> #import "WE_Logger.h" // This enumeration identifies the mapping apps // that this launcher knows how to support. typedef NS_ENUM(NSUInteger, LNApp) { LNAppAppleMaps = 0, // Preinstalled Apple Maps LNAppCitymapper, // Citymapper LNAppGoogleMaps, // Standalone Google Maps App LNAppNavigon, // Navigon LNAppTheTransitApp, // The Transit App LNAppWaze, // Waze LNAppYandex, // Yandex Navigator LNAppUber, // Uber LNAppTomTom, // TomTom LNAppSygic, // Sygic LNAppHereMaps, // HERE Maps LNAppMoovit, // Moovit LNAppLyft, // Lyft LNAppMapsMe, // MAPS.ME LNAppCabify, // Cabify LNAppBaidu, // Baidu LNAppTaxis99, // 99 Taxi LNAppGaode // Gaode (Amap) }; static NSString*const LOG_TAG = @"LN_LaunchNavigator[native]"; static NSString*const LNLocTypeNone = @"none"; static NSString*const LNLocTypeBoth = @"both"; static NSString*const LNLocTypeAddress = @"name"; static NSString*const LNLocTypeCoords = @"coords"; /** Indicates an empty coordinate */ static CLLocationCoordinate2D LNEmptyCoord; /** Indicates an empty latitude or longitude component */ static const CLLocationDegrees LNEmptyLocation = 0.000000; @interface LN_LaunchNavigator : NSObject <CLLocationManagerDelegate> {} typedef void (^NavigateSuccessBlock)(void); typedef void (^NavigateFailBlock)(NSString* errorMsg); typedef void(^LocationSuccessBlock)(CLLocation*); typedef void(^LocationErrorBlock)(NSError*); @property (nonatomic, strong) NavigateSuccessBlock navigateSuccess; @property (nonatomic, strong) NavigateFailBlock navigateFail; @property (nonatomic, strong) LocationSuccessBlock locationSuccess; @property (nonatomic, strong) LocationErrorBlock locationError; @property (retain, nonatomic) CLLocationManager* locationManager; /******************* * Public API *******************/ - (id)init:(WE_Logger*) logger; - (void)setLogger:(WE_Logger*) logger; - (WE_Logger*)getLogger; - (void) navigate:(NSDictionary*)params success:(NavigateSuccessBlock)success fail:(NavigateFailBlock)fail; - (BOOL) isAppAvailable:(NSString*)appName; - (NSDictionary*) availableApps; @end
1,252
890
/* * * Copyright 2019 Asylo 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 * * 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. * */ // This test checks the POSIX-compliance of Asylo's implementations of pipe(), // pipe2(), and the F_(GET|SET)PIPE_SZ commands to fcntl(). It is run inside an // enclave. It is also independently run on the host to confirm the test logic. // For pipe2(). #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif // _GNU_SOURCE #include <fcntl.h> #include <sys/stat.h> #include <unistd.h> #include <bitset> #include <cerrno> #include <climits> #include <cstddef> #include <cstdint> #include <cstring> #include <fstream> #include <ostream> #include <vector> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/types/span.h" #include "asylo/test/util/memory_matchers.h" #include "asylo/util/cleanup.h" namespace asylo { namespace { using ::testing::Eq; using ::testing::Ge; using ::testing::Gt; using ::testing::Le; using ::testing::Ne; class BasePipeTest : public ::testing::Test { protected: void SetUp() override { int pipe_fds[2]; ASSERT_THAT(CallPipe(pipe_fds), Eq(0)) << strerror(errno); read_fd_ = pipe_fds[0]; write_fd_ = pipe_fds[1]; int pipe_size = fcntl(write_fd_, F_GETPIPE_SZ, 0); ASSERT_THAT(pipe_size, Ne(-1)) << strerror(errno); small_data_ = {'f', 'o', 'o', 'b', 'a', 'r', '\0'}; packet_data_ = TestBuffer(0, PIPE_BUF); pipe_capacity_data_ = TestBuffer(0xff, pipe_size); large_data_ = TestBuffer(0xaa, pipe_size * 2); } void TearDown() override { ASSERT_THAT(close(read_fd_), Eq(0)) << strerror(errno); ASSERT_THAT(close(write_fd_), Eq(0)) << strerror(errno); } // Returns non-periodic test data of length |length|, using to |modifier| to // distinguish the data from data returned by other invocations of this // function. std::vector<uint8_t> TestBuffer(uint8_t modifier, size_t length) { std::vector<uint8_t> buffer(length); for (int i = 0; i < buffer.size(); ++i) { buffer[i] = modifier ^ std::bitset<8 * sizeof(i)>(i).count(); } return buffer; } // As pipe(), but may call pipe2() with flags instead. virtual int CallPipe(int pipe_fds[2]) = 0; // Attempts to enlarge the pipe. Updates |pipe_size_| and // |pipe_capacity_data_| and returns true if the operation succeeds. // Otherwise, returns false. bool EnlargePipe() { constexpr char kMaxPipeSizeFile[] = "/proc/sys/fs/pipe-max-size"; std::ifstream max_pipe_size_file(kMaxPipeSizeFile); int max_pipe_size; max_pipe_size_file >> max_pipe_size; EXPECT_THAT(pipe_capacity_data_.size(), Le(max_pipe_size)); if (pipe_capacity_data_.size() == max_pipe_size) { return false; } int fcntl_result = fcntl(write_fd_, F_SETPIPE_SZ, max_pipe_size); if (fcntl_result < 0) { EXPECT_THAT(fcntl_result, Eq(-1)); EXPECT_THAT(errno, Eq(EPERM)) << strerror(errno); return false; } EXPECT_THAT(fcntl_result, Eq(max_pipe_size)); pipe_capacity_data_ = TestBuffer(0x24, fcntl_result); return fcntl_result; } // The read end of the pipe. int read_fd_; // The write end of the pipe. int write_fd_; // Test data that should fit within a default-sized pipe's buffer without // filling it. std::vector<uint8_t> small_data_; // Test data that should take up an entire O_DIRECT pipe packet. std::vector<uint8_t> packet_data_; // Test data that should fill an empty default-sized pipe's buffer // without overflowing. std::vector<uint8_t> pipe_capacity_data_; // Test data that should exceed a default-sized pipe's buffer. std::vector<uint8_t> large_data_; }; class PipeTest : public BasePipeTest { public: int CallPipe(int pipe_fds[2]) override { return pipe(pipe_fds); } }; template <int kPipe2Flags> class Pipe2Test : public BasePipeTest { public: int CallPipe(int pipe_fds[2]) override { return pipe2(pipe_fds, kPipe2Flags); } }; template <typename T> using AllPipeVarietiesTest = T; using PipeTestFixtures = ::testing::Types< PipeTest, Pipe2Test<0>, Pipe2Test<O_CLOEXEC>, Pipe2Test<O_DIRECT>, Pipe2Test<O_NONBLOCK>, Pipe2Test<O_CLOEXEC | O_DIRECT>, Pipe2Test<O_CLOEXEC | O_NONBLOCK>, Pipe2Test<O_DIRECT | O_NONBLOCK>, Pipe2Test<O_CLOEXEC | O_DIRECT | O_NONBLOCK>>; TYPED_TEST_SUITE(AllPipeVarietiesTest, PipeTestFixtures); using CloexecPipeTest = Pipe2Test<O_CLOEXEC>; using DirectPipeTest = Pipe2Test<O_DIRECT>; using NonblockPipeTest = Pipe2Test<O_NONBLOCK>; // Tests that pipe() populates the pipe_fds array with two distinct, non- // negative file descriptors. TYPED_TEST(AllPipeVarietiesTest, PipeGivesValidFileDescriptorPairs) { EXPECT_THAT(this->read_fd_, Ge(0)); EXPECT_THAT(this->write_fd_, Ge(0)); EXPECT_THAT(this->read_fd_, Ne(this->write_fd_)); } // Tests that the file descriptors returned by pipe() refer to FIFO files. TYPED_TEST(AllPipeVarietiesTest, PipeFdsAreFifos) { struct stat statbuf; ASSERT_THAT(fstat(this->read_fd_, &statbuf), Eq(0)) << strerror(errno); EXPECT_TRUE(S_ISFIFO(statbuf.st_mode)); ASSERT_THAT(fstat(this->write_fd_, &statbuf), Eq(0)) << strerror(errno); EXPECT_TRUE(S_ISFIFO(statbuf.st_mode)); } // Tests that small writes to an open pipe succeed. TYPED_TEST(AllPipeVarietiesTest, SmallWritingToOpenPipesSucceeds) { EXPECT_THAT(write(this->write_fd_, this->small_data_.data(), this->small_data_.size()), Ge(0)) << strerror(errno); } // Tests that PIPE_BUF-sized writes to an open pipe succeed. TYPED_TEST(AllPipeVarietiesTest, CapacitySizedWritingToOpenPipesSucceeds) { EXPECT_THAT(write(this->write_fd_, this->pipe_capacity_data_.data(), this->pipe_capacity_data_.size()), Ge(0)) << strerror(errno); } // Tests that reads from an open, non-empty pipe succeed when using small data. TYPED_TEST(AllPipeVarietiesTest, ReadingFromOpenNonEmptyPipesSucceedsWithSmallData) { ASSERT_THAT(write(this->write_fd_, this->small_data_.data(), this->small_data_.size()), Ge(0)) << strerror(errno); std::vector<uint8_t> read_buf(this->small_data_.size()); ssize_t read_result = read(this->read_fd_, read_buf.data(), read_buf.size()); ASSERT_THAT(read_result, Gt(0)); EXPECT_THAT(read_buf.data(), MemEq(this->small_data_.data(), read_result)); } // Tests that reads from an open, non-empty pipe succeed when using medium data. TYPED_TEST(AllPipeVarietiesTest, ReadingFromOpenNonEmptyPipesSucceedsWithCapacitySizedData) { ASSERT_THAT(write(this->write_fd_, this->pipe_capacity_data_.data(), this->pipe_capacity_data_.size()), Ge(0)) << strerror(errno); std::vector<uint8_t> read_buf(this->pipe_capacity_data_.size()); ssize_t read_result = read(this->read_fd_, read_buf.data(), read_buf.size()); ASSERT_THAT(read_result, Gt(0)); EXPECT_THAT(read_buf.data(), MemEq(this->pipe_capacity_data_.data(), read_result)); } // Tests that reads from an open, non-empty pipe succeed when using medium data, // but only reading part of the written data. TYPED_TEST(AllPipeVarietiesTest, ReadingFromOpenNonEmptyPipesSucceedsWhenReadingPartOfWrittenData) { ASSERT_THAT(write(this->write_fd_, this->pipe_capacity_data_.data(), this->pipe_capacity_data_.size()), Ge(0)) << strerror(errno); std::vector<uint8_t> read_buf(this->pipe_capacity_data_.size() / 2); ssize_t read_result = read(this->read_fd_, read_buf.data(), read_buf.size()); ASSERT_THAT(read_result, Gt(0)); EXPECT_THAT(read_buf.data(), MemEq(this->pipe_capacity_data_.data(), read_result)); } // Tests that pipe2() fails with EINVAL if given any flags outside of O_CLOEXEC // | O_DIRECT | O_NONBLOCK. TEST(FixturelessPipeTest, Pipe2RejectsUnknownFlags) { constexpr int kBadFlags = 0xf & ~(O_CLOEXEC | O_DIRECT | O_NONBLOCK); int pipe_fds[2]; EXPECT_THAT(pipe2(pipe_fds, O_DIRECT | kBadFlags), Eq(-1)); EXPECT_THAT(errno, Eq(EINVAL)); } // Tests that many pipes can be opened. TEST(FixturelessPipeTest, ManyPipesCanBeOpened) { constexpr int kNumPipes = 500; std::vector<std::array<int, 2>> pipes; pipes.reserve(kNumPipes); for (int i = 0; i < kNumPipes; ++i) { pipes.emplace_back(); ASSERT_THAT(pipe(pipes.back().data()), Eq(0)) << strerror(errno) << " at pipe " << i; } for (int i = 0; i < kNumPipes; ++i) { EXPECT_THAT(close(pipes[i][0]), Eq(0)) << strerror(errno) << " at pipe " << i; EXPECT_THAT(close(pipes[i][1]), Eq(0)) << strerror(errno) << " at pipe " << i; } } // Tests that O_CLOEXEC pipes have the FD_CLOEXEC file descriptor flag set. TEST_F(CloexecPipeTest, OCloexecPipesHaveFdCloexecFlagSet) { int fd_flags = fcntl(read_fd_, F_GETFD, 0); ASSERT_THAT(fd_flags, Ne(-1)) << strerror(errno); EXPECT_TRUE(fd_flags & FD_CLOEXEC); fd_flags = fcntl(write_fd_, F_GETFD, 0); ASSERT_THAT(fd_flags, Ne(-1)) << strerror(errno); EXPECT_TRUE(fd_flags & FD_CLOEXEC); } // Tests that the writing file descriptor of an O_DIRECT pipe has O_DIRECT set // in its file status flags. TEST_F(DirectPipeTest, WriteFdOnODirectPipeHasODirectFlagSet) { int fd_flags = fcntl(write_fd_, F_GETFL, 0); ASSERT_THAT(fd_flags, Ne(-1)) << strerror(errno); EXPECT_TRUE(fd_flags & O_DIRECT); } // Tests that writes of greater than PIPE_BUF bytes to non-blocking O_DIRECT // pipes succeed. using DirectNonblockPipeTest = Pipe2Test<O_DIRECT | O_NONBLOCK>; TEST_F(DirectNonblockPipeTest, LargeWritesToODirectPipesSucceedAndWriteOnlyPipeBufBytes) { EXPECT_THAT(write(write_fd_, large_data_.data(), large_data_.size()), Eq(pipe_capacity_data_.size())) << strerror(errno); } // Tests that reads of less than PIPE_BUF bytes from O_DIRECT pipes succeed and // discard the rest of the packet they read from. TEST_F(DirectPipeTest, SmallReadsFromODirectPipesSucceedAndDiscardRestOfPacket) { std::vector<uint8_t> read_buf(PIPE_BUF / 2); ASSERT_THAT(write(write_fd_, packet_data_.data(), packet_data_.size()), Eq(PIPE_BUF)) << strerror(errno); ASSERT_THAT(read(read_fd_, read_buf.data(), PIPE_BUF / 2), Eq(PIPE_BUF / 2)); EXPECT_THAT(read_buf.data(), MemEq(packet_data_.data(), PIPE_BUF / 2)); ASSERT_THAT(write(write_fd_, packet_data_.data(), packet_data_.size()), Eq(PIPE_BUF)) << strerror(errno); ASSERT_THAT(read(read_fd_, read_buf.data(), PIPE_BUF / 2), Eq(PIPE_BUF / 2)); EXPECT_THAT(read_buf.data(), MemEq(packet_data_.data(), PIPE_BUF / 2)); } // Tests that reads of PIPE_BUF bytes from O_DIRECT pipes succeed. TEST_F(DirectPipeTest, PipeBufSizedReadsFromODirectPipesSucceed) { ASSERT_THAT(write(write_fd_, packet_data_.data(), packet_data_.size()), Eq(PIPE_BUF)) << strerror(errno); std::vector<uint8_t> read_buf(PIPE_BUF); ASSERT_THAT(read(read_fd_, read_buf.data(), PIPE_BUF), Eq(PIPE_BUF)); EXPECT_THAT(read_buf.data(), MemEq(packet_data_.data(), PIPE_BUF)); } // Tests that reads of greater than PIPE_BUF bytes from O_DIRECT pipes succeed // but only read PIPE_BUF bytes. TEST_F(DirectPipeTest, LargeReadsFromODirectPipesSucceedButOnlyReadPipeBufBytes) { if (PIPE_BUF < pipe_capacity_data_.size()) { ASSERT_THAT(write(write_fd_, packet_data_.data(), packet_data_.size()), Eq(PIPE_BUF)) << strerror(errno); ASSERT_THAT(write(write_fd_, pipe_capacity_data_.data(), pipe_capacity_data_.size() - PIPE_BUF), Eq(pipe_capacity_data_.size() - PIPE_BUF)) << strerror(errno); std::vector<uint8_t> read_buf(pipe_capacity_data_.size()); ASSERT_THAT(read(read_fd_, read_buf.data(), read_buf.size()), Eq(PIPE_BUF)); EXPECT_THAT(read_buf.data(), MemEq(packet_data_.data(), PIPE_BUF)); } } // Tests that non-blocking pipes have the O_NONBLOCK file status flag set. TEST_F(NonblockPipeTest, NonBlockingPipesHaveONonblockFileStatusFlag) { int fd_flags = fcntl(read_fd_, F_GETFL, 0); ASSERT_THAT(fd_flags, Ne(-1)) << strerror(errno); EXPECT_TRUE(fd_flags & O_NONBLOCK); fd_flags = fcntl(write_fd_, F_GETFL, 0); ASSERT_THAT(fd_flags, Ne(-1)) << strerror(errno); EXPECT_TRUE(fd_flags & O_NONBLOCK); } // Tests that medium-sized writes to a non-blocking pipe succeed. TEST_F(NonblockPipeTest, CapacitySizedWritesToNonBlockingPipesSucceed) { EXPECT_THAT( write(write_fd_, pipe_capacity_data_.data(), pipe_capacity_data_.size()), Eq(pipe_capacity_data_.size())) << strerror(errno); } // Tests that writes to a full non-blocking pipe fail with EAGAIN. TEST_F(NonblockPipeTest, LargeWritesToNonBlockingPipesFailWithEAgain) { ASSERT_THAT( write(write_fd_, pipe_capacity_data_.data(), pipe_capacity_data_.size()), Eq(pipe_capacity_data_.size())) << strerror(errno); ASSERT_THAT(write(write_fd_, small_data_.data(), small_data_.size()), Eq(-1)); EXPECT_THAT(errno, Eq(EAGAIN)); } // Tests that reads from an empty non-blocking pipe fail with EAGAIN. TEST_F(NonblockPipeTest, ReadsFromEmptyNonBlockingPipesFailWithEAgain) { uint8_t read_val; ASSERT_THAT(read(read_fd_, &read_val, 1), Eq(-1)); EXPECT_THAT(errno, Eq(EAGAIN)); } // Tests that medium-sized reads from a full non-blocking pipe succeed. TEST_F(NonblockPipeTest, CapacitySizedReadsFromFullNonBlockingPipesSucceed) { ASSERT_THAT( write(write_fd_, pipe_capacity_data_.data(), pipe_capacity_data_.size()), Eq(pipe_capacity_data_.size())) << strerror(errno); std::vector<uint8_t> read_buf(pipe_capacity_data_.size()); ASSERT_THAT(read(read_fd_, read_buf.data(), read_buf.size()), Eq(read_buf.size())) << strerror(errno); EXPECT_THAT(read_buf.data(), MemEq(pipe_capacity_data_.data(), pipe_capacity_data_.size())); } // Tests that large-sized reads from a full non-blocking pipe fail with EAGAIN. TEST_F(NonblockPipeTest, LargeReadsFromFullNonBlockingPipesSucceed) { ASSERT_THAT( write(write_fd_, pipe_capacity_data_.data(), pipe_capacity_data_.size()), Eq(pipe_capacity_data_.size())) << strerror(errno); std::vector<uint8_t> read_buf(large_data_.size()); ASSERT_THAT(read(read_fd_, read_buf.data(), read_buf.size()), Eq(pipe_capacity_data_.size())) << strerror(errno); EXPECT_THAT(read_buf.data(), MemEq(pipe_capacity_data_.data(), pipe_capacity_data_.size())); } // Tests that updates to the size of a pipe are visible when the size is read. TEST_F(PipeTest, FcntlFSetpipeSzChangesPipeSize) { if (EnlargePipe()) { int new_pipe_size = fcntl(write_fd_, F_GETPIPE_SZ, 0); ASSERT_THAT(new_pipe_size, Ne(-1)) << strerror(errno); EXPECT_THAT(new_pipe_size, Eq(pipe_capacity_data_.size())); } } // Tests that a resized pipe fills up when a number of bytes equal to its new // size have been written. TEST_F(NonblockPipeTest, ResizedPipesHaveSmallerCapacity) { if (EnlargePipe()) { ASSERT_THAT(write(write_fd_, pipe_capacity_data_.data(), pipe_capacity_data_.size()), Eq(pipe_capacity_data_.size())) << strerror(errno); ASSERT_THAT(write(write_fd_, small_data_.data(), small_data_.size()), Eq(-1)); EXPECT_THAT(errno, Eq(EAGAIN)); } } // Tests that fcntl() cannot shrink a pipe's size below the number of bytes // currently in it. TEST_F(PipeTest, FcntlCannotShrinkPipeBelowCurrentlyHeldBytes) { // Pipes cannot be made smaller than one memory page. constexpr int kMinimumPipeSize = 4096; if (EnlargePipe()) { ASSERT_THAT(write(write_fd_, pipe_capacity_data_.data(), pipe_capacity_data_.size()), Eq(pipe_capacity_data_.size())) << strerror(errno); ASSERT_THAT(fcntl(write_fd_, F_SETPIPE_SZ, kMinimumPipeSize), Eq(-1)); EXPECT_THAT(errno, Eq(EBUSY)); } } } // namespace } // namespace asylo
6,948
2,890
package com.bilibili.boxing.ui; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.annotation.Nullable; import android.text.TextUtils; import android.widget.Toast; import com.bilibili.boxing.demo.R; import com.bilibili.boxing.model.BoxingManager; import com.bilibili.boxing.model.config.BoxingConfig; import com.bilibili.boxing.model.config.BoxingCropOption; import com.bilibili.boxing.model.entity.BaseMedia; import com.bilibili.boxing.utils.BoxingFileHelper; import com.bilibili.boxing_impl.ui.BoxingActivity; import java.util.List; import java.util.Locale; /** * A demo to show a Picker Activity with intent filter, which can start by other apps. * Get absolute path through {@link Intent#getDataString()} in {@link #onActivityResult(int, int, Intent)}. * * @author ChenSL */ public class IntentFilterActivity extends BoxingActivity { @Override protected void onCreate(Bundle savedInstanceState) { // in DCIM/bili/boxing String cropPath = BoxingFileHelper.getBoxingPathInDCIM(); if (TextUtils.isEmpty(cropPath)) { Toast.makeText(getApplicationContext(), R.string.boxing_storage_deny, Toast.LENGTH_SHORT).show(); return; } Uri destUri = new Uri.Builder() .scheme("file") .appendPath(cropPath) .appendPath(String.format(Locale.US, "%s.jpg", System.currentTimeMillis())) .build(); BoxingConfig config = new BoxingConfig(BoxingConfig.Mode.SINGLE_IMG).needCamera(R.drawable.ic_boxing_camera_white).withCropOption(new BoxingCropOption(destUri)); BoxingManager.getInstance().setBoxingConfig(config); super.onCreate(savedInstanceState); } @Override public void onBoxingFinish(Intent intent, @Nullable List<BaseMedia> medias) { if (medias != null && medias.size() > 0) { intent.setData(Uri.parse(medias.get(0).getPath())); setResult(RESULT_OK, intent); } else { setResult(RESULT_CANCELED, null); } finish(); } }
840
12,278
<gh_stars>1000+ #ifndef BOOST_METAPARSE_V1_CPP11_IMPL_SIZE_HPP #define BOOST_METAPARSE_V1_CPP11_IMPL_SIZE_HPP // Copyright <NAME> (<EMAIL>) 2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <boost/metaparse/v1/cpp11/fwd/string.hpp> #include <boost/mpl/int.hpp> #include <type_traits> namespace boost { namespace metaparse { namespace v1 { namespace impl { template <class S> struct size; template <char... Cs> struct size<string<Cs...>> : boost::mpl::int_<sizeof...(Cs)> {}; } } } } #endif
327
4,901
/* * Copyright (C) 2016 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 libcore.java.lang.reflect.annotations; import java.lang.annotation.Annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Repeatable; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.AnnotatedElement; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.StringJoiner; 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; /** * Utility methods and annotation definitions for use when testing implementations of * AnnotatedElement. * * <p>For compactness, the repeated annotation methods that take strings use a format based on Java * syntax rather than the toString() of annotations. For example, "@Repeated(1)" rather than * "@libcore.java.lang.reflect.annotations.AnnotatedElementTestSupport.Repeated(value=1)". Use * {@link #EXPECT_EMPTY} to indicate "no annotationed expected". */ public class AnnotatedElementTestSupport { @Retention(RetentionPolicy.RUNTIME) public @interface AnnotationA {} @Inherited @Retention(RetentionPolicy.RUNTIME) public @interface AnnotationB {} @Retention(RetentionPolicy.RUNTIME) public @interface AnnotationC {} @Retention(RetentionPolicy.RUNTIME) public @interface AnnotationD {} @Retention(RetentionPolicy.RUNTIME) @Inherited @Target({ ElementType.TYPE, ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.PACKAGE }) public @interface Container { Repeated[] value(); } @Repeatable(Container.class) @Retention(RetentionPolicy.RUNTIME) @Inherited @Target({ ElementType.TYPE, ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.PACKAGE }) public @interface Repeated { int value(); } /** * A named constant that can be used with assert methods below that take * "String[] expectedAnnotationStrings" as their final argument to indicate "none". */ public static final String[] EXPECT_EMPTY = new String[0]; private AnnotatedElementTestSupport() { } /** * Test the {@link AnnotatedElement} methods associated with "presence". i.e. methods that * deal with annotations being "present" (i.e. "direct" or "inherited" annotations, not * "indirect"). * * <p>Asserts that calling {@link AnnotatedElement#getAnnotations()} on the supplied element * returns annotations of the supplied expected classes. * * <p>Where the expected classes contains some subset from * {@link AnnotationA}, {@link AnnotationB}, {@link AnnotationC}, {@link AnnotationD} this * method also asserts that {@link AnnotatedElement#isAnnotationPresent(Class)} and * {@link AnnotatedElement#getAnnotation(Class)} works as expected. * * <p>This method also confirms that {@link AnnotatedElement#isAnnotationPresent(Class)} and * {@link AnnotatedElement#getAnnotation(Class)} work correctly with a {@code null} argument. */ static void checkAnnotatedElementPresentMethods( AnnotatedElement element, Class<? extends Annotation>... expectedAnnotations) { Set<Class<? extends Annotation>> actualTypes = annotationsToTypes(element.getAnnotations()); Set<Class<? extends Annotation>> expectedTypes = set(expectedAnnotations); assertEquals(expectedTypes, actualTypes); // getAnnotations() should be consistent with isAnnotationPresent() and getAnnotation() assertPresent(expectedTypes.contains(AnnotationA.class), element, AnnotationA.class); assertPresent(expectedTypes.contains(AnnotationB.class), element, AnnotationB.class); assertPresent(expectedTypes.contains(AnnotationC.class), element, AnnotationC.class); assertPresent(expectedTypes.contains(AnnotationD.class), element, AnnotationD.class); try { element.isAnnotationPresent(null); fail(); } catch (NullPointerException expected) { } try { element.getAnnotation(null); fail(); } catch (NullPointerException expected) { } } /** * Test the {@link AnnotatedElement} methods associated with "direct" annotations. * * <p>Asserts that calling {@link AnnotatedElement#getDeclaredAnnotations()} on the supplied * element returns annotations of the supplied expected classes. * * <p>Where the expected classes contains some subset from * {@link AnnotationA}, {@link AnnotationB} and {@link AnnotationC}, this method also asserts * that {@link AnnotatedElement#getDeclaredAnnotation(Class)} works as expected. * * <p>This method also confirms that {@link AnnotatedElement#isAnnotationPresent(Class)} and * {@link AnnotatedElement#getAnnotation(Class)} work correctly with a {@code null} argument. */ static void checkAnnotatedElementDirectMethods( AnnotatedElement element, Class<? extends Annotation>... expectedDeclaredAnnotations) { Set<Class<? extends Annotation>> actualTypes = annotationsToTypes(element.getDeclaredAnnotations()); Set<Class<? extends Annotation>> expectedTypes = set(expectedDeclaredAnnotations); assertEquals(expectedTypes, actualTypes); assertDeclared(expectedTypes.contains(AnnotationA.class), element, AnnotationA.class); assertDeclared(expectedTypes.contains(AnnotationB.class), element, AnnotationB.class); assertDeclared(expectedTypes.contains(AnnotationC.class), element, AnnotationC.class); try { element.getDeclaredAnnotation(null); fail(); } catch (NullPointerException expected) { } } /** * Extracts the annotation types ({@link Annotation#annotationType()} from the supplied * annotations. */ static Set<Class<? extends Annotation>> annotationsToTypes(Annotation[] annotations) { Set<Class<? extends Annotation>> result = new HashSet<Class<? extends Annotation>>(); for (Annotation annotation : annotations) { result.add(annotation.annotationType()); } return result; } private static void assertPresent(boolean present, AnnotatedElement element, Class<? extends Annotation> annotation) { if (present) { assertNotNull(element.getAnnotation(annotation)); assertTrue(element.isAnnotationPresent(annotation)); } else { assertNull(element.getAnnotation(annotation)); assertFalse(element.isAnnotationPresent(annotation)); } } private static void assertDeclared(boolean present, AnnotatedElement element, Class<? extends Annotation> annotation) { if (present) { assertNotNull(element.getDeclaredAnnotation(annotation)); } else { assertNull(element.getDeclaredAnnotation(annotation)); } } @SafeVarargs static <T> Set<T> set(T... instances) { return new HashSet<>(Arrays.asList(instances)); } /** * Asserts that {@link AnnotatedElement#isAnnotationPresent(Class)} returns the expected result. */ static void assertIsAnnotationPresent( AnnotatedElement element, Class<? extends Annotation> annotationType, boolean expected) { assertEquals("element.isAnnotationPresent() for " + element + " and " + annotationType, expected, element.isAnnotationPresent(annotationType)); } /** * Asserts that {@link AnnotatedElement#getDeclaredAnnotation(Class)} returns the expected * result. The result is specified using a String. See {@link AnnotatedElementTestSupport} for * the string syntax. */ static void assertGetDeclaredAnnotation(AnnotatedElement annotatedElement, Class<? extends Annotation> annotationType, String expectedAnnotationString) { Annotation annotation = annotatedElement.getDeclaredAnnotation(annotationType); assertAnnotationMatches(annotation, expectedAnnotationString); } /** * Asserts that {@link AnnotatedElement#getDeclaredAnnotationsByType(Class)} returns the * expected result. The result is specified using a String. See * {@link AnnotatedElementTestSupport} for the string syntax. */ static void assertGetDeclaredAnnotationsByType( AnnotatedElement annotatedElement, Class<? extends Annotation> annotationType, String[] expectedAnnotationStrings) { Annotation[] annotations = annotatedElement.getDeclaredAnnotationsByType(annotationType); assertAnnotationsMatch(annotations, expectedAnnotationStrings); } /** * Asserts that {@link AnnotatedElement#getAnnotationsByType(Class)} returns the * expected result. The result is specified using a String. See * {@link AnnotatedElementTestSupport} for the string syntax. */ static void assertGetAnnotationsByType(AnnotatedElement annotatedElement, Class<? extends Annotation> annotationType, String[] expectedAnnotationStrings) throws Exception { Annotation[] annotations = annotatedElement.getAnnotationsByType(annotationType); assertAnnotationsMatch(annotations, expectedAnnotationStrings); } private static void assertAnnotationMatches( Annotation annotation, String expectedAnnotationString) { if (expectedAnnotationString == null) { assertNull(annotation); } else { assertNotNull(annotation); assertEquals(expectedAnnotationString, createAnnotationTestString(annotation)); } } /** * Asserts that the supplied annotations match the expectation Strings. See * {@link AnnotatedElementTestSupport} for the string syntax. */ static void assertAnnotationsMatch(Annotation[] annotations, String[] expectedAnnotationStrings) { // Due to Android's dex format insisting that Annotations are sorted by name the ordering of // annotations is determined by the (simple?) name of the Annotation, not just the order // that they are defined in the source. Tests have to be sensitive to that when handling // mixed usage of "Container" and "Repeated" - the "Container" annotations will be // discovered before "Repeated" due to their sort ordering. // // This code assumes that repeated annotations with the same name will be specified in the // source their natural sort order when attributes are considered, just to make the testing // simpler. // e.g. @Repeated(1) @Repeated(2), never @Repeated(2) @Repeated(1) // Sorting the expected and actual strings _should_ work providing the assumptions above // hold. It may mask random ordering issues but it's harder to deal with that while the // source ordering is no observed. Providing no developers are ascribing meaning to the // relative order of annotations things should be ok. Arrays.sort(expectedAnnotationStrings); String[] actualAnnotationStrings = createAnnotationTestStrings(annotations); Arrays.sort(actualAnnotationStrings); assertEquals( Arrays.asList(expectedAnnotationStrings), Arrays.asList(actualAnnotationStrings)); } private static String[] createAnnotationTestStrings(Annotation[] annotations) { String[] annotationStrings = new String[annotations.length]; for (int i = 0; i < annotations.length; i++) { annotationStrings[i] = createAnnotationTestString(annotations[i]); } return annotationStrings; } private static String createAnnotationTestString(Annotation annotation) { return "@" + annotation.annotationType().getSimpleName() + createArgumentsTestString(annotation); } private static String createArgumentsTestString(Annotation annotation) { if (annotation instanceof Repeated) { Repeated repeated = (Repeated) annotation; return "(" + repeated.value() + ")"; } else if (annotation instanceof Container) { Container container = (Container) annotation; String[] repeatedValues = createAnnotationTestStrings(container.value()); StringJoiner joiner = new StringJoiner(", ", "{", "}"); for (String repeatedValue : repeatedValues) { joiner.add(repeatedValue); } String repeatedValuesString = joiner.toString(); return "(" + repeatedValuesString + ")"; } return ""; } }
4,700
478
<filename>tests/unit/transforms/test_html.py # -*- coding: utf-8 -*- from bs4 import BeautifulSoup from .helpers import run_transform, HTML def test_tag_selector(): ok, content = run_transform('tag', 'a', HTML) assert ok is True assert content == '<a href="page.html" id="page-link">Page</a>' def test_css_selector(): ok, content = run_transform('css', 'body h2.nav a#page-link', HTML) assert ok is True assert content == '<a href="page.html" id="page-link">Page</a>' def test_css_selector_all(): ok, content = run_transform('css-all', 'div', HTML) assert ok is True assert prettify(content) == u'\n'.join([ u'<div id="content">', u' Привет, Мир!', u'</div>', u'', u'<div class="footer">', u' Footer content', u'</div>', ]) def test_extract_test(): ok, content = run_transform('text', None, HTML) assert ok is True assert content.strip() == u"\n".join([ u"Page", u"Привет, Мир!", u"Footer content", ]) def prettify(html): return "\n".join( child.prettify() for child in BeautifulSoup(html, "lxml").html.body.children )
534
825
<filename>QmlPlugin/QmlPluginTest/QmlPluginTest.h /*! *@file QmlPluginTest.h *@brief Qml调用插件 *@version 1.0 *@section LICENSE Copyright (C) 2003-2103 CamelSoft Corporation *@author zhengtianzuo */ #pragma once #include <QObject> class QmlPluginTest : public QObject { Q_OBJECT public: QmlPluginTest(); Q_INVOKABLE void showWindow(); };
150
715
/* * Copyright 2019 Lightbend Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.cloudstate.samples.shoppingcart; import com.example.valueentity.shoppingcart.Shoppingcart; import com.example.valueentity.shoppingcart.persistence.Domain; import com.google.protobuf.Empty; import io.cloudstate.javasupport.EntityId; import io.cloudstate.javasupport.entity.CommandContext; import io.cloudstate.javasupport.entity.CommandHandler; import io.cloudstate.javasupport.entity.Entity; import java.util.Comparator; import java.util.List; import java.util.Optional; import java.util.function.Predicate; import java.util.stream.Collectors; /** A value based entity. */ @Entity(persistenceId = "shopping-cart") public class ShoppingCartEntity { private final String entityId; public ShoppingCartEntity(@EntityId String entityId) { this.entityId = entityId; } @CommandHandler public Shoppingcart.Cart getCart(CommandContext<Domain.Cart> ctx) { Domain.Cart cart = ctx.getState().orElse(Domain.Cart.newBuilder().build()); List<Shoppingcart.LineItem> allItems = cart.getItemsList().stream() .map(this::convert) .sorted(Comparator.comparing(Shoppingcart.LineItem::getProductId)) .collect(Collectors.toList()); return Shoppingcart.Cart.newBuilder().addAllItems(allItems).build(); } @CommandHandler public Empty addItem(Shoppingcart.AddLineItem item, CommandContext<Domain.Cart> ctx) { if (item.getQuantity() <= 0) { ctx.fail("Cannot add negative quantity of to item " + item.getProductId()); } Domain.Cart cart = ctx.getState().orElse(Domain.Cart.newBuilder().build()); Domain.LineItem lineItem = updateItem(item, cart); List<Domain.LineItem> lineItems = removeItemByProductId(cart, item.getProductId()); lineItems.add(lineItem); lineItems.sort(Comparator.comparing(Domain.LineItem::getProductId)); ctx.updateState(Domain.Cart.newBuilder().addAllItems(lineItems).build()); return Empty.getDefaultInstance(); } @CommandHandler public Empty removeItem(Shoppingcart.RemoveLineItem item, CommandContext<Domain.Cart> ctx) { Domain.Cart cart = ctx.getState().orElse(Domain.Cart.newBuilder().build()); Optional<Domain.LineItem> lineItem = findItemByProductId(cart, item.getProductId()); if (!lineItem.isPresent()) { ctx.fail("Cannot remove item " + item.getProductId() + " because it is not in the cart."); } List<Domain.LineItem> items = removeItemByProductId(cart, item.getProductId()); items.sort(Comparator.comparing(Domain.LineItem::getProductId)); ctx.updateState(Domain.Cart.newBuilder().addAllItems(items).build()); return Empty.getDefaultInstance(); } @CommandHandler public Empty removeCart(Shoppingcart.RemoveShoppingCart cart, CommandContext<Domain.Cart> ctx) { ctx.deleteState(); return Empty.getDefaultInstance(); } private Domain.LineItem updateItem(Shoppingcart.AddLineItem item, Domain.Cart cart) { return findItemByProductId(cart, item.getProductId()) .map(li -> li.toBuilder().setQuantity(li.getQuantity() + item.getQuantity()).build()) .orElse(newItem(item)); } private Domain.LineItem newItem(Shoppingcart.AddLineItem item) { return Domain.LineItem.newBuilder() .setProductId(item.getProductId()) .setName(item.getName()) .setQuantity(item.getQuantity()) .build(); } private Optional<Domain.LineItem> findItemByProductId(Domain.Cart cart, String productId) { Predicate<Domain.LineItem> lineItemExists = lineItem -> lineItem.getProductId().equals(productId); return cart.getItemsList().stream().filter(lineItemExists).findFirst(); } private List<Domain.LineItem> removeItemByProductId(Domain.Cart cart, String productId) { return cart.getItemsList().stream() .filter(lineItem -> !lineItem.getProductId().equals(productId)) .collect(Collectors.toList()); } private Shoppingcart.LineItem convert(Domain.LineItem item) { return Shoppingcart.LineItem.newBuilder() .setProductId(item.getProductId()) .setName(item.getName()) .setQuantity(item.getQuantity()) .build(); } }
1,575
451
/*Header-MicMac-eLiSe-25/06/2007 MicMac : Multi Image Correspondances par Methodes Automatiques de Correlation eLiSe : ELements of an Image Software Environnement www.micmac.ign.fr Copyright : Institut Geographique National Author : <NAME> Contributors : <NAME>, <NAME>. [1] <NAME>, <NAME>. "A multiresolution and optimization-based image matching approach: An application to surface reconstruction from SPOT5-HRS stereo imagery." In IAPRS vol XXXVI-1/W41 in ISPRS Workshop On Topographic Mapping From Space (With Special Emphasis on Small Satellites), Ankara, Turquie, 02-2006. [2] <NAME>, "MicMac, un lociel de mise en correspondance d'images, adapte au contexte geograhique" to appears in Bulletin d'information de l'Institut Geographique National, 2007. Francais : MicMac est un logiciel de mise en correspondance d'image adapte au contexte de recherche en information geographique. Il s'appuie sur la bibliotheque de manipulation d'image eLiSe. Il est distibue sous la licences Cecill-B. Voir en bas de fichier et http://www.cecill.info. English : MicMac is an open source software specialized in image matching for research in geographic information. MicMac is built on the eLiSe image library. MicMac is governed by the "Cecill-B licence". See below and http://www.cecill.info. Header-MicMac-eLiSe-25/06/2007*/ #include "StdAfx.h" #if (ELISE_MacOs) #define SSTR( x ) (std::ostringstream()<< std::dec << x).str() #else #define SSTR( x ) static_cast< std::ostringstream & >( ( std::ostringstream() << std::dec << x ) ).str() #endif int CilliaImgt_main(int argc, char ** argv) { std::string aImg1; std::string aImg2; std::string aXmlFile; std::string aLigne; std::string aColone; ElInitArgMain ( argc ,argv , LArgMain() <<EAMC(aImg1, "image 1" ) <<EAMC(aImg2, "image 2" ) <<EAMC(aXmlFile, "homorg.xml" ) <<EAMC(aLigne, "homorg.xml" ) <<EAMC(aColone, "homorg.xml" ), LArgMain() ); /*** Récuperer le nobre de processeur **/ int aNb= NbProcSys(); std::string mDir, mPat; // cInterfChantierNameManipulateur * mICNM; Tiff_Im ImgTiff= Tiff_Im::UnivConvStd(aImg1.c_str()); Im2D<INT4,INT> I(ImgTiff.sz().x, ImgTiff.sz().y); ELISE_COPY ( I.all_pts(), ImgTiff.in(), I.out() ); //std::cout << ImgTiff.sz() <<"\n"; std::string aNom,aNom1; int x1= atoi( aLigne.c_str() ); int y1= atoi( aColone.c_str() ); Pt2di aSz(x1 ,y1); cElMap2D * aMaps ; aMaps = cElMap2D::FromFile(aXmlFile); Tiff_Im ImgTiff2= Tiff_Im::UnivConvStd(aImg2.c_str()); Im2D<INT4,INT> I2(ImgTiff2.sz().x, ImgTiff2.sz().y); ELISE_COPY ( I2.all_pts(), ImgTiff2.in(), I2.out() ); std::pair<std::string, std::string > tPair; std::vector<std::pair<std::string,std::string> > Vec,Vec1, Vec2; std::string aCom; std::list<std::string> aLCom; int aNbc;//nombre de couple d'image à appliquer la commande Tapioca en parallel ; int i; i=1; aNbc=aNb/2; for (int j=1 ; j<=8 ;j++) // pour parcourir toute l'image { for (i=i; i<=aNbc ; i++ ) { std::string Cnt = SSTR( i ); aNom="im"+Cnt+".""tif"; Tiff_Im aTOut ( aNom.c_str(), aSz, ImgTiff.type_el(), Tiff_Im::No_Compr, Tiff_Im::BlackIsZero ); ELISE_COPY ( rectangle(Pt2di(0,0),Pt2di(x1,y1)), trans( I.in(),Pt2di((i-1)*x1,0)), aTOut.out() ); Pt2di aPaa((i-1)*x1 ,0); Pt2di aaPa1(i*x1,y1); Pt2dr aQaa = (*aMaps)(Pt2dr(aPaa)); Pt2dr aQ1aa = (*aMaps)(Pt2dr(aaPa1)); int aQaaxi; if(aQaa.x >0)// pour verifier si la coordonées x est bien dasn l'image { aQaaxi=floor(aQaa.x); } else { aQaaxi=0 ; } int aQaayi; if(aQaa.y >0)// pour vérifier si la coordonnée y est bien dans l'image { aQaayi=floor(aQaa.y); } else { aQaayi=0 ; } int aQ1aaxi=floor(aQ1aa.x); int aQ1aayi=floor(aQ1aa.y); Pt2di aPPaa(aQaaxi,aQaayi); Pt2di aPP1aa(aQ1aaxi,aQ1aayi); aNom1="imm"+Cnt+".""tif"; Tiff_Im aTOut1 ( aNom1.c_str(), aSz, GenIm::u_int1, Tiff_Im::No_Compr, Tiff_Im::BlackIsZero ); ELISE_COPY ( rectangle(Pt2di(0,0) ,Pt2di(aSz.x,aSz.y)), trans(I2.in(),Pt2di(aPPaa)), aTOut1.out() ); aCom= MMBinFile("mm3d Tapioca All ") + "\"("+ aNom +"|" + aNom1 +")\"" + BLANK + "-1 " +BLANK + "ByP=1" ; aLCom.push_back(aCom); tPair.first=aNom; tPair.second=aNom1; Vec.push_back(tPair); } cEl_GPAO::DoComInParal(aLCom); aNbc=i+3; } /***** Deuxième rangé **/ int n,m; n=1; m=aNb/2; for (int j=1 ; j<=8 ;j++) { for (n=n; n<=m ; n++ ) { std::string Cnt = SSTR( n ); aNom="img"+Cnt+".""tif"; Tiff_Im aTOut ( aNom.c_str(), aSz, ImgTiff.type_el(), Tiff_Im::No_Compr, Tiff_Im::BlackIsZero ); ELISE_COPY ( rectangle(Pt2di(0,0),Pt2di(x1,2*y1)), trans( I.in(),Pt2di((n-1)*x1,y1)), aTOut.out() ); Pt2di aPaa((n-1)*x1 ,y1); Pt2di aaPa1(n*x1,2*y1); Pt2dr aQaa = (*aMaps)(Pt2dr(aPaa)); Pt2dr aQ1aa = (*aMaps)(Pt2dr(aaPa1)); int aQaaxi; if(aQaa.x >0)//pour vérifier si la coordonnée x est bien à l'interieure de l'image { aQaaxi=floor(aQaa.x); } else { aQaaxi=0 ; } int aQaayi; if(aQaa.y >0)//pour vérifier que la coordonnées y est bien à l'interrieure de l'image { aQaayi=floor(aQaa.y); } else { aQaayi=0 ; } int aQ1aaxi=floor(aQ1aa.x); int aQ1aayi=floor(aQ1aa.y); Pt2di aPPaa(aQaaxi,aQaayi); Pt2di aPP1aa(aQ1aaxi,aQ1aayi); aNom1="imgg"+Cnt+".""tif"; Tiff_Im aTOut1 ( aNom1.c_str(), aSz, GenIm::u_int1, Tiff_Im::No_Compr, Tiff_Im::BlackIsZero ); ELISE_COPY ( rectangle(Pt2di(0,0) ,Pt2di(aSz.x,aSz.y)), trans(I2.in(),Pt2di(aPPaa)), aTOut1.out() ); aCom= MMBinFile("mm3d Tapioca All ") + "\"("+ aNom +"|" + aNom1 +")\"" + BLANK + "-1 " +BLANK + "ByP=1" ; aLCom.push_back(aCom); tPair.first=aNom; tPair.second=aNom1; Vec1.push_back(tPair); } cEl_GPAO::DoComInParal(aLCom); m=n+3; } /****** Troisieme range ***//// // int y=1075; int c,l; c=1; l=aNb/2; for (int j=1 ; j<=8 ;j++) { for (c=c; c<=l ; c++ ) { std::string Cnt = SSTR( c ); aNom="imge"+Cnt+".""tif"; Tiff_Im aTOut ( aNom.c_str(), aSz, ImgTiff.type_el(), Tiff_Im::No_Compr, Tiff_Im::BlackIsZero ); ELISE_COPY ( rectangle(Pt2di(0,0),Pt2di(x1,y1)), trans( I.in(),Pt2di((c-1)*x1,2*y1)), aTOut.out() ); Pt2di aPaa((c-1)*x1 ,2*y1); Pt2di aaPa1(c*x1,3*y1); Pt2dr aQaa = (*aMaps)(Pt2dr(aPaa)); Pt2dr aQ1aa = (*aMaps)(Pt2dr(aaPa1)); int aQaaxi; if(aQaa.x >0) { aQaaxi=floor(aQaa.x); } else { aQaaxi=0 ; } int aQaayi; if(aQaa.y >0) { aQaayi=floor(aQaa.y); } else { aQaayi=0 ; } int aQ1aaxi=floor(aQ1aa.x); int aQ1aayi=floor(aQ1aa.y); Pt2di aPPaa(aQaaxi,aQaayi); Pt2di aPP1aa(aQ1aaxi,aQ1aayi); aNom1="imgge"+Cnt+".""tif"; Tiff_Im aTOut1 ( aNom1.c_str(), aSz, GenIm::u_int1, Tiff_Im::No_Compr, Tiff_Im::BlackIsZero ); ELISE_COPY ( rectangle(Pt2di(0,0) ,Pt2di(x1,y1)), trans(I2.in(),Pt2di(aPPaa)), aTOut1.out() ); aCom= MMBinFile("mm3d Tapioca All ") + "\"("+ aNom +"|" + aNom1 +")\"" + BLANK + "-1 " +BLANK + "ByP=1" ; aLCom.push_back(aCom); tPair.first=aNom; tPair.second=aNom1; Vec2.push_back(tPair); } cEl_GPAO::DoComInParal(aLCom); l=c+3; } std::string mFullName= "/home/cillia/Bureau/a-transferer/Data/Dimage/DADF/.*tif"; SplitDirAndFile(mDir,mPat,mFullName); std::cout << mPat <<"\n"; //cInterfChantierNameManipulateur *mICNM = cInterfChantierNameManipulateur::BasicAlloc(mDir); std::cout << "directory" << mDir << "\n"; ElPackHomologue aPckOut , aPckOut1; std::string aHmOut =mDir + "Homol1" ; ELISE_fp::MkDir( aHmOut ); std::string mPas= aHmOut +"/Pastis" + aImg1; ELISE_fp::MkDir( mPas ); std::string mPas1= aHmOut +"/Pastis" + aImg2; ELISE_fp::MkDir( mPas1 ); std::string aHomOut= mPas + "/" + aImg2 + ".txt"; std::string aHomOut1= mPas1 + "/" + aImg1 + ".txt"; for( int aS1=0; aS1<int(Vec.size()); aS1++ ) { std::string mPatHom = mDir + "Homol/Pastis" + Vec.at(aS1).first + "/" + Vec.at(aS1).second + ".dat"; std::string mPatHom2 = mDir + "Homol/Pastis" + Vec.at(aS1).second + "/" + Vec.at(aS1).first + ".dat" ; if( ELISE_fp::exist_file(mPatHom)) { ElPackHomologue aPack = ElPackHomologue::FromFile(mPatHom); for ( ElPackHomologue::iterator iTH=aPack.begin(); iTH!=aPack.end(); iTH++ ) { Pt2dr aP1 = iTH->P1(); Pt2dr aP2 = iTH->P2(); double aP= aP1.x + aS1 * x1; int aIn=floor(aP); int aIn1=floor(aP1.y); Pt2dr aPP1(aIn,aIn1); double aPP= aP2.x + aS1*x1; int aIn2=floor(aPP); int aIn22=floor(aP2.y); Pt2dr aPP2(aIn2, aIn22); aPckOut.Cple_Add(ElCplePtsHomologues (aPP1,aPP2)); } aPckOut.StdPutInFile(aHomOut); } else { std::cout << "le fichier n'existe pas " <<"\n"; } } for( int aS1=0; aS1<int(Vec1.size()); aS1++ ) { std::cout << "first" << Vec1.at(aS1).first <<"\n"; std::string mPatHom1 = mDir + "Homol/Pastis" + Vec1.at(aS1).first + "/" + Vec1.at(aS1).second + ".dat"; std::string mPatHom2 = mDir + "Homol/Pastis" + Vec1.at(aS1).second + "/" + Vec1.at(aS1).first + ".dat" ; std::cout<<" mPatHom" << mPatHom1 <<"\n"; if( ELISE_fp::exist_file(mPatHom1)) { ElPackHomologue aPack1 = ElPackHomologue::FromFile(mPatHom1); // std::cout << " pppp"<< "\n"; for ( ElPackHomologue::iterator iTH=aPack1.begin(); iTH!=aPack1.end(); iTH++ ) { Pt2dr aP1 = iTH->P1(); Pt2dr aP2 = iTH->P2(); // std::cout <<" appp" << aP1.x << "\n"; double aP= aP1.x + aS1 * x1; double aPP=aP1.y + y1; int aIn=floor(aP); int aIn1=floor(aPP); Pt2dr aPP1(aIn,aIn1); double aPPX= aP2.x + aS1*x1; double aPPY= aP2.y + y1; int aIn2=floor(aPPX); int aIn22=floor(aPPY); Pt2dr aPP2(aIn2, aIn22); aPckOut.Cple_Add(ElCplePtsHomologues (aPP1,aPP2)); } aPckOut.StdPutInFile(aHomOut); } else { std::cout << "le fichier n'existe pas " <<"\n"; } } for( int aS1=0; aS1<int(Vec2.size()); aS1++ ) { std::string mPatHom1 = mDir + "Homol/Pastis" + Vec2.at(aS1).first + "/" + Vec2.at(aS1).second + ".dat"; std::string mPatHom2 = mDir + "Homol/Pastis" + Vec2.at(aS1).second + "/" + Vec2.at(aS1).first + ".dat" ; if( ELISE_fp::exist_file(mPatHom1) && ELISE_fp::exist_file(mPatHom2) ) { ElPackHomologue aPack1 = ElPackHomologue::FromFile(mPatHom1); ElPackHomologue aPack2 = ElPackHomologue::FromFile(mPatHom2); // std::cout << " pppp"<< "\n"; for ( ElPackHomologue::iterator iTH=aPack1.begin(); iTH!=aPack1.end(); iTH++ ) { Pt2dr aP1 = iTH->P1(); Pt2dr aP2 = iTH->P2(); // std::cout <<" appp" << aP1.x << "\n"; double aP= aP1.x + aS1 * x1; double aPP=aP1.y + 2*y1; int aIn=floor(aP); int aIn1=floor(aPP); Pt2dr aPP1(aIn,aIn1); double aPPX= aP2.x + aS1*x1; double aPPY= aP2.y + y1; int aIn2=floor(aPPX); int aIn22=floor(aPPY); Pt2dr aPP2(aIn2, aIn22); aPckOut.Cple_Add(ElCplePtsHomologues (aPP1,aPP2)); } aPckOut.StdPutInFile(aHomOut); for ( ElPackHomologue::iterator iTH1=aPack2.begin(); iTH1!=aPack2.end(); iTH1++ ) { Pt2dr aP1 = iTH1->P1(); Pt2dr aP2 = iTH1->P2(); // std::cout <<" appp" << aP1.x << "\n"; double aP= aP1.x + aS1 * x1; double aPP=aP1.y + 2*y1; int aIn=floor(aP); int aIn1=floor(aPP); Pt2dr aPP1(aIn,aIn1); double aPPX= aP2.x + aS1*x1; double aPPY= aP2.y + y1; int aIn2=floor(aPPX); int aIn22=floor(aPPY); Pt2dr aPP2(aIn2, aIn22); aPckOut.Cple_Add(ElCplePtsHomologues (aPP1,aPP2)); } aPckOut.StdPutInFile(aHomOut1); } else { std::cout << "le fichier n'existe pas " <<"\n"; } } return(1); }
14,242
311
#pragma once // License: MIT http://opensource.org/licenses/MIT // Author: dustpg mailto:<EMAIL> #include <stdint.h> //#define SFC_SMF_DEFINED // 目前使用16.16定点小数, 可以换成6.10~8.8的16bit typedef uint32_t sfc_fixed_t; #define SFC_FIXED(x) (x << 16) // 创建 static inline sfc_fixed_t sfc_fixed_make(uint32_t a, uint32_t b) { // 防溢出操作 // 整数部分 const uint32_t part0 = a / b; const uint32_t hi16 = part0 << 16; // 小数部分 const uint32_t part1 = a % b; const uint32_t lo16 = (part1 << 16) / b; return hi16 | lo16; } // 增加 static inline uint32_t sfc_fixed_add(sfc_fixed_t* a, sfc_fixed_t b) { *a += b; const uint32_t rv = *a >> 16; *a &= 0xffff; return rv; } // ------------------------------------------------------- // 2A03 // ------------------------------------------------------- /* 95.88 square_out = ----------------------- 8128 ----------------- + 100 square1 + square2 159.79 tnd_out = ------------------------------ 1 ------------------------ + 100 triangle noise dmc -------- + ----- + ----- 8227 12241 22638 */ /// <summary> /// StepFC: 混方波 /// </summary> /// <param name="sq1">The SQ1.</param> /// <param name="sq2">The SQ2.</param> /// <returns></returns> static inline float sfc_mix_square(float sq1, float sq2) { return 95.88f / ((8128.f / (sq1 + sq2)) + 100.f); } /// <summary> /// StepFC: 混TND /// </summary> /// <param name="triangle">The triangle.</param> /// <param name="noise">The noise.</param> /// <param name="dmc">The DMC.</param> /// <returns></returns> static inline float sfc_mix_tnd(float triangle, float noise, float dmc) { return 159.79f / (1.f / (triangle / 8227.f + noise / 12241.f + dmc / 22638.f) + 100.f); } /// <summary> /// 方波状态 /// </summary> typedef struct { // 方波 周期(+1s) 预乘2 uint16_t period_x2; // 方波 音量 uint8_t volume; // 方波 占空比 预乘8 uint8_t duty; } sfc_square_ch_state_t; typedef sfc_square_ch_state_t sfc_square_channel_state_t; /// <summary> /// 三角波状态 /// </summary> typedef struct { // 三角波 周期 uint16_t period; // 三角波 递增掩码 uint8_t inc_mask; // 三角波 播放掩码 uint8_t play_mask; } sfc_triangle_ch_state_t; /// <summary> /// 噪声状态 /// </summary> typedef struct { // 噪声 周期 uint16_t period; // 噪声 右移位数 6[短模式], 1[长模式] uint8_t count; // 三角波 音量 uint8_t volume; } sfc_noise_ch_state_t; // typedef struct sfc_famicom; typedef struct sfc_famicom sfc_famicom_t; /// <summary> /// StepFC: 2A03 用 样本模式整型上下文 /// </summary> typedef struct { // 方波#1 输出 float sq1_output; // 方波#2 输出 float sq2_output; // 三角波 输出 float tri_output; // 噪音 输出 float noi_output; // DMC 输出 float dmc_output; // 方波#1 状态 sfc_square_ch_state_t sq1_state; // 方波#2 状态 sfc_square_ch_state_t sq2_state; // 三角波状态 sfc_triangle_ch_state_t tri_state; // 噪音状态 sfc_noise_ch_state_t noi_state; // 定点小数 方波#1 sfc_fixed_t sq1_clock; // 定点小数 方波#2 sfc_fixed_t sq2_clock; // 定点小数 三角波澜 sfc_fixed_t tri_clock; // 定点小数 噪音 sfc_fixed_t noi_clock; // 定点小数 DMC sfc_fixed_t dmc_clock; } sfc_2a03_smi_ctx_t; // 2A03 整型采样模式 - 采样 void sfc_2a03_smi_sample(sfc_famicom_t*, sfc_2a03_smi_ctx_t*, const float[], sfc_fixed_t cps); // 2A03 整型采样模式 - 更新方波#1 void sfc_2a03_smi_update_sq1(const sfc_famicom_t*, sfc_2a03_smi_ctx_t*); // 2A03 整型采样模式 - 更新方波#2 void sfc_2a03_smi_update_sq2(const sfc_famicom_t*, sfc_2a03_smi_ctx_t*); // 2A03 整型采样模式 - 更新三角波 void sfc_2a03_smi_update_tri(const sfc_famicom_t*, sfc_2a03_smi_ctx_t*); // 2A03 整型采样模式 - 更新噪音 void sfc_2a03_smi_update_noi(const sfc_famicom_t*, sfc_2a03_smi_ctx_t*); // ------------------------------------------------------- // VRC6 // ------------------------------------------------------- /// <summary> /// StepFC: VRC7 用 样本模式整型上下文 /// </summary> typedef struct { // 方波#1 输出 float square1_output; // 方波#2 输出 float square2_output; // 锯齿波输出 float sawtooth_output; // 方波#1 定点小数 sfc_fixed_t sq1_clock; // 方波#2 定点小数 sfc_fixed_t sq2_clock; // 锯齿波 定点小数 sfc_fixed_t saw_clock; } sfc_vrc6_smi_ctx_t; // VRC6 整型采样模式 - 采样 void sfc_vrc6_smi_sample(sfc_famicom_t*, sfc_vrc6_smi_ctx_t*, const float[], sfc_fixed_t cps); // ------------------------------------------------------- // VRC7 // ------------------------------------------------------- /// <summary> /// StepFC: VRC7 用 样本模式整型上下文 /// </summary> typedef struct { // 输出 float output[6]; // 合成 float mixed; // 定点小数 sfc_fixed_t clock; } sfc_vrc7_smi_ctx_t; // VRC7 整型采样模式 - 采样 void sfc_vrc7_smi_sample(sfc_famicom_t*, sfc_vrc7_smi_ctx_t*, const float[], sfc_fixed_t cps); // ------------------------------------------------------- // FDS1 // ------------------------------------------------------- /// <summary> /// StepFC: FDS1 用 样本模式整型上下文 /// </summary> typedef struct { // 输出 float output; // 定点小数 音量包络 sfc_fixed_t volenv_clock; // 定点小数 调制包络 sfc_fixed_t modenv_clock; // 定点小数 波输出 sfc_fixed_t wavout_clock; // 定点小数 调制器 sfc_fixed_t mdunit_clock; } sfc_fds1_smi_ctx_t; // FDS1 整型采样模式 - 采样 void sfc_fds1_smi_sample(sfc_famicom_t*, sfc_fds1_smi_ctx_t*, const float[], sfc_fixed_t cps); // 浮点版本 #ifdef SFC_SMF_DEFINED // FDS 高级接口1 float sfc_fds1_get_output(sfc_famicom_t*); void sfc_fds1_per_cpu_clock(sfc_famicom_t*); // FDS 高级接口2 typedef struct { float volenv_clock; float volenv_tps; float modenv_clock; float modenv_tps; float wavout_clock; float mdunit_clock; float mdunit_rate; float cycle_remain; } sfc_fds1_ctx_t; float sfc_fds1_per_sample(sfc_famicom_t*, sfc_fds1_ctx_t*, float cps); void sfc_fds1_samplemode_begin(sfc_famicom_t*, sfc_fds1_ctx_t*); void sfc_fds1_samplemode_end(sfc_famicom_t*, sfc_fds1_ctx_t*); #endif // ------------------------------------------------------- // MMC5 // ------------------------------------------------------- /// <summary> /// StepFC: MMC5 用 样本模式整型上下文 /// </summary> typedef struct { // 方波#1 输出 float sq1_output; // 方波#2 输出 float sq2_output; // PCM 输出 float pcm_output; // 方波#1 状态 sfc_square_ch_state_t sq1_state; // 方波#2 状态 sfc_square_ch_state_t sq2_state; // 定点小数 方波#1 sfc_fixed_t sq1_clock; // 定点小数 方波#2 sfc_fixed_t sq2_clock; } sfc_mmc5_smi_ctx_t; // MMC5 整型采样模式 - 采样 void sfc_mmc5_smi_sample(sfc_famicom_t*, sfc_mmc5_smi_ctx_t*, const float[], sfc_fixed_t cps); // MMC5 整型采样模式 - 更新方波#1 void sfc_mmc5_smi_update_sq1(const sfc_famicom_t*, sfc_mmc5_smi_ctx_t*); // MMC5 整型采样模式 - 更新方波#2 void sfc_mmc5_smi_update_sq2(const sfc_famicom_t*, sfc_mmc5_smi_ctx_t*); // MMC5 整型采样模式 - 更新PCM //void sfc_mmc5_smi_update_pcm(const sfc_famicom_t*, sfc_mmc5_smi_ctx_t*); // 浮点版本 #ifdef SFC_SMF_DEFINED typedef struct { // 声道状态 sfc_square_ch_state_t state; // 方波 时钟周期 - 浮点误差修正 float clock; // 方波 浮点周期 float period; // 方波 输出音量 float output; }sfc_mmc5_square_ctx_t; typedef struct { sfc_mmc5_square_ctx_t squ1; sfc_mmc5_square_ctx_t squ2; } sfc_mmc5_ctx_t; void sfc_mmc5_per_sample(sfc_famicom_t*, sfc_mmc5_ctx_t*, float cps); void sfc_mmc5_samplemode_begin(sfc_famicom_t*, sfc_mmc5_ctx_t*); void sfc_mmc5_samplemode_end(sfc_famicom_t*, sfc_mmc5_ctx_t*); #endif // ------------------------------------------------------- // N163 // ------------------------------------------------------- /// <summary> /// StepFC: FME7用 样本模式整型上下文 /// </summary> /// <remarks> /// 各个声道直接访问 .apu.fme7 数据 /// </remarks> typedef struct { // 输出 float output; // 副Mapper指定权重 float subweight; // 定点小数 包络用时钟数 sfc_fixed_t clock; } sfc_n163_smi_ctx_t; // N163 整型采样模式 - 采样 void sfc_n163_smi_sample(sfc_famicom_t*, sfc_n163_smi_ctx_t*, const float[], sfc_fixed_t cps, uint8_t mode); // N163 整型采样模式 - 更新副权重 void sfc_n163_smi_update_subweight(const sfc_famicom_t*, sfc_n163_smi_ctx_t* ); // 浮点版本 #ifdef SFC_SMF_DEFINED typedef struct { float clock; float subweight; } sfc_n163_ctx_t; float sfc_n163_per_sample(sfc_famicom_t*, sfc_n163_ctx_t*, float cps, uint8_t mode); void sfc_n163_samplemode_begin(sfc_famicom_t*, sfc_n163_ctx_t*); void sfc_n163_samplemode_end(sfc_famicom_t*, sfc_n163_ctx_t*); #endif // ------------------------------------------------------- // FME-7(5B) // ------------------------------------------------------- /// <summary> /// StepFC: FME7用 样本模式整型上下文 /// </summary> typedef struct { // 输出 float output[3]; // 声道用时钟数 定点小数 sfc_fixed_t chn_clock[3]; // 噪音用时钟数 定点小数 sfc_fixed_t noi_clock; // 包络用时钟数 定点小数 sfc_fixed_t env_clock; } sfc_fme7_smi_ctx_t; // FME7 整型采样模式 - 采样 void sfc_fme7_smi_sample(sfc_famicom_t*, sfc_fme7_smi_ctx_t*, const float[], sfc_fixed_t cps); // 浮点版本 #ifdef SFC_SMF_DEFINED typedef struct { struct sfc_fme7_tone_s { float period; float clock; } ch[3]; float noise_period; float noise_clock; float env_period; float env_clock; } sfc_fme7_ctx_t; float sfc_fme7_per_sample(sfc_famicom_t*, sfc_fme7_ctx_t*, float cps); void sfc_fme7_samplemode_begin(sfc_famicom_t*, sfc_fme7_ctx_t*); void sfc_fme7_samplemode_end(sfc_famicom_t*, sfc_fme7_ctx_t*); #endif
6,360
6,058
# -*- coding: utf-8 -*- # Copyright (c) 2013, <NAME> # # 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. # # * The names of the contributors may not be used to endorse or # promote products derived from this software without specific # prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from __future__ import print_function def gobs_program(): """ A pure-Python implementation of Gob's Algorithm (2006). A brief explanation can be found here: https://www.youtube.com/watch?v=JbnjusltDHk """ while True: print("Penus", end=" ") if __name__ == '__main__': gobs_program()
586
892
<filename>advisories/github-reviewed/2022/05/GHSA-pjch-4g28-fxx7/GHSA-pjch-4g28-fxx7.json { "schema_version": "1.2.0", "id": "GHSA-pjch-4g28-fxx7", "modified": "2022-05-24T20:58:43Z", "published": "2022-05-07T00:00:31Z", "aliases": [ "CVE-2021-23792" ], "summary": "External Entity Reference in TwelveMonkeys ImageIO", "details": "The package com.twelvemonkeys.imageio:imageio-metadata before version 3.7.1 is vulnerable to XML External Entity (XXE) Injection due to an insecurely initialized XML parser for reading XMP Metadata. An attacker can exploit this vulnerability if they are able to supply a file (e.g. when an online profile picture is processed) with a malicious XMP segment. If the XMP metadata of the uploaded image is parsed, then the XXE vulnerability is triggered.", "severity": [ { "type": "CVSS_V3", "score": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H" } ], "affected": [ { "package": { "ecosystem": "Maven", "name": "com.twelvemonkeys.imageio:imageio-metadata" }, "ranges": [ { "type": "ECOSYSTEM", "events": [ { "introduced": "0" }, { "fixed": "3.7.1" } ] } ] } ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2021-23792" }, { "type": "WEB", "url": "https://github.com/haraldk/TwelveMonkeys/commit/da4efe98bf09e1cce91b7633cb251958a200fc80" }, { "type": "WEB", "url": "https://snyk.io/vuln/SNYK-JAVA-COMTWELVEMONKEYSIMAGEIO-2316763" }, { "type": "PACKAGE", "url": "https://github.com/haraldk/TwelveMonkeys" } ], "database_specific": { "cwe_ids": [ "CWE-611" ], "severity": "CRITICAL", "github_reviewed": true } }
940
3,710
#pragma once #ifndef COLUMNFAN_INCLUDED #define COLUMNFAN_INCLUDED #include "tcommon.h" #undef DVAPI #undef DVVAR #ifdef TOONZLIB_EXPORTS #define DVAPI DV_EXPORT_API #define DVVAR DV_EXPORT_VAR #else #define DVAPI DV_IMPORT_API #define DVVAR DV_IMPORT_VAR #endif class TOStream; class TIStream; //============================================================================= //! The ColumnFan class is used to menage display columns. /*!The class allows to fold a column by column index, deactivate(), to open folded columns, activate() and to know if column is folded or not, isActive(). Class provides column layer-axis coordinate too. It's possible to know column index by column layer-axis coordinate, colToLayerAxis() and vice versa, layerAxisToCol(). */ //============================================================================= class DVAPI ColumnFan { class Column { public: bool m_active; int m_pos; Column() : m_active(true), m_pos(0) {} }; std::vector<Column> m_columns; std::map<int, int> m_table; int m_firstFreePos; int m_unfolded, m_folded; bool m_cameraActive; int m_cameraColumnDim; /*! Called by activate() and deactivate() to update columns coordinates. */ void update(); public: /*! Constructs a ColumnFan with default value. */ ColumnFan(); //! Adjust column sizes when switching orientation void setDimensions(int unfolded, int cameraColumn); /*! Set column \b col not folded. \sa deactivate() and isActive() */ void activate(int col); /*! Fold column \b col. \sa activate() and isActive() */ void deactivate(int col); /*! Return true if column \b col is active, column is not folded, else return false. \sa activate() and deactivate() */ bool isActive(int col) const; /*! Return column index of column in layer axis (x for vertical timeline, y for horizontal). \sa colToLayerAxis() */ int layerAxisToCol(int layerAxis) const; /*! Return layer coordinate (x for vertical timeline, y for horizontal) of column identified by \b col. \sa layerAxisToCol() */ int colToLayerAxis(int col) const; void copyFoldedStateFrom(const ColumnFan &from); bool isEmpty() const; void saveData(TOStream &os); void loadData(TIStream &is); void rollLeftFoldedState(int index, int count); void rollRightFoldedState(int index, int count); }; #endif
750
631
/***************************************************************************** * * * OpenNI 1.x Alpha * * Copyright (C) 2012 PrimeSense Ltd. * * * * This file is part of OpenNI. * * * * 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. * * * *****************************************************************************/ //--------------------------------------------------------------------------- // Includes //--------------------------------------------------------------------------- #include <XnOS.h> #include <XnLog.h> #include "XnOSWin32Internal.h" //--------------------------------------------------------------------------- // Types //--------------------------------------------------------------------------- struct XnOSSharedMemory { HANDLE hMapFile; void* pAddress; }; //--------------------------------------------------------------------------- // Code //--------------------------------------------------------------------------- static XnStatus AccessFlagsToWin32MapFlags(XnUInt32 nAccessFlags, DWORD* pFlags) { DWORD result = 0; if ((nAccessFlags & XN_OS_FILE_READ) == 0) { return (XN_STATUS_INVALID_OPERATION); } if ((nAccessFlags & XN_OS_FILE_WRITE) != 0) { result = PAGE_READWRITE; } else { result = PAGE_READONLY; } *pFlags = result; return (XN_STATUS_OK); } static XnStatus AccessFlagsToWin32ViewFlags(XnUInt32 nAccessFlags, DWORD* pFlags) { DWORD result = 0; if ((nAccessFlags & XN_OS_FILE_READ) == 0) { return (XN_STATUS_INVALID_OPERATION); } if ((nAccessFlags & XN_OS_FILE_WRITE) != 0) { result = FILE_MAP_WRITE; } else { result = FILE_MAP_READ; } *pFlags = result; return (XN_STATUS_OK); } XN_C_API XnStatus XN_C_DECL xnOSCreateSharedMemory(const XnChar* strName, XnUInt32 nSize, XnUInt32 nAccessFlags, XN_SHARED_MEMORY_HANDLE* phSharedMem) { return xnOSCreateSharedMemoryEx(strName, nSize, nAccessFlags, FALSE, phSharedMem); } XN_C_API XnStatus XN_C_DECL xnOSCreateSharedMemoryEx(const XnChar* strName, XnUInt32 nSize, XnUInt32 nAccessFlags, XnBool bAllowOtherUsers, XN_SHARED_MEMORY_HANDLE* phSharedMem) { XnStatus nRetVal = XN_STATUS_OK; XN_VALIDATE_INPUT_PTR(strName); XN_VALIDATE_OUTPUT_PTR(phSharedMem); DWORD mapflags; nRetVal = AccessFlagsToWin32MapFlags(nAccessFlags, &mapflags); XN_IS_STATUS_OK(nRetVal); DWORD viewflags; nRetVal = AccessFlagsToWin32ViewFlags(nAccessFlags, &viewflags); XN_IS_STATUS_OK(nRetVal); XnChar strWinName[XN_FILE_MAX_PATH]; nRetVal = XnWin32CreateKernelObjectName(strWinName, MAX_PATH, strName, bAllowOtherUsers); if (nRetVal != XN_STATUS_OK) { return XN_STATUS_OS_EVENT_CREATION_FAILED; } SECURITY_ATTRIBUTES* pSecurityAttributes = NULL; nRetVal = XnWin32GetSecurityAttributes(bAllowOtherUsers, &pSecurityAttributes); if (nRetVal != XN_STATUS_OK) { return XN_STATUS_OS_EVENT_CREATION_FAILED; } // allocate handle XnOSSharedMemory* pHandle; XN_VALIDATE_CALLOC(pHandle, XnOSSharedMemory, 1); // create file mapping pHandle->hMapFile = CreateFileMapping( INVALID_HANDLE_VALUE, // use paging file pSecurityAttributes, // security mapflags, // read/write access 0, // max. object size nSize, // buffer size strWinName); // name of mapping object if (pHandle->hMapFile == NULL) { XN_LOG_ERROR_RETURN(XN_STATUS_OS_FAILED_TO_CREATE_SHARED_MEMORY, XN_MASK_OS, "Could not create file mapping object (%d).", GetLastError()); } // map it to the process pHandle->pAddress = MapViewOfFile( pHandle->hMapFile, // handle to map object viewflags, // read/write permission 0, 0, nSize); if (pHandle->pAddress == NULL) { XN_LOG_ERROR_RETURN(XN_STATUS_OS_FAILED_TO_CREATE_SHARED_MEMORY, XN_MASK_OS, "Could not map view of file (%d).", GetLastError()); } *phSharedMem = pHandle; return (XN_STATUS_OK); } XN_C_API XnStatus xnOSOpenSharedMemory(const XnChar* strName, XnUInt32 nAccessFlags, XN_SHARED_MEMORY_HANDLE* phSharedMem) { return xnOSOpenSharedMemoryEx(strName, nAccessFlags, FALSE, phSharedMem); } XN_C_API XnStatus XN_C_DECL xnOSOpenSharedMemoryEx(const XnChar* strName, XnUInt32 nAccessFlags, XnBool bAllowOtherUsers, XN_SHARED_MEMORY_HANDLE* phSharedMem) { XnStatus nRetVal = XN_STATUS_OK; XN_VALIDATE_INPUT_PTR(strName); XN_VALIDATE_OUTPUT_PTR(phSharedMem); DWORD flags; nRetVal = AccessFlagsToWin32ViewFlags(nAccessFlags, &flags); XN_IS_STATUS_OK(nRetVal); XnChar strWinName[XN_FILE_MAX_PATH]; nRetVal = XnWin32CreateKernelObjectName(strWinName, MAX_PATH, strName, bAllowOtherUsers); if (nRetVal != XN_STATUS_OK) { return XN_STATUS_OS_FAILED_TO_OPEN_SHARED_MEMORY; } // allocate handle XnOSSharedMemory* pHandle; XN_VALIDATE_CALLOC(pHandle, XnOSSharedMemory, 1); // create file mapping pHandle->hMapFile = OpenFileMapping( flags, // read/write access FALSE, // do not inherit the name strWinName); // name of mapping object if (pHandle->hMapFile == NULL) { XN_LOG_ERROR_RETURN(XN_STATUS_OS_FAILED_TO_OPEN_SHARED_MEMORY, XN_MASK_OS, "Could not open file mapping object (%d).", GetLastError()); } // map it to the process pHandle->pAddress = MapViewOfFile( pHandle->hMapFile, // handle to map object flags, // read/write permission 0, 0, 0); if (pHandle->pAddress == NULL) { XN_LOG_ERROR_RETURN(XN_STATUS_OS_FAILED_TO_OPEN_SHARED_MEMORY, XN_MASK_OS, "Could not map view of file (%d).", GetLastError()); } *phSharedMem = pHandle; return (XN_STATUS_OK); } XN_C_API XnStatus xnOSCloseSharedMemory(XN_SHARED_MEMORY_HANDLE hSharedMem) { XN_VALIDATE_INPUT_PTR(hSharedMem); if (!UnmapViewOfFile(hSharedMem->pAddress)) { XN_LOG_ERROR_RETURN(XN_STATUS_OS_FAILED_TO_CLOSE_SHARED_MEMORY, XN_MASK_OS, "Could not unmap view of file (%d).", GetLastError()); } if (!CloseHandle(hSharedMem->hMapFile)) { XN_LOG_ERROR_RETURN(XN_STATUS_OS_FAILED_TO_CLOSE_SHARED_MEMORY, XN_MASK_OS, "Could not close shared memory handle (%d).", GetLastError()); } xnOSFree(hSharedMem); return (XN_STATUS_OK); } XN_C_API XnStatus xnOSSharedMemoryGetAddress(XN_SHARED_MEMORY_HANDLE hSharedMem, void** ppAddress) { XN_VALIDATE_INPUT_PTR(hSharedMem); XN_VALIDATE_OUTPUT_PTR(ppAddress); *ppAddress = hSharedMem->pAddress; return (XN_STATUS_OK); }
3,827
679
<reponame>Grosskopf/openoffice<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. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_extensions.hxx" #include "browserlistbox.hxx" #ifndef EXTENSIONS_PROPRESID_HRC #include "propresid.hrc" #endif #include "proplinelistener.hxx" #include "propcontrolobserver.hxx" #include "linedescriptor.hxx" #include "inspectorhelpwindow.hxx" /** === begin UNO includes === **/ #include <com/sun/star/lang/DisposedException.hpp> #include <com/sun/star/lang/XComponent.hpp> #include <com/sun/star/inspection/PropertyControlType.hpp> /** === end UNO includes === **/ #include <tools/debug.hxx> #include <tools/diagnose_ex.h> #include <comphelper/asyncnotification.hxx> #include <cppuhelper/implbase1.hxx> #include <vcl/svapp.hxx> #include <vos/mutex.hxx> //............................................................................ namespace pcr { //............................................................................ #define FRAME_OFFSET 4 // TODO: find out what this is really for ... and check if it does make sense in the new // browser environment #define LAYOUT_HELP_WINDOW_DISTANCE_APPFONT 3 /** === begin UNO using === **/ using ::com::sun::star::uno::Any; using ::com::sun::star::uno::Exception; using ::com::sun::star::inspection::XPropertyControlContext; using ::com::sun::star::uno::Reference; using ::com::sun::star::inspection::XPropertyControl; using ::com::sun::star::uno::RuntimeException; using ::com::sun::star::lang::DisposedException; using ::com::sun::star::lang::XComponent; using ::com::sun::star::uno::UNO_QUERY; using ::com::sun::star::graphic::XGraphic; /** === end UNO using === **/ namespace PropertyControlType = ::com::sun::star::inspection::PropertyControlType; //================================================================== //= ControlEvent //================================================================== enum ControlEventType { FOCUS_GAINED, VALUE_CHANGED, ACTIVATE_NEXT }; struct ControlEvent : public ::comphelper::AnyEvent { Reference< XPropertyControl > xControl; ControlEventType eType; ControlEvent( const Reference< XPropertyControl >& _rxControl, ControlEventType _eType ) :xControl( _rxControl ) ,eType( _eType ) { } }; //================================================================== //= SharedNotifier //================================================================== class SharedNotifier { private: static ::osl::Mutex& getMutex(); static ::rtl::Reference< ::comphelper::AsyncEventNotifier > s_pNotifier; public: static const ::rtl::Reference< ::comphelper::AsyncEventNotifier >& getNotifier(); private: SharedNotifier(); // never implemented SharedNotifier( const SharedNotifier& ); // never implemented SharedNotifier& operator=( const SharedNotifier& ); // never implemented }; //------------------------------------------------------------------ ::rtl::Reference< ::comphelper::AsyncEventNotifier > SharedNotifier::s_pNotifier; //------------------------------------------------------------------ ::osl::Mutex& SharedNotifier::getMutex() { static ::osl::Mutex s_aMutex; return s_aMutex; } //------------------------------------------------------------------ const ::rtl::Reference< ::comphelper::AsyncEventNotifier >& SharedNotifier::getNotifier() { ::osl::MutexGuard aGuard( getMutex() ); if ( !s_pNotifier.is() ) { s_pNotifier.set( new ::comphelper::AsyncEventNotifier ); s_pNotifier->create(); } return s_pNotifier; } //================================================================== //= PropertyControlContext_Impl //================================================================== /** implementation for of <type scope="com::sun::star::inspection">XPropertyControlContext</type> which forwards all events to a non-UNO version of this interface */ typedef ::cppu::WeakImplHelper1< XPropertyControlContext > PropertyControlContext_Impl_Base; class PropertyControlContext_Impl :public PropertyControlContext_Impl_Base ,public ::comphelper::IEventProcessor { public: enum NotifcationMode { eSynchronously, eAsynchronously }; private: IControlContext* m_pContext; NotifcationMode m_eMode; public: /** creates an instance @param _rContextImpl the instance to delegate events to */ PropertyControlContext_Impl( IControlContext& _rContextImpl ); /** disposes the context. When you call this method, all subsequent callbacks to the <type scope="com::sun::star::inspection">XPropertyControlContext</type> methods will throw a <type scope="com::sun::star::lang">DisposedException</type>. */ void SAL_CALL dispose(); /** sets the notification mode, so that notifications received from the controls are forwarded to our IControlContext either synchronously or asynchronously @param _eMode the new notification mode */ void setNotificationMode( NotifcationMode _eMode ); virtual void SAL_CALL acquire() throw(); virtual void SAL_CALL release() throw(); protected: ~PropertyControlContext_Impl(); // XPropertyControlObserver virtual void SAL_CALL focusGained( const Reference< XPropertyControl >& Control ) throw (RuntimeException); virtual void SAL_CALL valueChanged( const Reference< XPropertyControl >& Control ) throw (RuntimeException); // XPropertyControlContext virtual void SAL_CALL activateNextControl( const Reference< XPropertyControl >& CurrentControl ) throw (RuntimeException); // IEventProcessor virtual void processEvent( const ::comphelper::AnyEvent& _rEvent ); private: /** processes the given event, i.e. notifies it to our IControlContext @param _rEvent the event no notify @precond our mutex (well, the SolarMutex) is locked */ void impl_processEvent_throw( const ::comphelper::AnyEvent& _rEvent ); /** checks whether we're alive @throws DisposedException if the instance is already disposed */ void impl_checkAlive_throw() const; /** checks whether the instance is already disposed */ bool impl_isDisposed_nothrow() const { return m_pContext == NULL; } /** notifies the given event originating from the given control @throws DisposedException @param _rxControl @param _eType */ void impl_notify_throw( const Reference< XPropertyControl >& _rxControl, ControlEventType _eType ); }; //-------------------------------------------------------------------- PropertyControlContext_Impl::PropertyControlContext_Impl( IControlContext& _rContextImpl ) :m_pContext( &_rContextImpl ) ,m_eMode( eAsynchronously ) { } //-------------------------------------------------------------------- PropertyControlContext_Impl::~PropertyControlContext_Impl() { if ( !impl_isDisposed_nothrow() ) dispose(); } //-------------------------------------------------------------------- void PropertyControlContext_Impl::impl_checkAlive_throw() const { if ( impl_isDisposed_nothrow() ) throw DisposedException( ::rtl::OUString(), *const_cast< PropertyControlContext_Impl* >( this ) ); } //-------------------------------------------------------------------- void SAL_CALL PropertyControlContext_Impl::dispose() { ::vos::OGuard aGuard( Application::GetSolarMutex() ); if ( impl_isDisposed_nothrow() ) return; SharedNotifier::getNotifier()->removeEventsForProcessor( this ); m_pContext = NULL; } //-------------------------------------------------------------------- void PropertyControlContext_Impl::setNotificationMode( NotifcationMode _eMode ) { ::vos::OGuard aGuard( Application::GetSolarMutex() ); m_eMode = _eMode; } //-------------------------------------------------------------------- void PropertyControlContext_Impl::impl_notify_throw( const Reference< XPropertyControl >& _rxControl, ControlEventType _eType ) { ::comphelper::AnyEventRef pEvent; { ::vos::OGuard aGuard( Application::GetSolarMutex() ); impl_checkAlive_throw(); pEvent = new ControlEvent( _rxControl, _eType ); if ( m_eMode == eSynchronously ) { impl_processEvent_throw( *pEvent ); return; } } SharedNotifier::getNotifier()->addEvent( pEvent, this ); } //-------------------------------------------------------------------- void SAL_CALL PropertyControlContext_Impl::focusGained( const Reference< XPropertyControl >& Control ) throw (RuntimeException) { DBG_TRACE( "PropertyControlContext_Impl: FOCUS_GAINED" ); impl_notify_throw( Control, FOCUS_GAINED ); } //-------------------------------------------------------------------- void SAL_CALL PropertyControlContext_Impl::valueChanged( const Reference< XPropertyControl >& Control ) throw (RuntimeException) { DBG_TRACE( "PropertyControlContext_Impl: VALUE_CHANGED" ); impl_notify_throw( Control, VALUE_CHANGED ); } //-------------------------------------------------------------------- void SAL_CALL PropertyControlContext_Impl::activateNextControl( const Reference< XPropertyControl >& CurrentControl ) throw (RuntimeException) { DBG_TRACE( "PropertyControlContext_Impl: ACTIVATE_NEXT" ); impl_notify_throw( CurrentControl, ACTIVATE_NEXT ); } //-------------------------------------------------------------------- void SAL_CALL PropertyControlContext_Impl::acquire() throw() { PropertyControlContext_Impl_Base::acquire(); } //-------------------------------------------------------------------- void SAL_CALL PropertyControlContext_Impl::release() throw() { PropertyControlContext_Impl_Base::release(); } //-------------------------------------------------------------------- void PropertyControlContext_Impl::processEvent( const ::comphelper::AnyEvent& _rEvent ) { ::vos::OGuard aGuard( Application::GetSolarMutex() ); if ( impl_isDisposed_nothrow() ) return; try { impl_processEvent_throw( _rEvent ); } catch( const Exception& ) { // can't handle otherwise, since our caller (the notification thread) does not allow // for exceptions (it could itself abort only) DBG_UNHANDLED_EXCEPTION(); } } //-------------------------------------------------------------------- void PropertyControlContext_Impl::impl_processEvent_throw( const ::comphelper::AnyEvent& _rEvent ) { const ControlEvent& rControlEvent = static_cast< const ControlEvent& >( _rEvent ); switch ( rControlEvent.eType ) { case FOCUS_GAINED: DBG_TRACE( "PropertyControlContext_Impl::processEvent: FOCUS_GAINED" ); m_pContext->focusGained( rControlEvent.xControl ); break; case VALUE_CHANGED: DBG_TRACE( "PropertyControlContext_Impl::processEvent: VALUE_CHANGED" ); m_pContext->valueChanged( rControlEvent.xControl ); break; case ACTIVATE_NEXT: DBG_TRACE( "PropertyControlContext_Impl::processEvent: ACTIVATE_NEXT" ); m_pContext->activateNextControl( rControlEvent.xControl ); break; } } //================================================================== //= OBrowserListBox //================================================================== DBG_NAME(OBrowserListBox) //------------------------------------------------------------------ OBrowserListBox::OBrowserListBox( Window* pParent, WinBits nWinStyle) :Control(pParent, nWinStyle| WB_CLIPCHILDREN) ,m_aLinesPlayground(this,WB_DIALOGCONTROL | WB_CLIPCHILDREN) ,m_aVScroll(this,WB_VSCROLL|WB_REPEAT|WB_DRAG) ,m_pHelpWindow( new InspectorHelpWindow( this ) ) ,m_pLineListener(NULL) ,m_pControlObserver( NULL ) ,m_nYOffset(0) ,m_nCurrentPreferredHelpHeight(0) ,m_nTheNameSize(0) ,m_bIsActive(sal_False) ,m_bUpdate(sal_True) ,m_pControlContextImpl( new PropertyControlContext_Impl( *this ) ) { DBG_CTOR(OBrowserListBox,NULL); ListBox aListBox(this,WB_DROPDOWN); aListBox.SetPosSizePixel(Point(0,0),Size(100,100)); m_nRowHeight = (sal_uInt16)aListBox.GetSizePixel().Height()+2; SetBackground( pParent->GetBackground() ); m_aLinesPlayground.SetBackground( GetBackground() ); m_aLinesPlayground.SetPosPixel(Point(0,0)); m_aLinesPlayground.SetPaintTransparent(sal_True); m_aLinesPlayground.Show(); m_aVScroll.Hide(); m_aVScroll.SetScrollHdl(LINK(this, OBrowserListBox, ScrollHdl)); } //------------------------------------------------------------------ OBrowserListBox::~OBrowserListBox() { OSL_ENSURE( !IsModified(), "OBrowserListBox::~OBrowserListBox: still modified - should have been committed before!" ); // doing the commit here, while we, as well as our owner, as well as some other components, // are already "half dead" (means within their dtor) is potentially dangerous. // By definition, CommitModified has to be called (if necessary) before destruction // #105868# - 2002-12-13 - <EMAIL> m_pControlContextImpl->dispose(); m_pControlContextImpl.clear(); Hide(); Clear(); DBG_DTOR(OBrowserListBox,NULL); } //------------------------------------------------------------------ sal_Bool OBrowserListBox::IsModified( ) const { sal_Bool bModified = sal_False; if ( m_bIsActive && m_xActiveControl.is() ) bModified = m_xActiveControl->isModified(); return bModified; } //------------------------------------------------------------------ void OBrowserListBox::CommitModified( ) { if ( IsModified() && m_xActiveControl.is() ) { // for the time of this commit, notify all events synchronously // #i63814# / 2006-03-31 / <EMAIL> m_pControlContextImpl->setNotificationMode( PropertyControlContext_Impl::eSynchronously ); try { m_xActiveControl->notifyModifiedValue(); } catch( const Exception& ) { DBG_UNHANDLED_EXCEPTION(); } m_pControlContextImpl->setNotificationMode( PropertyControlContext_Impl::eAsynchronously ); } } //------------------------------------------------------------------ void OBrowserListBox::ActivateListBox(sal_Bool _bActive) { m_bIsActive = _bActive; if (m_bIsActive) { // TODO: what's the sense of this? m_aVScroll.SetThumbPos(100); MoveThumbTo(0); Resize(); } } //------------------------------------------------------------------ long OBrowserListBox::impl_getPrefererredHelpHeight() { return HasHelpSection() ? m_pHelpWindow->GetOptimalHeightPixel() : 0; } //------------------------------------------------------------------ void OBrowserListBox::Resize() { Rectangle aPlayground( Point( 0, 0 ), GetOutputSizePixel() ); Size aHelpWindowDistance( LogicToPixel( Size( 0, LAYOUT_HELP_WINDOW_DISTANCE_APPFONT ), MAP_APPFONT ) ); long nHelpWindowHeight = m_nCurrentPreferredHelpHeight = impl_getPrefererredHelpHeight(); bool bPositionHelpWindow = ( nHelpWindowHeight != 0 ); Rectangle aLinesArea( aPlayground ); if ( bPositionHelpWindow ) { aLinesArea.Bottom() -= nHelpWindowHeight; aLinesArea.Bottom() -= aHelpWindowDistance.Height(); } m_aLinesPlayground.SetPosSizePixel( aLinesArea.TopLeft(), aLinesArea.GetSize() ); UpdateVScroll(); sal_Bool bNeedScrollbar = m_aOrderedLines.size() > (sal_uInt32)CalcVisibleLines(); if ( !bNeedScrollbar ) { if ( m_aVScroll.IsVisible() ) m_aVScroll.Hide(); // scroll to top m_nYOffset = 0; m_aVScroll.SetThumbPos( 0 ); } else { Size aVScrollSize( m_aVScroll.GetSizePixel() ); // adjust the playground's width aLinesArea.Right() -= aVScrollSize.Width(); m_aLinesPlayground.SetPosSizePixel( aLinesArea.TopLeft(), aLinesArea.GetSize() ); // position the scrollbar aVScrollSize.Height() = aLinesArea.GetHeight(); Point aVScrollPos( aLinesArea.GetWidth(), 0 ); m_aVScroll.SetPosSizePixel( aVScrollPos, aVScrollSize ); } for ( sal_uInt16 i = 0; i < m_aOrderedLines.size(); ++i ) m_aOutOfDateLines.insert( i ); // repaint EnablePaint(sal_False); UpdatePlayGround(); EnablePaint(sal_True); // show the scrollbar if ( bNeedScrollbar ) m_aVScroll.Show(); // position the help window if ( bPositionHelpWindow ) { Rectangle aHelpArea( aPlayground ); aHelpArea.Top() = aLinesArea.Bottom() + aHelpWindowDistance.Height(); m_pHelpWindow->SetPosSizePixel( aHelpArea.TopLeft(), aHelpArea.GetSize() ); } } //------------------------------------------------------------------ void OBrowserListBox::SetListener( IPropertyLineListener* _pListener ) { m_pLineListener = _pListener; } //------------------------------------------------------------------ void OBrowserListBox::SetObserver( IPropertyControlObserver* _pObserver ) { m_pControlObserver = _pObserver; } //------------------------------------------------------------------ void OBrowserListBox::EnableHelpSection( bool _bEnable ) { m_pHelpWindow->Show( _bEnable ); Resize(); } //------------------------------------------------------------------ bool OBrowserListBox::HasHelpSection() const { return m_pHelpWindow->IsVisible(); } //------------------------------------------------------------------ void OBrowserListBox::SetHelpText( const ::rtl::OUString& _rHelpText ) { OSL_ENSURE( HasHelpSection(), "OBrowserListBox::SetHelpText: help section not visible!" ); m_pHelpWindow->SetText( _rHelpText ); if ( m_nCurrentPreferredHelpHeight != impl_getPrefererredHelpHeight() ) Resize(); } //------------------------------------------------------------------ void OBrowserListBox::SetHelpLineLimites( sal_Int32 _nMinLines, sal_Int32 _nMaxLines ) { m_pHelpWindow->SetLimits( _nMinLines, _nMaxLines ); } //------------------------------------------------------------------ sal_uInt16 OBrowserListBox::CalcVisibleLines() { Size aSize(m_aLinesPlayground.GetOutputSizePixel()); sal_uInt16 nResult = 0; if (0 != m_nRowHeight) nResult = (sal_uInt16) aSize.Height()/m_nRowHeight; return nResult; } //------------------------------------------------------------------ void OBrowserListBox::UpdateVScroll() { sal_uInt16 nLines = CalcVisibleLines(); m_aVScroll.SetPageSize(nLines-1); m_aVScroll.SetVisibleSize(nLines-1); size_t nCount = m_aLines.size(); if (nCount>0) { m_aVScroll.SetRange(Range(0,nCount-1)); m_nYOffset = -m_aVScroll.GetThumbPos()*m_nRowHeight; } else { m_aVScroll.SetRange(Range(0,0)); m_nYOffset = 0; } } //------------------------------------------------------------------ void OBrowserListBox::PositionLine( sal_uInt16 _nIndex ) { Size aSize(m_aLinesPlayground.GetOutputSizePixel()); Point aPos(0, m_nYOffset); aSize.Height() = m_nRowHeight; aPos.Y() += _nIndex * m_nRowHeight; if ( _nIndex < m_aOrderedLines.size() ) { m_aOrderedLines[ _nIndex ]->second.pLine->SetPosSizePixel( aPos, aSize ); m_aOrderedLines[ _nIndex ]->second.pLine->SetTitleWidth( m_nTheNameSize + 2 * FRAME_OFFSET ); // show the line if necessary if ( !m_aOrderedLines[ _nIndex ]->second.pLine->IsVisible() ) m_aOrderedLines[ _nIndex ]->second.pLine->Show(); } } //------------------------------------------------------------------ void OBrowserListBox::UpdatePosNSize() { for ( ::std::set< sal_uInt16 >::const_iterator aLoop = m_aOutOfDateLines.begin(); aLoop != m_aOutOfDateLines.end(); ++aLoop ) { DBG_ASSERT( *aLoop < m_aOrderedLines.size(), "OBrowserListBox::UpdatePosNSize: invalid line index!" ); if ( *aLoop < m_aOrderedLines.size() ) PositionLine( *aLoop ); } m_aOutOfDateLines.clear(); } //------------------------------------------------------------------ void OBrowserListBox::UpdatePlayGround() { sal_Int32 nThumbPos = m_aVScroll.GetThumbPos(); sal_Int32 nLines = CalcVisibleLines(); sal_uInt16 nEnd = (sal_uInt16)(nThumbPos + nLines); if (nEnd >= m_aOrderedLines.size()) nEnd = (sal_uInt16)m_aOrderedLines.size()-1; if ( !m_aOrderedLines.empty() ) { for ( sal_uInt16 i = (sal_uInt16)nThumbPos; i <= nEnd; ++i ) m_aOutOfDateLines.insert( i ); UpdatePosNSize(); } } //------------------------------------------------------------------ void OBrowserListBox::UpdateAll() { Resize(); } //------------------------------------------------------------------ void OBrowserListBox::DisableUpdate() { m_bUpdate = sal_False; } //------------------------------------------------------------------ void OBrowserListBox::EnableUpdate() { m_bUpdate = sal_True; UpdateAll(); } //------------------------------------------------------------------ void OBrowserListBox::SetPropertyValue(const ::rtl::OUString& _rEntryName, const Any& _rValue, bool _bUnknownValue ) { ListBoxLines::iterator line = m_aLines.find( _rEntryName ); if ( line != m_aLines.end() ) { if ( _bUnknownValue ) { Reference< XPropertyControl > xControl( line->second.pLine->getControl() ); OSL_ENSURE( xControl.is(), "OBrowserListBox::SetPropertyValue: illegal control!" ); if ( xControl.is() ) xControl->setValue( Any() ); } else impl_setControlAsPropertyValue( line->second, _rValue ); } } //------------------------------------------------------------------------ sal_uInt16 OBrowserListBox::GetPropertyPos( const ::rtl::OUString& _rEntryName ) const { sal_uInt16 nRet = LISTBOX_ENTRY_NOTFOUND; for ( OrderedListBoxLines::const_iterator linePos = m_aOrderedLines.begin(); linePos != m_aOrderedLines.end(); ++linePos ) { if ( (*linePos)->first == _rEntryName ) { nRet = (sal_uInt16)( linePos - m_aOrderedLines.begin() ); break; } } return nRet; } //------------------------------------------------------------------------ bool OBrowserListBox::impl_getBrowserLineForName( const ::rtl::OUString& _rEntryName, BrowserLinePointer& _out_rpLine ) const { ListBoxLines::const_iterator line = m_aLines.find( _rEntryName ); if ( line != m_aLines.end() ) _out_rpLine = line->second.pLine; else _out_rpLine.reset(); return ( NULL != _out_rpLine.get() ); } //------------------------------------------------------------------------ void OBrowserListBox::EnablePropertyControls( const ::rtl::OUString& _rEntryName, sal_Int16 _nControls, bool _bEnable ) { BrowserLinePointer pLine; if ( impl_getBrowserLineForName( _rEntryName, pLine ) ) pLine->EnablePropertyControls( _nControls, _bEnable ); } //------------------------------------------------------------------------ void OBrowserListBox::EnablePropertyLine( const ::rtl::OUString& _rEntryName, bool _bEnable ) { BrowserLinePointer pLine; if ( impl_getBrowserLineForName( _rEntryName, pLine ) ) pLine->EnablePropertyLine( _bEnable ); } //------------------------------------------------------------------------ Reference< XPropertyControl > OBrowserListBox::GetPropertyControl( const ::rtl::OUString& _rEntryName ) { BrowserLinePointer pLine; if ( impl_getBrowserLineForName( _rEntryName, pLine ) ) return pLine->getControl(); return NULL; } //------------------------------------------------------------------ sal_uInt16 OBrowserListBox::InsertEntry(const OLineDescriptor& _rPropertyData, sal_uInt16 _nPos) { // create a new line BrowserLinePointer pBrowserLine( new OBrowserLine( _rPropertyData.sName, &m_aLinesPlayground ) ); ListBoxLine aNewLine( pBrowserLine, _rPropertyData.xPropertyHandler ); ::std::pair< ListBoxLines::iterator, bool > insertPoint = m_aLines.insert( ListBoxLines::value_type( _rPropertyData.sName, aNewLine ) ); OSL_ENSURE( insertPoint.second, "OBrowserListBox::InsertEntry: already have another line for this name!" ); sal_uInt16 nInsertPos = _nPos; if ( nInsertPos > m_aOrderedLines.size() ) nInsertPos = EDITOR_LIST_APPEND; if ( EDITOR_LIST_APPEND == nInsertPos ) { nInsertPos = (sal_uInt16)m_aOrderedLines.size(); m_aOrderedLines.push_back( insertPoint.first ); } else m_aOrderedLines.insert( m_aOrderedLines.begin() + nInsertPos, insertPoint.first ); pBrowserLine->SetTitleWidth(m_nTheNameSize); if (m_bUpdate) { UpdateVScroll(); Invalidate(); } // initialize the entry ChangeEntry(_rPropertyData, nInsertPos); // update the positions of possibly affected lines sal_uInt16 nUpdatePos = nInsertPos; while ( nUpdatePos < m_aOrderedLines.size() ) m_aOutOfDateLines.insert( nUpdatePos++ ); UpdatePosNSize( ); return nInsertPos; } //------------------------------------------------------------------ sal_Int32 OBrowserListBox::GetMinimumWidth() { return m_nTheNameSize + 2 * FRAME_OFFSET + (m_nRowHeight - 4) * 8; } //------------------------------------------------------------------ sal_Int32 OBrowserListBox::GetMinimumHeight() { // assume that we want to display 5 rows, at least sal_Int32 nMinHeight = m_nRowHeight * 5; if ( HasHelpSection() ) { Size aHelpWindowDistance( LogicToPixel( Size( 0, LAYOUT_HELP_WINDOW_DISTANCE_APPFONT ), MAP_APPFONT ) ); nMinHeight += aHelpWindowDistance.Height(); nMinHeight += m_pHelpWindow->GetMinimalHeightPixel(); } return nMinHeight; } //------------------------------------------------------------------ void OBrowserListBox::ShowEntry(sal_uInt16 _nPos) { if ( _nPos < m_aOrderedLines.size() ) { sal_Int32 nThumbPos = m_aVScroll.GetThumbPos(); if (_nPos < nThumbPos) MoveThumbTo(_nPos); else { sal_Int32 nLines = CalcVisibleLines(); if (_nPos >= nThumbPos + nLines) MoveThumbTo(_nPos - nLines + 1); } } } //------------------------------------------------------------------ void OBrowserListBox::MoveThumbTo(sal_Int32 _nNewThumbPos) { // disable painting to prevent flicker m_aLinesPlayground.EnablePaint(sal_False); sal_Int32 nDelta = _nNewThumbPos - m_aVScroll.GetThumbPos(); // adjust the scrollbar m_aVScroll.SetThumbPos(_nNewThumbPos); sal_Int32 nThumbPos = _nNewThumbPos; m_nYOffset = -m_aVScroll.GetThumbPos() * m_nRowHeight; sal_Int32 nLines = CalcVisibleLines(); sal_uInt16 nEnd = (sal_uInt16)(nThumbPos + nLines); m_aLinesPlayground.Scroll(0, -nDelta * m_nRowHeight, SCROLL_CHILDREN); if (1 == nDelta) { // TODO: what's the sense of this two PositionLines? Why not just one call? PositionLine(nEnd-1); PositionLine(nEnd); } else if (-1 == nDelta) { PositionLine((sal_uInt16)nThumbPos); } else if (0 != nDelta) { UpdatePlayGround(); } m_aLinesPlayground.EnablePaint(sal_True); m_aLinesPlayground.Invalidate(INVALIDATE_CHILDREN); } //------------------------------------------------------------------ IMPL_LINK(OBrowserListBox, ScrollHdl, ScrollBar*, _pScrollBar ) { DBG_ASSERT(_pScrollBar == &m_aVScroll, "OBrowserListBox::ScrollHdl: where does this come from?"); (void)_pScrollBar; // disable painting to prevent flicker m_aLinesPlayground.EnablePaint(sal_False); sal_Int32 nThumbPos = m_aVScroll.GetThumbPos(); sal_Int32 nDelta = m_aVScroll.GetDelta(); m_nYOffset = -nThumbPos * m_nRowHeight; sal_uInt16 nEnd = (sal_uInt16)(nThumbPos + CalcVisibleLines()); m_aLinesPlayground.Scroll(0, -nDelta * m_nRowHeight, SCROLL_CHILDREN); if (1 == nDelta) { PositionLine(nEnd-1); PositionLine(nEnd); } else if (nDelta==-1) { PositionLine((sal_uInt16)nThumbPos); } else if (nDelta!=0 || m_aVScroll.GetType() == SCROLL_DONTKNOW) { UpdatePlayGround(); } m_aLinesPlayground.EnablePaint(sal_True); return 0; } //------------------------------------------------------------------ void OBrowserListBox::buttonClicked( OBrowserLine* _pLine, sal_Bool _bPrimary ) { DBG_ASSERT( _pLine, "OBrowserListBox::buttonClicked: invalid browser line!" ); if ( _pLine && m_pLineListener ) { m_pLineListener->Clicked( _pLine->GetEntryName(), _bPrimary ); } } //------------------------------------------------------------------ void OBrowserListBox::impl_setControlAsPropertyValue( const ListBoxLine& _rLine, const Any& _rPropertyValue ) { Reference< XPropertyControl > xControl( _rLine.pLine->getControl() ); try { if ( _rPropertyValue.getValueType().equals( _rLine.pLine->getControl()->getValueType() ) ) { xControl->setValue( _rPropertyValue ); } else { #ifdef DBG_UTIL if ( !_rLine.xHandler.is() ) { ::rtl::OString sMessage( "OBrowserListBox::impl_setControlAsPropertyValue: no handler -> no conversion (property: '" ); ::rtl::OUString sPropertyName( _rLine.pLine->GetEntryName() ); sMessage += ::rtl::OString( sPropertyName.getStr(), sPropertyName.getLength(), RTL_TEXTENCODING_ASCII_US ); sMessage += ::rtl::OString( "')!" ); DBG_ERROR( sMessage ); } #endif if ( _rLine.xHandler.is() ) { Any aControlValue = _rLine.xHandler->convertToControlValue( _rLine.pLine->GetEntryName(), _rPropertyValue, xControl->getValueType() ); xControl->setValue( aControlValue ); } } } catch( const Exception& ) { DBG_UNHANDLED_EXCEPTION(); } } //------------------------------------------------------------------ Any OBrowserListBox::impl_getControlAsPropertyValue( const ListBoxLine& _rLine ) const { Reference< XPropertyControl > xControl( _rLine.pLine->getControl() ); Any aPropertyValue; try { #ifdef DBG_UTIL if ( !_rLine.xHandler.is() ) { ::rtl::OString sMessage( "OBrowserListBox::impl_getControlAsPropertyValue: no handler -> no conversion (property: '" ); ::rtl::OUString sPropertyName( _rLine.pLine->GetEntryName() ); sMessage += ::rtl::OString( sPropertyName.getStr(), sPropertyName.getLength(), RTL_TEXTENCODING_ASCII_US ); sMessage += ::rtl::OString( "')!" ); DBG_ERROR( sMessage ); } #endif if ( _rLine.xHandler.is() ) aPropertyValue = _rLine.xHandler->convertToPropertyValue( _rLine.pLine->GetEntryName(), xControl->getValue() ); else aPropertyValue = xControl->getValue(); } catch( const Exception& ) { DBG_UNHANDLED_EXCEPTION(); } return aPropertyValue; } //------------------------------------------------------------------ sal_uInt16 OBrowserListBox::impl_getControlPos( const Reference< XPropertyControl >& _rxControl ) const { for ( OrderedListBoxLines::const_iterator search = m_aOrderedLines.begin(); search != m_aOrderedLines.end(); ++search ) if ( (*search)->second.pLine->getControl().get() == _rxControl.get() ) return sal_uInt16( search - m_aOrderedLines.begin() ); DBG_ERROR( "OBrowserListBox::impl_getControlPos: invalid control - not part of any of our lines!" ); return (sal_uInt16)-1; } //-------------------------------------------------------------------- void SAL_CALL OBrowserListBox::focusGained( const Reference< XPropertyControl >& _rxControl ) throw (RuntimeException) { DBG_TESTSOLARMUTEX(); DBG_ASSERT( _rxControl.is(), "OBrowserListBox::focusGained: invalid event source!" ); if ( !_rxControl.is() ) return; if ( m_pControlObserver ) m_pControlObserver->focusGained( _rxControl ); m_xActiveControl = _rxControl; ShowEntry( impl_getControlPos( m_xActiveControl ) ); } //-------------------------------------------------------------------- void SAL_CALL OBrowserListBox::valueChanged( const Reference< XPropertyControl >& _rxControl ) throw (RuntimeException) { DBG_TESTSOLARMUTEX(); DBG_ASSERT( _rxControl.is(), "OBrowserListBox::valueChanged: invalid event source!" ); if ( !_rxControl.is() ) return; if ( m_pControlObserver ) m_pControlObserver->valueChanged( _rxControl ); if ( m_pLineListener ) { const ListBoxLine& rLine = impl_getControlLine( _rxControl ); m_pLineListener->Commit( rLine.pLine->GetEntryName(), impl_getControlAsPropertyValue( rLine ) ); } } //-------------------------------------------------------------------- void SAL_CALL OBrowserListBox::activateNextControl( const Reference< XPropertyControl >& _rxCurrentControl ) throw (RuntimeException) { DBG_TESTSOLARMUTEX(); sal_uInt16 nLine = impl_getControlPos( _rxCurrentControl ); // cycle forwards, 'til we've the next control which can grab the focus ++nLine; while ( (size_t)nLine < m_aOrderedLines.size() ) { if ( m_aOrderedLines[nLine]->second.pLine->GrabFocus() ) break; ++nLine; } if ( ( (size_t)nLine >= m_aOrderedLines.size() ) && ( m_aOrderedLines.size() > 0 ) ) // wrap around m_aOrderedLines[0]->second.pLine->GrabFocus(); } //------------------------------------------------------------------ namespace { //.............................................................. void lcl_implDisposeControl_nothrow( const Reference< XPropertyControl >& _rxControl ) { if ( !_rxControl.is() ) return; try { _rxControl->setControlContext( NULL ); Reference< XComponent > xControlComponent( _rxControl, UNO_QUERY ); if ( xControlComponent.is() ) xControlComponent->dispose(); } catch( const Exception& ) { DBG_UNHANDLED_EXCEPTION(); } } } //------------------------------------------------------------------ void OBrowserListBox::Clear() { for ( ListBoxLines::iterator loop = m_aLines.begin(); loop != m_aLines.end(); ++loop ) { // hide the line loop->second.pLine->Hide(); // reset the listener lcl_implDisposeControl_nothrow( loop->second.pLine->getControl() ); } clearContainer( m_aLines ); clearContainer( m_aOrderedLines ); } //------------------------------------------------------------------ sal_Bool OBrowserListBox::RemoveEntry( const ::rtl::OUString& _rName ) { sal_uInt16 nPos = GetPropertyPos( _rName ); if ( nPos == LISTBOX_ENTRY_NOTFOUND ) return sal_False; OrderedListBoxLines::iterator orderedPos = m_aOrderedLines.begin() + nPos; BrowserLinePointer pLine = (*orderedPos)->second.pLine; pLine->Hide(); lcl_implDisposeControl_nothrow( pLine->getControl() ); m_aLines.erase( *orderedPos ); m_aOrderedLines.erase( orderedPos ); m_aOutOfDateLines.erase( (sal_uInt16)m_aOrderedLines.size() ); // this index *may* have been out of date, which is obsoleted now by m_aOrderedLines shrinking // update the positions of possibly affected lines while ( nPos < m_aOrderedLines.size() ) m_aOutOfDateLines.insert( nPos++ ); UpdatePosNSize( ); return sal_True; } //------------------------------------------------------------------ void OBrowserListBox::ChangeEntry( const OLineDescriptor& _rPropertyData, sal_uInt16 nPos ) { OSL_PRECOND( _rPropertyData.Control.is(), "OBrowserListBox::ChangeEntry: invalid control!" ); if ( !_rPropertyData.Control.is() ) return; if ( nPos == EDITOR_LIST_REPLACE_EXISTING ) nPos = GetPropertyPos( _rPropertyData.sName ); if ( nPos < m_aOrderedLines.size() ) { Window* pRefWindow = NULL; if ( nPos > 0 ) pRefWindow = m_aOrderedLines[nPos-1]->second.pLine->GetRefWindow(); // the current line and control ListBoxLine& rLine = m_aOrderedLines[nPos]->second; // the old control and some data about it Reference< XPropertyControl > xControl = rLine.pLine->getControl(); Window* pControlWindow = rLine.pLine->getControlWindow(); Point aControlPos; if ( pControlWindow ) aControlPos = pControlWindow->GetPosPixel(); // clean up the old control lcl_implDisposeControl_nothrow( xControl ); // set the new control at the line rLine.pLine->setControl( _rPropertyData.Control ); xControl = rLine.pLine->getControl(); if ( xControl.is() ) xControl->setControlContext( m_pControlContextImpl.get() ); // the initial property value if ( _rPropertyData.bUnknownValue ) xControl->setValue( Any() ); else impl_setControlAsPropertyValue( rLine, _rPropertyData.aValue ); rLine.pLine->SetTitle(_rPropertyData.DisplayName); rLine.xHandler = _rPropertyData.xPropertyHandler; sal_uInt16 nTextWidth = (sal_uInt16)m_aLinesPlayground.GetTextWidth(_rPropertyData.DisplayName); if (m_nTheNameSize< nTextWidth) m_nTheNameSize = nTextWidth; if ( _rPropertyData.HasPrimaryButton ) { if ( _rPropertyData.PrimaryButtonImageURL.getLength() ) rLine.pLine->ShowBrowseButton( _rPropertyData.PrimaryButtonImageURL, true ); else if ( _rPropertyData.PrimaryButtonImage.is() ) rLine.pLine->ShowBrowseButton( Image( _rPropertyData.PrimaryButtonImage ), true ); else rLine.pLine->ShowBrowseButton( true ); if ( _rPropertyData.HasSecondaryButton ) { if ( _rPropertyData.SecondaryButtonImageURL.getLength() ) rLine.pLine->ShowBrowseButton( _rPropertyData.SecondaryButtonImageURL, false ); else if ( _rPropertyData.SecondaryButtonImage.is() ) rLine.pLine->ShowBrowseButton( Image( _rPropertyData.SecondaryButtonImage ), false ); else rLine.pLine->ShowBrowseButton( false ); } else rLine.pLine->HideBrowseButton( false ); rLine.pLine->SetClickListener( this ); } else { rLine.pLine->HideBrowseButton( true ); rLine.pLine->HideBrowseButton( false ); } DBG_ASSERT( ( _rPropertyData.IndentLevel == 0 ) || ( _rPropertyData.IndentLevel == 1 ), "OBrowserListBox::ChangeEntry: unsupported indent level!" ); rLine.pLine->IndentTitle( _rPropertyData.IndentLevel > 0 ); if ( nPos > 0 ) rLine.pLine->SetTabOrder( pRefWindow, WINDOW_ZORDER_BEHIND ); else rLine.pLine->SetTabOrder( pRefWindow, WINDOW_ZORDER_FIRST ); m_aOutOfDateLines.insert( nPos ); rLine.pLine->SetComponentHelpIds( HelpIdUrl::getHelpId( _rPropertyData.HelpURL ), rtl::OUStringToOString( _rPropertyData.PrimaryButtonId, RTL_TEXTENCODING_UTF8 ), rtl::OUStringToOString( _rPropertyData.SecondaryButtonId, RTL_TEXTENCODING_UTF8 ) ); if ( _rPropertyData.bReadOnly ) { rLine.pLine->SetReadOnly( true ); // user controls (i.e. the ones not provided by the usual // XPropertyControlFactory) have no chance to know that they should be read-only, // since XPropertyHandler::describePropertyLine does not transport this // information. // So, we manually switch this to read-only. if ( xControl.is() && ( xControl->getControlType() == PropertyControlType::Unknown ) ) { Edit* pControlWindowAsEdit = dynamic_cast< Edit* >( rLine.pLine->getControlWindow() ); if ( pControlWindowAsEdit ) pControlWindowAsEdit->SetReadOnly( sal_True ); else pControlWindowAsEdit->Enable( sal_False ); } } } } //------------------------------------------------------------------ long OBrowserListBox::PreNotify( NotifyEvent& _rNEvt ) { switch ( _rNEvt.GetType() ) { case EVENT_KEYINPUT: { const KeyEvent* pKeyEvent = _rNEvt.GetKeyEvent(); if ( ( pKeyEvent->GetKeyCode().GetModifier() != 0 ) || ( ( pKeyEvent->GetKeyCode().GetCode() != KEY_PAGEUP ) && ( pKeyEvent->GetKeyCode().GetCode() != KEY_PAGEDOWN ) ) ) break; long nScrollOffset = 0; if ( m_aVScroll.IsVisible() ) { if ( pKeyEvent->GetKeyCode().GetCode() == KEY_PAGEUP ) nScrollOffset = -m_aVScroll.GetPageSize(); else if ( pKeyEvent->GetKeyCode().GetCode() == KEY_PAGEDOWN ) nScrollOffset = m_aVScroll.GetPageSize(); } if ( nScrollOffset ) { long nNewThumbPos = m_aVScroll.GetThumbPos() + nScrollOffset; nNewThumbPos = ::std::max( nNewThumbPos, m_aVScroll.GetRangeMin() ); nNewThumbPos = ::std::min( nNewThumbPos, m_aVScroll.GetRangeMax() ); m_aVScroll.DoScroll( nNewThumbPos ); nNewThumbPos = m_aVScroll.GetThumbPos(); sal_uInt16 nFocusControlPos = 0; sal_uInt16 nActiveControlPos = impl_getControlPos( m_xActiveControl ); if ( nActiveControlPos < nNewThumbPos ) nFocusControlPos = (sal_uInt16)nNewThumbPos; else if ( nActiveControlPos >= nNewThumbPos + CalcVisibleLines() ) nFocusControlPos = (sal_uInt16)nNewThumbPos + CalcVisibleLines() - 1; if ( nFocusControlPos ) { if ( nFocusControlPos < m_aOrderedLines.size() ) { m_aOrderedLines[ nFocusControlPos ]->second.pLine->GrabFocus(); } else OSL_ENSURE( false, "OBrowserListBox::PreNotify: internal error, invalid focus control position!" ); } } return 1L; // handled this. In particular, we also consume PageUp/Down events if we do not use them for scrolling, // otherwise they would be used to scroll the document view, which does not sound like it is desired by // the user. } } return Control::PreNotify( _rNEvt ); } //------------------------------------------------------------------ long OBrowserListBox::Notify( NotifyEvent& _rNEvt ) { switch ( _rNEvt.GetType() ) { case EVENT_COMMAND: { const CommandEvent* pCommand = _rNEvt.GetCommandEvent(); if ( ( COMMAND_WHEEL == pCommand->GetCommand() ) || ( COMMAND_STARTAUTOSCROLL == pCommand->GetCommand() ) || ( COMMAND_AUTOSCROLL == pCommand->GetCommand() ) ) { // interested in scroll events if we have a scrollbar if ( m_aVScroll.IsVisible() ) { HandleScrollCommand( *pCommand, NULL, &m_aVScroll ); } } } break; } return Control::Notify( _rNEvt ); } //............................................................................ } // namespace pcr //............................................................................
19,035
436
/** * The MIT License * Copyright (c) 2019- Nordic Institute for Interoperability Solutions (NIIS) * Copyright (c) 2018 Estonian Information System Authority (RIA), * Nordic Institute for Interoperability Solutions (NIIS), Population Register Centre (VRK) * Copyright (c) 2015-2017 Estonian Information System Authority (RIA), Population Register Centre (VRK) * * 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 ee.ria.xroad.common.opmonitoring; import ee.ria.xroad.common.PortNumbers; import lombok.extern.slf4j.Slf4j; import static ee.ria.xroad.common.SystemProperties.PREFIX; import static ee.ria.xroad.common.SystemProperties.getConfPath; /** * Contains constants for operational monitor system properties. */ @Slf4j public final class OpMonitoringSystemProperties { private static final String DEFAULT_OP_MONITOR_MAX_RECORDS_IN_PAYLOAD = "10000"; // Operational monitoring buffer --------------------------------------- // /** * Property name of the maximum size of operational monitoring buffer. */ private static final String OP_MONITOR_BUFFER_SIZE = PREFIX + "op-monitor-buffer.size"; /** * Property name of the maximum records in message sent by the operational * monitoring buffer to the operational monitoring daemon. */ private static final String OP_MONITOR_BUFFER_MAX_RECORDS_IN_MESSAGE = PREFIX + "op-monitor-buffer.max-records-in-message"; /** * Property name of the operational monitoring buffer sending interval seconds. */ private static final String OP_MONITOR_BUFFER_SENDING_INTERVAL_SECONDS = PREFIX + "op-monitor-buffer.sending-interval-seconds"; /** * Property name of the operational monitoring buffer HTTP client SO_TIMEOUT seconds. */ private static final String OP_MONITOR_BUFFER_SOCKET_TIMEOUT_SECONDS = PREFIX + "op-monitor-buffer.socket-timeout-seconds"; /** * Property name of the operational monitoring buffer HTTP client connection timeout seconds. */ private static final String OP_MONITOR_BUFFER_CONNECTION_TIMEOUT_SECONDS = PREFIX + "op-monitor-buffer.connection-timeout-seconds"; // Operational monitoring service ---------------------------------------// /** * Property name of the operational monitoring service HTTP client SO_TIMEOUT seconds. */ private static final String OP_MONITOR_SERVICE_SOCKET_TIMEOUT_SECONDS = PREFIX + "op-monitor-service.socket-timeout-seconds"; /** * Property name of the operational monitoring service HTTP client connection timeout seconds. */ private static final String OP_MONITOR_SERVICE_CONNECTION_TIMEOUT_SECONDS = PREFIX + "op-monitor-service.connection-timeout-seconds"; // Operational monitoring daemon --------------------------------------- // /** * Property name of the host address that the operational monitoring daemon listens on. */ private static final String OP_MONITOR_HOST = PREFIX + "op-monitor.host"; /** * Property name of the URI scheme name which the operational monitoring daemon uses. */ private static final String OP_MONITOR_SCHEME = PREFIX + "op-monitor.scheme"; /** * Property name of the port on which the operational monitoring daemon listens for JSON/SOAP requests. */ private static final String OP_MONITOR_PORT = PREFIX + "op-monitor.port"; /** * Property name of the path to the location of the operational monitoring daemon TLS certificate. */ private static final String OP_MONITOR_TLS_CERTIFICATE = PREFIX + "op-monitor.tls-certificate"; /** * Property name of the path to the location of the TLS certificate used by the HTTP client sending requests to the * operational data daemon. Validated by the daemon server and should be the security server internal certificate. */ private static final String OP_MONITOR_CLIENT_TLS_CERTIFICATE = PREFIX + "op-monitor.client-tls-certificate"; /** * Property name of the offset seconds used to calculate timestamp to which the operational data records are * available. Records with earlier timestamp (monitoringDataTs) than 'currentSeconds - offset' are available. */ private static final String OP_MONITOR_RECORDS_AVAILABLE_TIMESTAMP_OFFSET_SECONDS = PREFIX + "op-monitor.records-available-timestamp-offset-seconds"; /** * Property name of the period in seconds for gathering statistics about services. */ private static final String OP_MONITOR_HEALTH_STATISTICS_PERIOD_SECONDS = PREFIX + "op-monitor.health-statistics-period-seconds"; /** * Property name of the period in days for keeping operational data records in the database. */ private static final String OP_MONITOR_KEEP_RECORDS_FOR_DAYS = PREFIX + "op-monitor.keep-records-for-days"; /** * Property name of the interval for running the operational monitoring data cleanup operation represented as a * Cron expression. */ private static final String OP_MONITOR_CLEAN_INTERVAL = PREFIX + "op-monitor.clean-interval"; /** * Property name of the maximum records in the get operational data response payload. */ private static final String OP_MONITOR_MAX_RECORDS_IN_PAYLOAD = PREFIX + "op-monitor.max-records-in-payload"; private OpMonitoringSystemProperties() { } /** * @return the size of the operational monitoring buffer, '20000' by default. In case buffer size < 1, operational * monitoring data is not stored. */ public static int getOpMonitorBufferSize() { return Integer.parseInt(System.getProperty(OP_MONITOR_BUFFER_SIZE, "20000")); } /** * @return max records in message sent to the operational monitoring daemon, '100' by default. */ public static int getOpMonitorBufferMaxRecordsInMessage() { return Integer.parseInt(System.getProperty(OP_MONITOR_BUFFER_MAX_RECORDS_IN_MESSAGE, "100")); } /** * @return the interval in seconds at which operational monitoring buffer additionally tries to send records to the * operational monitoring daemon, '5' by default. */ public static long getOpMonitorBufferSendingIntervalSeconds() { return Long.parseLong(System.getProperty(OP_MONITOR_BUFFER_SENDING_INTERVAL_SECONDS, "5")); } /** * @return the operational monitoring buffer HTTP client SO_TIMEOUT in seconds, '60' by default. */ public static int getOpMonitorBufferSocketTimeoutSeconds() { return Integer.parseInt(System.getProperty(OP_MONITOR_BUFFER_SOCKET_TIMEOUT_SECONDS, "60")); } /** * @return the operational monitoring buffer HTTP client connection timeout in seconds, '30' by default. */ public static int getOpMonitorBufferConnectionTimeoutSeconds() { return Integer.parseInt(System.getProperty(OP_MONITOR_BUFFER_CONNECTION_TIMEOUT_SECONDS, "30")); } /** * @return the operational monitoring service HTTP client SO_TIMEOUT in seconds, '60' by default. */ public static int getOpMonitorServiceSocketTimeoutSeconds() { return Integer.parseInt(System.getProperty(OP_MONITOR_SERVICE_SOCKET_TIMEOUT_SECONDS, "60")); } /** * @return the operational monitoring service HTTP client connection timeout in seconds, '30' by default. */ public static int getOpMonitorServiceConnectionTimeoutSeconds() { return Integer.parseInt(System.getProperty(OP_MONITOR_SERVICE_CONNECTION_TIMEOUT_SECONDS, "30")); } /** * @return the host address on which the operational monitoring daemon listens, 'localhost' by default. */ public static String getOpMonitorHost() { return System.getProperty(OP_MONITOR_HOST, "localhost"); } /** * @return the URI scheme name of the operational monitoring daemon, 'http' by default. */ public static String getOpMonitorDaemonScheme() { return System.getProperty(OP_MONITOR_SCHEME, "http"); } /** * @return the port number on which the operational monitoring daemon listens. */ public static int getOpMonitorPort() { return Integer.parseInt(System.getProperty(OP_MONITOR_PORT, Integer.toString(PortNumbers.OP_MONITOR_DAEMON_PORT))); } /** * @return the path to the location of the operational monitoring daemon TLS certificate, * '/etc/xroad/ssl/opmonitor.crt' by default. */ public static String getOpMonitorCertificatePath() { return System.getProperty(OP_MONITOR_TLS_CERTIFICATE, getConfPath() + "ssl/opmonitor.crt"); } /** * @return path to the TLS certificate used by the HTTP client making sending requests to the operational data * daemon. validated by the daemon server and should be the security server internal certificate. */ public static String getOpMonitorClientCertificatePath() { return System.getProperty(OP_MONITOR_CLIENT_TLS_CERTIFICATE, getConfPath() + "ssl/internal.crt"); } /** * @return the period in seconds that is used for gathering health statistics about services, 600 by default. */ public static int getOpMonitorHealthStatisticsPeriodSeconds() { return Integer.parseInt(System.getProperty(OP_MONITOR_HEALTH_STATISTICS_PERIOD_SECONDS, "600")); } /** * @return the period in days for keeping operational data records in the database, 7 days by default. */ public static int getOpMonitorKeepRecordsForDays() { return Integer.parseInt(System.getProperty(OP_MONITOR_KEEP_RECORDS_FOR_DAYS, "7")); } /** * @return the time interval as a Cron expression for running the operational monitoring data cleanup operation, * '0 0 0/12 1/1 * ? *' by default. */ public static String getOpMonitorCleanInterval() { return System.getProperty(OP_MONITOR_CLEAN_INTERVAL, "0 0 0/12 1/1 * ? *"); } /** * @return the maximum records in the get operational data response payload, 10000 by default. */ public static int getOpMonitorMaxRecordsInPayload() { int payload = Integer.parseInt(System.getProperty(OP_MONITOR_MAX_RECORDS_IN_PAYLOAD, DEFAULT_OP_MONITOR_MAX_RECORDS_IN_PAYLOAD)); if (payload < 1) { log.warn("Property {} has invalid value, using default '{}'", OP_MONITOR_MAX_RECORDS_IN_PAYLOAD, DEFAULT_OP_MONITOR_MAX_RECORDS_IN_PAYLOAD); payload = Integer.parseInt(DEFAULT_OP_MONITOR_MAX_RECORDS_IN_PAYLOAD); } return payload; } /** * @return the offset seconds used to calculate timestamp to which the operational data records are available, * 60 by default. */ public static int getOpMonitorRecordsAvailableTimestampOffsetSeconds() { return Integer.parseInt(System.getProperty(OP_MONITOR_RECORDS_AVAILABLE_TIMESTAMP_OFFSET_SECONDS, "60")); } }
4,072
313
<filename>titus-common/src/main/java/com/netflix/titus/common/framework/simplereconciler/internal/ChangeActionHolder.java /* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.framework.simplereconciler.internal; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Function; import javax.annotation.Nullable; import com.netflix.titus.common.util.rx.ReactorExt; import reactor.core.Disposable; import reactor.core.publisher.Mono; import reactor.core.publisher.MonoSink; public final class ChangeActionHolder<DATA> { private final Function<DATA, Mono<Function<DATA, DATA>>> action; private final long transactionId; private final long createTimestamp; private final MonoSink<DATA> subscriberSink; private AtomicBoolean cancelledRef = new AtomicBoolean(); private final Queue<Disposable> cancelCallbacks = new ConcurrentLinkedQueue<>(); public ChangeActionHolder(Function<DATA, Mono<Function<DATA, DATA>>> action, long transactionId, long createTimestamp, @Nullable MonoSink<DATA> subscriberSink) { this.action = action; this.transactionId = transactionId; this.createTimestamp = createTimestamp; this.subscriberSink = subscriberSink; if (subscriberSink != null) { subscriberSink.onCancel(() -> { cancelledRef.set(true); Disposable next; while ((next = cancelCallbacks.poll()) != null) { ReactorExt.safeDispose(next); } }); } } public Function<DATA, Mono<Function<DATA, DATA>>> getAction() { return action; } public long getTransactionId() { return transactionId; } public long getCreateTimestamp() { return createTimestamp; } public boolean isCancelled() { return cancelledRef.get(); } @Nullable public MonoSink<DATA> getSubscriberSink() { return subscriberSink; } /** * All callbacks should obey the {@link Disposable#dispose()} idempotence contract. */ public void addCancelCallback(Disposable cancelCallback) { cancelCallbacks.add(cancelCallback); if (cancelledRef.get()) { ReactorExt.safeDispose(cancelCallback); } } }
1,145
675
#pragma once #include <QProcess> #include "ui_About.h" #include <engine/core/util/StringUtil.h> namespace Studio { class AboutWindow : public QMainWindow, public Ui_AboutWindow { public: AboutWindow(QWidget* parent=0); ~AboutWindow(); private: }; }
99
8,148
<gh_stars>1000+ #pragma once #include "d3d9_adapter.h" #include "../dxvk/dxvk_instance.h" namespace dxvk { /** * \brief D3D9 interface implementation * * Implements the IDirect3DDevice9Ex interfaces * which provides the way to get adapters and create other objects such as \ref IDirect3DDevice9Ex. * similar to \ref DxgiFactory but for D3D9. */ class D3D9InterfaceEx final : public ComObjectClamp<IDirect3D9Ex> { public: D3D9InterfaceEx(bool bExtended); HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppvObject); HRESULT STDMETHODCALLTYPE RegisterSoftwareDevice(void* pInitializeFunction); UINT STDMETHODCALLTYPE GetAdapterCount(); HRESULT STDMETHODCALLTYPE GetAdapterIdentifier( UINT Adapter, DWORD Flags, D3DADAPTER_IDENTIFIER9* pIdentifier); UINT STDMETHODCALLTYPE GetAdapterModeCount(UINT Adapter, D3DFORMAT Format); HRESULT STDMETHODCALLTYPE GetAdapterDisplayMode(UINT Adapter, D3DDISPLAYMODE* pMode); HRESULT STDMETHODCALLTYPE CheckDeviceType( UINT Adapter, D3DDEVTYPE DevType, D3DFORMAT AdapterFormat, D3DFORMAT BackBufferFormat, BOOL bWindowed); HRESULT STDMETHODCALLTYPE CheckDeviceFormat( UINT Adapter, D3DDEVTYPE DeviceType, D3DFORMAT AdapterFormat, DWORD Usage, D3DRESOURCETYPE RType, D3DFORMAT CheckFormat); HRESULT STDMETHODCALLTYPE CheckDeviceMultiSampleType( UINT Adapter, D3DDEVTYPE DeviceType, D3DFORMAT SurfaceFormat, BOOL Windowed, D3DMULTISAMPLE_TYPE MultiSampleType, DWORD* pQualityLevels); HRESULT STDMETHODCALLTYPE CheckDepthStencilMatch( UINT Adapter, D3DDEVTYPE DeviceType, D3DFORMAT AdapterFormat, D3DFORMAT RenderTargetFormat, D3DFORMAT DepthStencilFormat); HRESULT STDMETHODCALLTYPE CheckDeviceFormatConversion( UINT Adapter, D3DDEVTYPE DeviceType, D3DFORMAT SourceFormat, D3DFORMAT TargetFormat); HRESULT STDMETHODCALLTYPE GetDeviceCaps( UINT Adapter, D3DDEVTYPE DeviceType, D3DCAPS9* pCaps); HMONITOR STDMETHODCALLTYPE GetAdapterMonitor(UINT Adapter); HRESULT STDMETHODCALLTYPE CreateDevice( UINT Adapter, D3DDEVTYPE DeviceType, HWND hFocusWindow, DWORD BehaviorFlags, D3DPRESENT_PARAMETERS* pPresentationParameters, IDirect3DDevice9** ppReturnedDeviceInterface); HRESULT STDMETHODCALLTYPE EnumAdapterModes( UINT Adapter, D3DFORMAT Format, UINT Mode, D3DDISPLAYMODE* pMode); // Ex Methods UINT STDMETHODCALLTYPE GetAdapterModeCountEx(UINT Adapter, CONST D3DDISPLAYMODEFILTER* pFilter); HRESULT STDMETHODCALLTYPE EnumAdapterModesEx( UINT Adapter, const D3DDISPLAYMODEFILTER* pFilter, UINT Mode, D3DDISPLAYMODEEX* pMode); HRESULT STDMETHODCALLTYPE GetAdapterDisplayModeEx( UINT Adapter, D3DDISPLAYMODEEX* pMode, D3DDISPLAYROTATION* pRotation); HRESULT STDMETHODCALLTYPE CreateDeviceEx( UINT Adapter, D3DDEVTYPE DeviceType, HWND hFocusWindow, DWORD BehaviorFlags, D3DPRESENT_PARAMETERS* pPresentationParameters, D3DDISPLAYMODEEX* pFullscreenDisplayMode, IDirect3DDevice9Ex** ppReturnedDeviceInterface); HRESULT STDMETHODCALLTYPE GetAdapterLUID(UINT Adapter, LUID* pLUID); const D3D9Options& GetOptions() { return m_d3d9Options; } D3D9Adapter* GetAdapter(UINT Ordinal) { return Ordinal < m_adapters.size() ? &m_adapters[Ordinal] : nullptr; } bool IsExtended() { return m_extended; } Rc<DxvkInstance> GetInstance() { return m_instance; } private: void CacheModes(D3D9Format Format); static const char* GetDriverDllName(DxvkGpuVendor vendor); Rc<DxvkInstance> m_instance; bool m_extended; D3D9Options m_d3d9Options; std::vector<D3D9Adapter> m_adapters; }; }
2,438
398
<gh_stars>100-1000 package io.joyrpc.util; /*- * #%L * joyrpc * %% * Copyright (C) 2019 joyrpc.io * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ /** * 接口描述语言产生的类型描述 */ public class IDLType { /** * 请求类型 */ protected final Class<?> clazz; /** * 包装请求 */ protected final boolean wrapper; /** * 转换函数 */ protected final IDLConverter conversion; /** * 构造函数 * * @param clazz 类型 * @param wrapper 包装类型标识 */ public IDLType(Class<?> clazz, boolean wrapper) { this.clazz = clazz; this.wrapper = wrapper; this.conversion = wrapper ? ClassUtils.getConversion(clazz) : null; } public Class<?> getClazz() { return clazz; } public boolean isWrapper() { return wrapper; } public IDLConverter getConversion() { return conversion; } }
604
396
package me.everything.providers.android.media; import android.net.Uri; import android.provider.BaseColumns; import android.provider.MediaStore; import me.everything.providers.core.Entity; import me.everything.providers.core.FieldMapping; import me.everything.providers.core.IgnoreMapping; /** * Created by sromku */ public class Audio extends Entity { @IgnoreMapping public static Uri uriExternal = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; @IgnoreMapping public static Uri uriInternal = MediaStore.Audio.Media.INTERNAL_CONTENT_URI; @FieldMapping(columnName = BaseColumns._ID, physicalType = FieldMapping.PhysicalType.Long) public long id; @FieldMapping(columnName = MediaStore.MediaColumns.DATA, physicalType = FieldMapping.PhysicalType.Blob) public byte[] data; @FieldMapping(columnName = MediaStore.MediaColumns.SIZE, physicalType = FieldMapping.PhysicalType.Int) public int size; @FieldMapping(columnName = MediaStore.MediaColumns.DISPLAY_NAME, physicalType = FieldMapping.PhysicalType.String) public String displayName; @FieldMapping(columnName = MediaStore.MediaColumns.TITLE, physicalType = FieldMapping.PhysicalType.String) public String title; @FieldMapping(columnName = MediaStore.MediaColumns.DATE_ADDED, physicalType = FieldMapping.PhysicalType.Int, logicalType = FieldMapping.LogicalType.Long) public long dateAdded; @FieldMapping(columnName = MediaStore.MediaColumns.DATE_MODIFIED, physicalType = FieldMapping.PhysicalType.Int, logicalType = FieldMapping.LogicalType.Long) public long dateModified; @FieldMapping(columnName = MediaStore.MediaColumns.MIME_TYPE, physicalType = FieldMapping.PhysicalType.String) public String mimeType; @FieldMapping(columnName = MediaStore.Audio.AudioColumns.TITLE_KEY, physicalType = FieldMapping.PhysicalType.String) public String titleKey; @FieldMapping(columnName = MediaStore.Audio.AudioColumns.DURATION, physicalType = FieldMapping.PhysicalType.Int, logicalType = FieldMapping.LogicalType.Long) public long duration; @FieldMapping(columnName = MediaStore.Audio.AudioColumns.BOOKMARK, physicalType = FieldMapping.PhysicalType.Int, logicalType = FieldMapping.LogicalType.Long) public long bookmark; @FieldMapping(columnName = MediaStore.Audio.AudioColumns.ARTIST_ID, physicalType = FieldMapping.PhysicalType.Int, logicalType = FieldMapping.LogicalType.Long) public long artistId; @FieldMapping(columnName = MediaStore.Audio.AudioColumns.ARTIST, physicalType = FieldMapping.PhysicalType.String) public String artist; @FieldMapping(columnName = MediaStore.Audio.AudioColumns.ARTIST_KEY, physicalType = FieldMapping.PhysicalType.String) public String artistKey; @FieldMapping(columnName = MediaStore.Audio.AudioColumns.COMPOSER, physicalType = FieldMapping.PhysicalType.String) public String composer; @FieldMapping(columnName = MediaStore.Audio.AudioColumns.ALBUM_ID, physicalType = FieldMapping.PhysicalType.Int, logicalType = FieldMapping.LogicalType.Long) public long albumId; @FieldMapping(columnName = MediaStore.Audio.AudioColumns.ALBUM, physicalType = FieldMapping.PhysicalType.String) public String album; @FieldMapping(columnName = MediaStore.Audio.AudioColumns.ALBUM_KEY, physicalType = FieldMapping.PhysicalType.String) public String albumKey; @FieldMapping(columnName = MediaStore.Audio.AudioColumns.TRACK, physicalType = FieldMapping.PhysicalType.Int) public int track; @FieldMapping(columnName = MediaStore.Audio.AudioColumns.YEAR, physicalType = FieldMapping.PhysicalType.Int) public int year; @FieldMapping(columnName = MediaStore.Audio.AudioColumns.IS_MUSIC, physicalType = FieldMapping.PhysicalType.Int, logicalType = FieldMapping.LogicalType.Boolean) public boolean isMusic; @FieldMapping(columnName = MediaStore.Audio.AudioColumns.IS_PODCAST, physicalType = FieldMapping.PhysicalType.Int, logicalType = FieldMapping.LogicalType.Boolean) public boolean isPodcast; @FieldMapping(columnName = MediaStore.Audio.AudioColumns.IS_RINGTONE, physicalType = FieldMapping.PhysicalType.Int, logicalType = FieldMapping.LogicalType.Boolean) public boolean isRingtone; @FieldMapping(columnName = MediaStore.Audio.AudioColumns.IS_ALARM, physicalType = FieldMapping.PhysicalType.Int, logicalType = FieldMapping.LogicalType.Boolean) public boolean isAlarm; @FieldMapping(columnName = MediaStore.Audio.AudioColumns.IS_NOTIFICATION, physicalType = FieldMapping.PhysicalType.Int, logicalType = FieldMapping.LogicalType.Boolean) public boolean isNotification; }
1,471
390
/* Copyright 2013-present Barefoot Networks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * <NAME> (<EMAIL>) * */ #include <bm/bm_sim/_assert.h> #include <bm/bm_sim/learning.h> #include <bm/bm_sim/switch.h> #include <PI/p4info/digests.h> #include <PI/target/pi_learn_imp.h> #include "common.h" namespace { pi_status_t get_bm_list_id(const pi_p4info_t *p4info, bm::LearnEngineIface *learn_engine, pi_p4_id_t learn_id, bm::LearnEngineIface::list_id_t *list_id) { const char *name = pi_p4info_digest_name_from_id(p4info, learn_id); if (name == nullptr) return PI_STATUS_TARGET_ERROR; auto rc = learn_engine->list_get_id_from_name(name, list_id); if (rc != bm::LearnEngineIface::LearnErrorCode::SUCCESS) return pibmv2::convert_error_code(rc); return PI_STATUS_SUCCESS; } } // namespace extern "C" { pi_status_t _pi_learn_config_set(pi_session_handle_t session_handle, pi_dev_id_t dev_id, pi_p4_id_t learn_id, const pi_learn_config_t *config) { _BM_UNUSED(session_handle); const auto *p4info = pibmv2::get_device_info(dev_id); assert(p4info != nullptr); auto *learn_engine = pibmv2::switch_->get_learn_engine(0); assert(learn_engine != nullptr); bm::LearnEngineIface::list_id_t list_id; auto status = get_bm_list_id(p4info, learn_engine, learn_id, &list_id); if (status != PI_STATUS_SUCCESS) return status; // TODO(antonin): here we do not anything when we should be disabling // learning, we rely on the PI client to ignore notifications if (config == nullptr) return PI_STATUS_SUCCESS; auto max_samples = static_cast<size_t>( (config->max_size == 0) ? 1024 : config->max_size); auto timeout_ms = static_cast<unsigned int>( config->max_timeout_ns / 1000000.); { auto rc = learn_engine->list_set_max_samples(list_id, max_samples); if (rc != bm::LearnEngineIface::LearnErrorCode::SUCCESS) return pibmv2::convert_error_code(rc); } { auto rc = learn_engine->list_set_timeout(list_id, timeout_ms); if (rc != bm::LearnEngineIface::LearnErrorCode::SUCCESS) return pibmv2::convert_error_code(rc); } return PI_STATUS_SUCCESS; } pi_status_t _pi_learn_msg_ack(pi_session_handle_t session_handle, pi_dev_id_t dev_id, pi_p4_id_t learn_id, pi_learn_msg_id_t msg_id) { _BM_UNUSED(session_handle); const auto *p4info = pibmv2::get_device_info(dev_id); assert(p4info != nullptr); auto *learn_engine = pibmv2::switch_->get_learn_engine(0); assert(learn_engine != nullptr); bm::LearnEngineIface::list_id_t list_id; auto status = get_bm_list_id(p4info, learn_engine, learn_id, &list_id); if (status != PI_STATUS_SUCCESS) return status; auto rc = learn_engine->ack_buffer(list_id, msg_id); if (rc != bm::LearnEngineIface::LearnErrorCode::SUCCESS) return pibmv2::convert_error_code(rc); return PI_STATUS_SUCCESS; } pi_status_t _pi_learn_msg_done(pi_learn_msg_t *msg) { delete[] msg->entries; delete msg; return PI_STATUS_SUCCESS; } }
1,573
372
/* * $Header$ * * Copyright 2008 Massachusetts Institute of Technology. * All Rights Reserved. * * Export of this software from the United States of America may * require a specific license from the United States Government. * It is the responsibility of any person or organization contemplating * export to obtain such a license before exporting. * * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and * distribute this software and its documentation for any purpose and * without fee is hereby granted, provided that the above copyright * notice appear in all copies and that both that copyright notice and * this permission notice appear in supporting documentation, and that * the name of M.I.T. not be used in advertising or publicity pertaining * to distribution of the software without specific, written prior * permission. Furthermore if you modify this software you must label * your software as modified software and not distribute it in such a * fashion that it might be confused with the original M.I.T. software. * M.I.T. makes no representations about the suitability of * this software for any purpose. It is provided "as is" without express * or implied warranty. */ #ifdef KIM_BUILTIN_UI #include "kim_private.h" // --------------------------------------------------------------------------- static kim_error kim_ui_cli_read_string (kim_string *out_string, kim_boolean in_hide_reply, const char *in_format, ...) { kim_error err = KIM_NO_ERROR; krb5_context k5context = NULL; krb5_prompt prompts[1]; char prompt_string [BUFSIZ]; krb5_data reply_data; char reply_string [BUFSIZ]; if (!err && !out_string) { err = check_error (KIM_NULL_PARAMETER_ERR); } if (!err && !in_format ) { err = check_error (KIM_NULL_PARAMETER_ERR); } if (!err) { err = krb5_init_context (&k5context); } if (!err) { unsigned int count; va_list args; va_start (args, in_format); count = vsnprintf (prompt_string, sizeof (prompt_string), in_format, args); va_end (args); if (count > sizeof (prompt_string)) { kim_debug_printf ("%s(): WARNING! Prompt should be %d characters\n", __FUNCTION__, count); prompt_string [sizeof (prompt_string) - 1] = '\0'; } } if (!err) { /* Build the prompt structures */ prompts[0].prompt = prompt_string; prompts[0].hidden = in_hide_reply; prompts[0].reply = &reply_data; prompts[0].reply->data = reply_string; prompts[0].reply->length = sizeof (reply_string); err = krb5_prompter_posix (k5context, NULL, NULL, NULL, 1, prompts); if (err == KRB5_LIBOS_PWDINTR || err == KRB5_LIBOS_CANTREADPWD) { err = check_error (KIM_USER_CANCELED_ERR); } } if (!err) { err = kim_string_create_from_buffer (out_string, prompts[0].reply->data, prompts[0].reply->length); } if (k5context) { krb5_free_context (k5context); } return check_error (err); } /* ------------------------------------------------------------------------ */ kim_error kim_ui_cli_init (kim_ui_context *io_context) { if (io_context) { io_context->tcontext = NULL; } return KIM_NO_ERROR; } /* ------------------------------------------------------------------------ */ kim_error kim_ui_cli_enter_identity (kim_ui_context *in_context, kim_options io_options, kim_identity *out_identity, kim_boolean *out_change_password) { kim_error err = KIM_NO_ERROR; kim_string enter_identity_string = NULL; kim_string identity_string = NULL; if (!err && !io_options ) { err = check_error (KIM_NULL_PARAMETER_ERR); } if (!err && !out_identity ) { err = check_error (KIM_NULL_PARAMETER_ERR); } if (!err && !out_change_password) { err = check_error (KIM_NULL_PARAMETER_ERR); } if (!err) { err = kim_os_string_create_localized (&enter_identity_string, "Please enter your Kerberos identity"); } if (!err) { err = kim_ui_cli_read_string (&identity_string, 0, enter_identity_string); } if (!err) { err = kim_identity_create_from_string (out_identity, identity_string); } if (!err) { *out_change_password = 0; } kim_string_free (&identity_string); kim_string_free (&enter_identity_string); return check_error (err); } /* ------------------------------------------------------------------------ */ kim_error kim_ui_cli_select_identity (kim_ui_context *in_context, kim_selection_hints io_hints, kim_identity *out_identity, kim_boolean *out_change_password) { kim_error err = KIM_NO_ERROR; kim_options options = NULL; if (!err && !io_hints ) { err = check_error (KIM_NULL_PARAMETER_ERR); } if (!err && !out_identity ) { err = check_error (KIM_NULL_PARAMETER_ERR); } if (!err && !out_change_password) { err = check_error (KIM_NULL_PARAMETER_ERR); } if (!err) { err = kim_selection_hints_get_options (io_hints, &options); } if (!err) { err = kim_ui_cli_enter_identity (in_context, options, out_identity, out_change_password); } if (!err) { err = kim_selection_hints_set_options (io_hints, options); } kim_options_free (&options); return check_error (err); } /* ------------------------------------------------------------------------ */ kim_error kim_ui_cli_auth_prompt (kim_ui_context *in_context, kim_identity in_identity, kim_prompt_type in_type, kim_boolean in_allow_save_reply, kim_boolean in_hide_reply, kim_string in_title, kim_string in_message, kim_string in_description, char **out_reply, kim_boolean *out_save_reply) { kim_error err = KIM_NO_ERROR; if (!err && !in_identity) { err = check_error (KIM_NULL_PARAMETER_ERR); } if (!err && !out_reply ) { err = check_error (KIM_NULL_PARAMETER_ERR); } /* in_title, in_message or in_description may be NULL */ if (!err) { if (in_type == kim_prompt_type_password) { kim_string enter_password_format = NULL; kim_string identity_string = NULL; err = kim_os_string_create_localized (&enter_password_format, "Please enter the password for %s"); if (!err) { err = kim_identity_get_display_string (in_identity, &identity_string); } if (!err) { err = kim_ui_cli_read_string ((kim_string *) out_reply, 1, enter_password_format, identity_string); } kim_string_free (&identity_string); kim_string_free (&enter_password_format); } else { krb5_context k5context = NULL; krb5_prompt prompts[1]; krb5_data reply_data; char reply_string [BUFSIZ]; prompts[0].prompt = (char *) in_description; prompts[0].hidden = in_hide_reply; prompts[0].reply = &reply_data; prompts[0].reply->data = reply_string; prompts[0].reply->length = sizeof (reply_string); err = krb5_init_context (&k5context); if (!err) { err = krb5_prompter_posix (k5context, in_context, in_title, in_message, 1, prompts); if (err == KRB5_LIBOS_PWDINTR || err == KRB5_LIBOS_CANTREADPWD) { err = check_error (KIM_USER_CANCELED_ERR); } } if (!err) { err = kim_string_create_from_buffer ((kim_string *) out_reply, prompts[0].reply->data, prompts[0].reply->length); if (!err) { /* always allow password saving */ *out_save_reply = (in_allow_save_reply && in_type == kim_prompt_type_password); } } if (k5context) { krb5_free_context (k5context); } } } return check_error (err); } /* ------------------------------------------------------------------------ */ static kim_error kim_ui_cli_ask_change_password (kim_string in_identity_string) { kim_error err = KIM_NO_ERROR; kim_string ask_change_password = NULL; kim_string yes = NULL; kim_string no = NULL; kim_string unknown_response = NULL; kim_boolean done = 0; kim_comparison no_comparison, yes_comparison; if (!err) { err = kim_os_string_create_localized (&ask_change_password, "Your password has expired, would you like to change it? (yes/no)"); } if (!err) { err = kim_os_string_create_localized (&yes, "yes"); } if (!err) { err = kim_os_string_create_localized (&no, "no"); } if (!err) { err = kim_os_string_create_localized (&unknown_response, "%s is not a response I understand. Please try again."); } while (!err && !done) { kim_string answer = NULL; err = kim_ui_cli_read_string (&answer, 0, ask_change_password); if (!err) { err = kim_os_string_compare (answer, no, 1 /* case insensitive */, &no_comparison); } if (!err && kim_comparison_is_equal_to (no_comparison)) { err = check_error (KIM_USER_CANCELED_ERR); } if (!err) { err = kim_os_string_compare (answer, yes, 1 /* case insensitive */, &yes_comparison); } if (!err) { if (kim_comparison_is_equal_to (yes_comparison)) { done = 1; } else { fprintf (stdout, unknown_response, answer); fprintf (stdout, "\n"); } } kim_string_free (&answer); } kim_string_free (&ask_change_password); kim_string_free (&yes); kim_string_free (&no); kim_string_free (&unknown_response); return check_error (err); } /* ------------------------------------------------------------------------ */ kim_error kim_ui_cli_change_password (kim_ui_context *in_context, kim_identity in_identity, kim_boolean in_old_password_expired, char **out_old_password, char **out_new_password, char **out_verify_password) { kim_error err = KIM_NO_ERROR; kim_string enter_old_password_format = NULL; kim_string enter_new_password_format = NULL; kim_string enter_verify_password_format = NULL; kim_string identity_string = NULL; kim_string old_password = NULL; kim_string new_password = NULL; kim_string verify_password = NULL; kim_boolean done = 0; if (!err && !in_identity ) { err = check_error (KIM_NULL_PARAMETER_ERR); } if (!err && !out_old_password ) { err = check_error (KIM_NULL_PARAMETER_ERR); } if (!err && !out_new_password ) { err = check_error (KIM_NULL_PARAMETER_ERR); } if (!err && !out_verify_password) { err = check_error (KIM_NULL_PARAMETER_ERR); } if (!err) { err = kim_identity_get_display_string (in_identity, &identity_string); } if (!err && in_old_password_expired) { err = kim_ui_cli_ask_change_password (identity_string); } if (!err) { err = kim_os_string_create_localized (&enter_old_password_format, "Please enter the old password for %s"); } if (!err) { err = kim_os_string_create_localized (&enter_new_password_format, "Please enter the new password for %s"); } if (!err) { err = kim_os_string_create_localized (&enter_verify_password_format, "Verifying, please re-enter the new password for %s again"); } while (!err && !done) { kim_boolean was_prompted = 0; /* ignore because we always prompt */ kim_string_free (&old_password); err = kim_ui_cli_read_string (&old_password, 1, enter_old_password_format, identity_string); if (!err && strlen (old_password) < 1) { /* Empty password: Synthesize bad password err */ err = KRB5KRB_AP_ERR_BAD_INTEGRITY; } if (!err) { err = kim_credential_create_for_change_password ((kim_credential *) &in_context->tcontext, in_identity, old_password, in_context, &was_prompted); } if (err && err != KIM_USER_CANCELED_ERR) { /* new creds failed, report error to user */ err = kim_ui_handle_kim_error (in_context, in_identity, kim_ui_error_type_change_password, err); } else { done = 1; } } if (!err) { err = kim_ui_cli_read_string (&new_password, 1, enter_new_password_format, identity_string); } if (!err) { err = kim_ui_cli_read_string (&verify_password, 1, enter_verify_password_format, identity_string); } if (!err) { *out_old_password = (char *) old_password; old_password = NULL; *out_new_password = (char *) new_password; new_password = NULL; *out_verify_password = (char *) verify_password; verify_password = NULL; } kim_string_free (&old_password); kim_string_free (&new_password); kim_string_free (&verify_password); kim_string_free (&identity_string); kim_string_free (&enter_old_password_format); kim_string_free (&enter_new_password_format); kim_string_free (&enter_verify_password_format); return check_error (err); } /* ------------------------------------------------------------------------ */ kim_error kim_ui_cli_handle_error (kim_ui_context *in_context, kim_identity in_identity, kim_error in_error, kim_string in_error_message, kim_string in_error_description) { kim_error err = KIM_NO_ERROR; if (!err && !in_error_message ) { err = check_error (KIM_NULL_PARAMETER_ERR); } if (!err && !in_error_description) { err = check_error (KIM_NULL_PARAMETER_ERR); } if (!err) { fprintf (stdout, "%s\n%s\n\n", in_error_message, in_error_description); } return check_error (err); } /* ------------------------------------------------------------------------ */ void kim_ui_cli_free_string (kim_ui_context *in_context, char **io_string) { kim_string_free ((kim_string *) io_string); } /* ------------------------------------------------------------------------ */ kim_error kim_ui_cli_fini (kim_ui_context *io_context) { if (io_context) { kim_credential_free ((kim_credential *) &io_context->tcontext); } return KIM_NO_ERROR; } #endif /* KIM_BUILTIN_UI */
8,792
711
package com.java110.store.bmo.contractAttr; import com.java110.dto.contractAttr.ContractAttrDto; import org.springframework.http.ResponseEntity; public interface IGetContractAttrBMO { /** * 查询合同属性 * add by wuxw * * @param contractAttrDto * @return */ ResponseEntity<String> get(ContractAttrDto contractAttrDto); }
156
307
from typing import List, Union from tdw.controller import Controller from tdw.output_data import OutputData, Keyboard class KeyboardController(Controller): """ Listen for keyboard input to send commands. Keyboard input is registered _from the build, not the controller._ For this controller to work, you must: - Run the build on the same machine as the keyboard. - Have the build window as the focused window (i.e. not minimized). Usage: ```python from tdw.keyboard_controller import KeyboardController from tdw.tdw_utils import TDWUtils def stop(): done = True c.communicate({"$type": "terminate"}) done = False c = KeyboardController() c.start() # Quit. c.listen(key="esc", function=stop) # Equivalent to c.start() c.listen(key="r", commands={"$type": "load_scene", "scene_name": "ProcGenScene"}) while not done: # Receive data. Load the scene when r is pressed. Quit when Esc is pressed. c.communicate([]) ``` """ def __init__(self, port: int = 1071, check_version: bool = True, launch_build: bool = True): """ Create the network socket and bind the socket to the port. :param port: The port number. :param check_version: If true, the controller will check the version of the build and print the result. :param launch_build: If True, automatically launch the build. If one doesn't exist, download and extract the correct version. Set this to False to use your own build, or (if you are a backend developer) to use Unity Editor. """ # Commands that should be added due to key presses on this frame. self.on_key_commands: List[dict] = [] # Dictionaries of actions. Key = a keyboard key as a string. self._press = dict() self._hold = dict() self._release = dict() super().__init__(port=port, check_version=check_version, launch_build=launch_build) self.communicate({"$type": "send_keyboard", "frequency": "always"}) def _do_event(self, k: str, events: dict) -> None: """ Invoke an event if the key is in the events dictionary. :param k: The keyboard key as a string. :param events: The events dictionary. """ if k in events: # Append commands to the next `communicate()` call. if isinstance(events[k], list): self.on_key_commands.extend(events[k]) # Invoke a function. else: events[k]() def communicate(self, commands: Union[dict, List[dict]]) -> List[bytes]: if isinstance(commands, dict): commands = [commands] # Add commands from key presses. commands.extend(self.on_key_commands[:]) # Clear the on-key commands. self.on_key_commands.clear() # Send the commands. resp = super().communicate(commands) # Get keyboard input. for i in range(len(resp) - 1): r_id = OutputData.get_data_type_id(resp[i]) if r_id == "keyb": keys = Keyboard(resp[i]) # Listen for events where the key was first pressed on the previous frame. for j in range(keys.get_num_pressed()): self._do_event(k=keys.get_pressed(j), events=self._press) # Listen for keys currently held down. for j in range(keys.get_num_held()): self._do_event(k=keys.get_held(j), events=self._hold) # Listen for keys that were released. for j in range(keys.get_num_released()): self._do_event(k=keys.get_released(j), events=self._release) return resp def listen(self, key: str, commands: Union[dict, List[dict]] = None, function=None, events: List[str] = None) -> None: """ Listen for when a key is pressed and send commands. :param key: The keyboard key. :param commands: Commands to be sent when the key is pressed. :param function: Function to invoke when the key is pressed. :param events: Listen to these keyboard events for this `key`. Options: `"press"`, `"hold"`, `"release"`. If None, this defaults to `["press"]`. """ response = None if commands is not None: if isinstance(commands, dict): commands = [commands] response = commands elif function is not None: response = function if response is None: return if events is None: events = ["press"] # Subscribe to events. if "press" in events: self._press[key] = response if "hold" in events: self._hold[key] = response if "release" in events: self._release[key] = response def _set_frame_commands(self, commands: Union[dict, List[dict]]) -> None: """ Set the next frame's commands. :param commands: The commands to send on this frame. """ if isinstance(commands, dict): commands = [commands] self.on_key_commands = commands
2,338
346
<filename>Chapter 05/dir-brute.py import urllib import urllib2 import threading import Queue threads = 50 # Be aware that a large number of threads can cause a denial of service!!! target_url = "http://www.example.com" wordlist_file = "directory-list.txt" user_agent = "Mozilla/5.0 (X11; Linux x86_64; rv:19.0) Gecko/20100101 Firefox/19.0" def wordlist(wordlist_file): # read in the word list file wordlist_file = open(wordlist_file,"rb") raw_words = wordlist_file.readlines() wordlist_file.close() words = Queue.Queue() # iterating over each word in the word file for word in raw_words: word = word.rstrip() words.put(word) return words def dir_bruteforce(extensions=None): while not word_queue.empty(): attempt = word_queue.get() attempt_list = [] # check if there is a file extension if not # it's a directory path we're bruting if "." not in attempt: attempt_list.append("/%s/" % attempt) else: attempt_list.append("/%s" % attempt) # if we want to bruteforce extensions if extensions: for extension in extensions: attempt_list.append("/%s%s" % (attempt,extension)) # iterate over our list of attempts for brute in attempt_list: url = "%s%s" % (target_url,urllib.quote(brute)) try: headers = {} headers["User-Agent"] = user_agent r = urllib2.Request(url,headers=headers) response = urllib2.urlopen(r) if len(response.read()): print "[%d] => %s" % (response.code,url) except urllib2.HTTPError,e: if e.code != 404: print "!!! %d => %s" % (e.code,url) pass word_queue = wordlist(wordlist_file) extensions = [".php",".bak",".orig",".inc"] for i in range(threads): t = threading.Thread(target=dir_bruteforce,args=(extensions,)) t.start()
1,177
460
<reponame>dyzmapl/BumpTop #include "../../../tools/assistant/lib/qhelpcollectionhandler_p.h"
38
852
#ifndef DataFormats_Provenance_History_h #define DataFormats_Provenance_History_h //---------------------------------------------------------------------- // // Class History represents the processing history of a single Event. // It includes ordered sequences of elements, each of which contains // information about a specific 'process' through which the Event has // passed, with earlier processes at the beginning of the sequence. // This class is needed for backward compatibility only. // It is relevant if and only if fileFormatVersion.eventHistoryTree() is true. // // //---------------------------------------------------------------------- #include <vector> #include "DataFormats/Provenance/interface/EventSelectionID.h" #include "DataFormats/Provenance/interface/BranchListIndex.h" #include "DataFormats/Provenance/interface/ProcessHistoryID.h" namespace edm { class History { public: typedef std::size_t size_type; // Compiler-generated default c'tor, copy c'tor, assignment and // d'tor are all correct. // Return the number of 'processing steps' recorded in this // History. size_type size() const; // Add the given entry to this History. When a new data member is // added to the History class, this function should be modified to // take an instance of the type of the new data member. void addEventSelectionEntry(EventSelectionID const& eventSelection); void addBranchListIndexEntry(BranchListIndex const& branchListIndex); EventSelectionID const& getEventSelectionID(size_type i) const; EventSelectionIDVector const& eventSelectionIDs() const { return eventSelections_; } EventSelectionIDVector& eventSelectionIDs() { return eventSelections_; } ProcessHistoryID const& processHistoryID() const { return processHistoryID_; } void setProcessHistoryID(ProcessHistoryID const& phid) { processHistoryID_ = phid; } BranchListIndexes const& branchListIndexes() const { return branchListIndexes_; } BranchListIndexes& branchListIndexes() { return branchListIndexes_; } private: // Note: We could, instead, define a struct that contains the // appropriate information for each history entry, and then contain // only one data member: a vector of this struct. This might make // iteration more convenient. But it would seem to complicate // persistence. The current plan is to have parallel vectors, one // for each type of item stored as data. EventSelectionIDVector eventSelections_; BranchListIndexes branchListIndexes_; ProcessHistoryID processHistoryID_; }; } // namespace edm #endif
719
3,267
<reponame>Becavalier/playground-weex /* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.alibaba.weex.appframework; public final class R { public static final class attr { /** <p>Must be one of the following constant values.</p> <table> <colgroup align="left" /> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Constant</th><th>Value</th><th>Description</th></tr> <tr><td><code>none</code></td><td>-1</td><td></td></tr> <tr><td><code>fitXY</code></td><td>0</td><td></td></tr> <tr><td><code>fitStart</code></td><td>1</td><td></td></tr> <tr><td><code>fitCenter</code></td><td>2</td><td></td></tr> <tr><td><code>fitEnd</code></td><td>3</td><td></td></tr> <tr><td><code>center</code></td><td>4</td><td></td></tr> <tr><td><code>centerInside</code></td><td>5</td><td></td></tr> <tr><td><code>centerCrop</code></td><td>6</td><td></td></tr> <tr><td><code>focusCrop</code></td><td>7</td><td></td></tr> </table> */ public static int actualImageScaleType=0x7f01000b; /** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static int backgroundImage=0x7f01000c; /** <p>Must be an integer value, such as "<code>100</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static int fadeDuration=0x7f010000; /** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static int failureImage=0x7f010006; /** <p>Must be one of the following constant values.</p> <table> <colgroup align="left" /> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Constant</th><th>Value</th><th>Description</th></tr> <tr><td><code>none</code></td><td>-1</td><td></td></tr> <tr><td><code>fitXY</code></td><td>0</td><td></td></tr> <tr><td><code>fitStart</code></td><td>1</td><td></td></tr> <tr><td><code>fitCenter</code></td><td>2</td><td></td></tr> <tr><td><code>fitEnd</code></td><td>3</td><td></td></tr> <tr><td><code>center</code></td><td>4</td><td></td></tr> <tr><td><code>centerInside</code></td><td>5</td><td></td></tr> <tr><td><code>centerCrop</code></td><td>6</td><td></td></tr> <tr><td><code>focusCrop</code></td><td>7</td><td></td></tr> </table> */ public static int failureImageScaleType=0x7f010007; /** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static int overlayImage=0x7f01000d; /** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static int placeholderImage=0x7f010002; /** <p>Must be one of the following constant values.</p> <table> <colgroup align="left" /> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Constant</th><th>Value</th><th>Description</th></tr> <tr><td><code>none</code></td><td>-1</td><td></td></tr> <tr><td><code>fitXY</code></td><td>0</td><td></td></tr> <tr><td><code>fitStart</code></td><td>1</td><td></td></tr> <tr><td><code>fitCenter</code></td><td>2</td><td></td></tr> <tr><td><code>fitEnd</code></td><td>3</td><td></td></tr> <tr><td><code>center</code></td><td>4</td><td></td></tr> <tr><td><code>centerInside</code></td><td>5</td><td></td></tr> <tr><td><code>centerCrop</code></td><td>6</td><td></td></tr> <tr><td><code>focusCrop</code></td><td>7</td><td></td></tr> </table> */ public static int placeholderImageScaleType=0x7f010003; /** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static int pressedStateOverlayImage=0x7f01000e; /** <p>Must be an integer value, such as "<code>100</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static int progressBarAutoRotateInterval=0x7f01000a; /** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static int progressBarImage=0x7f010008; /** <p>Must be one of the following constant values.</p> <table> <colgroup align="left" /> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Constant</th><th>Value</th><th>Description</th></tr> <tr><td><code>none</code></td><td>-1</td><td></td></tr> <tr><td><code>fitXY</code></td><td>0</td><td></td></tr> <tr><td><code>fitStart</code></td><td>1</td><td></td></tr> <tr><td><code>fitCenter</code></td><td>2</td><td></td></tr> <tr><td><code>fitEnd</code></td><td>3</td><td></td></tr> <tr><td><code>center</code></td><td>4</td><td></td></tr> <tr><td><code>centerInside</code></td><td>5</td><td></td></tr> <tr><td><code>centerCrop</code></td><td>6</td><td></td></tr> <tr><td><code>focusCrop</code></td><td>7</td><td></td></tr> </table> */ public static int progressBarImageScaleType=0x7f010009; /** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static int retryImage=0x7f010004; /** <p>Must be one of the following constant values.</p> <table> <colgroup align="left" /> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Constant</th><th>Value</th><th>Description</th></tr> <tr><td><code>none</code></td><td>-1</td><td></td></tr> <tr><td><code>fitXY</code></td><td>0</td><td></td></tr> <tr><td><code>fitStart</code></td><td>1</td><td></td></tr> <tr><td><code>fitCenter</code></td><td>2</td><td></td></tr> <tr><td><code>fitEnd</code></td><td>3</td><td></td></tr> <tr><td><code>center</code></td><td>4</td><td></td></tr> <tr><td><code>centerInside</code></td><td>5</td><td></td></tr> <tr><td><code>centerCrop</code></td><td>6</td><td></td></tr> <tr><td><code>focusCrop</code></td><td>7</td><td></td></tr> </table> */ public static int retryImageScaleType=0x7f010005; /** <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static int roundAsCircle=0x7f01000f; /** <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static int roundBottomLeft=0x7f010014; /** <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static int roundBottomRight=0x7f010013; /** <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static int roundTopLeft=0x7f010011; /** <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static int roundTopRight=0x7f010012; /** <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static int roundWithOverlayColor=0x7f010015; /** <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static int roundedCornerRadius=0x7f010010; /** <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static int roundingBorderColor=0x7f010017; /** <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static int roundingBorderPadding=0x7f010018; /** <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static int roundingBorderWidth=0x7f010016; /** <p>Must be a floating point value, such as "<code>1.2</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static int viewAspectRatio=0x7f010001; } public static final class id { public static int center=0x7f020000; public static int centerCrop=0x7f020001; public static int centerInside=0x7f020002; public static int fitCenter=0x7f020003; public static int fitEnd=0x7f020004; public static int fitStart=0x7f020005; public static int fitXY=0x7f020006; public static int focusCrop=0x7f020007; public static int none=0x7f020008; } public static final class styleable { /** Attributes that can be used with a GenericDraweeHierarchy. <p>Includes the following attributes:</p> <table> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Attribute</th><th>Description</th></tr> <tr><td><code>{@link #GenericDraweeHierarchy_actualImageScaleType com.alibaba.weex.appframework:actualImageScaleType}</code></td><td></td></tr> <tr><td><code>{@link #GenericDraweeHierarchy_backgroundImage com.alibaba.weex.appframework:backgroundImage}</code></td><td></td></tr> <tr><td><code>{@link #GenericDraweeHierarchy_fadeDuration com.alibaba.weex.appframework:fadeDuration}</code></td><td></td></tr> <tr><td><code>{@link #GenericDraweeHierarchy_failureImage com.alibaba.weex.appframework:failureImage}</code></td><td></td></tr> <tr><td><code>{@link #GenericDraweeHierarchy_failureImageScaleType com.alibaba.weex.appframework:failureImageScaleType}</code></td><td></td></tr> <tr><td><code>{@link #GenericDraweeHierarchy_overlayImage com.alibaba.weex.appframework:overlayImage}</code></td><td></td></tr> <tr><td><code>{@link #GenericDraweeHierarchy_placeholderImage com.alibaba.weex.appframework:placeholderImage}</code></td><td></td></tr> <tr><td><code>{@link #GenericDraweeHierarchy_placeholderImageScaleType com.alibaba.weex.appframework:placeholderImageScaleType}</code></td><td></td></tr> <tr><td><code>{@link #GenericDraweeHierarchy_pressedStateOverlayImage com.alibaba.weex.appframework:pressedStateOverlayImage}</code></td><td></td></tr> <tr><td><code>{@link #GenericDraweeHierarchy_progressBarAutoRotateInterval com.alibaba.weex.appframework:progressBarAutoRotateInterval}</code></td><td></td></tr> <tr><td><code>{@link #GenericDraweeHierarchy_progressBarImage com.alibaba.weex.appframework:progressBarImage}</code></td><td></td></tr> <tr><td><code>{@link #GenericDraweeHierarchy_progressBarImageScaleType com.alibaba.weex.appframework:progressBarImageScaleType}</code></td><td></td></tr> <tr><td><code>{@link #GenericDraweeHierarchy_retryImage com.alibaba.weex.appframework:retryImage}</code></td><td></td></tr> <tr><td><code>{@link #GenericDraweeHierarchy_retryImageScaleType com.alibaba.weex.appframework:retryImageScaleType}</code></td><td></td></tr> <tr><td><code>{@link #GenericDraweeHierarchy_roundAsCircle com.alibaba.weex.appframework:roundAsCircle}</code></td><td></td></tr> <tr><td><code>{@link #GenericDraweeHierarchy_roundBottomLeft com.alibaba.weex.appframework:roundBottomLeft}</code></td><td></td></tr> <tr><td><code>{@link #GenericDraweeHierarchy_roundBottomRight com.alibaba.weex.appframework:roundBottomRight}</code></td><td></td></tr> <tr><td><code>{@link #GenericDraweeHierarchy_roundTopLeft com.alibaba.weex.appframework:roundTopLeft}</code></td><td></td></tr> <tr><td><code>{@link #GenericDraweeHierarchy_roundTopRight com.alibaba.weex.appframework:roundTopRight}</code></td><td></td></tr> <tr><td><code>{@link #GenericDraweeHierarchy_roundWithOverlayColor com.alibaba.weex.appframework:roundWithOverlayColor}</code></td><td></td></tr> <tr><td><code>{@link #GenericDraweeHierarchy_roundedCornerRadius com.alibaba.weex.appframework:roundedCornerRadius}</code></td><td></td></tr> <tr><td><code>{@link #GenericDraweeHierarchy_roundingBorderColor com.alibaba.weex.appframework:roundingBorderColor}</code></td><td></td></tr> <tr><td><code>{@link #GenericDraweeHierarchy_roundingBorderPadding com.alibaba.weex.appframework:roundingBorderPadding}</code></td><td></td></tr> <tr><td><code>{@link #GenericDraweeHierarchy_roundingBorderWidth com.alibaba.weex.appframework:roundingBorderWidth}</code></td><td></td></tr> <tr><td><code>{@link #GenericDraweeHierarchy_viewAspectRatio com.alibaba.weex.appframework:viewAspectRatio}</code></td><td></td></tr> </table> @see #GenericDraweeHierarchy_actualImageScaleType @see #GenericDraweeHierarchy_backgroundImage @see #GenericDraweeHierarchy_fadeDuration @see #GenericDraweeHierarchy_failureImage @see #GenericDraweeHierarchy_failureImageScaleType @see #GenericDraweeHierarchy_overlayImage @see #GenericDraweeHierarchy_placeholderImage @see #GenericDraweeHierarchy_placeholderImageScaleType @see #GenericDraweeHierarchy_pressedStateOverlayImage @see #GenericDraweeHierarchy_progressBarAutoRotateInterval @see #GenericDraweeHierarchy_progressBarImage @see #GenericDraweeHierarchy_progressBarImageScaleType @see #GenericDraweeHierarchy_retryImage @see #GenericDraweeHierarchy_retryImageScaleType @see #GenericDraweeHierarchy_roundAsCircle @see #GenericDraweeHierarchy_roundBottomLeft @see #GenericDraweeHierarchy_roundBottomRight @see #GenericDraweeHierarchy_roundTopLeft @see #GenericDraweeHierarchy_roundTopRight @see #GenericDraweeHierarchy_roundWithOverlayColor @see #GenericDraweeHierarchy_roundedCornerRadius @see #GenericDraweeHierarchy_roundingBorderColor @see #GenericDraweeHierarchy_roundingBorderPadding @see #GenericDraweeHierarchy_roundingBorderWidth @see #GenericDraweeHierarchy_viewAspectRatio */ public static final int[] GenericDraweeHierarchy = { 0x7f010000, 0x7f010001, 0x7f010002, 0x7f010003, 0x7f010004, 0x7f010005, 0x7f010006, 0x7f010007, 0x7f010008, 0x7f010009, 0x7f01000a, 0x7f01000b, 0x7f01000c, 0x7f01000d, 0x7f01000e, 0x7f01000f, 0x7f010010, 0x7f010011, 0x7f010012, 0x7f010013, 0x7f010014, 0x7f010015, 0x7f010016, 0x7f010017, 0x7f010018 }; /** <p>This symbol is the offset where the {@link com.alibaba.weex.appframework.R.attr#actualImageScaleType} attribute's value can be found in the {@link #GenericDraweeHierarchy} array. <p>Must be one of the following constant values.</p> <table> <colgroup align="left" /> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Constant</th><th>Value</th><th>Description</th></tr> <tr><td><code>none</code></td><td>-1</td><td></td></tr> <tr><td><code>fitXY</code></td><td>0</td><td></td></tr> <tr><td><code>fitStart</code></td><td>1</td><td></td></tr> <tr><td><code>fitCenter</code></td><td>2</td><td></td></tr> <tr><td><code>fitEnd</code></td><td>3</td><td></td></tr> <tr><td><code>center</code></td><td>4</td><td></td></tr> <tr><td><code>centerInside</code></td><td>5</td><td></td></tr> <tr><td><code>centerCrop</code></td><td>6</td><td></td></tr> <tr><td><code>focusCrop</code></td><td>7</td><td></td></tr> </table> @attr name com.alibaba.weex.appframework:actualImageScaleType */ public static int GenericDraweeHierarchy_actualImageScaleType = 11; /** <p>This symbol is the offset where the {@link com.alibaba.weex.appframework.R.attr#backgroundImage} attribute's value can be found in the {@link #GenericDraweeHierarchy} array. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". @attr name com.alibaba.weex.appframework:backgroundImage */ public static int GenericDraweeHierarchy_backgroundImage = 12; /** <p>This symbol is the offset where the {@link com.alibaba.weex.appframework.R.attr#fadeDuration} attribute's value can be found in the {@link #GenericDraweeHierarchy} array. <p>Must be an integer value, such as "<code>100</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.alibaba.weex.appframework:fadeDuration */ public static int GenericDraweeHierarchy_fadeDuration = 0; /** <p>This symbol is the offset where the {@link com.alibaba.weex.appframework.R.attr#failureImage} attribute's value can be found in the {@link #GenericDraweeHierarchy} array. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". @attr name com.alibaba.weex.appframework:failureImage */ public static int GenericDraweeHierarchy_failureImage = 6; /** <p>This symbol is the offset where the {@link com.alibaba.weex.appframework.R.attr#failureImageScaleType} attribute's value can be found in the {@link #GenericDraweeHierarchy} array. <p>Must be one of the following constant values.</p> <table> <colgroup align="left" /> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Constant</th><th>Value</th><th>Description</th></tr> <tr><td><code>none</code></td><td>-1</td><td></td></tr> <tr><td><code>fitXY</code></td><td>0</td><td></td></tr> <tr><td><code>fitStart</code></td><td>1</td><td></td></tr> <tr><td><code>fitCenter</code></td><td>2</td><td></td></tr> <tr><td><code>fitEnd</code></td><td>3</td><td></td></tr> <tr><td><code>center</code></td><td>4</td><td></td></tr> <tr><td><code>centerInside</code></td><td>5</td><td></td></tr> <tr><td><code>centerCrop</code></td><td>6</td><td></td></tr> <tr><td><code>focusCrop</code></td><td>7</td><td></td></tr> </table> @attr name com.alibaba.weex.appframework:failureImageScaleType */ public static int GenericDraweeHierarchy_failureImageScaleType = 7; /** <p>This symbol is the offset where the {@link com.alibaba.weex.appframework.R.attr#overlayImage} attribute's value can be found in the {@link #GenericDraweeHierarchy} array. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". @attr name com.alibaba.weex.appframework:overlayImage */ public static int GenericDraweeHierarchy_overlayImage = 13; /** <p>This symbol is the offset where the {@link com.alibaba.weex.appframework.R.attr#placeholderImage} attribute's value can be found in the {@link #GenericDraweeHierarchy} array. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". @attr name com.alibaba.weex.appframework:placeholderImage */ public static int GenericDraweeHierarchy_placeholderImage = 2; /** <p>This symbol is the offset where the {@link com.alibaba.weex.appframework.R.attr#placeholderImageScaleType} attribute's value can be found in the {@link #GenericDraweeHierarchy} array. <p>Must be one of the following constant values.</p> <table> <colgroup align="left" /> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Constant</th><th>Value</th><th>Description</th></tr> <tr><td><code>none</code></td><td>-1</td><td></td></tr> <tr><td><code>fitXY</code></td><td>0</td><td></td></tr> <tr><td><code>fitStart</code></td><td>1</td><td></td></tr> <tr><td><code>fitCenter</code></td><td>2</td><td></td></tr> <tr><td><code>fitEnd</code></td><td>3</td><td></td></tr> <tr><td><code>center</code></td><td>4</td><td></td></tr> <tr><td><code>centerInside</code></td><td>5</td><td></td></tr> <tr><td><code>centerCrop</code></td><td>6</td><td></td></tr> <tr><td><code>focusCrop</code></td><td>7</td><td></td></tr> </table> @attr name com.alibaba.weex.appframework:placeholderImageScaleType */ public static int GenericDraweeHierarchy_placeholderImageScaleType = 3; /** <p>This symbol is the offset where the {@link com.alibaba.weex.appframework.R.attr#pressedStateOverlayImage} attribute's value can be found in the {@link #GenericDraweeHierarchy} array. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". @attr name com.alibaba.weex.appframework:pressedStateOverlayImage */ public static int GenericDraweeHierarchy_pressedStateOverlayImage = 14; /** <p>This symbol is the offset where the {@link com.alibaba.weex.appframework.R.attr#progressBarAutoRotateInterval} attribute's value can be found in the {@link #GenericDraweeHierarchy} array. <p>Must be an integer value, such as "<code>100</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.alibaba.weex.appframework:progressBarAutoRotateInterval */ public static int GenericDraweeHierarchy_progressBarAutoRotateInterval = 10; /** <p>This symbol is the offset where the {@link com.alibaba.weex.appframework.R.attr#progressBarImage} attribute's value can be found in the {@link #GenericDraweeHierarchy} array. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". @attr name com.alibaba.weex.appframework:progressBarImage */ public static int GenericDraweeHierarchy_progressBarImage = 8; /** <p>This symbol is the offset where the {@link com.alibaba.weex.appframework.R.attr#progressBarImageScaleType} attribute's value can be found in the {@link #GenericDraweeHierarchy} array. <p>Must be one of the following constant values.</p> <table> <colgroup align="left" /> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Constant</th><th>Value</th><th>Description</th></tr> <tr><td><code>none</code></td><td>-1</td><td></td></tr> <tr><td><code>fitXY</code></td><td>0</td><td></td></tr> <tr><td><code>fitStart</code></td><td>1</td><td></td></tr> <tr><td><code>fitCenter</code></td><td>2</td><td></td></tr> <tr><td><code>fitEnd</code></td><td>3</td><td></td></tr> <tr><td><code>center</code></td><td>4</td><td></td></tr> <tr><td><code>centerInside</code></td><td>5</td><td></td></tr> <tr><td><code>centerCrop</code></td><td>6</td><td></td></tr> <tr><td><code>focusCrop</code></td><td>7</td><td></td></tr> </table> @attr name com.alibaba.weex.appframework:progressBarImageScaleType */ public static int GenericDraweeHierarchy_progressBarImageScaleType = 9; /** <p>This symbol is the offset where the {@link com.alibaba.weex.appframework.R.attr#retryImage} attribute's value can be found in the {@link #GenericDraweeHierarchy} array. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". @attr name com.alibaba.weex.appframework:retryImage */ public static int GenericDraweeHierarchy_retryImage = 4; /** <p>This symbol is the offset where the {@link com.alibaba.weex.appframework.R.attr#retryImageScaleType} attribute's value can be found in the {@link #GenericDraweeHierarchy} array. <p>Must be one of the following constant values.</p> <table> <colgroup align="left" /> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Constant</th><th>Value</th><th>Description</th></tr> <tr><td><code>none</code></td><td>-1</td><td></td></tr> <tr><td><code>fitXY</code></td><td>0</td><td></td></tr> <tr><td><code>fitStart</code></td><td>1</td><td></td></tr> <tr><td><code>fitCenter</code></td><td>2</td><td></td></tr> <tr><td><code>fitEnd</code></td><td>3</td><td></td></tr> <tr><td><code>center</code></td><td>4</td><td></td></tr> <tr><td><code>centerInside</code></td><td>5</td><td></td></tr> <tr><td><code>centerCrop</code></td><td>6</td><td></td></tr> <tr><td><code>focusCrop</code></td><td>7</td><td></td></tr> </table> @attr name com.alibaba.weex.appframework:retryImageScaleType */ public static int GenericDraweeHierarchy_retryImageScaleType = 5; /** <p>This symbol is the offset where the {@link com.alibaba.weex.appframework.R.attr#roundAsCircle} attribute's value can be found in the {@link #GenericDraweeHierarchy} array. <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.alibaba.weex.appframework:roundAsCircle */ public static int GenericDraweeHierarchy_roundAsCircle = 15; /** <p>This symbol is the offset where the {@link com.alibaba.weex.appframework.R.attr#roundBottomLeft} attribute's value can be found in the {@link #GenericDraweeHierarchy} array. <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.alibaba.weex.appframework:roundBottomLeft */ public static int GenericDraweeHierarchy_roundBottomLeft = 20; /** <p>This symbol is the offset where the {@link com.alibaba.weex.appframework.R.attr#roundBottomRight} attribute's value can be found in the {@link #GenericDraweeHierarchy} array. <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.alibaba.weex.appframework:roundBottomRight */ public static int GenericDraweeHierarchy_roundBottomRight = 19; /** <p>This symbol is the offset where the {@link com.alibaba.weex.appframework.R.attr#roundTopLeft} attribute's value can be found in the {@link #GenericDraweeHierarchy} array. <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.alibaba.weex.appframework:roundTopLeft */ public static int GenericDraweeHierarchy_roundTopLeft = 17; /** <p>This symbol is the offset where the {@link com.alibaba.weex.appframework.R.attr#roundTopRight} attribute's value can be found in the {@link #GenericDraweeHierarchy} array. <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.alibaba.weex.appframework:roundTopRight */ public static int GenericDraweeHierarchy_roundTopRight = 18; /** <p>This symbol is the offset where the {@link com.alibaba.weex.appframework.R.attr#roundWithOverlayColor} attribute's value can be found in the {@link #GenericDraweeHierarchy} array. <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.alibaba.weex.appframework:roundWithOverlayColor */ public static int GenericDraweeHierarchy_roundWithOverlayColor = 21; /** <p>This symbol is the offset where the {@link com.alibaba.weex.appframework.R.attr#roundedCornerRadius} attribute's value can be found in the {@link #GenericDraweeHierarchy} array. <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.alibaba.weex.appframework:roundedCornerRadius */ public static int GenericDraweeHierarchy_roundedCornerRadius = 16; /** <p>This symbol is the offset where the {@link com.alibaba.weex.appframework.R.attr#roundingBorderColor} attribute's value can be found in the {@link #GenericDraweeHierarchy} array. <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.alibaba.weex.appframework:roundingBorderColor */ public static int GenericDraweeHierarchy_roundingBorderColor = 23; /** <p>This symbol is the offset where the {@link com.alibaba.weex.appframework.R.attr#roundingBorderPadding} attribute's value can be found in the {@link #GenericDraweeHierarchy} array. <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.alibaba.weex.appframework:roundingBorderPadding */ public static int GenericDraweeHierarchy_roundingBorderPadding = 24; /** <p>This symbol is the offset where the {@link com.alibaba.weex.appframework.R.attr#roundingBorderWidth} attribute's value can be found in the {@link #GenericDraweeHierarchy} array. <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.alibaba.weex.appframework:roundingBorderWidth */ public static int GenericDraweeHierarchy_roundingBorderWidth = 22; /** <p>This symbol is the offset where the {@link com.alibaba.weex.appframework.R.attr#viewAspectRatio} attribute's value can be found in the {@link #GenericDraweeHierarchy} array. <p>Must be a floating point value, such as "<code>1.2</code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.alibaba.weex.appframework:viewAspectRatio */ public static int GenericDraweeHierarchy_viewAspectRatio = 1; }; }
16,118
7,353
#include "crypto_kdf.h" #include "randombytes.h" const char * crypto_kdf_primitive(void) { return crypto_kdf_PRIMITIVE; } size_t crypto_kdf_bytes_min(void) { return crypto_kdf_BYTES_MIN; } size_t crypto_kdf_bytes_max(void) { return crypto_kdf_BYTES_MAX; } size_t crypto_kdf_contextbytes(void) { return crypto_kdf_CONTEXTBYTES; } size_t crypto_kdf_keybytes(void) { return crypto_kdf_KEYBYTES; } int crypto_kdf_derive_from_key(unsigned char *subkey, size_t subkey_len, uint64_t subkey_id, const char ctx[crypto_kdf_CONTEXTBYTES], const unsigned char key[crypto_kdf_KEYBYTES]) { return crypto_kdf_blake2b_derive_from_key(subkey, subkey_len, subkey_id, ctx, key); } void crypto_kdf_keygen(unsigned char k[crypto_kdf_KEYBYTES]) { randombytes_buf(k, crypto_kdf_KEYBYTES); }
504
712
<reponame>alionurdemetoglu/gearmand /* vim:expandtab:shiftwidth=2:tabstop=2:smarttab: * * Gearmand client and server library. * * Copyright (C) 2011 Data Differential, http://datadifferential.com/ * Copyright (C) 2008 <NAME>, <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. * * * The names of its contributors may not be used to endorse or * promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /** * @file * @brief Worker Declarations */ #pragma once #include <libgearman-1.0/interface/worker.h> /** @addtogroup gearman_worker Worker Declarations * * This is the interface gearman workers should use. * * @ref main_page_worker "See Main Page for full details." * @{ */ enum gearman_worker_state_t { GEARMAN_WORKER_STATE_START, GEARMAN_WORKER_STATE_FUNCTION_SEND, GEARMAN_WORKER_STATE_CONNECT, GEARMAN_WORKER_STATE_GRAB_JOB_SEND, GEARMAN_WORKER_STATE_GRAB_JOB_RECV, GEARMAN_WORKER_STATE_PRE_SLEEP }; enum gearman_worker_universal_t { GEARMAN_WORKER_WORK_UNIVERSAL_GRAB_JOB, GEARMAN_WORKER_WORK_UNIVERSAL_FUNCTION, GEARMAN_WORKER_WORK_UNIVERSAL_COMPLETE, GEARMAN_WORKER_WORK_UNIVERSAL_FAIL }; #ifdef __cplusplus #define gearman_has_reducer(A) (A) ? static_cast<bool>((A)->reducer.final_fn) : false #else #define gearman_has_reducer(A) (A) ? (bool)((A)->reducer.final_fn) : false #endif #ifdef __cplusplus extern "C" { #endif /** * Initialize a worker structure. Always check the return value even if passing * in a pre-allocated structure. Some other initialization may have failed. It * is not required to memset() a structure before providing it. * * @param[in] worker Caller allocated structure, or NULL to allocate one. * @return On success, a pointer to the (possibly allocated) structure. On * failure this will be NULL. */ GEARMAN_API gearman_worker_st *gearman_worker_create(gearman_worker_st *worker); /** * Clone a worker structure. * * @param[in] worker Caller allocated structure, or NULL to allocate one. * @param[in] from Structure to use as a source to clone from. * @return Same return as gearman_worker_create(). */ GEARMAN_API gearman_worker_st *gearman_worker_clone(gearman_worker_st *worker, const gearman_worker_st *from); /** * Free resources used by a worker structure. * * @param[in] worker Structure previously initialized with * gearman_worker_create() or gearman_worker_clone(). */ GEARMAN_API void gearman_worker_free(gearman_worker_st *worker); /** * See gearman_error() for details. */ GEARMAN_API const char *gearman_worker_error(const gearman_worker_st *worker); /** * See gearman_errno() for details. */ GEARMAN_API int gearman_worker_errno(gearman_worker_st *worker); /** * Get options for a worker structure. * * @param[in] worker Structure previously initialized with * gearman_worker_create() or gearman_worker_clone(). * @return Options set for the worker structure. */ GEARMAN_API gearman_worker_options_t gearman_worker_options(const gearman_worker_st *worker); /** * Set options for a worker structure. * * @param[in] worker Structure previously initialized with * gearman_worker_create() or gearman_worker_clone(). * @param options Available options for worker structures. */ GEARMAN_API void gearman_worker_set_options(gearman_worker_st *worker, gearman_worker_options_t options); /** * Add options for a worker structure. * * @param[in] worker Structure previously initialized with * gearman_worker_create() or gearman_worker_clone(). * @param options Available options for worker structures. */ GEARMAN_API void gearman_worker_add_options(gearman_worker_st *worker, gearman_worker_options_t options); /** * Remove options for a worker structure. * * @param[in] worker Structure previously initialized with * gearman_worker_create() or gearman_worker_clone(). * @param options Available options for worker structures. */ GEARMAN_API void gearman_worker_remove_options(gearman_worker_st *worker, gearman_worker_options_t options); /** * See gearman_universal_timeout() for details. */ GEARMAN_API int gearman_worker_timeout(gearman_worker_st *worker); /** * See gearman_universal_set_timeout() for details. */ GEARMAN_API void gearman_worker_set_timeout(gearman_worker_st *worker, int timeout); /** * See gearman_universal_set_ssl() for details. */ GEARMAN_API void gearman_worker_set_ssl(gearman_worker_st *worker, bool ssl, const char *ca_file, const char *certificate, const char *key_file); /** * Get the application context for a worker. * * @param[in] worker Structure previously initialized with * gearman_worker_create() or gearman_worker_clone(). * @return Application context that was previously set, or NULL. */ GEARMAN_API void *gearman_worker_context(const gearman_worker_st *worker); /** * Set the application context for a worker. * * @param[in] worker Structure previously initialized with * gearman_worker_create() or gearman_worker_clone(). * @param[in] context Application context to set. */ GEARMAN_API void gearman_worker_set_context(gearman_worker_st *worker, void *context); /** * See gearman_set_log_fn() for details. */ GEARMAN_API void gearman_worker_set_log_fn(gearman_worker_st *worker, gearman_log_fn *function, void *context, gearman_verbose_t verbose); /** * See gearman_set_workload_malloc_fn() for details. */ GEARMAN_API void gearman_worker_set_workload_malloc_fn(gearman_worker_st *worker, gearman_malloc_fn *function, void *context); /** * Set custom memory free function for workloads. Normally gearman uses the * standard system free to free memory used with workloads. The provided * function will be used instead. * * @param[in] gearman Structure previously initialized with gearman_universal_create() or * gearman_clone(). * @param[in] function Memory free function to use instead of free(). * @param[in] context Argument to pass into the callback function. */ GEARMAN_API void gearman_worker_set_workload_free_fn(gearman_worker_st *worker, gearman_free_fn *function, void *context); /** * Add a job server to a worker. This goes into a list of servers that can be * used to run tasks. No socket I/O happens here, it is just added to a list. * * @param[in] worker Structure previously initialized with * gearman_worker_create() or gearman_worker_clone(). * @param[in] host Hostname or IP address (IPv4 or IPv6) of the server to add. * @param[in] port Port of the server to add. * @return Standard gearman return value. */ GEARMAN_API gearman_return_t gearman_worker_add_server(gearman_worker_st *worker, const char *host, in_port_t port); /** * Add a list of job servers to a worker. The format for the server list is: * SERVER[:PORT][,SERVER[:PORT]]... * Some examples are: * 10.0.0.1,10.0.0.2,10.0.0.3 * localhost234,jobserver2.domain.com:7003,10.0.0.3 * * @param[in] worker Structure previously initialized with * gearman_worker_create() or gearman_worker_clone(). * @param[in] servers Server list described above. * @return Standard gearman return value. */ GEARMAN_API gearman_return_t gearman_worker_add_servers(gearman_worker_st *worker, const char *servers); /** * Remove all servers currently associated with the worker. * * @param[in] worker Structure previously initialized with * gearman_worker_create() or gearman_worker_clone(). */ GEARMAN_API void gearman_worker_remove_servers(gearman_worker_st *worker); /** * When in non-blocking I/O mode, wait for activity from one of the servers. * * @param[in] worker Structure previously initialized with * gearman_worker_create() or gearman_worker_clone(). * @return Standard gearman return value. */ GEARMAN_API gearman_return_t gearman_worker_wait(gearman_worker_st *worker); /** * Register function with job servers with an optional timeout. The timeout * specifies how many seconds the server will wait before marking a job as * failed. If timeout is zero, there is no timeout. * * @param[in] worker Structure previously initialized with * gearman_worker_create() or gearman_worker_clone(). * @param[in] function_name Function name to register. * @param[in] timeout Optional timeout (in seconds) that specifies the maximum * time a job should. This is enforced on the job server. A value of 0 means * an infinite time. * @return Standard gearman return value. */ GEARMAN_API gearman_return_t gearman_worker_register(gearman_worker_st *worker, const char *function_name, uint32_t timeout); /** * Unregister function with job servers. * * @param[in] worker Structure previously initialized with * gearman_worker_create() or gearman_worker_clone(). * @param[in] function_name Function name to unregister. * @return Standard gearman return value. */ GEARMAN_API gearman_return_t gearman_worker_unregister(gearman_worker_st *worker, const char *function_name); /** * Unregister all functions with job servers. * * @param[in] worker Structure previously initialized with * gearman_worker_create() or gearman_worker_clone(). * @return Standard gearman return value. */ GEARMAN_API gearman_return_t gearman_worker_unregister_all(gearman_worker_st *worker); /** * Get a job from one of the job servers. This does not used the callback * interface below, which means results must be sent back to the job server * manually. It is also the responsibility of the caller to free the job once * it has been completed. * * @param[in] worker Structure previously initialized with * gearman_worker_create() or gearman_worker_clone(). * @param[in] job Caller allocated structure, or NULL to allocate one. * @param[out] ret_ptr Standard gearman return value. * @return On success, a pointer to the (possibly allocated) structure. On * failure this will be NULL. */ GEARMAN_API gearman_job_st *gearman_worker_grab_job(gearman_worker_st *worker, gearman_job_st *job, gearman_return_t *ret_ptr); /** * Free all jobs for a gearman structure. * * @param[in] worker Structure previously initialized with * gearman_worker_create() or gearman_worker_clone(). */ GEARMAN_API void gearman_job_free_all(gearman_worker_st *worker); /** * See if a function exists in the server. It will not return * true if the function is currently being de-allocated. * @param[in] worker gearman_worker_st that will be used. * @param[in] function_name Function name for search. * @param[in] function_length Length of function name. * @return bool */ GEARMAN_API bool gearman_worker_function_exist(gearman_worker_st *worker, const char *function_name, size_t function_length); /** * Register and add callback function for worker. To remove functions that have * been added, call gearman_worker_unregister() or * gearman_worker_unregister_all(). * * @param[in] worker Structure previously initialized with * gearman_worker_create() or gearman_worker_clone(). * @param[in] function_name Function name to register. * @param[in] timeout Optional timeout (in seconds) that specifies the maximum * time a job should. This is enforced on the job server. A value of 0 means * an infinite time. * @param[in] function Function to run when there is a job ready. * @param[in] context Argument to pass into the callback function. * @return Standard gearman return value. */ GEARMAN_API gearman_return_t gearman_worker_add_function(gearman_worker_st *worker, const char *function_name, uint32_t timeout, gearman_worker_fn *function, void *context); GEARMAN_API gearman_return_t gearman_worker_define_function(gearman_worker_st *worker, const char *function_name, const size_t function_name_length, const gearman_function_t function, const uint32_t timeout, void *context); /** * Wait for a job and call the appropriate callback function when it gets one. * * @param[in] worker Structure previously initialized with * gearman_worker_create() or gearman_worker_clone(). * @return Standard gearman return value. */ GEARMAN_API gearman_return_t gearman_worker_work(gearman_worker_st *worker); /** * Send data to all job servers to see if they echo it back. This is a test * function to see if job servers are responding properly. * * @param[in] worker Structure previously initialized with * gearman_worker_create() or gearman_worker_clone(). * @param[in] workload The workload to ask the server to echo back. * @param[in] workload_size Size of the workload. * @return Standard gearman return value. */ GEARMAN_API gearman_return_t gearman_worker_echo(gearman_worker_st *worker, const void *workload, size_t workload_size); GEARMAN_API gearman_return_t gearman_worker_set_memory_allocators(gearman_worker_st *, gearman_malloc_fn *malloc_fn, gearman_free_fn *free_fn, gearman_realloc_fn *realloc_fn, gearman_calloc_fn *calloc_fn, void *context); GEARMAN_API bool gearman_worker_set_server_option(gearman_worker_st *self, const char *option_arg, size_t option_arg_size); GEARMAN_API void gearman_worker_set_namespace(gearman_worker_st *self, const char *namespace_key, size_t namespace_key_size); GEARMAN_API const char *gearman_worker_namespace(gearman_worker_st *self); GEARMAN_API gearman_id_t gearman_worker_shutdown_handle(gearman_worker_st *self); GEARMAN_API gearman_id_t gearman_worker_id(gearman_worker_st *self); GEARMAN_API gearman_return_t gearman_worker_set_identifier(gearman_worker_st *worker, const char *id, size_t id_size); /** @} */ #ifdef __cplusplus } #endif
6,097
647
# Copyright (C) 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Unit tests for the loader module. from __future__ import absolute_import import re from StringIO import StringIO import tempfile from tests import util import transitfeed import zipfile import zlib class UnrecognizedColumnRecorder(transitfeed.ProblemReporter): """Keeps track of unrecognized column errors.""" def __init__(self, test_case): self.accumulator = util.RecordingProblemAccumulator(test_case, ignore_types=("ExpirationDate",)) self.column_errors = [] def UnrecognizedColumn(self, file_name, column_name, context=None): self.column_errors.append((file_name, column_name)) # ensure that there are no exceptions when attempting to load # (so that the validator won't crash) class NoExceptionTestCase(util.RedirectStdOutTestCaseBase): def runTest(self): for feed in util.GetDataPathContents(): loader = transitfeed.Loader(util.DataPath(feed), problems=transitfeed.ProblemReporter(), extra_validation=True) schedule = loader.Load() schedule.Validate() class EndOfLineCheckerTestCase(util.TestCase): def setUp(self): self.accumulator = util.RecordingProblemAccumulator( self, ("ExpirationDate")) self.problems = transitfeed.ProblemReporter(self.accumulator) def RunEndOfLineChecker(self, end_of_line_checker): # Iterating using for calls end_of_line_checker.next() until a # StopIteration is raised. EndOfLineChecker does the final check for a mix # of CR LF and LF ends just before raising StopIteration. for line in end_of_line_checker: pass def testInvalidLineEnd(self): f = transitfeed.EndOfLineChecker(StringIO("line1\r\r\nline2"), "<StringIO>", self.problems) self.RunEndOfLineChecker(f) e = self.accumulator.PopException("InvalidLineEnd") self.assertEqual(e.file_name, "<StringIO>") self.assertEqual(e.row_num, 1) self.assertEqual(e.bad_line_end, r"\r\r\n") self.accumulator.AssertNoMoreExceptions() def testInvalidLineEndToo(self): f = transitfeed.EndOfLineChecker( StringIO("line1\nline2\r\nline3\r\r\r\n"), "<StringIO>", self.problems) self.RunEndOfLineChecker(f) e = self.accumulator.PopException("InvalidLineEnd") self.assertEqual(e.file_name, "<StringIO>") self.assertEqual(e.row_num, 3) self.assertEqual(e.bad_line_end, r"\r\r\r\n") e = self.accumulator.PopException("OtherProblem") self.assertEqual(e.file_name, "<StringIO>") self.assertTrue(e.description.find("consistent line end") != -1) self.accumulator.AssertNoMoreExceptions() def testEmbeddedCr(self): f = transitfeed.EndOfLineChecker( StringIO("line1\rline1b"), "<StringIO>", self.problems) self.RunEndOfLineChecker(f) e = self.accumulator.PopException("OtherProblem") self.assertEqual(e.file_name, "<StringIO>") self.assertEqual(e.row_num, 1) self.assertEqual(e.FormatProblem(), "Line contains ASCII Carriage Return 0x0D, \\r") self.accumulator.AssertNoMoreExceptions() def testEmbeddedUtf8NextLine(self): f = transitfeed.EndOfLineChecker( StringIO("line1b\xc2\x85"), "<StringIO>", self.problems) self.RunEndOfLineChecker(f) e = self.accumulator.PopException("OtherProblem") self.assertEqual(e.file_name, "<StringIO>") self.assertEqual(e.row_num, 1) self.assertEqual(e.FormatProblem(), "Line contains Unicode NEXT LINE SEPARATOR U+0085") self.accumulator.AssertNoMoreExceptions() def testEndOfLineMix(self): f = transitfeed.EndOfLineChecker( StringIO("line1\nline2\r\nline3\nline4"), "<StringIO>", self.problems) self.RunEndOfLineChecker(f) e = self.accumulator.PopException("OtherProblem") self.assertEqual(e.file_name, "<StringIO>") self.assertEqual(e.FormatProblem(), "Found 1 CR LF \"\\r\\n\" line end (line 2) and " "2 LF \"\\n\" line ends (lines 1, 3). A file must use a " "consistent line end.") self.accumulator.AssertNoMoreExceptions() def testEndOfLineManyMix(self): f = transitfeed.EndOfLineChecker( StringIO("1\n2\n3\n4\n5\n6\n7\r\n8\r\n9\r\n10\r\n11\r\n"), "<StringIO>", self.problems) self.RunEndOfLineChecker(f) e = self.accumulator.PopException("OtherProblem") self.assertEqual(e.file_name, "<StringIO>") self.assertEqual(e.FormatProblem(), "Found 5 CR LF \"\\r\\n\" line ends (lines 7, 8, 9, 10, " "11) and 6 LF \"\\n\" line ends (lines 1, 2, 3, 4, 5, " "...). A file must use a consistent line end.") self.accumulator.AssertNoMoreExceptions() def testLoad(self): loader = transitfeed.Loader( util.DataPath("bad_eol.zip"), problems=self.problems, extra_validation=True) loader.Load() e = self.accumulator.PopException("OtherProblem") self.assertEqual(e.file_name, "calendar.txt") self.assertTrue(re.search( r"Found 1 CR LF.* \(line 2\) and 2 LF .*\(lines 1, 3\)", e.FormatProblem())) e = self.accumulator.PopException("InvalidLineEnd") self.assertEqual(e.file_name, "routes.txt") self.assertEqual(e.row_num, 5) self.assertTrue(e.FormatProblem().find(r"\r\r\n") != -1) e = self.accumulator.PopException("OtherProblem") self.assertEqual(e.file_name, "trips.txt") self.assertEqual(e.row_num, 1) self.assertTrue(re.search( r"contains ASCII Form Feed", e.FormatProblem())) # TODO(Tom): avoid this duplicate error for the same issue e = self.accumulator.PopException("CsvSyntax") self.assertEqual(e.row_num, 1) self.assertTrue(re.search( r"header row should not contain any space char", e.FormatProblem())) self.accumulator.AssertNoMoreExceptions() class LoadFromZipTestCase(util.TestCase): def runTest(self): loader = transitfeed.Loader( util.DataPath('good_feed.zip'), problems=util.GetTestFailureProblemReporter(self), extra_validation=True) loader.Load() # now try using Schedule.Load schedule = transitfeed.Schedule( problem_reporter=util.ExceptionProblemReporterNoExpiration()) schedule.Load(util.DataPath('good_feed.zip'), extra_validation=True) class LoadAndRewriteFromZipTestCase(util.TestCase): def runTest(self): schedule = transitfeed.Schedule( problem_reporter=util.ExceptionProblemReporterNoExpiration()) schedule.Load(util.DataPath('good_feed.zip'), extra_validation=True) # Finally see if write crashes schedule.WriteGoogleTransitFeed(tempfile.TemporaryFile()) class BasicMemoryZipTestCase(util.MemoryZipTestCase): def runTest(self): self.MakeLoaderAndLoad() self.accumulator.AssertNoMoreExceptions() class ZipCompressionTestCase(util.MemoryZipTestCase): def runTest(self): schedule = self.MakeLoaderAndLoad() self.zip.close() write_output = StringIO() schedule.WriteGoogleTransitFeed(write_output) recompressedzip = zlib.compress(write_output.getvalue()) write_size = len(write_output.getvalue()) recompressedzip_size = len(recompressedzip) # If zlib can compress write_output it probably wasn't compressed self.assertFalse( recompressedzip_size < write_size * 0.60, "Are you sure WriteGoogleTransitFeed wrote a compressed zip? " "Orginial size: %d recompressed: %d" % (write_size, recompressedzip_size)) class LoadUnknownFileInZipTestCase(util.MemoryZipTestCase): def runTest(self): self.SetArchiveContents( "stpos.txt", "stop_id,stop_name,stop_lat,stop_lon,location_type,parent_station\n" "BEATTY_AIRPORT,Airport,36.868446,-116.784582,,STATION\n" "STATION,Airport,36.868446,-116.784582,1,\n" "BULLFROG,Bullfrog,36.88108,-116.81797,,\n" "STAGECOACH,Stagecoach Hotel,36.915682,-116.751677,,\n") schedule = self.MakeLoaderAndLoad() e = self.accumulator.PopException('UnknownFile') self.assertEquals('stpos.txt', e.file_name) self.accumulator.AssertNoMoreExceptions() class TabDelimitedTestCase(util.MemoryZipTestCase): def runTest(self): # Create an extremely corrupt file by replacing each comma with a tab, # ignoring csv quoting. for arcname in self.GetArchiveNames(): contents = self.GetArchiveContents(arcname) self.SetArchiveContents(arcname, contents.replace(",", "\t")) schedule = self.MakeLoaderAndLoad() # Don't call self.accumulator.AssertNoMoreExceptions() because there are # lots of problems but I only care that the validator doesn't crash. In the # magical future the validator will stop when the csv is obviously hosed. class LoadFromDirectoryTestCase(util.TestCase): def runTest(self): loader = transitfeed.Loader( util.DataPath('good_feed'), problems=util.GetTestFailureProblemReporter(self), extra_validation=True) loader.Load() class LoadUnknownFeedTestCase(util.TestCase): def runTest(self): feed_name = util.DataPath('unknown_feed') loader = transitfeed.Loader( feed_name, problems=util.ExceptionProblemReporterNoExpiration(), extra_validation=True) try: loader.Load() self.fail('FeedNotFound exception expected') except transitfeed.FeedNotFound as e: self.assertEqual(feed_name, e.feed_name) class LoadUnknownFormatTestCase(util.TestCase): def runTest(self): feed_name = util.DataPath('unknown_format.zip') loader = transitfeed.Loader( feed_name, problems=util.ExceptionProblemReporterNoExpiration(), extra_validation=True) try: loader.Load() self.fail('UnknownFormat exception expected') except transitfeed.UnknownFormat as e: self.assertEqual(feed_name, e.feed_name) class LoadUnrecognizedColumnsTestCase(util.TestCase): def runTest(self): problems = UnrecognizedColumnRecorder(self) loader = transitfeed.Loader(util.DataPath('unrecognized_columns'), problems=problems) loader.Load() found_errors = set(problems.column_errors) expected_errors = set([ ('agency.txt', 'agency_lange'), ('stops.txt', 'stop_uri'), ('routes.txt', 'Route_Text_Color'), ('calendar.txt', 'leap_day'), ('calendar_dates.txt', 'leap_day'), ('trips.txt', 'sharpe_id'), ('stop_times.txt', 'shapedisttraveled'), ('stop_times.txt', 'drop_off_time'), ('fare_attributes.txt', 'transfer_time'), ('fare_rules.txt', 'source_id'), ('frequencies.txt', 'superfluous'), ('transfers.txt', 'to_stop') ]) # Now make sure we got the unrecognized column errors that we expected. not_expected = found_errors.difference(expected_errors) self.failIf(not_expected, 'unexpected errors: %s' % str(not_expected)) not_found = expected_errors.difference(found_errors) self.failIf(not_found, 'expected but not found: %s' % str(not_found)) class LoadExtraCellValidationTestCase(util.LoadTestCase): """Check that the validation detects too many cells in a row.""" def runTest(self): self.Load('extra_row_cells') e = self.accumulator.PopException("OtherProblem") self.assertEquals("routes.txt", e.file_name) self.assertEquals(4, e.row_num) self.accumulator.AssertNoMoreExceptions() class LoadMissingCellValidationTestCase(util.LoadTestCase): """Check that the validation detects missing cells in a row.""" def runTest(self): self.Load('missing_row_cells') e = self.accumulator.PopException("OtherProblem") self.assertEquals("routes.txt", e.file_name) self.assertEquals(4, e.row_num) self.accumulator.AssertNoMoreExceptions() class LoadUnknownFileTestCase(util.TestCase): """Check that the validation detects unknown files.""" def runTest(self): feed_name = util.DataPath('unknown_file') self.accumulator = util.RecordingProblemAccumulator( self, ("ExpirationDate")) self.problems = transitfeed.ProblemReporter(self.accumulator) loader = transitfeed.Loader( feed_name, problems=self.problems, extra_validation=True) loader.Load() e = self.accumulator.PopException('UnknownFile') self.assertEqual('frecuencias.txt', e.file_name) self.accumulator.AssertNoMoreExceptions() class LoadMissingAgencyTestCase(util.LoadTestCase): def runTest(self): self.ExpectMissingFile('missing_agency', 'agency.txt') class LoadMissingStopsTestCase(util.LoadTestCase): def runTest(self): self.ExpectMissingFile('missing_stops', 'stops.txt') class LoadMissingRoutesTestCase(util.LoadTestCase): def runTest(self): self.ExpectMissingFile('missing_routes', 'routes.txt') class LoadMissingTripsTestCase(util.LoadTestCase): def runTest(self): self.ExpectMissingFile('missing_trips', 'trips.txt') class LoadMissingStopTimesTestCase(util.LoadTestCase): def runTest(self): self.ExpectMissingFile('missing_stop_times', 'stop_times.txt') class LoadMissingCalendarTestCase(util.LoadTestCase): def runTest(self): self.ExpectMissingFile('missing_calendar', 'calendar.txt') class EmptyFileTestCase(util.TestCase): def runTest(self): loader = transitfeed.Loader( util.DataPath('empty_file'), problems=util.ExceptionProblemReporterNoExpiration(), extra_validation = True) try: loader.Load() self.fail('EmptyFile exception expected') except transitfeed.EmptyFile as e: self.assertEqual('agency.txt', e.file_name) class MissingColumnTestCase(util.TestCase): def runTest(self): loader = transitfeed.Loader( util.DataPath('missing_column'), problems=util.ExceptionProblemReporterNoExpiration(), extra_validation = True) try: loader.Load() self.fail('MissingColumn exception expected') except transitfeed.MissingColumn as e: self.assertEqual('agency.txt', e.file_name) self.assertEqual('agency_name', e.column_name) class LoadUTF8BOMTestCase(util.TestCase): def runTest(self): loader = transitfeed.Loader( util.DataPath('utf8bom'), problems=util.GetTestFailureProblemReporter(self), extra_validation=True) loader.Load() class LoadUTF16TestCase(util.TestCase): def runTest(self): # utf16 generated by `recode utf8..utf16 *' accumulator = transitfeed.ExceptionProblemAccumulator() problem_reporter = transitfeed.ProblemReporter(accumulator) loader = transitfeed.Loader( util.DataPath('utf16'), problems=problem_reporter, extra_validation=True) try: loader.Load() # TODO: make sure processing proceeds beyond the problem self.fail('FileFormat exception expected') except transitfeed.FileFormat as e: # make sure these don't raise an exception self.assertTrue(re.search(r'encoded in utf-16', e.FormatProblem())) e.FormatContext() class BadUtf8TestCase(util.LoadTestCase): def runTest(self): self.Load('bad_utf8') self.accumulator.PopException("UnrecognizedColumn") self.accumulator.PopInvalidValue("agency_name", "agency.txt") self.accumulator.PopInvalidValue("route_long_name", "routes.txt") self.accumulator.PopInvalidValue("route_short_name", "routes.txt") self.accumulator.PopInvalidValue("stop_headsign", "stop_times.txt") self.accumulator.PopInvalidValue("stop_name", "stops.txt") self.accumulator.PopInvalidValue("trip_headsign", "trips.txt") self.accumulator.AssertNoMoreExceptions() class LoadNullTestCase(util.TestCase): def runTest(self): accumulator = transitfeed.ExceptionProblemAccumulator() problem_reporter = transitfeed.ProblemReporter(accumulator) loader = transitfeed.Loader( util.DataPath('contains_null'), problems=problem_reporter, extra_validation=True) try: loader.Load() self.fail('FileFormat exception expected') except transitfeed.FileFormat as e: self.assertTrue(re.search(r'contains a null', e.FormatProblem())) # make sure these don't raise an exception e.FormatContext() class CsvDictTestCase(util.TestCase): def setUp(self): self.accumulator = util.RecordingProblemAccumulator(self) self.problems = transitfeed.ProblemReporter(self.accumulator) self.zip = zipfile.ZipFile(StringIO(), 'a') self.loader = transitfeed.Loader( problems=self.problems, zip=self.zip) def tearDown(self): self.accumulator.TearDownAssertNoMoreExceptions() def testEmptyFile(self): self.zip.writestr("test.txt", "") results = list(self.loader._ReadCsvDict("test.txt", [], [], [])) self.assertEquals([], results) self.accumulator.PopException("EmptyFile") self.accumulator.AssertNoMoreExceptions() def testHeaderOnly(self): self.zip.writestr("test.txt", "test_id,test_name") results = list(self.loader._ReadCsvDict("test.txt", ["test_id", "test_name"], [], [])) self.assertEquals([], results) self.accumulator.AssertNoMoreExceptions() def testHeaderAndNewLineOnly(self): self.zip.writestr("test.txt", "test_id,test_name\n") results = list(self.loader._ReadCsvDict("test.txt", ["test_id", "test_name"], [], [])) self.assertEquals([], results) self.accumulator.AssertNoMoreExceptions() def testHeaderWithSpaceBefore(self): self.zip.writestr("test.txt", " test_id, test_name\n") results = list(self.loader._ReadCsvDict("test.txt", ["test_id", "test_name"], [], [])) self.assertEquals([], results) self.accumulator.AssertNoMoreExceptions() def testHeaderWithSpaceBeforeAfter(self): self.zip.writestr("test.txt", "test_id , test_name\n") results = list(self.loader._ReadCsvDict("test.txt", ["test_id", "test_name"], [], [])) self.assertEquals([], results) e = self.accumulator.PopException("CsvSyntax") self.accumulator.AssertNoMoreExceptions() def testHeaderQuoted(self): self.zip.writestr("test.txt", "\"test_id\", \"test_name\"\n") results = list(self.loader._ReadCsvDict("test.txt", ["test_id", "test_name"], [], [])) self.assertEquals([], results) self.accumulator.AssertNoMoreExceptions() def testHeaderSpaceAfterQuoted(self): self.zip.writestr("test.txt", "\"test_id\" , \"test_name\"\n") results = list(self.loader._ReadCsvDict("test.txt", ["test_id", "test_name"], [], [])) self.assertEquals([], results) e = self.accumulator.PopException("CsvSyntax") self.accumulator.AssertNoMoreExceptions() def testHeaderSpaceInQuotesAfterValue(self): self.zip.writestr("test.txt", "\"test_id \",\"test_name\"\n") results = list(self.loader._ReadCsvDict("test.txt", ["test_id", "test_name"], [], [])) self.assertEquals([], results) e = self.accumulator.PopException("CsvSyntax") self.accumulator.AssertNoMoreExceptions() def testHeaderSpaceInQuotesBeforeValue(self): self.zip.writestr("test.txt", "\"test_id\",\" test_name\"\n") results = list(self.loader._ReadCsvDict("test.txt", ["test_id", "test_name"], [], [])) self.assertEquals([], results) e = self.accumulator.PopException("CsvSyntax") self.accumulator.AssertNoMoreExceptions() def testHeaderEmptyColumnName(self): self.zip.writestr("test.txt", 'test_id,test_name,\n') results = list(self.loader._ReadCsvDict("test.txt", ["test_id", "test_name"], [], [])) self.assertEquals([], results) e = self.accumulator.PopException("CsvSyntax") self.accumulator.AssertNoMoreExceptions() def testHeaderAllUnknownColumnNames(self): self.zip.writestr("test.txt", 'id,nam\n') results = list(self.loader._ReadCsvDict("test.txt", ["test_id", "test_name"], [], [])) self.assertEquals([], results) e = self.accumulator.PopException("CsvSyntax") self.assertTrue(e.FormatProblem().find("missing the header") != -1) self.accumulator.AssertNoMoreExceptions() def testFieldWithSpaces(self): self.zip.writestr("test.txt", "test_id,test_name\n" "id1 , my name\n") results = list(self.loader._ReadCsvDict("test.txt", ["test_id", "test_name"], [], [])) self.assertEquals([({"test_id": "id1", "test_name": "my name"}, 2, ["test_id", "test_name"], ["id1", "my name"])], results) self.accumulator.AssertNoMoreExceptions() def testFieldWithOnlySpaces(self): self.zip.writestr("test.txt", "test_id,test_name\n" "id1, \n") # spaces are skipped to yield empty field results = list(self.loader._ReadCsvDict("test.txt", ["test_id", "test_name"], [], [])) self.assertEquals([({"test_id": "id1", "test_name": ""}, 2, ["test_id", "test_name"], ["id1", ""])], results) self.accumulator.AssertNoMoreExceptions() def testQuotedFieldWithSpaces(self): self.zip.writestr("test.txt", 'test_id,"test_name",test_size\n' '"id1" , "my name" , "234 "\n') results = list(self.loader._ReadCsvDict("test.txt", ["test_id", "test_name", "test_size"], [], [])) self.assertEquals( [({"test_id": "id1", "test_name": "my name", "test_size": "234"}, 2, ["test_id", "test_name", "test_size"], ["id1", "my name", "234"])], results) self.accumulator.AssertNoMoreExceptions() def testQuotedFieldWithCommas(self): self.zip.writestr("test.txt", 'id,name1,name2\n' '"1", "brown, tom", "brown, ""tom"""\n') results = list(self.loader._ReadCsvDict("test.txt", ["id", "name1", "name2"], [], [])) self.assertEquals( [({"id": "1", "name1": "<NAME>", "name2": "brown, \"tom\""}, 2, ["id", "name1", "name2"], ["1", "<NAME>", "brown, \"tom\""])], results) self.accumulator.AssertNoMoreExceptions() def testUnknownColumn(self): # A small typo (omitting '_' in a header name) is detected self.zip.writestr("test.txt", "test_id,testname\n") results = list(self.loader._ReadCsvDict("test.txt", ["test_id", "test_name"], [], [])) self.assertEquals([], results) e = self.accumulator.PopException("UnrecognizedColumn") self.assertEquals("testname", e.column_name) self.accumulator.AssertNoMoreExceptions() def testDeprecatedColumn(self): self.zip.writestr("test.txt", "test_id,test_old\n") results = list(self.loader._ReadCsvDict("test.txt", ["test_id", "test_new"], ["test_id"], [("test_old", "test_new")])) self.assertEquals([], results) e = self.accumulator.PopException("DeprecatedColumn") self.assertEquals("test_old", e.column_name) self.assertTrue("test_new" in e.reason) self.accumulator.AssertNoMoreExceptions() def testDeprecatedColumnWithoutNewColumn(self): self.zip.writestr("test.txt", "test_id,test_old\n") results = list(self.loader._ReadCsvDict("test.txt", ["test_id", "test_new"], ["test_id"], [("test_old", None)])) self.assertEquals([], results) e = self.accumulator.PopException("DeprecatedColumn") self.assertEquals("test_old", e.column_name) self.assertTrue(not e.reason or "use the new column" not in e.reason) self.accumulator.AssertNoMoreExceptions() def testDeprecatedValuesBeingRead(self): self.zip.writestr("test.txt", "test_id,test_old\n" "1,old_value1\n" "2,old_value2\n") results = list(self.loader._ReadCsvDict("test.txt", ["test_id", "test_new"], ["test_id"], [("test_old", "test_new")])) self.assertEquals(2, len(results)) self.assertEquals('old_value1', results[0][0]['test_old']) self.assertEquals('old_value2', results[1][0]['test_old']) e = self.accumulator.PopException("DeprecatedColumn") self.assertEquals('test_old', e.column_name) self.accumulator.AssertNoMoreExceptions() def testMissingRequiredColumn(self): self.zip.writestr("test.txt", "test_id,test_size\n") results = list(self.loader._ReadCsvDict("test.txt", ["test_id", "test_size"], ["test_name"], [])) self.assertEquals([], results) e = self.accumulator.PopException("MissingColumn") self.assertEquals("test_name", e.column_name) self.accumulator.AssertNoMoreExceptions() def testRequiredNotInAllCols(self): self.zip.writestr("test.txt", "test_id,test_name,test_size\n") results = list(self.loader._ReadCsvDict("test.txt", ["test_id", "test_size"], ["test_name"], [])) self.assertEquals([], results) e = self.accumulator.PopException("UnrecognizedColumn") self.assertEquals("test_name", e.column_name) self.accumulator.AssertNoMoreExceptions() def testBlankLine(self): # line_num is increased for an empty line self.zip.writestr("test.txt", "test_id,test_name\n" "\n" "id1,my name\n") results = list(self.loader._ReadCsvDict("test.txt", ["test_id", "test_name"], [], [])) self.assertEquals([({"test_id": "id1", "test_name": "my name"}, 3, ["test_id", "test_name"], ["id1", "my name"])], results) self.accumulator.AssertNoMoreExceptions() def testExtraComma(self): self.zip.writestr("test.txt", "test_id,test_name\n" "id1,my name,\n") results = list(self.loader._ReadCsvDict("test.txt", ["test_id", "test_name"], [], [])) self.assertEquals([({"test_id": "id1", "test_name": "my name"}, 2, ["test_id", "test_name"], ["id1", "my name"])], results) e = self.accumulator.PopException("OtherProblem") self.assertTrue(e.FormatProblem().find("too many cells") != -1) self.accumulator.AssertNoMoreExceptions() def testMissingComma(self): self.zip.writestr("test.txt", "test_id,test_name\n" "id1 my name\n") results = list(self.loader._ReadCsvDict("test.txt", ["test_id", "test_name"], [], [])) self.assertEquals([({"test_id": "id1 my name"}, 2, ["test_id", "test_name"], ["id1 my name"])], results) e = self.accumulator.PopException("OtherProblem") self.assertTrue(e.FormatProblem().find("missing cells") != -1) self.accumulator.AssertNoMoreExceptions() def testDetectsDuplicateHeaders(self): self.zip.writestr( "transfers.txt", "from_stop_id,from_stop_id,to_stop_id,transfer_type,min_transfer_time," "min_transfer_time,min_transfer_time,min_transfer_time,unknown," "unknown\n" "BEATTY_AIRPORT,BEATTY_AIRPORT,BULLFROG,3,,2,,,,\n" "BULLFROG,BULLFROG,BEATTY_AIRPORT,2,1200,1,,,,\n") list(self.loader._ReadCsvDict("transfers.txt", transitfeed.Transfer._FIELD_NAMES, transitfeed.Transfer._REQUIRED_FIELD_NAMES, transitfeed.Transfer._DEPRECATED_FIELD_NAMES)) self.accumulator.PopDuplicateColumn("transfers.txt", "from_stop_id", 2) self.accumulator.PopDuplicateColumn("transfers.txt", "min_transfer_time", 4) self.accumulator.PopDuplicateColumn("transfers.txt", "unknown", 2) e = self.accumulator.PopException("UnrecognizedColumn") self.assertEquals("unknown", e.column_name) self.accumulator.AssertNoMoreExceptions() class ReadCsvTestCase(util.TestCase): def setUp(self): self.accumulator = util.RecordingProblemAccumulator(self) self.problems = transitfeed.ProblemReporter(self.accumulator) self.zip = zipfile.ZipFile(StringIO(), 'a') self.loader = transitfeed.Loader( problems=self.problems, zip=self.zip) def tearDown(self): self.accumulator.TearDownAssertNoMoreExceptions() def testDetectsDuplicateHeaders(self): self.zip.writestr( "calendar.txt", "service_id,monday,tuesday,wednesday,thursday,friday,saturday,sunday," "start_date,end_date,end_date,end_date,tuesday,unknown,unknown\n" "FULLW,1,1,1,1,1,1,1,20070101,20101231,,,,,\n") list(self.loader._ReadCSV("calendar.txt", transitfeed.ServicePeriod._FIELD_NAMES, transitfeed.ServicePeriod._REQUIRED_FIELD_NAMES, transitfeed.ServicePeriod._DEPRECATED_FIELD_NAMES )) self.accumulator.PopDuplicateColumn("calendar.txt", "end_date", 3) self.accumulator.PopDuplicateColumn("calendar.txt", "tuesday", 2) self.accumulator.PopDuplicateColumn("calendar.txt", "unknown", 2) e = self.accumulator.PopException("UnrecognizedColumn") self.assertEquals("unknown", e.column_name) self.accumulator.AssertNoMoreExceptions() def testDeprecatedColumn(self): self.zip.writestr("test.txt", "test_id,test_old\n") results = list(self.loader._ReadCSV("test.txt", ["test_id", "test_new"], ["test_id"], [("test_old", "test_new")])) self.assertEquals([], results) e = self.accumulator.PopException("DeprecatedColumn") self.assertEquals("test_old", e.column_name) self.assertTrue("test_new" in e.reason) self.accumulator.AssertNoMoreExceptions() def testDeprecatedColumnWithoutNewColumn(self): self.zip.writestr("test.txt", "test_id,test_old\n") results = list(self.loader._ReadCSV("test.txt", ["test_id", "test_new"], ["test_id"], [("test_old", None)])) self.assertEquals([], results) e = self.accumulator.PopException("DeprecatedColumn") self.assertEquals("test_old", e.column_name) self.assertTrue(not e.reason or "use the new column" not in e.reason) self.accumulator.AssertNoMoreExceptions() class BasicParsingTestCase(util.TestCase): """Checks that we're getting the number of child objects that we expect.""" def assertLoadedCorrectly(self, schedule): """Check that the good_feed looks correct""" self.assertEqual(1, len(schedule._agencies)) self.assertEqual(5, len(schedule.routes)) self.assertEqual(2, len(schedule.service_periods)) self.assertEqual(10, len(schedule.stops)) self.assertEqual(11, len(schedule.trips)) self.assertEqual(0, len(schedule.fare_zones)) def assertLoadedStopTimesCorrectly(self, schedule): self.assertEqual(5, len(schedule.GetTrip('CITY1').GetStopTimes())) self.assertEqual('to airport', schedule.GetTrip('STBA').GetStopTimes()[0].stop_headsign) self.assertEqual(2, schedule.GetTrip('CITY1').GetStopTimes()[1].pickup_type) self.assertEqual(3, schedule.GetTrip('CITY1').GetStopTimes()[1].drop_off_type) def test_MemoryDb(self): loader = transitfeed.Loader( util.DataPath('good_feed.zip'), problems=util.GetTestFailureProblemReporter(self), extra_validation=True, memory_db=True) schedule = loader.Load() self.assertLoadedCorrectly(schedule) self.assertLoadedStopTimesCorrectly(schedule) def test_TemporaryFile(self): loader = transitfeed.Loader( util.DataPath('good_feed.zip'), problems=util.GetTestFailureProblemReporter(self), extra_validation=True, memory_db=False) schedule = loader.Load() self.assertLoadedCorrectly(schedule) self.assertLoadedStopTimesCorrectly(schedule) def test_NoLoadStopTimes(self): problems = util.GetTestFailureProblemReporter( self, ignore_types=("ExpirationDate", "UnusedStop", "OtherProblem")) loader = transitfeed.Loader( util.DataPath('good_feed.zip'), problems=problems, extra_validation=True, load_stop_times=False) schedule = loader.Load() self.assertLoadedCorrectly(schedule) self.assertEqual(0, len(schedule.GetTrip('CITY1').GetStopTimes())) class UndefinedStopAgencyTestCase(util.LoadTestCase): def runTest(self): self.ExpectInvalidValue('undefined_stop', 'stop_id')
14,713
2,542
<gh_stars>1000+ { "Default": { }, "Tests": [ { "Name": "Mgmt_SetupEntryPoint_XCopy", "Type": "V2_DllTest", "Owners": "maburlik,vaishnav,vipulm", "Environment": "Iaas", "ResourcesRequired": "Server:5", "TestExecutionParameters": { "SetupTimeout": "900", "ConfigName": "WinFabricTest\\Config\\Suite_348_V2_FunctionalSuite_7M_Kerberos_FQDN.txt", "DllPath": "ms.test.winfabric.cases.dll", "ClassName": "SecurityTestCases", "TaskName": "Security_KerberosPrepare", "ExecutionTimeout": "4200", "CleanupTimeout": "2100" } }, { "Name": "Backup-CIT_XCopy_InstallScripts", "Type": "V2_ScriptTest", "Owners": "maburlik,rsinha,ratando", "Environment": "Iaas", "ResourcesRequired": "Server:1", "TestExecutionParameters": { "SetupType": "XCopy", "SetupTimeout": "900", "ConfigName": "WinFabricTest\\Config\\V2_Script_Replicator_CITs.txt", "TaskName": "Backup-CIT.test", "ExecutionTimeout": "3600", "CleanupType": "XCopy", "CleanupTimeout": "2100" } }, { "Name": "VerifyAzureInstallUsingXCopyTest", "Type": "Azure_ScriptTest", "Owners": "maburlik,rsinha", "Environment": "Iaas", "ResourcesRequired": "Server:1&Azure:1", "TestExecutionParameters": { "SetupType": "XCopy", "SetupTimeout": "900", "TaskName": "VerifyAzureInstallUsingXCopy.test", "ExecutionTimeout": "14400", "CleanupType": "XCopy", "CleanupTimeout": "2100" } } ] }
799
631
<reponame>767248371/octo-rpc<filename>dorado/dorado-core/src/main/java/com/meituan/dorado/transport/http/AbstractHttpServer.java /* * Copyright 2018 <NAME>. 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.meituan.dorado.transport.http; import com.meituan.dorado.check.http.HttpCheckHandler; import com.meituan.dorado.common.Constants; import com.meituan.dorado.common.RpcRole; import com.meituan.dorado.common.extension.ExtensionLoader; import com.meituan.dorado.common.util.NetUtil; import com.meituan.dorado.rpc.handler.http.HttpHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.InetSocketAddress; import java.util.Random; public abstract class AbstractHttpServer implements HttpServer { private static final Logger logger = LoggerFactory.getLogger(AbstractHttpServer.class); private static volatile boolean started; private static volatile boolean destroyed; private static final int PORT_BIND_RETRY_TIMES = 10; protected HttpHandler httpHandler; protected InetSocketAddress localAddress; private volatile ShutDownHook hook; private static Random random = new Random(); public AbstractHttpServer(RpcRole role) { this.httpHandler = ExtensionLoader.getExtension(HttpCheckHandler.class); httpHandler.setRole(role); start(); } @Override public void close() { synchronized (HttpServer.class) { if (destroyed) { return; } logger.info("Closing HttpServer bind {}", localAddress); try { doClose(); } catch (Throwable e) { logger.error("HttpServer close failed", e); } started = false; destroyed = true; } } @Override public boolean isStart() { return started; } @Override public HttpHandler getHttpHandler() { return httpHandler; } @Override public InetSocketAddress getLocalAddress() { return localAddress; } public void start() { synchronized (HttpServer.class) { if (started) { return; } try { doStart(); started = true; logger.info("Start HttpServer bind {}", localAddress); } catch (Throwable e) { // http是服务功能不影响核心链路,不抛异常只输出日志 logger.error("HttpServer start failed", e); } } addShutDownHook(); } private synchronized void addShutDownHook() { if (hook == null) { hook = new ShutDownHook(this); Runtime.getRuntime().addShutdownHook(hook); } } protected void bindPort() { int port = NetUtil.getAvailablePort(Constants.DEFAULT_HTTP_SERVER_PORT); int bindCount = 0; while (!started) { try { bindCount++; if (bindCount > 1) { // 测试该重试策略, 50个进程并发没有问题 try { // 随机等待 减少并发冲突 Thread.sleep(random.nextInt(100)); } catch (InterruptedException e) { } if (bindCount <= PORT_BIND_RETRY_TIMES / 2) { port = NetUtil.getAvailablePort(port++); } else { // 重试五次后都失败, 则端口尝试增加随机值避免冲突 port = NetUtil.getAvailablePort(port + random.nextInt(10)); } } localAddress = new InetSocketAddress(port); doBind(localAddress); break; } catch (Throwable e) { if (bindCount > PORT_BIND_RETRY_TIMES) { throw e; } logger.info("HttpServer bind {} failed, will do {} retry, errorMsg: {}", localAddress, bindCount, e.getMessage()); } } } protected abstract void doStart(); protected abstract void doBind(InetSocketAddress localAddress); protected abstract void doClose(); class ShutDownHook extends Thread { private HttpServer server; public ShutDownHook(HttpServer server) { this.server = server; } @Override public void run() { hook = null; server.close(); } } }
2,349
5,267
<filename>modules/swagger-maven-plugin/src/test/java/io/swagger/v3/plugin/maven/resources/model/ModelWithJsonIdentityCyclic.java package io.swagger.v3.plugin.maven.resources.model; import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.fasterxml.jackson.annotation.JsonIdentityReference; import com.fasterxml.jackson.annotation.ObjectIdGenerators; import java.util.List; public class ModelWithJsonIdentityCyclic { public Long id; public List<SourceDefinition> sourceDefinitions; @JsonIdentityInfo( generator = ObjectIdGenerators.PropertyGenerator.class, property = "name") public static class SourceDefinition { public String driver; public String name; @JsonIdentityReference(alwaysAsId=true) @JsonIdentityInfo( generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") public ModelWithJsonIdentityCyclic model; } }
372
2,859
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB (<EMAIL>). * See LICENSE for details. */ package advanced.platformer; import com.almasb.fxgl.app.GameApplication; import com.almasb.fxgl.app.GameSettings; import com.almasb.fxgl.entity.state.StateComponent; import com.almasb.fxgl.input.UserAction; import javafx.scene.input.KeyCode; import javafx.scene.paint.Color; import static com.almasb.fxgl.dsl.FXGL.*; /** * @author <NAME> (<EMAIL>) */ public class RobotPlatformerSample extends GameApplication { private RobotComponent getControl() { return getGameWorld().getSingleton(e -> e.hasComponent(RobotComponent.class)) .getComponent(RobotComponent.class); } @Override protected void initSettings(GameSettings settings) { settings.setTitle("Robot platformer sample"); settings.setWidth(1280); settings.setHeight(720); settings.setDeveloperMenuEnabled(true); } @Override protected void initInput() { onKey(KeyCode.W, () -> getControl().jump()); onKey(KeyCode.F, () -> getControl().roll()); onKey(KeyCode.X, () -> getControl().die()); getInput().addAction(new UserAction("Left") { @Override protected void onAction() { getControl().walkLeft(); } @Override protected void onActionEnd() { getControl().stop(); } }, KeyCode.A); getInput().addAction(new UserAction("Right") { @Override protected void onAction() { getControl().walkRight(); } @Override protected void onActionEnd() { getControl().stop(); } }, KeyCode.D); getInput().addAction(new UserAction("Run Left") { @Override protected void onAction() { getControl().runLeft(); } @Override protected void onActionEnd() { getControl().stop(); } }, KeyCode.Q); getInput().addAction(new UserAction("Run Right") { @Override protected void onAction() { getControl().runRight(); } @Override protected void onActionEnd() { getControl().stop(); } }, KeyCode.E); getInput().addAction(new UserAction("Crouch Left") { @Override protected void onAction() { getControl().crouchLeft(); } @Override protected void onActionEnd() { getControl().stop(); } }, KeyCode.Z); getInput().addAction(new UserAction("Crouch Right") { @Override protected void onAction() { getControl().crouchRight(); } @Override protected void onActionEnd() { getControl().stop(); } }, KeyCode.C); } @Override protected void initGame() { getGameWorld().addEntityFactory(new RobotFactory()); setLevelFromMap("robot/level1.tmx"); entityBuilder().buildScreenBoundsAndAttach(20); spawn("robot", 200, 100); getPhysicsWorld().setGravity(0, 1250); } @Override protected void initUI() { var text = getUIFactoryService().newText("", Color.BLACK, 26.0); text.textProperty().bind( getGameWorld() .getEntitiesByComponent(StateComponent.class) .get(0) .getComponent(StateComponent.class) .currentStateProperty() .asString("State: %s") ); addUINode(text, 50, 50); } public static void main(String[] args) { launch(args); } }
1,897
1,199
# coding=utf-8 # Copyright 2018 The Google AI Language Team 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 # # 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. """Utilities for writing tf.Example files.""" import collections from language.nqg.model.parser.data import forest_serialization from language.nqg.model.parser.data import parsing_utils from language.nqg.model.parser.data import tokenization_utils import tensorflow as tf def _pad_values(values, padded_length): if len(values) > padded_length: raise ValueError("length %s is > %s" % (len(values), padded_length)) for _ in range(len(values), padded_length): values.append(0) return values def _create_int_feature(values, padded_length): values = _pad_values(values, padded_length) feature = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values))) return feature def get_rule_to_idx_map(rules): rule_to_idx_map = {} for idx, rule in enumerate(rules): rule_to_idx_map[rule] = idx + 1 # Reserve 0 for padding. return rule_to_idx_map def _get_applications(root_node, rule_to_idx_map, token_start_wp_idx, token_end_wp_idx): """Returns structures for anchored applications.""" # Traverse all nodes. node_stack = [root_node] seen_fingerprints = set() # Set of (span_begin, span_end, rule). applications = set() while node_stack: node = node_stack.pop() fingerprint = id(node) if fingerprint in seen_fingerprints: continue seen_fingerprints.add(fingerprint) if isinstance(node, parsing_utils.AggregationNode): for child in node.children: node_stack.append(child) elif isinstance(node, parsing_utils.RuleApplicationNode): for child in node.children: node_stack.append(child) applications.add((node.span_begin, node.span_end, node.rule)) else: raise ValueError("Unexpected node type.") # Map of (span_begin, span_end, rule) to integer idx. application_key_to_idx_map = {} # Lists of integers. application_span_begin = [] application_span_end = [] application_rule_idx = [] # Sort applications to avoid non-determinism. applications = sorted(applications) for idx, (span_begin, span_end, rule) in enumerate(applications): application_key_to_idx_map[(span_begin, span_end, rule)] = idx application_span_begin.append(token_start_wp_idx[span_begin]) # token_end_wp_idx is an *inclusive* idx. # span_end is an *exclusive* idx. # application_span_end is an *inclusive* idx. application_span_end.append(token_end_wp_idx[span_end - 1]) rule_idx = rule_to_idx_map[rule] application_rule_idx.append(rule_idx) return (application_key_to_idx_map, application_span_begin, application_span_end, application_rule_idx) def _convert_to_tf_example(example, tokenizer, rules, config, max_sizes=None): """Return tf.Example generated for input (source, target).""" source = example[0] target = example[1] tokens = source.split(" ") num_tokens = len(tokens) # Tokenize. (wordpiece_ids, num_wordpieces, token_start_wp_idx, token_end_wp_idx) = tokenization_utils.get_wordpiece_inputs( tokens, tokenizer) # Run chart parser. target_node = parsing_utils.get_target_node(source, target, rules) if not target_node: raise ValueError("No parse returned for target for example: (%s, %s)" % (source, target)) merged_node = parsing_utils.get_merged_node(source, rules) # Get anchored applications. rule_to_idx_map = get_rule_to_idx_map(rules) (application_key_to_idx_map, application_span_begin, application_span_end, application_rule_idx) = _get_applications(merged_node, rule_to_idx_map, token_start_wp_idx, token_end_wp_idx) num_applications = len(application_span_begin) def application_idx_fn(span_begin, span_end, rule): return application_key_to_idx_map[(span_begin, span_end, rule)] # Get numerator forest. (nu_node_type, nu_node_1_idx, nu_node_2_idx, nu_application_idx, nu_num_nodes) = forest_serialization.get_forest_lists( target_node, num_tokens, application_idx_fn) # Get denominator forest. (de_node_type, de_node_1_idx, de_node_2_idx, de_application_idx, de_num_nodes) = forest_serialization.get_forest_lists( merged_node, num_tokens, application_idx_fn) # Create features dict. features = collections.OrderedDict() features["wordpiece_ids"] = _create_int_feature(wordpiece_ids, config["max_num_wordpieces"]) features["num_wordpieces"] = _create_int_feature([num_wordpieces], 1) features["application_span_begin"] = _create_int_feature( application_span_begin, config["max_num_applications"]) features["application_span_end"] = _create_int_feature( application_span_end, config["max_num_applications"]) features["application_rule_idx"] = _create_int_feature( application_rule_idx, config["max_num_applications"]) features["nu_node_type"] = _create_int_feature( nu_node_type, config["max_num_numerator_nodes"]) features["nu_node_1_idx"] = _create_int_feature( nu_node_1_idx, config["max_num_numerator_nodes"]) features["nu_node_2_idx"] = _create_int_feature( nu_node_2_idx, config["max_num_numerator_nodes"]) features["nu_application_idx"] = _create_int_feature( nu_application_idx, config["max_num_numerator_nodes"]) features["nu_num_nodes"] = _create_int_feature([nu_num_nodes], 1) features["de_node_type"] = _create_int_feature( de_node_type, config["max_num_denominator_nodes"]) features["de_node_1_idx"] = _create_int_feature( de_node_1_idx, config["max_num_denominator_nodes"]) features["de_node_2_idx"] = _create_int_feature( de_node_2_idx, config["max_num_denominator_nodes"]) features["de_application_idx"] = _create_int_feature( de_application_idx, config["max_num_denominator_nodes"]) features["de_num_nodes"] = _create_int_feature([de_num_nodes], 1) tf_example = tf.train.Example(features=tf.train.Features(feature=features)) # Update max sizes. if max_sizes is not None: max_sizes["num_wordpieces"] = max(max_sizes["num_wordpieces"], num_wordpieces) max_sizes["num_applications"] = max(max_sizes["num_applications"], num_applications) max_sizes["nu_num_nodes"] = max(max_sizes["nu_num_nodes"], nu_num_nodes) max_sizes["de_num_nodes"] = max(max_sizes["de_num_nodes"], de_num_nodes) return tf_example class ExampleConverter(object): """Converts inputs to tf.Example protos.""" def __init__(self, rules, tokenizer, config): self.rules = rules self.tokenizer = tokenizer self.config = config self.max_sizes = collections.defaultdict(int) def convert(self, example): """Return tf.Example or Raise.""" tf_example = _convert_to_tf_example(example, self.tokenizer, self.rules, self.config, self.max_sizes) return tf_example def print_max_sizes(self): """Print max sizes which is useful for determining necessary padding.""" print("max_sizes: %s" % self.max_sizes)
3,023
3,603
<gh_stars>1000+ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.trino.sql.planner.iterative.rule; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableListMultimap; import com.google.common.collect.ImmutableMap; import io.trino.sql.planner.Symbol; import io.trino.sql.planner.assertions.SetOperationOutputMatcher; import io.trino.sql.planner.iterative.rule.test.BaseRuleTest; import org.testng.annotations.Test; import java.util.Optional; import static io.trino.sql.planner.assertions.PlanMatchPattern.expression; import static io.trino.sql.planner.assertions.PlanMatchPattern.filter; import static io.trino.sql.planner.assertions.PlanMatchPattern.functionCall; import static io.trino.sql.planner.assertions.PlanMatchPattern.project; import static io.trino.sql.planner.assertions.PlanMatchPattern.specification; import static io.trino.sql.planner.assertions.PlanMatchPattern.strictProject; import static io.trino.sql.planner.assertions.PlanMatchPattern.union; import static io.trino.sql.planner.assertions.PlanMatchPattern.values; import static io.trino.sql.planner.assertions.PlanMatchPattern.window; public class TestImplementExceptAll extends BaseRuleTest { @Test public void test() { tester().assertThat(new ImplementExceptAll(tester().getMetadata())) .on(p -> { Symbol a = p.symbol("a"); Symbol a1 = p.symbol("a_1"); Symbol a2 = p.symbol("a_2"); Symbol b = p.symbol("b"); Symbol b1 = p.symbol("b_1"); Symbol b2 = p.symbol("b_2"); return p.except( ImmutableListMultimap.<Symbol, Symbol>builder() .put(a, a1) .put(a, a2) .put(b, b1) .put(b, b2) .build(), ImmutableList.of( p.values(a1, b1), p.values(a2, b2)), false); }) .matches( strictProject( ImmutableMap.of("a", expression("a"), "b", expression("b")), filter( "row_number <= greatest(count_1 - count_2, BIGINT '0')", strictProject( ImmutableMap.of("a", expression("a"), "b", expression("b"), "count_1", expression("count_1"), "count_2", expression("count_2"), "row_number", expression("row_number")), window(builder -> builder .specification(specification( ImmutableList.of("a", "b"), ImmutableList.of(), ImmutableMap.of())) .addFunction( "count_1", functionCall( "count", Optional.empty(), ImmutableList.of("marker_1"))) .addFunction( "count_2", functionCall( "count", Optional.empty(), ImmutableList.of("marker_2"))) .addFunction( "row_number", functionCall( "row_number", Optional.empty(), ImmutableList.of())), union( project( ImmutableMap.of( "a1", expression("a_1"), "b1", expression("b_1"), "marker_left_1", expression("true"), "marker_left_2", expression("CAST(null AS boolean)")), values("a_1", "b_1")), project( ImmutableMap.of( "a2", expression("a_2"), "b2", expression("b_2"), "marker_right_1", expression("CAST(null AS boolean)"), "marker_right_2", expression("true")), values("a_2", "b_2"))) .withAlias("a", new SetOperationOutputMatcher(0)) .withAlias("b", new SetOperationOutputMatcher(1)) .withAlias("marker_1", new SetOperationOutputMatcher(2)) .withAlias("marker_2", new SetOperationOutputMatcher(3))))))); } }
4,957
859
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import os import pytest import pymorphy2 from pymorphy2.opencorpora_dict.compile import ( _to_paradigm, convert_to_pymorphy2 ) from pymorphy2.opencorpora_dict.parse import parse_opencorpora_xml from pymorphy2.dawg import assert_can_create from pymorphy2 import lang class TestToyDictionary: XML_PATH = os.path.join( os.path.dirname(__file__), '..', 'dev_data', 'toy_dict.xml' ) def test_parse_xml(self): dct = parse_opencorpora_xml(self.XML_PATH) assert dct.version == '0.92' assert dct.revision == '389440' assert dct.links[0] == ('5', '6', '1') assert len(dct.links) == 13 assert dct.grammemes[1] == ('NOUN', 'POST', 'СУЩ', 'имя существительное') assert len(dct.grammemes) == 114 assert dct.lexemes['14'] == [('ёжиться', 'INFN,impf,intr')] # bad values should be dropped assert dct.lexemes['111111'] == [] assert dct.lexemes['222222'] == [] def test_convert_to_pymorphy2(self, tmpdir): # import logging # from pymorphy2.opencorpora_dict.compile import logger # logger.setLevel(logging.DEBUG) # logger.addHandler(logging.StreamHandler()) try: assert_can_create() except NotImplementedError as e: raise pytest.skip(str(e)) # create a dictionary out_path = str(tmpdir.join('dicts')) options = { 'min_paradigm_popularity': 0, 'min_ending_freq': 0, 'paradigm_prefixes': lang.ru.PARADIGM_PREFIXES, } convert_to_pymorphy2(self.XML_PATH, out_path, source_name='toy', language_code='ru', overwrite=True, compile_options=options) # use it morph = pymorphy2.MorphAnalyzer(out_path) assert morph.tag('ёжиться') == [morph.TagClass('INFN,impf,intr')] # tag simplification should work assert morph.tag("ёж")[0] == morph.tag("ванька-встанька")[0] # Init tags should be handled correctly assert 'Init' in morph.tag("Ц")[0] assert 'Init' not in morph.tag("ц")[0] # normalization tests assert morph.normal_forms('абсурднее') == ['абсурдный'] assert morph.normal_forms('а') == ['а'] class TestToParadigm(object): def test_simple(self): lexeme = [ ["ярче", "COMP,Qual"], ["ярчей", "COMP,Qual V-ej"], ] stem, forms = _to_paradigm(lexeme, lang.ru.PARADIGM_PREFIXES) assert stem == "ярче" assert forms == ( ("", "COMP,Qual", ""), ("й", "COMP,Qual V-ej", ""), ) def test_single_prefix(self): lexeme = [ ["ярче", "COMP,Qual"], ["поярче", "COMP,Qual Cmp2"], ] stem, forms = _to_paradigm(lexeme, lang.ru.PARADIGM_PREFIXES) assert stem == "ярче" assert forms == ( ("", "COMP,Qual", ""), ("", "COMP,Qual Cmp2", "по"), ) def test_multiple_prefixes(self): lexeme = [ ["ярче", "COMP,Qual"], ["ярчей", "COMP,Qual V-ej"], ["поярче", "COMP,Qual Cmp2"], ["поярчей", "COMP,Qual Cmp2,V-ej"], ["наиярчайший", "ADJF,Supr,Qual masc,sing,nomn"], ] stem, forms = _to_paradigm(lexeme, lang.ru.PARADIGM_PREFIXES) assert stem == 'ярч' def test_multiple_prefixes_2(self): lexeme = [ ["подробнейший", 1], ["наиподробнейший", 2], ["поподробнее", 3] ] stem, forms = _to_paradigm(lexeme, lang.ru.PARADIGM_PREFIXES) assert stem == 'подробне' assert forms == ( ("йший", 1, ""), ("йший", 2, "наи"), ("е", 3, "по"), ) def test_platina(self): lexeme = [ ["платиновее", 1], ["платиновей", 2], ["поплатиновее", 3], ["поплатиновей", 4], ] stem, forms = _to_paradigm(lexeme, lang.ru.PARADIGM_PREFIXES) assert forms == ( ("е", 1, ""), ("й", 2, ""), ("е", 3, "по"), ("й", 4, "по"), ) assert stem == 'платинове' def test_no_prefix(self): lexeme = [["английский", 1], ["английского", 2]] stem, forms = _to_paradigm(lexeme, lang.ru.PARADIGM_PREFIXES) assert stem == 'английск' assert forms == ( ("ий", 1, ""), ("ого", 2, ""), ) def test_single(self): lexeme = [["английски", 1]] stem, forms = _to_paradigm(lexeme, lang.ru.PARADIGM_PREFIXES) assert stem == 'английски' assert forms == (("", 1, ""),)
2,786
1,687
<filename>12-Backtracking-And-DFS/Type-3-FloodFill/0130-surrounded-regions/src/Solution2.java<gh_stars>1000+ import java.util.LinkedList; import java.util.Queue; public class Solution2 { // 方法二:广度优先遍历 public void solve(char[][] board) { int rows = board.length; if (rows == 0) { return; } int cols = board[0].length; int[][] directions = new int[][]{{-1, 0}, {0, -1}, {1, 0}, {0, 1}}; // 第 1 步:把四周的 'O' 全部推入队列,通过广度优先遍历,把与 'O' 连通的地方全部编辑 Queue<int[]> queue = new LinkedList<>(); for (int i = 0; i < rows; i++) { if (board[i][0] == 'O') { queue.offer(new int[]{i, 0}); } if (board[i][cols - 1] == 'O') { queue.offer(new int[]{i, cols - 1}); } } for (int j = 1; j < cols - 1; j++) { if (board[0][j] == 'O') { queue.offer(new int[]{0, j}); } if (board[rows - 1][j] == 'O') { queue.offer(new int[]{rows - 1, j}); } } while (!queue.isEmpty()) { int[] top = queue.poll(); int i = top[0]; int j = top[1]; board[i][j] = '-'; for (int[] direction : directions) { int newX = i + direction[0]; int newY = j + direction[1]; if (inArea(newX, newY, rows, cols) && board[newX][newY] == 'O') { queue.offer(new int[]{newX, newY}); } } } // 第 2 步:恢复 for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (board[i][j] == '-') { board[i][j] = 'O'; } else if (board[i][j] == 'O') { board[i][j] = 'X'; } } } } private boolean inArea(int x, int y, int rows, int cols) { return x >= 0 && x < rows && y >= 0 && y < cols; } }
1,260
464
<filename>mplleaflet/utils.py import json from json.encoder import JSONEncoder def iter_rings(data, pathcodes): ring = [] # TODO: Do this smartly by finding when pathcodes changes value and do # smart indexing on data, instead of iterating over each coordinate for point, code in zip(data, pathcodes): if code == 'M': # Emit the path and start a new one if len(ring): yield ring ring = [point] elif code == 'L' or code == 'Z' or code == 'S': ring.append(point) else: raise ValueError('Unrecognized code: {}'.format(code)) if len(ring): yield ring class FloatEncoder(JSONEncoder): _formatter = ".3f" def iterencode(self, o, _one_shot=False): """Encode the given object and yield each string representation as available. For example:: for chunk in JSONEncoder().iterencode(bigobject): mysocket.write(chunk) """ c_make_encoder_original = json.encoder.c_make_encoder json.encoder.c_make_encoder = None if self.check_circular: markers = {} else: markers = None if self.ensure_ascii: _encoder = json.encoder.encode_basestring_ascii else: _encoder = json.encoder.encode_basestring def floatstr(o, allow_nan=self.allow_nan, _repr=lambda x: format(x, self._formatter), _inf=float("inf"), _neginf=-float("inf")): # Check for specials. Note that this type of test is processor # and/or platform-specific, so do tests which don't depend on the # internals. if o != o: text = 'NaN' elif o == _inf: text = 'Infinity' elif o == _neginf: text = '-Infinity' else: return _repr(o) if not allow_nan: raise ValueError( "Out of range float values are not JSON compliant: " + repr(o)) return text if (_one_shot and json.encoder.c_make_encoder is not None and self.indent is None): _iterencode = json.encoder.c_make_encoder( markers, self.default, _encoder, self.indent, self.key_separator, self.item_separator, self.sort_keys, self.skipkeys, self.allow_nan) else: _iterencode = json.encoder._make_iterencode( markers, self.default, _encoder, self.indent, floatstr, self.key_separator, self.item_separator, self.sort_keys, self.skipkeys, _one_shot) json.encoder.c_make_encoder = c_make_encoder_original return _iterencode(o, 0)
1,417
751
<filename>rx-java/rxgrpc-stub/src/main/java/com/salesforce/rxgrpc/stub/FusionAwareQueueSubscriptionAdapter.java /* * Copyright (c) 2019, Salesforce.com, Inc. * All rights reserved. * Licensed under the BSD 3-Clause license. * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause */ package com.salesforce.rxgrpc.stub; import com.salesforce.reactivegrpc.common.FusionModeAwareSubscription; import com.salesforce.reactivegrpc.common.AbstractUnimplementedQueue; import io.reactivex.exceptions.Exceptions; import io.reactivex.internal.fuseable.QueueSubscription; /** * Implementation of FusionModeAwareSubscription which encapsulate * {@link QueueSubscription} from RxJava internals and allows treat it as a {@link java.util.Queue}. * * @param <T> T */ class FusionAwareQueueSubscriptionAdapter<T> extends AbstractUnimplementedQueue<T> implements QueueSubscription<T>, FusionModeAwareSubscription { private final QueueSubscription<T> delegate; private final int mode; FusionAwareQueueSubscriptionAdapter(QueueSubscription<T> delegate, int mode) { this.delegate = delegate; this.mode = mode; } @Override public int mode() { return mode; } @Override public int requestFusion(int mode) { return delegate.requestFusion(mode); } @Override public void request(long l) { delegate.request(l); } @Override public void cancel() { delegate.cancel(); } @Override public T poll() { try { return delegate.poll(); } catch (Exception e) { throw Exceptions.propagate(e); } } @Override public boolean offer(T t) { return delegate.offer(t); } @Override public boolean offer(T v1, T v2) { return delegate.offer(v1, v2); } @Override public boolean isEmpty() { return delegate.isEmpty(); } @Override public void clear() { delegate.clear(); } }
797
575
<reponame>Ron423c/chromium<gh_stars>100-1000 // Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "services/network/trust_tokens/trust_token_key_commitment_parser.h" #include "base/base64.h" #include "base/json/json_reader.h" #include "base/numerics/safe_conversions.h" #include "base/ranges/algorithm.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_piece.h" #include "base/values.h" #include "services/network/public/mojom/trust_tokens.mojom.h" #include "services/network/trust_tokens/suitable_trust_token_origin.h" namespace network { const char kTrustTokenKeyCommitmentProtocolVersionField[] = "protocol_version"; const char kTrustTokenKeyCommitmentIDField[] = "id"; const char kTrustTokenKeyCommitmentBatchsizeField[] = "batchsize"; const char kTrustTokenKeyCommitmentExpiryField[] = "expiry"; const char kTrustTokenKeyCommitmentKeyField[] = "Y"; const char kTrustTokenKeyCommitmentRequestIssuanceLocallyOnField[] = "request_issuance_locally_on"; const char kTrustTokenLocalOperationOsAndroid[] = "android"; const char kTrustTokenKeyCommitmentUnavailableLocalOperationFallbackField[] = "unavailable_local_operation_fallback"; const char kTrustTokenLocalOperationFallbackWebIssuance[] = "web_issuance"; const char kTrustTokenLocalOperationFallbackReturnWithError[] = "return_with_error"; namespace { // Parses a single key label. If |in| is the string representation of an integer // in in the representable range of uint32_t, returns true. Otherwise, returns // false. bool ParseSingleKeyLabel(base::StringPiece in) { uint64_t key_label_in_uint64; if (!base::StringToUint64(in, &key_label_in_uint64)) return false; if (!base::IsValueInRangeForNumericType<uint32_t>(key_label_in_uint64)) return false; return true; } enum class ParseKeyResult { // Continue as if the key didn't exist. kIgnore, // Fail parsing totally. kFail, // Parsing the key succeeded. kSucceed }; // Parses a single key, consisting of a body (the key material) and an expiry // timestamp. Fails the parse if either field is missing or malformed. If the // key has expired but is otherwise valid, ignores the key rather than failing // the prase. ParseKeyResult ParseSingleKeyExceptLabel( const base::Value& in, mojom::TrustTokenVerificationKey* out) { CHECK(in.is_dict()); const std::string* expiry = in.FindStringKey(kTrustTokenKeyCommitmentExpiryField); const std::string* key_body = in.FindStringKey(kTrustTokenKeyCommitmentKeyField); if (!expiry || !key_body) return ParseKeyResult::kFail; uint64_t expiry_microseconds_since_unix_epoch; if (!base::StringToUint64(*expiry, &expiry_microseconds_since_unix_epoch)) return ParseKeyResult::kFail; if (!base::Base64Decode(*key_body, &out->body)) return ParseKeyResult::kFail; out->expiry = base::Time::UnixEpoch() + base::TimeDelta::FromMicroseconds(expiry_microseconds_since_unix_epoch); if (out->expiry <= base::Time::Now()) return ParseKeyResult::kIgnore; return ParseKeyResult::kSucceed; } base::Optional<mojom::TrustTokenKeyCommitmentResult::Os> ParseOs( base::StringPiece os_string) { if (os_string == kTrustTokenLocalOperationOsAndroid) return mojom::TrustTokenKeyCommitmentResult::Os::kAndroid; return base::nullopt; } // Attempts to parse a string representation of a member of the // UnavailableLocalOperationFallback enum, returning true on success and false // on failure. bool ParseUnavailableLocalOperationFallback( base::StringPiece fallback_string, mojom::TrustTokenKeyCommitmentResult::UnavailableLocalOperationFallback* fallback_out) { if (fallback_string == kTrustTokenLocalOperationFallbackWebIssuance) { *fallback_out = mojom::TrustTokenKeyCommitmentResult:: UnavailableLocalOperationFallback::kWebIssuance; return true; } if (fallback_string == kTrustTokenLocalOperationFallbackReturnWithError) { *fallback_out = mojom::TrustTokenKeyCommitmentResult:: UnavailableLocalOperationFallback::kReturnWithError; return true; } return false; } // Given a per-issuer key commitment dictionary, looks for the local Trust // Tokens issuance-related fields request_issuance_locally_on and // unavailable_local_operation_fallback. // // Returns true if both are absent, or if both are present and well-formed; in // the latter case, updates |result| to with their parsed values. Otherwise, // returns false. bool ParseLocalOperationFieldsIfPresent( const base::Value& value, mojom::TrustTokenKeyCommitmentResult* result) { const base::Value* maybe_request_issuance_locally_on = value.FindKey(kTrustTokenKeyCommitmentRequestIssuanceLocallyOnField); // The local issuance field is optional... if (!maybe_request_issuance_locally_on) return true; // ...but needs to be the right type if it's provided. if (!maybe_request_issuance_locally_on->is_list()) return false; for (const base::Value& maybe_os_value : maybe_request_issuance_locally_on->GetList()) { if (!maybe_os_value.is_string()) return false; base::Optional<mojom::TrustTokenKeyCommitmentResult::Os> maybe_os = ParseOs(maybe_os_value.GetString()); if (!maybe_os) return false; result->request_issuance_locally_on.push_back(*maybe_os); } // Deduplicate the OS values: auto& oses = result->request_issuance_locally_on; base::ranges::sort(oses); auto to_remove = base::ranges::unique(oses); oses.erase(to_remove, oses.end()); const std::string* maybe_fallback = value.FindStringKey( kTrustTokenKeyCommitmentUnavailableLocalOperationFallbackField); if (!maybe_fallback || !ParseUnavailableLocalOperationFallback( *maybe_fallback, &result->unavailable_local_operation_fallback)) { return false; } return true; } mojom::TrustTokenKeyCommitmentResultPtr ParseSingleIssuer( const base::Value& value) { if (!value.is_dict()) return nullptr; auto result = mojom::TrustTokenKeyCommitmentResult::New(); // Confirm that the protocol_version field is present. const std::string* maybe_version = value.FindStringKey(kTrustTokenKeyCommitmentProtocolVersionField); if (!maybe_version) return nullptr; if (*maybe_version == "TrustTokenV2PMB") { result->protocol_version = mojom::TrustTokenProtocolVersion::kTrustTokenV2Pmb; } else if (*maybe_version == "TrustTokenV2VOPRF") { result->protocol_version = mojom::TrustTokenProtocolVersion::kTrustTokenV2Voprf; } else { return nullptr; } // Confirm that the id field is present and type-safe. base::Optional<int> maybe_id = value.FindIntKey(kTrustTokenKeyCommitmentIDField); if (!maybe_id || *maybe_id <= 0) return nullptr; result->id = *maybe_id; // Confirm that the batchsize field is present and type-safe. base::Optional<int> maybe_batch_size = value.FindIntKey(kTrustTokenKeyCommitmentBatchsizeField); if (!maybe_batch_size || *maybe_batch_size <= 0) return nullptr; result->batch_size = *maybe_batch_size; if (!ParseLocalOperationFieldsIfPresent(value, result.get())) return nullptr; // Parse the key commitments in the result (these are exactly the // key-value pairs in the dictionary with dictionary-typed values). for (const auto& kv : value.DictItems()) { const base::Value& item = kv.second; if (!item.is_dict()) continue; auto key = mojom::TrustTokenVerificationKey::New(); if (!ParseSingleKeyLabel(kv.first)) return nullptr; switch (ParseSingleKeyExceptLabel(item, key.get())) { case ParseKeyResult::kFail: return nullptr; case ParseKeyResult::kIgnore: continue; case ParseKeyResult::kSucceed: result->keys.push_back(std::move(key)); } } return result; } // Entry is a convenience struct used as an intermediate representation when // parsing multiple issuers. In addition to a parsed canonicalized issuer, it // preserves the raw JSON string key (the second entry) in order // deterministically to deduplicate entries with keys canonicalizing to the same // issuer. using Entry = std::tuple<SuitableTrustTokenOrigin, // canonicalized issuer std::string, // raw key from the JSON mojom::TrustTokenKeyCommitmentResultPtr>; SuitableTrustTokenOrigin& canonicalized_issuer(Entry& e) { return std::get<0>(e); } mojom::TrustTokenKeyCommitmentResultPtr& commitment(Entry& e) { return std::get<2>(e); } } // namespace mojom::TrustTokenKeyCommitmentResultPtr TrustTokenKeyCommitmentParser::Parse( base::StringPiece response_body) { base::Optional<base::Value> maybe_value = base::JSONReader::Read(response_body); if (!maybe_value) return nullptr; return ParseSingleIssuer(std::move(*maybe_value)); } std::unique_ptr<base::flat_map<SuitableTrustTokenOrigin, mojom::TrustTokenKeyCommitmentResultPtr>> TrustTokenKeyCommitmentParser::ParseMultipleIssuers( base::StringPiece response_body) { base::Optional<base::Value> maybe_value = base::JSONReader::Read(response_body); if (!maybe_value) return nullptr; if (!maybe_value->is_dict()) return nullptr; // The configuration might contain conflicting lists of keys for issuers with // the same canonicalized URLs but different string representations provided // by the server. In order to handle these deterministically, first transfer // the entries to intermediate storage while maintaining the initial JSON // keys; then deduplicate based on identical entries' JSON keys' lexicographic // value. std::vector<Entry> parsed_entries; for (const auto& kv : maybe_value->DictItems()) { const std::string& raw_key_from_json = kv.first; base::Optional<SuitableTrustTokenOrigin> maybe_issuer = SuitableTrustTokenOrigin::Create(GURL(raw_key_from_json)); if (!maybe_issuer) continue; mojom::TrustTokenKeyCommitmentResultPtr commitment_result = ParseSingleIssuer(kv.second); if (!commitment_result) continue; parsed_entries.emplace_back(Entry(std::move(*maybe_issuer), raw_key_from_json, std::move(commitment_result))); } // Deterministically deduplicate entries corresponding to the same issuer, // with the largest JSON key lexicographically winning. std::sort(parsed_entries.begin(), parsed_entries.end(), std::greater<>()); parsed_entries.erase(std::unique(parsed_entries.begin(), parsed_entries.end(), [](Entry& lhs, Entry& rhs) -> bool { return canonicalized_issuer(lhs) == canonicalized_issuer(rhs); }), parsed_entries.end()); // Finally, discard the raw JSON strings and construct a map to return. std::vector<std::pair<SuitableTrustTokenOrigin, mojom::TrustTokenKeyCommitmentResultPtr>> map_storage; map_storage.reserve(parsed_entries.size()); for (Entry& e : parsed_entries) { map_storage.emplace_back(std::move(canonicalized_issuer(e)), std::move(commitment(e))); } // Please don't remove this VLOG without first checking with // trust_tokens/OWNERS to see if it's still being used for manual // testing. VLOG(1) << "Successfully parsed " << map_storage.size() << " issuers' Trust Tokens key commitments."; return std::make_unique<base::flat_map< SuitableTrustTokenOrigin, mojom::TrustTokenKeyCommitmentResultPtr>>( std::move(map_storage)); } } // namespace network
4,290
306
<gh_stars>100-1000 import numpy as __np__ from numpy import sqrt as __sqrt__ from numpy import cos as __cos__ from numpy import sin as __sin__ import matplotlib.pyplot as __plt__ from matplotlib import cm as __cm__ from matplotlib.ticker import LinearLocator as __LinearLocator__ from matplotlib.ticker import FormatStrFormatter as __FormatStrFormatter__ #generate test surface figure def makecircle(a, r, PR): max = a.max() size = __np__.sqrt(a.size) for i in range(int(size)): for j in range(int(size)): if __np__.sqrt(r[i]**2+r[j]**2) > PR: a[i,j] = max def testsurface2(): lambda_1 = 632*(10**-9) PR = 1 r = __np__.linspace(-PR, PR, 200) x, y = __np__.meshgrid(r,r) r1 = __np__.sqrt(x**2 + y**2) Z4 = 1 Z5 = 0.6 ZX = Z4 * __np__.sqrt(3)*(2*r1**2-1) + Z5*2*__np__.sqrt(6)*x*y OPD = ZX*2/PR ph = 2 * __np__.pi * OPD Ia = 1 Ib = 1 Ixy = Ia + Ib + 2 * __np__.sqrt(Ia*Ib) * __np__.cos(ph) makecircle(Ixy, r, PR) fig = __plt__.figure(figsize=(9, 6), dpi=80) __plt__.imshow(-Ixy, extent=[-PR,PR,-PR,PR]) __plt__.set_cmap('Greys') __plt__.show() I1 = Ia + Ib + 2 * __np__.sqrt(Ia*Ib) * __np__.cos(ph) I2 = Ia + Ib + 2 * __np__.sqrt(Ia*Ib) * __np__.cos(ph+45.0/180*__np__.pi) I3 = Ia + Ib + 2 * __np__.sqrt(Ia*Ib) * __np__.cos(ph+90.0/180*__np__.pi) I4 = Ia + Ib + 2 * __np__.sqrt(Ia*Ib) * __np__.cos(ph+135.0/180*__np__.pi) Ilist = [I1,I2,I3,I4] for i in range(4): makecircle(Ilist[i], r, PR) fig = __plt__.figure(figsize=(9, 6), dpi=80) __plt__.imshow(-Ilist[i], extent=[-PR,PR,-PR,PR]) __plt__.set_cmap('Greys') __plt__.show() ph1 = __np__.arctan((I4-I2)/(I1-I3)) Ixy1 = Ia + Ib + 2 * __np__.sqrt(Ia*Ib) * __np__.cos(ph1) fig = __plt__.figure(figsize=(9, 6), dpi=80) __plt__.imshow(-Ixy, extent=[-PR,PR,-PR,PR]) __plt__.set_cmap('Greys') __plt__.show() OPD = ph*PR/2 Z = OPD fig = __plt__.figure(figsize=(6, 6), dpi=80) #ax = fig.gca(projection='3d') #surf = ax.plot_surface(x, y, Z, rstride=1, cstride=1, cmap=__cm__.RdYlGn,linewidth=0, antialiased=False, alpha = 0.6) im = __plt__.pcolormesh(x, y, Z, cmap=__cm__.RdYlGn) __plt__.colorbar() __plt__.show() for i in range(len(Z)): for j in range(len(Z)): if r[i]**2+r[j]**2>1: Z[i][j]=0 fig = __plt__.figure(figsize=(6, 6), dpi=80) im = __plt__.pcolormesh(x, y, Z, cmap=__cm__.RdYlGn) __plt__.colorbar() __plt__.show() return Z
1,252
1,239
<filename>prog/fuzzing/recog_basic_fuzzer.cc<gh_stars>1000+ #include "leptfuzz.h" #include <sys/types.h> #include <unistd.h> extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { leptSetStdNullHandler(); L_RECOG *recog; char filename[256]; sprintf(filename, "/tmp/libfuzzer.%d", getppid()); FILE *fp = fopen(filename, "wb"); if (!fp) return 0; fwrite(data, size, 1, fp); fclose(fp); recog = recogRead(filename); recogDestroy(&recog); unlink(filename); return 0; }
260
411
/* * 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.giraph.block_app.library.pagerank; import org.apache.giraph.block_app.framework.AbstractBlockFactory; import org.apache.giraph.block_app.framework.block.Block; import org.apache.giraph.comm.messages.MessageEncodeAndStoreType; import org.apache.giraph.conf.GiraphConfiguration; import org.apache.giraph.conf.GiraphConstants; import org.apache.giraph.edge.LongDoubleArrayEdges; import org.apache.giraph.edge.LongNullArrayEdges; import org.apache.giraph.graph.Vertex; import org.apache.hadoop.io.DoubleWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Writable; import org.apache.hadoop.io.WritableComparable; /** * Block factory for pagerank */ public class PageRankBlockFactory extends AbstractBlockFactory<Object> { @Override protected Class<? extends WritableComparable> getVertexIDClass( GiraphConfiguration conf) { return LongWritable.class; } @Override protected Class<? extends Writable> getVertexValueClass( GiraphConfiguration conf) { return DoubleWritable.class; } @Override protected Class<? extends Writable> getEdgeValueClass( GiraphConfiguration conf) { return PageRankSettings.isWeighted(conf) ? DoubleWritable.class : NullWritable.class; } @Override public Block createBlock(GiraphConfiguration conf) { if (PageRankSettings.isWeighted(conf)) { return PageRankBlockUtils.<LongWritable, DoubleWritable>weightedPagerank( (vertex, value) -> vertex.getValue().set(value.get()), Vertex::getValue, conf); } else { return PageRankBlockUtils.<LongWritable, DoubleWritable>unweightedPagerank( (vertex, value) -> vertex.getValue().set(value.get()), Vertex::getValue, conf); } } @Override public Object createExecutionStage(GiraphConfiguration conf) { return new Object(); } @Override protected void additionalInitConfig(GiraphConfiguration conf) { conf.setVertexValueFactoryClass(PageRankVertexValueFactory.class); if (PageRankSettings.isWeighted(conf)) { conf.setOutEdgesClass(LongDoubleArrayEdges.class); } else { // Save on network traffic by only sending one message value per worker GiraphConstants.MESSAGE_ENCODE_AND_STORE_TYPE.setIfUnset( conf, MessageEncodeAndStoreType.EXTRACT_BYTEARRAY_PER_PARTITION); conf.setOutEdgesClass(LongNullArrayEdges.class); } } }
1,108
970
<reponame>octopuserectus/nx-hbmenu<gh_stars>100-1000 #pragma once typedef struct { uint32_t width; uint32_t height; color_t *bg; char *text; } MessageBox; void menuCreateMsgBox(int width, int height, const char *text); void menuCloseMsgBox(); bool menuIsMsgBoxOpen(); void menuDrawMsgBox(void); MessageBox menuGetCurrentMsgBox(); void menuMsgBoxSetNetloaderState(bool enabled, const char *text, bool enable_progress, float progress);
161
543
package com.riiablo.excel; import org.junit.Test; public class SerializerGeneratorTest { @Test public void test() { } }
47
2,151
package org.mockito.internal.matchers.text; import java.util.Iterator; import static java.lang.String.valueOf; /** * Prints a Java object value in a way humans can read it neatly. * Inspired on hamcrest. Used for printing arguments in verification errors. */ public class ValuePrinter { /** * Prints given value so that it is neatly readable by humans. * Handles explosive toString() implementations. */ public static String print(Object value) { if (value == null) { return "null"; } else if (value instanceof String) { return "\"" + value + "\""; } else if (value instanceof Character) { return printChar((Character) value); } else if (value.getClass().isArray()) { return printValues("[", ", ", "]", new org.mockito.internal.matchers.text.ArrayIterator(value)); } else if (value instanceof FormattedText) { return (((FormattedText) value).getText()); } return descriptionOf(value); } /** * Print values in a nice format, e.g. (1, 2, 3) * * @param start the beginning of the values, e.g. "(" * @param separator the separator of values, e.g. ", " * @param end the end of the values, e.g. ")" * @param values the values to print * * @return neatly formatted value list */ public static String printValues(String start, String separator, String end, Iterator values) { if(start == null){ start = "("; } if (separator == null){ separator = ","; } if (end == null){ end = ")"; } if (values == null){ values = new ArrayIterator(new String[]{""}); } StringBuilder sb = new StringBuilder(start); while(values.hasNext()) { sb.append(print(values.next())); if (values.hasNext()) { sb.append(separator); } } return sb.append(end).toString(); } private static String printChar(char value) { StringBuilder sb = new StringBuilder(); sb.append('\''); switch (value) { case '"': sb.append("\\\""); break; case '\n': sb.append("\\n"); break; case '\r': sb.append("\\r"); break; case '\t': sb.append("\\t"); break; default: sb.append(value); } sb.append('\''); return sb.toString(); } private static String descriptionOf(Object value) { try { return valueOf(value); } catch (Exception e) { return value.getClass().getName() + "@" + Integer.toHexString(value.hashCode()); } } }
1,357
433
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 4.0.0 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ package xyz.redtorch.gateway.ctp.x64v6v3v19t1v.api; public class CThostFtdcExchangeOrderField { private transient long swigCPtr; protected transient boolean swigCMemOwn; protected CThostFtdcExchangeOrderField(long cPtr, boolean cMemoryOwn) { swigCMemOwn = cMemoryOwn; swigCPtr = cPtr; } protected static long getCPtr(CThostFtdcExchangeOrderField obj) { return (obj == null) ? 0 : obj.swigCPtr; } @SuppressWarnings("deprecation") protected void finalize() { delete(); } public synchronized void delete() { if (swigCPtr != 0) { if (swigCMemOwn) { swigCMemOwn = false; jctpv6v3v19t1x64apiJNI.delete_CThostFtdcExchangeOrderField(swigCPtr); } swigCPtr = 0; } } public void setOrderPriceType(char value) { jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_OrderPriceType_set(swigCPtr, this, value); } public char getOrderPriceType() { return jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_OrderPriceType_get(swigCPtr, this); } public void setDirection(char value) { jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_Direction_set(swigCPtr, this, value); } public char getDirection() { return jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_Direction_get(swigCPtr, this); } public void setCombOffsetFlag(String value) { jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_CombOffsetFlag_set(swigCPtr, this, value); } public String getCombOffsetFlag() { return jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_CombOffsetFlag_get(swigCPtr, this); } public void setCombHedgeFlag(String value) { jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_CombHedgeFlag_set(swigCPtr, this, value); } public String getCombHedgeFlag() { return jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_CombHedgeFlag_get(swigCPtr, this); } public void setLimitPrice(double value) { jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_LimitPrice_set(swigCPtr, this, value); } public double getLimitPrice() { return jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_LimitPrice_get(swigCPtr, this); } public void setVolumeTotalOriginal(int value) { jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_VolumeTotalOriginal_set(swigCPtr, this, value); } public int getVolumeTotalOriginal() { return jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_VolumeTotalOriginal_get(swigCPtr, this); } public void setTimeCondition(char value) { jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_TimeCondition_set(swigCPtr, this, value); } public char getTimeCondition() { return jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_TimeCondition_get(swigCPtr, this); } public void setGTDDate(String value) { jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_GTDDate_set(swigCPtr, this, value); } public String getGTDDate() { return jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_GTDDate_get(swigCPtr, this); } public void setVolumeCondition(char value) { jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_VolumeCondition_set(swigCPtr, this, value); } public char getVolumeCondition() { return jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_VolumeCondition_get(swigCPtr, this); } public void setMinVolume(int value) { jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_MinVolume_set(swigCPtr, this, value); } public int getMinVolume() { return jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_MinVolume_get(swigCPtr, this); } public void setContingentCondition(char value) { jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_ContingentCondition_set(swigCPtr, this, value); } public char getContingentCondition() { return jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_ContingentCondition_get(swigCPtr, this); } public void setStopPrice(double value) { jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_StopPrice_set(swigCPtr, this, value); } public double getStopPrice() { return jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_StopPrice_get(swigCPtr, this); } public void setForceCloseReason(char value) { jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_ForceCloseReason_set(swigCPtr, this, value); } public char getForceCloseReason() { return jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_ForceCloseReason_get(swigCPtr, this); } public void setIsAutoSuspend(int value) { jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_IsAutoSuspend_set(swigCPtr, this, value); } public int getIsAutoSuspend() { return jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_IsAutoSuspend_get(swigCPtr, this); } public void setBusinessUnit(String value) { jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_BusinessUnit_set(swigCPtr, this, value); } public String getBusinessUnit() { return jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_BusinessUnit_get(swigCPtr, this); } public void setRequestID(int value) { jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_RequestID_set(swigCPtr, this, value); } public int getRequestID() { return jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_RequestID_get(swigCPtr, this); } public void setOrderLocalID(String value) { jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_OrderLocalID_set(swigCPtr, this, value); } public String getOrderLocalID() { return jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_OrderLocalID_get(swigCPtr, this); } public void setExchangeID(String value) { jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_ExchangeID_set(swigCPtr, this, value); } public String getExchangeID() { return jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_ExchangeID_get(swigCPtr, this); } public void setParticipantID(String value) { jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_ParticipantID_set(swigCPtr, this, value); } public String getParticipantID() { return jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_ParticipantID_get(swigCPtr, this); } public void setClientID(String value) { jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_ClientID_set(swigCPtr, this, value); } public String getClientID() { return jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_ClientID_get(swigCPtr, this); } public void setExchangeInstID(String value) { jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_ExchangeInstID_set(swigCPtr, this, value); } public String getExchangeInstID() { return jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_ExchangeInstID_get(swigCPtr, this); } public void setTraderID(String value) { jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_TraderID_set(swigCPtr, this, value); } public String getTraderID() { return jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_TraderID_get(swigCPtr, this); } public void setInstallID(int value) { jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_InstallID_set(swigCPtr, this, value); } public int getInstallID() { return jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_InstallID_get(swigCPtr, this); } public void setOrderSubmitStatus(char value) { jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_OrderSubmitStatus_set(swigCPtr, this, value); } public char getOrderSubmitStatus() { return jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_OrderSubmitStatus_get(swigCPtr, this); } public void setNotifySequence(int value) { jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_NotifySequence_set(swigCPtr, this, value); } public int getNotifySequence() { return jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_NotifySequence_get(swigCPtr, this); } public void setTradingDay(String value) { jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_TradingDay_set(swigCPtr, this, value); } public String getTradingDay() { return jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_TradingDay_get(swigCPtr, this); } public void setSettlementID(int value) { jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_SettlementID_set(swigCPtr, this, value); } public int getSettlementID() { return jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_SettlementID_get(swigCPtr, this); } public void setOrderSysID(String value) { jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_OrderSysID_set(swigCPtr, this, value); } public String getOrderSysID() { return jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_OrderSysID_get(swigCPtr, this); } public void setOrderSource(char value) { jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_OrderSource_set(swigCPtr, this, value); } public char getOrderSource() { return jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_OrderSource_get(swigCPtr, this); } public void setOrderStatus(char value) { jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_OrderStatus_set(swigCPtr, this, value); } public char getOrderStatus() { return jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_OrderStatus_get(swigCPtr, this); } public void setOrderType(char value) { jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_OrderType_set(swigCPtr, this, value); } public char getOrderType() { return jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_OrderType_get(swigCPtr, this); } public void setVolumeTraded(int value) { jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_VolumeTraded_set(swigCPtr, this, value); } public int getVolumeTraded() { return jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_VolumeTraded_get(swigCPtr, this); } public void setVolumeTotal(int value) { jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_VolumeTotal_set(swigCPtr, this, value); } public int getVolumeTotal() { return jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_VolumeTotal_get(swigCPtr, this); } public void setInsertDate(String value) { jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_InsertDate_set(swigCPtr, this, value); } public String getInsertDate() { return jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_InsertDate_get(swigCPtr, this); } public void setInsertTime(String value) { jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_InsertTime_set(swigCPtr, this, value); } public String getInsertTime() { return jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_InsertTime_get(swigCPtr, this); } public void setActiveTime(String value) { jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_ActiveTime_set(swigCPtr, this, value); } public String getActiveTime() { return jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_ActiveTime_get(swigCPtr, this); } public void setSuspendTime(String value) { jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_SuspendTime_set(swigCPtr, this, value); } public String getSuspendTime() { return jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_SuspendTime_get(swigCPtr, this); } public void setUpdateTime(String value) { jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_UpdateTime_set(swigCPtr, this, value); } public String getUpdateTime() { return jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_UpdateTime_get(swigCPtr, this); } public void setCancelTime(String value) { jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_CancelTime_set(swigCPtr, this, value); } public String getCancelTime() { return jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_CancelTime_get(swigCPtr, this); } public void setActiveTraderID(String value) { jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_ActiveTraderID_set(swigCPtr, this, value); } public String getActiveTraderID() { return jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_ActiveTraderID_get(swigCPtr, this); } public void setClearingPartID(String value) { jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_ClearingPartID_set(swigCPtr, this, value); } public String getClearingPartID() { return jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_ClearingPartID_get(swigCPtr, this); } public void setSequenceNo(int value) { jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_SequenceNo_set(swigCPtr, this, value); } public int getSequenceNo() { return jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_SequenceNo_get(swigCPtr, this); } public void setBranchID(String value) { jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_BranchID_set(swigCPtr, this, value); } public String getBranchID() { return jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_BranchID_get(swigCPtr, this); } public void setIPAddress(String value) { jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_IPAddress_set(swigCPtr, this, value); } public String getIPAddress() { return jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_IPAddress_get(swigCPtr, this); } public void setMacAddress(String value) { jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_MacAddress_set(swigCPtr, this, value); } public String getMacAddress() { return jctpv6v3v19t1x64apiJNI.CThostFtdcExchangeOrderField_MacAddress_get(swigCPtr, this); } public CThostFtdcExchangeOrderField() { this(jctpv6v3v19t1x64apiJNI.new_CThostFtdcExchangeOrderField(), true); } }
5,890
544
# from . import COCO_data_pipeline # from . import heatmap # from . import ImageAugmentation # from . import paf # from . import preprocessing
44
2,151
<reponame>zipated/src<filename>native_client/tests/pnacl_dynamic_loading/test_pll.c /* * Copyright (c) 2015 The Native Client Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ /* This is an example library, for testing the ConvertToPSO pass. */ /* Test imports referenced by variables */ extern int imported_var; extern int imported_var_addend; extern int imported_var2; extern int imported_var3; /* Relocation without an addend. */ int *reloc_var = &imported_var; /* Const relocation without an addend. */ int *const reloc_var_const = &imported_var; /* Relocation with an addend. */ int *reloc_var_addend = &imported_var_addend + 1; /* Const relocation with an addend. */ int *const reloc_var_const_addend = &imported_var_addend + 1; /* Relocations in a compound initializer, with addends. */ int *reloc_var_offset[] = { 0, &imported_var2 + 100, &imported_var3 + 200, 0 }; /* Const relocations in a compound initializer, with addends. */ int *const reloc_var_const_offset[] = { 0, &imported_var + 300, &imported_var + 400, 0 }; /* * Local (non-imported) relocation. Test that these still work and that * they don't get mixed up with relocations for imports. */ static int local_var = 1234; int *local_reloc_var = &local_var; /* Test imports referenced by functions */ int *get_imported_var(void) { return &imported_var; } int *get_imported_var_addend(void) { return &imported_var_addend + 1; } void imported_func(void); typedef void (*func_type_t)(void); func_type_t get_imported_func(void) { return imported_func; } /* Test exports */ int var = 2345; int *get_var(void) { return &var; } int example_func(void) { return 5678; } /* Test aliases */ extern int var_alias __attribute__((alias("var"))); void example_func_alias(void) __attribute__((alias("example_func")));
683
1,338
#include <../private/support/DataPositionIOWrapper.h>
18
732
<gh_stars>100-1000 /* Copyright 2014 Adobe Systems Incorporated (http://www.adobe.com/). All Rights Reserved. This software is licensed as OpenSource, under the Apache License, Version 2.0. This license is available at: http://opensource.org/licenses/Apache-2.0. */ /* * Shared TrueType Open format definitions. */ #ifndef FORMAT_TTO_H #define FORMAT_TTO_H /* Special types */ typedef Card32 Tag; /* In the file an Offset is a byte offset of data relative to some format component, normally the beginning of the record it belongs to. The OFFSET macros allow a simple declaration of both the byte offset field and a structure containing the data for that offset. */ typedef Card16 Offset; typedef Card32 LOffset; #define OFFSET(type, name) \ Offset name; \ type _##name #define OFFSET_ARRAY(type, name) \ Offset *name; \ type *_##name #define LOFFSET(type, name) \ LOffset name; \ type _##name #define LOFFSET_ARRAY(type, name) \ LOffset *name; \ type *_##name /* --- ScriptList --- */ typedef struct { Offset LookupOrder; /* => LookupOrder, Reserved=NULL */ Card16 ReqFeatureIndex; Card16 FeatureCount; Card16 *FeatureIndex; /* [FeatureCount] */ } LangSys; typedef struct { Tag LangSysTag; OFFSET(LangSys, LangSys); /* From Script */ } LangSysRecord; typedef struct { OFFSET(LangSys, DefaultLangSys); Card16 LangSysCount; LangSysRecord *LangSysRecord; /* [LangSysCount] */ } Script; typedef struct { Tag ScriptTag; OFFSET(Script, Script); /* From ScriptList */ } ScriptRecord; typedef struct { Card16 ScriptCount; ScriptRecord *ScriptRecord; /* [ScriptCount] */ } ScriptList; /* --- FeatureList --- */ typedef void *FeatureParam; /* Fake type until MS specs this */ typedef struct { OFFSET(FeatureParam, FeatureParam); /* =>FeatureParam, Reserved=NULL */ Card16 LookupCount; Card16 *LookupListIndex; /* [LookupCount] */ } Feature; typedef struct { Tag FeatureTag; OFFSET(Feature, Feature); /* From FeatureList */ } FeatureRecord; typedef struct { Card16 FeatureCount; FeatureRecord *FeatureRecord; /* [FeatureCount] */ } FeatureList; /* --- LookupList --- */ typedef struct { Card16 LookupType; Card16 LookupFlag; #define RightToLeft (1 << 0) #define IgnoreBaseGlyphs (1 << 1) #define IgnoreLigatures (1 << 2) #define IgnoreMarks (1 << 3) #define UseMarkFilteringSet (1 << 4) #define MarkAttachmentType (0xFF00) #define kNumNamedLookups 6 #define DumpLookupSeen (1 << 8) /* our own flag for "spot" */ Card16 SubTableCount; OFFSET_ARRAY(void *, SubTable); /* [SubTableCount] */ Card16 MarkFilteringSet; } Lookup; typedef struct { Card16 LookupCount; OFFSET_ARRAY(Lookup, Lookup); /* [LookupCount] */ } LookupList; /* --- Coverage --- */ typedef struct { Card16 CoverageFormat; /* =1 */ Card16 GlyphCount; GlyphId *GlyphArray; /* [GlyphCount] */ } CoverageFormat1; typedef struct { GlyphId Start; GlyphId End; Card16 StartCoverageIndex; } RangeRecord; typedef struct { Card16 CoverageFormat; /* =2 */ Card16 RangeCount; RangeRecord *RangeRecord; /* [RangeCount] */ } CoverageFormat2; /* --- ClassDef --- */ typedef struct { Card16 ClassFormat; /* =1 */ GlyphId StartGlyph; Card16 GlyphCount; Card16 *ClassValueArray; /* [GlyphCount] */ } ClassDefFormat1; typedef struct { GlyphId Start; GlyphId End; Card16 Class; } ClassRangeRecord; typedef struct { Card16 ClassFormat; /* =2 */ Card16 ClassRangeCount; ClassRangeRecord *ClassRangeRecord; /* [ClassRangeCount] */ } ClassDefFormat2; /* --- DeviceTable --- */ typedef struct { Card16 StartSize; Card16 EndSize; Card16 DeltaFormat; #define DeltaBits2 1 #define DeltaBits4 2 #define DeltaBits8 3 Card16 *DeltaValue; /* [((EndSize-StartSize+1)*(2^DeltaFormat)+15)/16] */ } DeviceTable; #endif /* FORMAT_TTO_H */
1,529