max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
2,728
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- # Main Client from ._client import ModelsRepositoryClient # Constants from ._client import ( DEPENDENCY_MODE_DISABLED, DEPENDENCY_MODE_ENABLED, DEPENDENCY_MODE_TRY_FROM_EXPANDED, ) # Error handling from .exceptions import ModelError __all__ = [ "ModelsRepositoryClient", "ModelError", "DEPENDENCY_MODE_DISABLED", "DEPENDENCY_MODE_ENABLED", "DEPENDENCY_MODE_TRY_FROM_EXPANDED", ] from ._constants import VERSION __version__ = VERSION
228
1,483
/* * Copyright Lealone Database Group. * Licensed under the Server Side Public License, v 1. * Initial Developer: zhh */ package org.lealone.sql.expression.visitor; import java.util.Set; import org.lealone.db.DbObject; import org.lealone.db.table.Table; import org.lealone.sql.expression.ExpressionColumn; import org.lealone.sql.expression.SequenceValue; import org.lealone.sql.expression.aggregate.JavaAggregate; import org.lealone.sql.expression.function.JavaFunction; import org.lealone.sql.optimizer.TableFilter; import org.lealone.sql.query.Query; public class DependenciesVisitor extends VoidExpressionVisitor { private Set<DbObject> dependencies; public DependenciesVisitor(Set<DbObject> dependencies) { this.dependencies = dependencies; } public void addDependency(DbObject obj) { dependencies.add(obj); } public Set<DbObject> getDependencies() { return dependencies; } @Override public Void visitExpressionColumn(ExpressionColumn e) { if (e.getColumn() != null) addDependency(e.getColumn().getTable()); return null; } @Override public Void visitSequenceValue(SequenceValue e) { addDependency(e.getSequence()); return null; } @Override public Void visitJavaAggregate(JavaAggregate e) { addDependency(e.getUserAggregate()); super.visitJavaAggregate(e); return null; } @Override public Void visitJavaFunction(JavaFunction e) { addDependency(e.getFunctionAlias()); super.visitJavaFunction(e); return null; } @Override protected Void visitQuery(Query query) { super.visitQuery(query); for (int i = 0, size = query.getFilters().size(); i < size; i++) { TableFilter f = query.getFilters().get(i); Table table = f.getTable(); addDependency(table); table.addDependencies(dependencies); } return null; } }
776
340
//================================================================================================== /** EVE - Expressive Vector Engine Copyright : EVE Contributors & Maintainers SPDX-License-Identifier: MIT **/ //================================================================================================== #include "test.hpp" #include <eve/concept/value.hpp> #include <eve/constant/valmin.hpp> #include <eve/constant/valmax.hpp> #include <eve/function/asecpi.hpp> #include <eve/function/radinpi.hpp> #include <eve/function/diff/asecpi.hpp> #include <cmath> //================================================================================================== // Types tests //================================================================================================== EVE_TEST_TYPES( "Check return types of asecpi" , eve::test::simd::ieee_reals ) <typename T>(eve::as<T>) { using v_t = eve::element_type_t<T>; TTS_EXPR_IS( eve::asecpi(T()) , T); TTS_EXPR_IS( eve::asecpi(v_t()), v_t); }; //================================================================================================== // asecpi tests //================================================================================================== EVE_TEST( "Check behavior of asecpi on wide" , eve::test::simd::ieee_reals , eve::test::generate(eve::test::randoms(1.0, 100.0) , eve::test::randoms(1.0, eve::valmax) , eve::test::randoms(eve::valmin, -1.0) , eve::test::randoms(-100.0, -1.0)) ) <typename T>(T const& a0, T const& a1,T const& a2, T const& a3 ) { using eve::detail::map; using v_t = eve::element_type_t<T>; auto sasecpi = [](auto e) -> v_t { return eve::radinpi(std::acos(1/e)); }; auto dasecpi = [](auto e) -> v_t { return eve::radinpi(v_t(1)/(std::abs(e)*std::sqrt(e*e-1))); }; TTS_ULP_EQUAL(eve::asecpi(a0) , map(sasecpi, a0), 2); TTS_ULP_EQUAL(eve::diff(eve::asecpi)(a0), map(dasecpi, a0), 2); TTS_ULP_EQUAL(eve::asecpi(a1) , map(sasecpi, a1), 2); TTS_ULP_EQUAL(eve::diff(eve::asecpi)(a1), map(dasecpi, a1), 2); TTS_ULP_EQUAL(eve::asecpi(a2) , map(sasecpi, a2), 2); TTS_ULP_EQUAL(eve::diff(eve::asecpi)(a2), map(dasecpi, a2), 2); TTS_ULP_EQUAL(eve::asecpi(a3) , map(sasecpi, a3), 2); TTS_ULP_EQUAL(eve::diff(eve::asecpi)(a3), map(dasecpi, a3), 2); };
1,014
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_framework.hxx" //_________________________________________________________________________________________________________________ // my own includes //_________________________________________________________________________________________________________________ #include "uifactory/factoryconfiguration.hxx" #include <threadhelp/resetableguard.hxx> #include "services.h" //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #include <com/sun/star/beans/PropertyValue.hpp> #include <com/sun/star/beans/XPropertySet.hpp> #include <com/sun/star/container/XNameAccess.hpp> #include <com/sun/star/container/XNameContainer.hpp> #include <com/sun/star/container/XContainer.hpp> //_________________________________________________________________________________________________________________ // includes of other projects //_________________________________________________________________________________________________________________ #include <rtl/ustrbuf.hxx> #include <cppuhelper/weak.hxx> #include <rtl/logfile.hxx> //_________________________________________________________________________________________________________________ // Defines //_________________________________________________________________________________________________________________ // using namespace com::sun::star; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::beans; using namespace com::sun::star::container; //_________________________________________________________________________________________________________________ // Namespace //_________________________________________________________________________________________________________________ // namespace framework { rtl::OUString getHashKeyFromStrings( const rtl::OUString& aCommandURL, const rtl::OUString& aModuleName ) { rtl::OUStringBuffer aKey( aCommandURL ); aKey.appendAscii( "-" ); aKey.append( aModuleName ); return aKey.makeStringAndClear(); } //***************************************************************************************************************** // XInterface, XTypeProvider //***************************************************************************************************************** ConfigurationAccess_ControllerFactory::ConfigurationAccess_ControllerFactory( Reference< XMultiServiceFactory >& rServiceManager,const ::rtl::OUString& _sRoot,bool _bAskValue ) : ThreadHelpBase(), m_aPropCommand( RTL_CONSTASCII_USTRINGPARAM( "Command" )), m_aPropModule( RTL_CONSTASCII_USTRINGPARAM( "Module" )), m_aPropController( RTL_CONSTASCII_USTRINGPARAM( "Controller" )), m_aPropValue( RTL_CONSTASCII_USTRINGPARAM( "Value" )), m_sRoot(_sRoot), m_xServiceManager( rServiceManager ), m_bConfigAccessInitialized( sal_False ), m_bAskValue(_bAskValue) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "framework", "<EMAIL>", "ConfigurationAccess_ControllerFactory::ConfigurationAccess_ControllerFactory" ); m_xConfigProvider = Reference< XMultiServiceFactory >( rServiceManager->createInstance( SERVICENAME_CFGPROVIDER),UNO_QUERY ); } ConfigurationAccess_ControllerFactory::~ConfigurationAccess_ControllerFactory() { // SAFE ResetableGuard aLock( m_aLock ); Reference< XContainer > xContainer( m_xConfigAccess, UNO_QUERY ); if ( xContainer.is() ) xContainer->removeContainerListener( this ); } rtl::OUString ConfigurationAccess_ControllerFactory::getServiceFromCommandModule( const rtl::OUString& rCommandURL, const rtl::OUString& rModule ) const { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "framework", "<EMAIL>", "ConfigurationAccess_ControllerFactory::getServiceFromCommandModule" ); // SAFE ResetableGuard aLock( m_aLock ); MenuControllerMap::const_iterator pIter = m_aMenuControllerMap.find( getHashKeyFromStrings( rCommandURL, rModule )); if ( pIter != m_aMenuControllerMap.end() ) return pIter->second.m_aImplementationName; else if ( rModule.getLength() ) { // Try to detect if we have a generic popup menu controller pIter = m_aMenuControllerMap.find( getHashKeyFromStrings( rCommandURL, rtl::OUString() )); if ( pIter != m_aMenuControllerMap.end() ) return pIter->second.m_aImplementationName; } return rtl::OUString(); } rtl::OUString ConfigurationAccess_ControllerFactory::getValueFromCommandModule( const rtl::OUString& rCommandURL, const rtl::OUString& rModule ) const { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "framework", "<EMAIL>", "ConfigurationAccess_ControllerFactory::getValueFromCommandModule" ); // SAFE ResetableGuard aLock( m_aLock ); MenuControllerMap::const_iterator pIter = m_aMenuControllerMap.find( getHashKeyFromStrings( rCommandURL, rModule )); if ( pIter != m_aMenuControllerMap.end() ) return pIter->second.m_aValue; else if ( rModule.getLength() ) { // Try to detect if we have a generic popup menu controller pIter = m_aMenuControllerMap.find( getHashKeyFromStrings( rCommandURL, rtl::OUString() )); if ( pIter != m_aMenuControllerMap.end() ) return pIter->second.m_aValue; } return rtl::OUString(); } void ConfigurationAccess_ControllerFactory::addServiceToCommandModule( const rtl::OUString& rCommandURL, const rtl::OUString& rModule, const rtl::OUString& rServiceSpecifier ) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "framework", "<EMAIL>", "ConfigurationAccess_ControllerFactory::addServiceToCommandModule" ); // SAFE ResetableGuard aLock( m_aLock ); rtl::OUString aHashKey = getHashKeyFromStrings( rCommandURL, rModule ); m_aMenuControllerMap.insert( MenuControllerMap::value_type( aHashKey,ControllerInfo(rServiceSpecifier,::rtl::OUString()) )); } void ConfigurationAccess_ControllerFactory::removeServiceFromCommandModule( const rtl::OUString& rCommandURL, const rtl::OUString& rModule ) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "framework", "<EMAIL>", "ConfigurationAccess_ControllerFactory::removeServiceFromCommandModule" ); // SAFE ResetableGuard aLock( m_aLock ); rtl::OUString aHashKey = getHashKeyFromStrings( rCommandURL, rModule ); m_aMenuControllerMap.erase( aHashKey ); } // container.XContainerListener void SAL_CALL ConfigurationAccess_ControllerFactory::elementInserted( const ContainerEvent& aEvent ) throw(RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "framework", "<EMAIL>", "ConfigurationAccess_ControllerFactory::elementInserted" ); rtl::OUString aCommand; rtl::OUString aModule; rtl::OUString aService; rtl::OUString aValue; // SAFE ResetableGuard aLock( m_aLock ); if ( impl_getElementProps( aEvent.Element, aCommand, aModule, aService, aValue )) { // Create hash key from command and module as they are together a primary key to // the UNO service that implements the popup menu controller. rtl::OUString aHashKey( getHashKeyFromStrings( aCommand, aModule )); ControllerInfo& rControllerInfo = m_aMenuControllerMap[ aHashKey ]; rControllerInfo.m_aImplementationName = aService; rControllerInfo.m_aValue = aValue; } } void SAL_CALL ConfigurationAccess_ControllerFactory::elementRemoved ( const ContainerEvent& aEvent ) throw(RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "framework", "<EMAIL>", "ConfigurationAccess_ControllerFactory::elementRemoved" ); rtl::OUString aCommand; rtl::OUString aModule; rtl::OUString aService; rtl::OUString aValue; // SAFE ResetableGuard aLock( m_aLock ); if ( impl_getElementProps( aEvent.Element, aCommand, aModule, aService, aValue )) { // Create hash key from command and module as they are together a primary key to // the UNO service that implements the popup menu controller. rtl::OUString aHashKey( getHashKeyFromStrings( aCommand, aModule )); m_aMenuControllerMap.erase( aHashKey ); } } void SAL_CALL ConfigurationAccess_ControllerFactory::elementReplaced( const ContainerEvent& aEvent ) throw(RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "framework", "<EMAIL>", "ConfigurationAccess_ControllerFactory::elementReplaced" ); elementInserted(aEvent); } // lang.XEventListener void SAL_CALL ConfigurationAccess_ControllerFactory::disposing( const EventObject& ) throw(RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "framework", "<EMAIL>", "ConfigurationAccess_ControllerFactory::disposing" ); // SAFE // remove our reference to the config access ResetableGuard aLock( m_aLock ); m_xConfigAccess.clear(); } void ConfigurationAccess_ControllerFactory::readConfigurationData() { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "framework", "<EMAIL>", "ConfigurationAccess_ControllerFactory::readConfigurationData" ); // SAFE ResetableGuard aLock( m_aLock ); if ( !m_bConfigAccessInitialized ) { Sequence< Any > aArgs( 1 ); PropertyValue aPropValue; aPropValue.Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "nodepath" )); aPropValue.Value <<= m_sRoot; aArgs[0] <<= aPropValue; try { m_xConfigAccess = Reference< XNameAccess >( m_xConfigProvider->createInstanceWithArguments(SERVICENAME_CFGREADACCESS,aArgs ), UNO_QUERY ); } catch ( WrappedTargetException& ) { } m_bConfigAccessInitialized = sal_True; } if ( m_xConfigAccess.is() ) { // Read and update configuration data updateConfigurationData(); uno::Reference< container::XContainer > xContainer( m_xConfigAccess, uno::UNO_QUERY ); // UNSAFE aLock.unlock(); if ( xContainer.is() ) xContainer->addContainerListener( this ); } } void ConfigurationAccess_ControllerFactory::updateConfigurationData() { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "framework", "<EMAIL>", "ConfigurationAccess_ControllerFactory::updateConfigurationData" ); // SAFE ResetableGuard aLock( m_aLock ); if ( m_xConfigAccess.is() ) { Sequence< rtl::OUString > aPopupMenuControllers = m_xConfigAccess->getElementNames(); rtl::OUString aCommand; rtl::OUString aModule; rtl::OUString aService; rtl::OUString aHashKey; rtl::OUString aValue; m_aMenuControllerMap.clear(); for ( sal_Int32 i = 0; i < aPopupMenuControllers.getLength(); i++ ) { try { if ( impl_getElementProps( m_xConfigAccess->getByName( aPopupMenuControllers[i] ), aCommand, aModule, aService,aValue )) { // Create hash key from command and module as they are together a primary key to // the UNO service that implements the popup menu controller. aHashKey = getHashKeyFromStrings( aCommand, aModule ); m_aMenuControllerMap.insert( MenuControllerMap::value_type( aHashKey, ControllerInfo(aService,aValue) )); } } catch ( NoSuchElementException& ) { } catch ( WrappedTargetException& ) { } } } } sal_Bool ConfigurationAccess_ControllerFactory::impl_getElementProps( const Any& aElement, rtl::OUString& aCommand, rtl::OUString& aModule, rtl::OUString& aServiceSpecifier,rtl::OUString& aValue ) const { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "framework", "<EMAIL>", "ConfigurationAccess_ControllerFactory::impl_getElementProps" ); Reference< XPropertySet > xPropertySet; aElement >>= xPropertySet; if ( xPropertySet.is() ) { try { xPropertySet->getPropertyValue( m_aPropCommand ) >>= aCommand; xPropertySet->getPropertyValue( m_aPropModule ) >>= aModule; xPropertySet->getPropertyValue( m_aPropController ) >>= aServiceSpecifier; if ( m_bAskValue ) xPropertySet->getPropertyValue( m_aPropValue ) >>= aValue; } catch ( com::sun::star::beans::UnknownPropertyException& ) { return sal_False; } catch ( com::sun::star::lang::WrappedTargetException& ) { return sal_False; } } return sal_True; } } // namespace framework
4,748
460
#ifdef __WXMAC_CLASSIC__ #include "wx/mac/classic/listbox.h" #else #include "wx/mac/carbon/listbox.h" #endif
48
717
/* * $File: rbm.hh * $Date: Thu Nov 07 12:30:21 2013 +0000 * $Author: <NAME> <zxytim[at]gmail[dot]com> */ #pragma once #include <vector> #include "type.hh" #include "random.hh" /// Restricted Boltzmann Machine class RBM { public: // the visible_layer_size must match input dimension RBM(int visible_layer_size = 10, int hidden_layer_size = 10, int CD_k = 1, real_t learning_rate = 0.01, int batch_train_size = 100, bool hidden_use_probability = false, int n_iter_max = 20) { set_size(visible_layer_size, hidden_layer_size); this->learning_rate = learning_rate; this->CD_k = CD_k; this->hidden_use_probability = hidden_use_probability; this->batch_train_size = batch_train_size; this->n_iter_max = n_iter_max; } void set_size(int visible_layer_size, int hidden_layer_size); void set_CD_k(int CD_k) { this->CD_k = CD_k; } void set_learning_rate(real_t learning_rate) { this->learning_rate = learning_rate; } void set_n_iter_max(int n_iter_max) { this->n_iter_max = n_iter_max; } void set_batch_train_size(int batch_train_size) { this->batch_train_size = batch_train_size; } void dump(const char *fname); void load(const char *fname); /// currently, inputs are confined to binary. /// if real-valued inputs is given, a 0.5-threshold /// filter will be applied first. /// assuming all inputs are of the same distribution void fit(std::vector<std::vector<real_t>> &v); // fit one v at a time. this usually not workingc void fit_incremental(std::vector<real_t> &v); // begin and end are modulod by X.size() // if begin is greater than end, cycle from begin until reach end void fit_batch(std::vector<std::vector<real_t>> &X, int begin = 0, int end = 1); void reconstruct(std::vector<real_t> &v_in, std::vector<real_t> &v_out, int n_times = 1); void reconstruct_light(std::vector<real_t> &v_in, std::vector<real_t> &v_out, int n_times = 1); /// temporal array to store sample of /// hidden layer std::vector<real_t> h; std::vector<real_t> visible_layer_bias; std::vector<real_t> hidden_layer_bias; std::vector<std::vector<real_t>> w; // w[v][h] int get_hidden_layer_size() const { return hidden_layer_size; } int get_visible_layer_size() const { return visible_layer_size; } int get_batch_training_size() const { return batch_train_size; } void sample_hidden_layer(std::vector<real_t> &v, std::vector<real_t> &h, std::vector<real_t> &p); void sample_visible_layer(std::vector<real_t> &v, std::vector<real_t> &h); protected: real_t learning_rate; bool hidden_use_probability; int n_iter_max; int batch_train_size; int CD_k; int visible_layer_size, hidden_layer_size; Random random; /// seperate reconstruct purpose layer for clarity std::vector<real_t> h_reconstruct; /// temporary variable std::vector<std::vector<real_t>> w_0, w_inf; std::vector<real_t> v_0, v_inf; std::vector<real_t> h_0, h_inf; void reset_weights(); void resize_variables(); void resize_w(std::vector<std::vector<real_t>> &w); void update_parameters(std::vector<real_t> &v_0, std::vector<real_t> &h_0, std::vector<real_t> &v, std::vector<real_t> &h); void fit_batch_single(std::vector<real_t> &x); }; /** * vim: syntax=cpp11 foldmethod=marker */
1,316
349
<gh_stars>100-1000 /* * tcp.c - TCP support. */ #include <siri/net/tcp.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <uv.h> #include <xstr/xstr.h> #include <siri/cfg/cfg.h> #include <logger/logger.h> #define TCP_NAME_BUF_SZ 54 const char * sirinet_tcp_ip_support_str(uint8_t ip_support) { switch (ip_support) { case IP_SUPPORT_ALL: return "ALL"; case IP_SUPPORT_IPV4ONLY: return "IPV4ONLY"; case IP_SUPPORT_IPV6ONLY: return "IPV6ONLY"; default: return "UNKNOWN"; } } /* * Return a name for the connection if successful or NULL in case of a failure. * * The returned value is malloced and should be freed. */ char * sirinet_tcp_name(uv_tcp_t * client) { char * buffer = malloc(TCP_NAME_BUF_SZ); struct sockaddr_storage name; int namelen = sizeof(name); if (buffer == NULL || uv_tcp_getpeername(client, (struct sockaddr *) &name, &namelen)) { goto failed; } switch (name.ss_family) { case AF_INET: { char addr[INET_ADDRSTRLEN]; uv_inet_ntop( AF_INET, &((struct sockaddr_in *) &name)->sin_addr, addr, sizeof(addr)); sprintf( buffer, "%s:%d", addr, ntohs(((struct sockaddr_in *) &name)->sin_port)); } break; case AF_INET6: { char addr[INET6_ADDRSTRLEN]; uv_inet_ntop( AF_INET6, &((struct sockaddr_in6 *) &name)->sin6_addr, addr, sizeof(addr)); sprintf( buffer, "[%s]:%d", addr, ntohs(((struct sockaddr_in6 *) &name)->sin6_port)); } break; default: goto failed; } return buffer; failed: free(buffer); return NULL; } int sirinet_extract_addr_port( char * s, char * addr, uint16_t * addrport) { int test_port; char * strport; char * address; char hostname[SIRI_CFG_MAX_LEN_ADDRESS]; if (gethostname(hostname, SIRI_CFG_MAX_LEN_ADDRESS)) { log_debug( "Unable to read the systems host name. Since its only purpose " "is to apply this in the configuration file this might not be " "any problem. (using 'localhost' as fallback)"); strcpy(hostname, "localhost"); } if (*s == '[') { /* an IPv6 address... */ for (strport = address = s + 1; *strport; strport++) { if (*strport == ']') { *strport = 0; strport++; break; } } } else { strport = address = s; } for (; *strport; strport++) { if (*strport == ':') { *strport = 0; strport++; break; } } if (!strlen(address) || strlen(address) >= SIRI_CFG_MAX_LEN_ADDRESS) { log_error("error: got an unexpected address value '%s'.", s); return -1; } if (strcpy(addr, address) == NULL || xstr_replace_str( addr, "%HOSTNAME", hostname, SIRI_CFG_MAX_LEN_ADDRESS)) { log_critical("memory allocation while copying address"); return -1; } if (xstr_is_int(strport)) { test_port = atoi(strport); if (test_port < 1 || test_port > 65535) { log_error( "error: port should be between 1 and 65535, got '%d'.", test_port); return -1; } *addrport = (uint16_t) test_port; } log_debug("Read '%s': %s:%d", s, addr, *addrport); return 0; }
2,199
422
<gh_stars>100-1000 from all_models.models import TbAdminUserRoleRelation class UserRoleRelationService(object): @staticmethod def updateUserRole(userRoleData): tbModel = TbAdminUserRoleRelation.objects.filter(id=userRoleData["id"]) tbModel.update(**userRoleData)
107
432
from ..rfb_utils.operator_utils import get_bxdf_items, get_light_items, get_lightfilter_items from .. import rman_bl_nodes from .. import rfb_icons import bpy class NODE_MT_RM_Bxdf_Category_Menu(bpy.types.Menu): bl_label = "Bxdfs" bl_idname = "NODE_MT_RM_Bxdf_Category_Menu" @classmethod def poll(cls, context): rd = context.scene.render return rd.engine == 'PRMAN_RENDER' def draw(self, context): layout = self.layout nt = getattr(context, 'nodetree', None) for bxdf_cat, bxdfs in rman_bl_nodes.__RMAN_NODE_CATEGORIES__['bxdf'].items(): if not bxdfs[1]: continue tokens = bxdf_cat.split('_') if len(tokens) > 2: # this should be a subcategory/submenu continue bxdf_category = ' '.join(tokens[1:]) layout.context_pointer_set("nodetree", nt) layout.menu('NODE_MT_renderman_connection_submenu_%s' % bxdf_cat, text=bxdf_category.capitalize()) class NODE_MT_RM_Pattern_Category_Menu(bpy.types.Menu): bl_label = "Patterns" bl_idname = "NODE_MT_RM_Pattern_Category_Menu" @classmethod def poll(cls, context): rd = context.scene.render return rd.engine == 'PRMAN_RENDER' def draw(self, context): layout = self.layout nt = getattr(context, 'nodetree', None) for pattern_cat, patterns in rman_bl_nodes.__RMAN_NODE_CATEGORIES__['pattern'].items(): if not patterns[1]: continue tokens = pattern_cat.split('_') if len(tokens) > 2: # this should be a subcategory/submenu continue pattern_category = ' '.join(tokens[1:]) if pattern_category == 'pxrsurface': continue layout.context_pointer_set("nodetree", nt) layout.menu('NODE_MT_renderman_connection_submenu_%s' % pattern_cat, text=pattern_category.capitalize()) class NODE_MT_RM_Displacement_Category_Menu(bpy.types.Menu): bl_label = "Displacement" bl_idname = "NODE_MT_RM_Displacement_Category_Menu" @classmethod def poll(cls, context): rd = context.scene.render return rd.engine == 'PRMAN_RENDER' def draw(self, context): layout = self.layout nt = getattr(context, 'nodetree', None) for n in rman_bl_nodes.__RMAN_DISPLACE_NODES__: layout.context_pointer_set("nodetree", nt) rman_icon = rfb_icons.get_displacement_icon(n.name) op = layout.operator('node.rman_shading_create_node', text=n.name, icon_value=rman_icon.icon_id) op.node_name = n.name class NODE_MT_RM_PxrSurface_Category_Menu(bpy.types.Menu): bl_label = "PxrSurface" bl_idname = "NODE_MT_RM_PxrSurface_Category_Menu" @classmethod def poll(cls, context): rd = context.scene.render return rd.engine == 'PRMAN_RENDER' def draw(self, context): layout = self.layout nt = getattr(context, 'nodetree', None) node_name = 'PxrLayer' layout.context_pointer_set("nodetree", nt) rman_icon = rfb_icons.get_pattern_icon(node_name) op = layout.operator('node.rman_shading_create_node', text=node_name, icon_value=rman_icon.icon_id) op.node_name = node_name node_name = 'PxrLayerMixer' layout.context_pointer_set("nodetree", nt) rman_icon = rfb_icons.get_pattern_icon(node_name) op = layout.operator('node.rman_shading_create_node', text=node_name, icon_value=rman_icon.icon_id) op.node_name = node_name class NODE_MT_RM_Light_Category_Menu(bpy.types.Menu): bl_label = "Light" bl_idname = "NODE_MT_RM_Light_Category_Menu" @classmethod def poll(cls, context): rd = context.scene.render return rd.engine == 'PRMAN_RENDER' def draw(self, context): layout = self.layout nt = getattr(context, 'nodetree', None) node_name = 'PxrMeshLight' layout.context_pointer_set("nodetree", nt) rman_icon = rfb_icons.get_light_icon(node_name) op = layout.operator('node.rman_shading_create_node', text=node_name, icon_value=rman_icon.icon_id) op.node_name = node_name class NODE_MT_RM_Integrators_Category_Menu(bpy.types.Menu): bl_label = "Integrators" bl_idname = "NODE_MT_RM_Integrators_Category_Menu" @classmethod def poll(cls, context): rd = context.scene.render return rd.engine == 'PRMAN_RENDER' def draw(self, context): layout = self.layout nt = getattr(context, 'nodetree', None) for n in rman_bl_nodes.__RMAN_INTEGRATOR_NODES__: layout.context_pointer_set("nodetree", nt) rman_icon = rfb_icons.get_integrator_icon(n.name) op = layout.operator('node.rman_shading_create_node', text=n.name, icon_value=rman_icon.icon_id) op.node_name = n.name class NODE_MT_RM_SampleFilter_Category_Menu(bpy.types.Menu): bl_label = "Sample Filters" bl_idname = "NODE_MT_RM_SampleFilter_Category_Menu" @classmethod def poll(cls, context): rd = context.scene.render return rd.engine == 'PRMAN_RENDER' def draw(self, context): layout = self.layout nt = getattr(context, 'nodetree', None) for n in rman_bl_nodes.__RMAN_SAMPLEFILTER_NODES__: layout.context_pointer_set("nodetree", nt) rman_icon = rfb_icons.get_samplefilter_icon(n.name) op = layout.operator('node.rman_shading_create_node', text=n.name, icon_value=rman_icon.icon_id) op.node_name = n.name class NODE_MT_RM_DisplayFilter_Category_Menu(bpy.types.Menu): bl_label = "Display Filters" bl_idname = "NODE_MT_RM_DisplayFilter_Category_Menu" @classmethod def poll(cls, context): rd = context.scene.render return rd.engine == 'PRMAN_RENDER' def draw(self, context): layout = self.layout nt = getattr(context, 'nodetree', None) for n in rman_bl_nodes.__RMAN_DISPLAYFILTER_NODES__: layout.context_pointer_set("nodetree", nt) rman_icon = rfb_icons.get_displayfilter_icon(n.name) op = layout.operator('node.rman_shading_create_node', text=n.name, icon_value=rman_icon.icon_id) op.node_name = n.name classes = [ NODE_MT_RM_Bxdf_Category_Menu, NODE_MT_RM_Pattern_Category_Menu, NODE_MT_RM_Displacement_Category_Menu, NODE_MT_RM_PxrSurface_Category_Menu, NODE_MT_RM_Light_Category_Menu, NODE_MT_RM_Integrators_Category_Menu, NODE_MT_RM_SampleFilter_Category_Menu, NODE_MT_RM_DisplayFilter_Category_Menu ] def register(): for cls in classes: bpy.utils.register_class(cls) def unregister(): for cls in classes: try: bpy.utils.unregister_class(cls) except RuntimeError: rfb_log().debug('Could not unregister class: %s' % str(cls)) pass
3,543
551
<filename>profiles/msaaddev.json<gh_stars>100-1000 { "image": "https://user-images.githubusercontent.com/44341551/128627907-fbeb7a8a-f0d7-454f-a077-cf10c8876aaa.png", "issueId": 636, "name": "<NAME>", "username": "msaaddev" }
110
892
<reponame>github/advisory-database { "schema_version": "1.2.0", "id": "GHSA-w76g-6qc3-qpj6", "modified": "2022-05-13T01:46:41Z", "published": "2022-05-13T01:46:41Z", "aliases": [ "CVE-2017-6615" ], "details": "A vulnerability in the Simple Network Management Protocol (SNMP) subsystem of Cisco IOS XE 3.16 could allow an authenticated, remote attacker to cause a denial of service (DoS) condition. The vulnerability is due to a race condition that could occur when the affected software processes an SNMP read request that contains certain criteria for a specific object ID (OID) and an active crypto session is disconnected on an affected device. An attacker who can authenticate to an affected device could trigger this vulnerability by issuing an SNMP request for a specific OID on the device. A successful exploit will cause the device to restart due to an attempt to access an invalid memory region. The attacker does not control how or when crypto sessions are disconnected on the device. Cisco Bug IDs: CSCvb94392.", "severity": [ { "type": "CVSS_V3", "score": "CVSS:3.0/AV:N/AC:H/PR:L/UI:N/S:C/C:N/I:N/A:H" } ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2017-6615" }, { "type": "WEB", "url": "https://tools.cisco.com/security/center/content/CiscoSecurityAdvisory/cisco-sa-20170419-ios-xe-snmp" }, { "type": "WEB", "url": "http://www.securityfocus.com/bid/97930" }, { "type": "WEB", "url": "http://www.securitytracker.com/id/1038328" } ], "database_specific": { "cwe_ids": [ "CWE-362" ], "severity": "MODERATE", "github_reviewed": false } }
673
630
<gh_stars>100-1000 from flask import jsonify from flask_monitoringdashboard.controllers.outliers import get_outlier_graph, get_outlier_table from flask_monitoringdashboard.database.count import count_outliers from flask_monitoringdashboard.database import session_scope from flask_monitoringdashboard.core.auth import secure from flask_monitoringdashboard import blueprint @blueprint.route('/api/num_outliers/<endpoint_id>') @secure def num_outliers(endpoint_id): with session_scope() as session: return jsonify(count_outliers(session, endpoint_id)) @blueprint.route('/api/outlier_graph/<endpoint_id>') @secure def outlier_graph(endpoint_id): with session_scope() as session: return jsonify(get_outlier_graph(session, endpoint_id)) @blueprint.route('/api/outlier_table/<endpoint_id>/<offset>/<per_page>') @secure def outlier_table(endpoint_id, offset, per_page): with session_scope() as session: return jsonify(get_outlier_table(session, endpoint_id, offset, per_page))
352
2,151
<reponame>zipated/src // Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/bindings/core/v8/v8_script_runner.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/renderer/bindings/core/v8/referrer_script_info.h" #include "third_party/blink/renderer/bindings/core/v8/script_source_code.h" #include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h" #include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_testing.h" #include "third_party/blink/renderer/core/loader/resource/script_resource.h" #include "third_party/blink/renderer/platform/heap/handle.h" #include "third_party/blink/renderer/platform/loader/fetch/cached_metadata.h" #include "third_party/blink/renderer/platform/loader/fetch/cached_metadata_handler.h" #include "third_party/blink/renderer/platform/weborigin/kurl.h" #include "third_party/blink/renderer/platform/wtf/text/text_encoding.h" #include "v8/include/v8.h" namespace blink { namespace { class V8ScriptRunnerTest : public testing::Test { public: V8ScriptRunnerTest() = default; ~V8ScriptRunnerTest() override = default; void SetUp() override { // To trick various layers of caching, increment a counter for each // test and use it in Code() and Url(). counter_++; } WTF::String Code() const { // Simple function for testing. Note: // - Add counter to trick V8 code cache. // - Pad counter to 1000 digits, to trick minimal cacheability threshold. return WTF::String::Format("a = function() { 1 + 1; } // %01000d\n", counter_); } KURL Url() const { return KURL(WTF::String::Format("http://bla.com/bla%d", counter_)); } unsigned TagForCodeCache(SingleCachedMetadataHandler* cache_handler) const { return V8ScriptRunner::TagForCodeCache(cache_handler); } unsigned TagForTimeStamp(SingleCachedMetadataHandler* cache_handler) const { return V8ScriptRunner::TagForTimeStamp(cache_handler); } void SetCacheTimeStamp(SingleCachedMetadataHandler* cache_handler) { V8ScriptRunner::SetCacheTimeStamp(cache_handler); } bool CompileScript(v8::Isolate* isolate, ScriptState* script_state, const ScriptSourceCode& source_code, V8CacheOptions cache_options) { v8::ScriptCompiler::CompileOptions compile_options; V8ScriptRunner::ProduceCacheOptions produce_cache_options; v8::ScriptCompiler::NoCacheReason no_cache_reason; std::tie(compile_options, produce_cache_options, no_cache_reason) = V8ScriptRunner::GetCompileOptions(cache_options, source_code); v8::MaybeLocal<v8::Script> compiled_script = V8ScriptRunner::CompileScript( script_state, source_code, kNotSharableCrossOrigin, compile_options, no_cache_reason, ReferrerScriptInfo()); if (compiled_script.IsEmpty()) { return false; } V8ScriptRunner::ProduceCache(isolate, compiled_script.ToLocalChecked(), source_code, produce_cache_options, compile_options); return true; } bool CompileScript( v8::Isolate* isolate, ScriptState* script_state, const ScriptSourceCode& source_code, v8::ScriptCompiler::CompileOptions compile_options, v8::ScriptCompiler::NoCacheReason no_cache_reason, V8ScriptRunner::ProduceCacheOptions produce_cache_options) { v8::MaybeLocal<v8::Script> compiled_script = V8ScriptRunner::CompileScript( script_state, source_code, kNotSharableCrossOrigin, compile_options, no_cache_reason, ReferrerScriptInfo()); if (compiled_script.IsEmpty()) { return false; } V8ScriptRunner::ProduceCache(isolate, compiled_script.ToLocalChecked(), source_code, produce_cache_options, compile_options); return true; } ScriptResource* CreateEmptyResource() { return ScriptResource::CreateForTest(NullURL(), UTF8Encoding()); } ScriptResource* CreateResource(const WTF::TextEncoding& encoding) { ScriptResource* resource = ScriptResource::CreateForTest(Url(), encoding); String code = Code(); ResourceResponse response(Url()); response.SetHTTPStatusCode(200); resource->SetResponse(response); resource->AppendData(code.Utf8().data(), code.Utf8().length()); resource->FinishForTest(); return resource; } protected: static int counter_; }; int V8ScriptRunnerTest::counter_ = 0; TEST_F(V8ScriptRunnerTest, resourcelessShouldPass) { V8TestingScope scope; ScriptSourceCode source_code(Code(), ScriptSourceLocationType::kInternal, nullptr /* cache_handler */, Url()); EXPECT_TRUE(CompileScript(scope.GetIsolate(), scope.GetScriptState(), source_code, kV8CacheOptionsNone)); EXPECT_TRUE(CompileScript(scope.GetIsolate(), scope.GetScriptState(), source_code, kV8CacheOptionsCode)); } TEST_F(V8ScriptRunnerTest, emptyResourceDoesNotHaveCacheHandler) { ScriptResource* resource = CreateEmptyResource(); EXPECT_FALSE(resource->CacheHandler()); } TEST_F(V8ScriptRunnerTest, codeOption) { V8TestingScope scope; ScriptSourceCode source_code(nullptr, CreateResource(UTF8Encoding())); SingleCachedMetadataHandler* cache_handler = source_code.CacheHandler(); SetCacheTimeStamp(cache_handler); EXPECT_TRUE(CompileScript(scope.GetIsolate(), scope.GetScriptState(), source_code, kV8CacheOptionsCode)); EXPECT_TRUE(cache_handler->GetCachedMetadata(TagForCodeCache(cache_handler))); // The cached data is associated with the encoding. ScriptResource* another_resource = CreateResource(UTF16LittleEndianEncoding()); EXPECT_FALSE(cache_handler->GetCachedMetadata( TagForCodeCache(another_resource->CacheHandler()))); } TEST_F(V8ScriptRunnerTest, consumeCodeOption) { V8TestingScope scope; ScriptSourceCode source_code(nullptr, CreateResource(UTF8Encoding())); // Set timestamp to simulate a warm run. SingleCachedMetadataHandler* cache_handler = source_code.CacheHandler(); SetCacheTimeStamp(cache_handler); // Warm run - should produce code cache. EXPECT_TRUE(CompileScript(scope.GetIsolate(), scope.GetScriptState(), source_code, kV8CacheOptionsCode)); // Check the produced cache is for code cache. EXPECT_TRUE(cache_handler->GetCachedMetadata(TagForCodeCache(cache_handler))); // Hot run - should consume code cache. v8::ScriptCompiler::CompileOptions compile_options; V8ScriptRunner::ProduceCacheOptions produce_cache_options; v8::ScriptCompiler::NoCacheReason no_cache_reason; std::tie(compile_options, produce_cache_options, no_cache_reason) = V8ScriptRunner::GetCompileOptions(kV8CacheOptionsDefault, source_code); EXPECT_EQ(produce_cache_options, V8ScriptRunner::ProduceCacheOptions::kNoProduceCache); EXPECT_EQ(compile_options, v8::ScriptCompiler::CompileOptions::kConsumeCodeCache); EXPECT_TRUE(CompileScript(scope.GetIsolate(), scope.GetScriptState(), source_code, compile_options, no_cache_reason, produce_cache_options)); EXPECT_TRUE(cache_handler->GetCachedMetadata(TagForCodeCache(cache_handler))); } TEST_F(V8ScriptRunnerTest, produceAndConsumeCodeOption) { V8TestingScope scope; ScriptSourceCode source_code(nullptr, CreateResource(UTF8Encoding())); SingleCachedMetadataHandler* cache_handler = source_code.CacheHandler(); // Cold run - should set the timestamp EXPECT_TRUE(CompileScript(scope.GetIsolate(), scope.GetScriptState(), source_code, kV8CacheOptionsDefault)); EXPECT_TRUE(cache_handler->GetCachedMetadata(TagForTimeStamp(cache_handler))); EXPECT_FALSE( cache_handler->GetCachedMetadata(TagForCodeCache(cache_handler))); // Warm run - should produce code cache EXPECT_TRUE(CompileScript(scope.GetIsolate(), scope.GetScriptState(), source_code, kV8CacheOptionsDefault)); EXPECT_TRUE(cache_handler->GetCachedMetadata(TagForCodeCache(cache_handler))); // Hot run - should consume code cache v8::ScriptCompiler::CompileOptions compile_options; V8ScriptRunner::ProduceCacheOptions produce_cache_options; v8::ScriptCompiler::NoCacheReason no_cache_reason; std::tie(compile_options, produce_cache_options, no_cache_reason) = V8ScriptRunner::GetCompileOptions(kV8CacheOptionsDefault, source_code); EXPECT_EQ(produce_cache_options, V8ScriptRunner::ProduceCacheOptions::kNoProduceCache); EXPECT_EQ(compile_options, v8::ScriptCompiler::CompileOptions::kConsumeCodeCache); EXPECT_TRUE(CompileScript(scope.GetIsolate(), scope.GetScriptState(), source_code, compile_options, no_cache_reason, produce_cache_options)); EXPECT_TRUE(cache_handler->GetCachedMetadata(TagForCodeCache(cache_handler))); } } // namespace } // namespace blink
3,443
14,668
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chromecast/browser/accessibility/accessibility_sound_proxy.h" namespace chromecast { namespace shell { AccessibilitySoundProxy::AccessibilitySoundProxy( std::unique_ptr<AccessibilitySoundPlayer> player) : player_(std::move(player)) {} AccessibilitySoundProxy::~AccessibilitySoundProxy() {} void AccessibilitySoundProxy::ResetPlayer( std::unique_ptr<AccessibilitySoundPlayer> player) { player_ = std::move(player); } void AccessibilitySoundProxy::PlayPassthroughEarcon() { player_->PlayPassthroughEarcon(); } void AccessibilitySoundProxy::PlayPassthroughEndEarcon() { player_->PlayPassthroughEndEarcon(); } void AccessibilitySoundProxy::PlayEnterScreenEarcon() { player_->PlayEnterScreenEarcon(); } void AccessibilitySoundProxy::PlayExitScreenEarcon() { player_->PlayExitScreenEarcon(); } void AccessibilitySoundProxy::PlayTouchTypeEarcon() { player_->PlayTouchTypeEarcon(); } } // namespace shell } // namespace chromecast
339
2,576
/* * Copyright (c) 2010-2018. Axon Framework * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.axonframework.common.lock; /** * Exception indicating that a deadlock has been detected while a thread was attempting to acquire a lock. This * typically happens when a Thread attempts to acquire a lock that is owned by a Thread that is in turn waiting for a * lock held by the current thread. * <p/> * It is typically safe to retry the operation when this exception occurs. * * @author <NAME> * @since 2.0 */ public class DeadlockException extends LockAcquisitionFailedException { private static final long serialVersionUID = -5552006099153686607L; /** * Initializes the exception with given {@code message}. * * @param message The message describing the exception */ public DeadlockException(String message) { super(message); } }
387
828
<reponame>typetree/hasor /* * Copyright 2008-2009 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.registry.client.domain; import java.io.Serializable; import java.util.Map; /** * 服务提供功着信息 * @version : 2016年2月18日 * @author 赵永春 (<EMAIL>) */ public class ProviderPublishInfo implements Serializable { private static final long serialVersionUID = -6681610352758467621L; private int clientTimeout; // 获取客户端调用服务超时时间 private String serializeType; // 获取序列化方式 private int queueMaxSize; // 最大服务处理队列长度 private boolean sharedThreadPool; private Map<String, String> addressMap; private BeanInfo clientBeanInfo; // 客户端Bean信息 // public int getClientTimeout() { return clientTimeout; } public void setClientTimeout(int clientTimeout) { this.clientTimeout = clientTimeout; } public String getSerializeType() { return serializeType; } public void setSerializeType(String serializeType) { this.serializeType = serializeType; } public int getQueueMaxSize() { return queueMaxSize; } public void setQueueMaxSize(int queueMaxSize) { this.queueMaxSize = queueMaxSize; } public boolean isSharedThreadPool() { return sharedThreadPool; } public void setSharedThreadPool(boolean sharedThreadPool) { this.sharedThreadPool = sharedThreadPool; } public Map<String, String> getAddressMap() { return addressMap; } public void setAddressMap(Map<String, String> addressMap) { this.addressMap = addressMap; } public BeanInfo getClientBeanInfo() { return clientBeanInfo; } public void setClientBeanInfo(BeanInfo clientBeanInfo) { this.clientBeanInfo = clientBeanInfo; } }
1,040
312
<filename>spring-aot/src/main/java/org/springframework/nativex/type/NameDiscoverer.java<gh_stars>100-1000 /* * Copyright 2019-2022 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.nativex.type; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import org.springframework.asm.ClassReader; import org.springframework.asm.ClassVisitor; import org.springframework.asm.SpringAsmInfo; /** * @author <NAME> */ public class NameDiscoverer { public static String getClassName(byte[] bytes) { ClassReader reader = new ClassReader(bytes); NameDiscoveringVisitor nd = new NameDiscoveringVisitor(); reader.accept(nd, ClassReader.SKIP_DEBUG); return nd.name; } public static String getClassName(Path path) { try { byte[] bytes = Files.readAllBytes(path); return getClassName(bytes); } catch (IOException e) { throw new IllegalStateException(e); } } private static class NameDiscoveringVisitor extends ClassVisitor { public String name; public NameDiscoveringVisitor() { super(SpringAsmInfo.ASM_VERSION); } @Override public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { this.name = name; } } public static String getClassName(URL resource) { try { return getClassName(Path.of(resource.toURI())); } catch (URISyntaxException e) { throw new IllegalStateException(e); } } }
656
672
#include <assert.h> #include <pthread.h> #include <sys/types.h> #include <sys/wait.h> /* * Parent and child handlers are called in the order they were registered * prepare handlers are called in reverse order. The non-commutative * operations will ensure that we are calling them in the proper order. */ static int parentval = 0; static int childval = 0; static void prepare1(void) { parentval *= 2; } static void prepare2(void) { parentval = 3; } static void parent1(void) { parentval += 4; } static void parent2(void) { parentval *= 3; } static void child1(void) { childval = 5; } static void child2(void) { childval *= 3; } int main(void) { pid_t pid, child; int status; assert(!pthread_atfork(prepare1, parent1, child1)); assert(!pthread_atfork(prepare2, parent2, child2)); pid = fork(); assert(pid >= 0); if (pid == 0) { _exit(childval); } else { child = waitpid(pid, &status, 0); assert(child == pid); assert(WIFEXITED(status)); assert(WEXITSTATUS(status) == 15); assert(parentval == 30); } return 0; }
402
477
<reponame>security-geeks/iOS-11.1.2-15B202-Jailbreak<gh_stars>100-1000 #ifndef offsets_h #define offsets_h // offsets from the main kernel 0xfeedfacf extern uint64_t allproc_offset; extern uint64_t kernproc_offset; // offsets in struct proc extern uint64_t struct_proc_p_pid_offset; extern uint64_t struct_proc_task_offset; extern uint64_t struct_proc_p_uthlist_offset; extern uint64_t struct_proc_p_ucred_offset; extern uint64_t struct_proc_p_comm_offset; // offsets in struct kauth_cred extern uint64_t struct_kauth_cred_cr_ref_offset; // offsets in struct uthread extern uint64_t struct_uthread_uu_ucred_offset; extern uint64_t struct_uthread_uu_list_offset; // offsets in struct task extern uint64_t struct_task_ref_count_offset; extern uint64_t struct_task_itk_space_offset; // offsets in struct ipc_space extern uint64_t struct_ipc_space_is_table_offset; // offsets in struct ipc_port extern uint64_t struct_ipc_port_ip_kobject_offset; void init_offsets(void); #endif
373
2,381
package com.github.dockerjava.core.command; import com.github.dockerjava.api.command.ResizeExecCmd; import com.github.dockerjava.api.exception.NotFoundException; import static com.google.common.base.Preconditions.checkNotNull; public class ResizeExecCmdImpl extends AbstrDockerCmd<ResizeExecCmd, Void> implements ResizeExecCmd { private String execId; private Integer height; private Integer width; public ResizeExecCmdImpl(ResizeExecCmd.Exec exec, String execId) { super(exec); withExecId(execId); } @Override public String getExecId() { return execId; } @Override public Integer getHeight() { return height; } @Override public Integer getWidth() { return width; } @Override public ResizeExecCmd withExecId(String execId) { checkNotNull(execId, "execId was not specified"); this.execId = execId; return this; } @Override public ResizeExecCmd withSize(int height, int width) { this.height = height; this.width = width; return this; } /** * @throws NotFoundException no such exec instance */ @Override public Void exec() throws NotFoundException { return super.exec(); } }
492
1,801
<gh_stars>1000+ // $Id: mwbmatching.cpp,v 1.3 2007/10/28 08:47:20 rdmp1c Exp $ #include "mwbmatching.h" #include <cstdlib> #include <cassert> #include <iostream> #include <queue> #include <list> #include <map> #include <set> #include <stack> #ifdef __GNUC__ #include <algorithm> #endif #ifdef __BORLANDC__ #include <values.h> #endif #if (defined __MWERKS__) || (defined __GNUC__) #include <climits> #define MAXINT INT_MAX #endif mwbmatching::mwbmatching () : algorithm() { } void mwbmatching::set_vars(const GTL::edge_map<int>& edge_weight) { m_edge_weight = edge_weight; m_mwbm = 0; m_set_vars_executed = true; } int mwbmatching::check (GTL::graph& G) { if (!m_set_vars_executed) return(GTL_ERROR); if ((G.number_of_nodes() <= 1) || (!G.is_connected()) || (!G.is_directed())) return(GTL_ERROR); return GTL_OK; } int mwbmatching::run(GTL::graph& G) { // Initialise m_pot.init (G, 0); m_free.init (G, true); m_dist.init (G, 0); GTL::nodes_t A; GTL::nodes_t B; GTL::node n; // Partition graph based on direction of edges forall_nodes (n, G) { if (n.outdeg() == 0) B.push_back (n); else A.push_back(n); m_node_from_id[n.id()] = n; } // Simple heuristic int C = 0; GTL::edge e; forall_edges (e, G) { m_edge_from_id[e.id()] = e; if (m_edge_weight[e] > C) C = m_edge_weight[e]; } GTL::nodes_t::iterator it = A.begin(); GTL::nodes_t::iterator end = A.end(); while (it != end) { m_pot[*it] = C; it++; } it = A.begin(); while (it != end) { if (m_free[*it]) augment (G, *it); it++; } // Get edges in matching it = B.begin(); end = B.end(); while (it != end) { forall_out_edges (e, *it) { m_result.push_back (e); m_mwbm += m_edge_weight[e]; } it++; } return(GTL_OK); } int mwbmatching::augment(GTL::graph& G, GTL::node a) { // Initialise m_pred.init(G, -1); m_pq = fh_alloc(G.number_of_nodes()); m_dist[a] = 0; std::stack<GTL::node, std::vector<GTL::node> > RA; RA.push(a); std::stack<GTL::node, std::vector<GTL::node> > RB; GTL::node a1 = a; GTL::edge e; // Relax forall_adj_edges (e, a1) { const GTL::node& b = e.target_(); long db = m_dist[a1] + (m_pot[a1] + m_pot[b] - m_edge_weight[e]); if (m_pred[b] == -1) { m_dist[b] = db; m_pred[b] = e.id(); RB.push(b); fh_insert (m_pq, b.id(), db); } else { if (db < m_dist[b]) { m_dist[b] = db; m_pred[b] = e.id(); fh_decrease_key (m_pq, b.id(), db); } } } GTL::node best_node_in_A = a; long minA = m_pot[a]; long delta = 0; for (;;) { // Find node with minimum distance db int node_id = -1; long db = 0; if (m_pq->n != 0) { node_id = fh_delete_min (m_pq); db = m_dist[m_node_from_id[node_id]]; } if (node_id == -1 || db >= minA) { delta = minA; // augmentation by best node in A augment_path_to (G, best_node_in_A); m_free[a] = false; m_free[best_node_in_A] = true; break; } else { GTL::node b = m_node_from_id[node_id]; if (m_free[b]) { delta = db; // augmentation by path to b, so a and b are now matched augment_path_to (G, b); m_free[a] = false; m_free[b] = false; break; } else { // continue shortest path computation e = (*b.adj_edges_begin()); const GTL::node& a2 = e.target_(); m_pred[a2] = e.id(); RA.push(a2); m_dist[a2] = db; if (db + m_pot[a2] < minA) { best_node_in_A = a2; minA = db + m_pot[a2]; } // Relax forall_adj_edges (e, a2) { const GTL::node& b1 = e.target_(); long db1 = m_dist[a2] + (m_pot[a2] + m_pot[b1] - m_edge_weight[e]); if (m_pred[b1] == -1) { m_dist[b1] = db1; m_pred[b1] = e.id(); RB.push(b1); fh_insert (m_pq, b1.id(), db1); } else { if (db1 < m_dist[b1]) { m_dist[b1] = db1; m_pred[b1] = e.id(); fh_decrease_key (m_pq, b1.id(), db1); } } } } } } while (!RA.empty()) { GTL::node a_node = std::move(RA.top()); RA.pop(); m_pred[a_node] = -1; long pot_change = delta - m_dist[a_node]; if (pot_change <= 0) continue; m_pot[a_node] = m_pot[a_node] - pot_change; } while (!RB.empty()) { GTL::node b_node = std::move(RB.top()); RB.pop(); m_pred[b_node] = -1; long pot_change = delta - m_dist[b_node]; if (pot_change <= 0) continue; m_pot[b_node] = m_pot[b_node] + pot_change; } // Clean up fh_free(m_pq); return 0; } void mwbmatching::augment_path_to (GTL::graph &/*G*/, GTL::node v) { auto i = m_pred[v]; while (i != -1) { GTL::edge e = m_edge_from_id[i]; e.reverse(); i = m_pred[e.target()]; } } GTL::edges_t MAX_WEIGHT_BIPARTITE_MATCHING(GTL::graph &G, GTL::edge_map<int> weights) { GTL::edges_t L; mwbmatching mwbm; mwbm.set_vars(weights); //if (mwbm.check(G) != algorithm::GTL_OK) //{ // cout << "Maximum weight bipartite matching algorithm check failed" << endl; //exit(1); //} //else { if (mwbm.run(G) != GTL::algorithm::GTL_OK) std::cout << "Error running maximum weight bipartite matching algorithm" << std::endl; else L = mwbm.get_match(); } return L; }
2,858
3,102
<gh_stars>1000+ #include "d1.h" #undef assert
22
14,668
<reponame>zealoussnow/chromium // Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROMECAST_MEDIA_CMA_BACKEND_FUCHSIA_FUCHSIA_VOLUME_CONTROL_H_ #define CHROMECAST_MEDIA_CMA_BACKEND_FUCHSIA_FUCHSIA_VOLUME_CONTROL_H_ #include "chromecast/media/cma/backend/system_volume_control.h" namespace chromecast { namespace media { // SystemVolumeControl implementation for Fuchsia. Current implementation is // just a stub that doesn't do anything. Volume is still applied in the // StreamMixer. class FuchsiaVolumeControl : public SystemVolumeControl { public: FuchsiaVolumeControl(); FuchsiaVolumeControl(const FuchsiaVolumeControl&) = delete; FuchsiaVolumeControl& operator=(const FuchsiaVolumeControl&) = delete; ~FuchsiaVolumeControl() override; // SystemVolumeControl interface. float GetRoundtripVolume(float volume) override; float GetVolume() override; void SetVolume(float level) override; bool IsMuted() override; void SetMuted(bool muted) override; void SetPowerSave(bool power_save_on) override; void SetLimit(float limit) override; }; } // namespace media } // namespace chromecast #endif // CHROMECAST_MEDIA_CMA_BACKEND_FUCHSIA_FUCHSIA_VOLUME_CONTROL_H_
421
3,055
<reponame>kaidegit/u8g2<gh_stars>1000+ /* Fontname: -FreeType-Old Standard TT-Medium-R-Normal--36-360-72-72-P-189-ISO10646-1 Copyright: Copyright (C) 2006-2008 <NAME> <<EMAIL>> Glyphs: 191/1456 BBX Build Mode: 0 */ const uint8_t u8g2_font_osr26_tf[8816] U8G2_FONT_SECTION("u8g2_font_osr26_tf") = "\277\0\4\3\6\6\4\6\7&-\377\366\32\370\33\372\5\21\13\336\42S \6\0\200\240\22!\23D" "\266\240\62$\16\36L\210\350\237\304J\34TH\0\42\15\310\261\263\23\204\370H\42(\2\0#:S" "\266`\366\244b\245b\303b\243D\245D\245D\245\204\16\16\312\322\206\305F\211J\211J\211J\211J" "\305\206\305\206\205\35\34\24I\211J\211J\305\206\305F\311F\211J\311\1$W\320\247]\325B\202C" "\202Cb\357$B\42\206D\322\310$\11\12\221\11\11\222\220\11\211\231\220\11\11\241\220\11\11\241\30I" "\62S\22h\21y{z\20\30b\27\22\62\223$\346$\221I\242\232\220\240\232\220 \242\220\240\220\240" "\220\30\231$!R$\243\304!\301!a\0%K\230\266\237wh\305\202B\303\204\4\245\304\2\303\364" ",NL*PLHPL(R,HTH(\70(\71\221\20yP\214\260\214\220lPXh\220" "\230\240\220\230`\224\230\234\224\230\134\230^\11F\211E\12I\211N\210E\13\1&I\230\246\37\367\352" "a\204\342!\244\304\345\302\345\302\305\304\247\342\1\206\344!F\344A\352\241\250\16\244\12\347$\350\324\314" "\211I\215\205M\21\211-\12\33\34\211\233\254\233$\34\35$\35\213\30\64\12!\23!\211\242\230\262\214" "\207\0'\11\302\261\63\22\16*\2(\34H\310\232\323\244\224I\211\205\251\22S%\246\177\27'\246N" "LNLN\231\234\0)\35H\250Z\23\344\304\344\224\311\211\311\211\251\213\23\323\317\302\64\13S%&" "\245Y\34\0*\37\315\263\252\264FW\11\305\330\204PPD\220Q\316MD\214\220\204\334\304\324\314H" "\215\256\2+B\236\247\233\330\345\241\345\241\345\241\345\241\345\241\345\241\345\241\345\241\345\241\345\241\345\241\345" "\241\345\241\345\241\305\17>\20\227\207\226\207\226\207\226\207\226\207\226\207\226\207\226\207\226\207\226\207\226\207\226" "\207\226\207\26\7,\17\305\242\232\62&\16&\210\262\11\212I\3-\10\211\240h\23\36\20.\13D\261" "\240\62$\16*$\0/#\214\250\31tC\225\206*\15U\32\33*\32\33*\32\33*\32\33*\32" "\33\252\64Ti\250\322P\245\0\60\70\221\246_\325Jg\346\246\306\344\244\346f&G&G&'(" "\17\42\17\42\17\42\17\42\17\42\17\42\17\42\17\42)&G&G&g\346\206\346\246\344TINL" "\7\2\61\20L\306`\365B\25\22\35D\356\377\177tP\62,O\266`\225\354\244\206\344f\2)$" "-\17\17\304\16\304(\310fiw+\273.f\60F\62D\64DR\342\340\342\340\342\340\2\0\63." "\217\266_\225\354\244\246\342f\4G\346F\310F\310f\344\206g\227\35\12M\17\263\245\230;\20;\20" ";\20\63\244\20\234\21#\32\241\24\4\64*Q\246`u\343\1\304W\23\27G\314J\214\212\214\212L" "\312L\6\15\12\315I\315\205\215\211M\311M\35\34L\216\357\351A\1\65.\217\266_U\302\305\206\16" "\246\16\342\42(\303sR\67\64%\66\24G\23\70L\313\5\331\201\330\201\330\4\31\305\34\211\334\314\324" "\324A\24\0\66\60\217\266_\325*\205\304\24\211\315L\321\210\221\314\5\15\317\222\24Q\310\214XM\224" "M\324\35\376pbpbPflfLJjlb\66\16\0\67\35N\266_\25\376\201\350lDl" "DlDhtp\260pb\265\302\262K+{J\5\70\65\221\246_\265\16\247\246\4g&Ef%" "f%f%H%(e\352d\16b\304\16D\17\304D\16\202\304L$\17Bo\275\25\21\35\231\24" "\232\223\243\240\25\4\71/O\266_\265\12\205\304\24\215\315\314M\14N\14N\14~H\61V\61V\62" "\24ATBK;<\63\66B\66B\65\63\66#\66%\64w\5:\20D\264\240\62$\16*\344\21" "H\34TH\0;\26\305\265\332\62&\16\16\42\346\321M\34L\320h\23#\223\6\0<@\134\267\233" "\370A\347\1\347\1\347\1\347\1\347\1\351\1\347\1\347\1\347\1\347\1\347\1\351\1\347\1\347!\345\201" "\347\201\347\201\347\201\347a\351a\347\201\347\201\347\201\347\201\347\201\347a\347\201\347\201\7=\15\36\242\246" "\30~ \217\377\203\37\10>A\134\267\233\30\346\201\347\201\347\201\347\201\347a\347\201\347\201\347\201\347\201" "\347\201\347a\351a\347\201\347\201\345!\347\1\347\1\347\1\347\1\351\1\347\1\347\1\347\1\347\1\347\1" "\347\1\351\1\347\1\347A\1\77&M\246`\224\312\204f\342&\4\13\17\242\16\242&\306&w*\32" "+\33\24\27\24\27\23\71\17)J\311T\12\0@Y\32\247\237\267\343\241*\252EG\245\5\345\1\304" "\344A\204\4\351\202\304djD\304\244hD\244\304\246\42\244\306\246\250\344\246\250\344\304\210\346\304\210\344" "\306\210\344\306\42\204\344\304$\204\304\306D\202\244\310bTQ\5\251\11\21\12\213\42\252\223\7\225\7\225" "\216\35\225\256\231\207\232\5AB\231\246 \227\343!\345\341\346\341\346\341\350\241\352\241\352\241\42\350aD" "\346aD\346ab\350!\204\346!\204\346!\242\310\305\306\305\246\345\210\17\214#g%IEGc'" "e\11\205\347H\211\16\206\16\10B<\225\246`\26\36\204\16\12N\216M\216\215N\215N\215N\215N" "\215NM\216M\312\15\12\36\220\316\15N\216MR\215N\215\22\215\22\215\22\215\22\215\22MRM\216" "\15\316\34\34H\1C\71\323\266 \326\16\202\202\306Dd\6kDIf'h'\246%\246\235\327\3" "\320\3\320\3\320\3\320\3\320\3\320C\214G\214G\20\213\14\307\14\7\215\206\211\306\251$\31\227\3D" ";\231\246`\27\36\14O\216\316\16\16\317\15\223M\217MSMS\215O\215\23\215\23\215\23\215\23\215" "\23\215\23\215\23\215\23\215OMSMSM\217\15\317\15\317\315J.;\70\30\4E:\225\246`\26" ">\32%\232\35\32\26\32\26\232\16\232\16\32K\64\26;\26;%;%{\60;%;%;\26;" "\226h,\321t\320t\320\260\320\260\320\260\320\354\320\350\301\3\2F;\224\246 \26\36\30M\22\215\16" "\315\12\315\12\15\7\15\7\215E\5\215\205\216\205N\211N\211\36\214N\211N\211\216\205\216\205\216\205\316" "\203\314\203\314\203\314\203\314\203\314\203L\37P\2GD\26\267\237V\343A(\206\2\305F\342\4\313D" "\251f\247\206\205\246\205\246e\310c\310c\350a\350a\350a\10\17\216g\210g\210g\210\207\206\207\206" "\247f\247F\311DC\342\4E\2\305d\42G\244\202e\1H\77\230\246 \27\16\206\16\206f\347f" "\347f\347f\347f\347f\347f\347f\347f\347f\347f\347\16\16\346f\347f\347f\347f\347f\347" "f\347f\347f\347f\347f\347f\347fg\16\206\16\6I\17\212\246\240\23\16\206\346\366\377\377\233\203" "\1J\36\320\246\337\324\16F\247\367\377Gc\63U\63U\63d\63\202BrSbr#\263\222\0K" "A\230\246 \27\16f\16\246\6\13'W\212\16\312\316\11\217IO\211\17\311\3\14\311\3\314\314\3\214" "\224OD\220\223T\323P\17\25O\21O\325\216\321\216\225\316\221\16R\16\26N\22N\326\34\314\34\20" "L:\224\246 \26\16\250\347A\346A\346A\346A\346A\346A\346A\346A\346A\346A\346A\346A" "\346A\346A\346A\206\203\206\203\206\203f\205f\205f\205F\207F\207\6\17\36\20Ma\232\246\240\27" "\16boj\311L\311,#\306,#\306$&#\306$\350$\306$\350B\306D\346B\306D\310B" "\306D\250b\306d\246b\306d\246b\306dhd\306\204f\202\306\204f\202\306\204H\202\306\244&\204" "\306\244&\242\306\244&\242\306\304\250\306\304\226\211-\223\23\233\42\23\233\71\220\211\71\30NN\331\246\37" "\27.\17dj\307l\343l\343N\343$H\343D(\343D\12\343d\10\343\204\350\342\204\312\342\244\310" "\342\304\250\342\304\250\342\344\210\342\4i\342\4i\342$I\342D)\342D)\342d\353\204\351\204\351\244" "\307\250\205\16D\345!\203\0O<\25\267\237V\343!\330\312I\252\233\234\232\35\232\235\241%\231\36\231" "\236\240>\210>\210>\210>\210>\210>\210>\210\246\230\36\231\36\241\245\231\35\232\235\232\234\223T'" "KA\17\21\12P:\225\246`\26\36H\16\316M\216MR\215\22\215\22\215\22\215\22\215\22\215NM" "RM\216\15\316\35\220\316\303\314\303\314\303\314\303\314\303\314\303\314\303\314\303\314\303\314\303\214\37\220\2Q" "OU\270\232V\343!(\206\345$\325MN\315\16\315\316\320\222L\217LOP\37D\37D\37D\37" "D\37D\37D\37DSL\217L\217\320\322\14m\242fj\42HbN\42HBr\210(l\204*" "Rb*x*x(\234B\374\36\200\6\0R\77\226\246`\26\36\210\316\21\16\322M\222M\222M\222" "M\222M\222\15\322\15.\243<\30\36\223\35\33\235\233\234\233\234\233\234#\234#\234#\234\243\11\32\234" "\11\32\234\11\32\244\210\32\264\70\240\42\1S\66\321\266\240u\16b\224\211(\254\20\245\220\235\220\235\20" "\226\230\225\240\15\241\276=\10=\230<\20=\10\211\264\210\265.\256..\266\215\250\224\210\221\23\211\232" " \216\3T\71\225\266\240\26>\240\232:\33\253\233\243\233\243[\70(\70(\70(\70\30\71\17\63\17" "\63\17\63\17\63\17\63\17\63\17\63\17\63\17\63\17\63\17\63\17\63\17\63\17\63~P\4U\77\331\246" "_\27\16\306\16\204\246\307\306\343\306\343\306\343\306\343\306\343\306\343\306\343\306\343\306\343\306\343\306\343\306\343" "\306\343\306\343\306\343\306\343\306\343\306\343\306\3\245#\207Ce\203\7\303+\350\201d\1VD\231\246 " "\27\16j\16\206H\351h%I%Ic'e\11e\11\205\7\243\311\244\311\304\307\342\1\210\344\1\210" "\344!\206\342Af\344AH\344aF\342\201&\344\201\354\241\350\301\350\341\346\341\346\341\344!c\1W" "h\244\226\240\31\16H\16H\16\206\10\13\351()%')%\11\11E\351\12e\347\354d\347\354\202" "\311B\306\244\247D\306\244\247D\250\244\211\202\206\304i\204\206\344\1f\204\206\344\1f\204h\342!H" "\302F\344A&\304F\344A&\304F\342a&\2\353a\12\353\201\10\351\241(\347\241F\347\301D\347" "\301D\345\341\202c\1XC\230\246\340\26\16h\16\206\12'\11E\353d\311\244\251\302\211\344\1f\344" "!H\342a&\344a\352\241\346\301\350\241\350\241\352aB\350!D\350!\202\310\205\310\303\210\305h\5" "I%W\322Q\22\35\314\34\20YC\230\246\340\26\16\210\16dJ\347H%)%)c\351d\351\242" "\251\342\1\246\342\1h\342Af\342A(\342\201&\342\201\350\301\346\301\346\301\346\301\346\301\346\301\346\301" "\346\301\346\301\346\301\346\301\346A\16\252\0Z:\223\246\340U\16\16F\10i&I&i$\211$\211" "\42\251\42\251\2\311\351\1\310\351\1\346\1\310\351\1\310)\243F\203HcHeHEHGf'H" "\17B)\16\16(\0[\20\207\310\230\23\16h\206\366\377\377\377\310\342\0\134!\214\250\31\24be\323" "\312\246\225M+\233V\66\255\250l\254\250l\254\250lZ\331\264\262ie\3]\17\207\270\330\23n\210" "\366\377\377\377\305\201\1^\34O\263l\365\242\207g%Dc\42e\344\244\304\342\242\344d$c$%" "d\247\3_\10S\200\332\24\36\24`\12\206\261\63\24\204\26I)a$P\244\340\224*\205\306\304\246" "\304\246v=[G\62\265\243\261\241\261\31*\32\242\210\231\210\231\10\233\32\22\0b/\220\206\240\24\254" "\367o\346&d\244&\202\206\310\204\310f\346f\346f\346f\346f\346f\346f\346f\346f\310\204$" "\242\206b\202\244\202\210\0c\33L\244 \224\312\204d\304$\306$\304\274\334\251`\304\134\210X\220P" "X\15\0d,\220\246\340\364\254\367w$S#\22SBESDb\64s\63s\63s\63s\63s" "\63s\63sCrCSTRTBu$\6e\36M\244`\224\352d\206\244F\246F\344\334\35\34" "\224n\31\61\27\62\27#\27\244\256\6\0f\32\214\226 \263\312\204\202\206D\206F\206F&\267;\220" "\232\334\377w\7\62\0g\67Q\246\30\265j\206fHD\246&\326Y\314\15\315\15\315\15\315M\255\233" "\31\255\234\216\207\210\207\210\207\70 <\240\32\14\222\15\21\16\21\16\21\16\31\15\32\14<\210\2h=" "\222\226`\25\354\1\346\1\346\1\346\1\346\1\346\1\346\1\346\1\346\1f\352Fb\306&\242\246\310\246" "\310\246\346\246\346\246\346\246\346\246\346\246\346\246\346\246\346\246\346\246\346\246\346F\16b\16i\21H\226\240" "r\244\210\250\344QY\355\377'\7\1j\31\211x\330\362\304\326\311cc\266\377\377\42\310\306FBH" "$F\210\6\0k,\221\226\340\24\314\367o\216\246\344\246\2\207\4\207\42gBGb'F'F)" "&g\6g\6\207\346\206\310\246\306\246H\16\42\16\2l\15\211\226\340\22\314\366\377\377\67\7\2m\62" "Y\244`\27j\250\310FBfB\246&\202&\202\206\250\250\206\250\250\206\306\26\215-\32[\64\266h" "l\321\330\242\261Ec\213\306\26\215-\32[\362\1n*Q\244`\25j\312Fb\246&\242\206\310\206" "\310\206\346\206\346\206\346\206\346\206\346\206\346\206\346\206\346\206\346\206\346\206\346Fn\16o\35N\244\240\264" "\10\205\244\304d\306F\346$\6\375\341\304\234\310\330\214\230\224\220 \25\0p\60P\226\330\24L\350&" "d\244\212\206\310\204\310f\346f\346f\346f\346f\346f\346f\346f\346f\310\204\250\206&\202\244F" "\350\246\367\351\201\34\0q/P\246\230\224\210\242fR\11I\10ME\10\211\321\314\315\314\315\314\315\314" "\315\314\315\314\315\314\15\311\15MQIQ\315D\314\221L\357\247\7\2r\31L\244\340\23j\226\304\204" "L\304\210L\204\214\320\214\20\22N\356\357\256\0s\42L\244 TJb\204\42B\304D\344B\344B" "\306b\10\357\356,\342\354\12\353\314F\204$\202J\0t\32\13\226`\223B\263T\70v\60\63\270\377" "*d*d*\204F\346\252\4\0u*Q\224 \25\252\212\346\206\346\206\346\206\346\206\346\206\346\206\346" "\206\346\206\346\206\346\206\346\206\306\210\306\210\246\42\246fB\306j\12v(R\204\340\24\16bn\346\246" "\346\324\5\216\5\216E\16\205\16\305\12\305\216D\213DOD\323\3\314\3\314C\304\203\4\2wA[" "\204 \27\16B\16Bn\306\310\304\346\306\344\344\306\2\307\306\2\247\252\42\207\42\206B\207B\204bg" "BfbGbF\242E\202D\242'\202&\242\251\350\1\306\346\1\306\346!\342\344A\2\3\1x#" "P\244\340\24Nl\210\306\206\344\206\42GBGb\251W\23\323\206L\6I\6\315\205M\211\315\230\34" "\4y\65R\226\30\25\16bn\346\304\346\324\5\216\5\216EJ\205\16\205\16\305\312\4\217\4\217DW" "\223\323\3\314\3\310\203\304C\310C\204\16\205\316\210\316\304\216\10\23\3z!L\224\340\23\36\204\225M" "\304M\204\215D\315D\15N\16\256\212\231\12\31\13\31\213\30+;\70\10{\34H\270\331\323\244\302\302" "t\66\265Lga\62\203rqbZm%\246]`\240\0|\11\202\310\231\22\376\17\12}\33H\270" "\231\23\4\323\211\351j\225\230vq\202\63ba:\233\32\323\263Tb\0~\26\224\241&VjC\16" "$\205\16\302\344\16B&\17DDK\0\240\6\0\200\240\22\241\23D\266\230\62$\16*DcD\364" "/\16\36LH\0\242\61\214\306\134\365bsY%\222f$Db&Db&\302(\302($b(" "h(h(h(h(j&\305L\222\221\230\230\211\220\260\312\330\214\0\243:T\246_\226\313\205d" "\305B\305\6\305\10\305\350\306\6\347A\346A\346A\206\17\342A\16\202\347A\346A\346A\346A\346A" "\206GDgH\245&\247\312$\202B\16f\250n\0\244(\22\244\245\25\204l&\312j$\207be" "\204c\242E\302C\302C\302C\302C\242E\204\203b\205$g\312*fl\6\245\70T\226\240\25\16" "\242N(\247&\305\10\3\347\4\311B\247D\211\202g\204g\302'\304'\342\1\210\17\214\347A\206\17" "\214\347A\346A\346A\346A\346A\346A\246\17\250\0\246\13B\310\232\22~|\360\240\0\247\70\15\310" "\331\265\350\204\302\242\204\204\206\204\206\244\242fG\31FP\311\320\204\221\304Q\4\226RVF\320\205P" "\5\321\204Q\4\222\222\316NE\11\15\11\15\251\12\13\222\243\2\250\14\12\261\64\64\244\212\214&\244\4" "\251X\332\246\237W\355A\306\206U\212\313\311CH\311\321\304\10\205\11\21\305\204\211M\205D\315I\205" "D\315IEDM\206I\315CH\315CH\315CH\315CH\315CHM\206ED\315\205\205D\315" "\205\205\204\215\245\11\33\12\13\222+\223\222\207\220\23\227\24V(\17q\20\11\252\33\12\243\255\63\250d" "\364nJBHDfDfD\204D$\202b\342@\2\0\253!\212\303\242t\242B\204B\204D\204" "B\204D\204D\204D\204D\204D\204d\204R\5\5\11E\1\254\24\322\241\246\25\36\320C\310C\310" "C\310C\310C\310C\10\255\10\211\240h\23\36\20\256X\332\246\237W\355A\306\206U\212\313\311CH" "\211\34P\11E\15M\305\204MM\205\204MM\205\204MME\304M\215\311\15\315\311\235\312\15\11\312" "M\311\311M\215\311M\215E\204M\215d\66\65\222\331\324H\232\250\25!A\42G\24R\362\20r\342" "\222\302\12\345!\16\42\1\257\10I\260\365\23\16\4\260\23\212\342\260u\210\224\204E\4j\30\21\26\42" "$D\3\261\66^\246\237\330\345\241\345\241\345\241\345\241\345\241\345\241\345\241\345\241\345\241\305\17>\20\227" "\207\226\207\226\207\226\207\226\207\226\207\226\207\226\207\226\207\226\207\226\307\371\301\7\2\262\26\312\263*T\212" "\202&\302\310\214\214\346\264\13\214\23\213\210;x\263\31\312\303*T\212\202&\244$\206\346\324\224\16\12" "\32\31\221I\10\315\324\0\264\13\206\361\63\224dFf\64\2\265A\323\246\226\65\4\305\346\250\346\250\346" "\250\346\250\346\250\346\250\346\250\346\250$\345\42\345\42\345\2\347\224EL\325HD\34\204X\304\24Q\304" "\303\310\203\310\203\310\203\310\203\314C\314C\314C\320C\310C\0\266E\317\247\333t\16J\212\202\214b" "\216b\216b\216b\216b\216b\216\202\214\242\212\42\203\42\203\42\203\42\203\42\203\42\203\42\203\42\203\42" "\203\42\203\42\203\42\203\42\203\42\203\42\203\42\203\42\203\42\203\42\203\42\203b\0\267\13D\261\251\62$" "\16*$\0\270\16\307\301\30t\242\342\306\244\206$*\0\271\16\310\303j\264\302\244F\254\366\237\34\4" "\272\25\11\263\355s\206dDd$f|\63!#\42#\64s \273\37\211\303b\24\202\262Q\23\24" "\243DFDFDFDF$HBF$($H.\6\0\274G\230\306\340\367\201\344\302\343\244\243" "\212\5\205#e%eCEc%e%\203\5\243\5\303\244\344\302\246\304\304\246\304R\210\34\204\204\205" "\10\207\205\310\206\305\210\212\305\210\206\5I\206EI\206\35\214E\313I\313\205\213\5\37\275K\330\306\337" "\367a\4\243\3\205\303\212#eCeCEc%e%\203\5\243\5\243\345b\312\344B\202\206\304B" "\242h\244D\302\16Hb\206&\243\204&C'cECE\323\12J\205\5\306EE\306E\5\36\14" "E\36H\305\3\1\276P\230\306\340Wj\303\202D\243\24\206\15\11\206\15\311\205\213I\313E\26\212O" "\305C\314\304\203\314\204\16\215\204\311\14M\210\311\204M\204\315DMHE\10\331\204E\10\207\205\10\207" "\205\310\206\305\210\212\305\210\206\5I\212\35\214\5\13\12\13F\313\5\37\277#M\226X\264D)\231\312" "N\306\210E\205E\205\5\311&\235\334%\325\304\330\303B\211\271\230!\261\42\0\300N\231\250 \27\345" "\1\347\341\346!\345!\345!\343q\36\17)\17\67\17\67\17G\17U\17U\17\25A\17#\62\17#" "\62\17\23C\17!\64\17!\64\17\21E.\66.\66-G|`\34\71+I*:\32;)K(" "<GJt\60t@\301O\231\250 \367!\344\341\346\301\346\301\346\341\344\341\342q\36\17)\17\67\17" "\67\17G\17U\17U\17\25A\17#\62\17#\62\17\23C\17!\64\17!\64\17\21E.\66.\66" "-G|`\34\71+I*:\32;)K(<GJt\60t@\302Q\231\250 \227\343\1\347\341" "\350\241D\344a\242\344\1\4\343q\31\17)\17\67\17\67\17G\17U\17U\17\25A\17#\62\17#" "\62\17\23C\17!\64\17!\64\17\21E.\66.\66-G|`\34\71+I*:\32;)K(" "<GJt\60t@\303NY\250 \67\247\342\1l\342\1B\316\243\350\361U<\244<\334<\334<" "\34=T=T=T\4=\214\310<\214\310<L\14=\204\320<\204\320<D\24\271\330\270\330\264\34" "\361\201q\344\254$\251\350h\354\244,\241\360\34)\321\301\320\1\1\304OY\250 \27\245\344\1\246\306" "\247\346\1\244\344\361U<\240<\340<\334<\30=X=T=\220\304<P\10=L\314<\210\314<" "\210\14=D\324<\200\324<\200\330x\334\264\334\364\201q\344\254\344\254\350h\354\244\354\244,\35)\321" "\301\320\1\1\305Y\331\250 w\347\301b\342\201\242\342a\242\342a\242\342a\242\342\201b\342\301\346\261" "\211\207\224\207\233\207\233\207\243\207\252\207\212\230\207\212\240\207\221\240\207\211\231\207\211\241\207\220\241\207\210\232" "\7\220\42\227\42\217\233\226#>\60\216\234\225$\225$\215\235\224%\224\245#%:\30: \306\134\241" "\226 \271\17\16\354\1H\351\1h\307\213\305#\206\245%\246\223L\7\213\314E\5\307\314\305\203\310\314" "\305\203\4\215\311C\10\215\311C\10\35\320\3H\215\311\3H\215\211\213\315\205\213\315E\305\35\324E\305" "\5N\207\11N\207E\16KI\16KI\16\13M\316\316P\216\36\334\34\34\30\307F\223\270\31\326\16" "b\204\306Dd\6kDIf'h'\246%\246\235\327\3\320\3\320\3\320\3\320\3\320\3\320C\214" "G\214G\20\213\14\307\14\7\311\206I\312\251$\21\237\207\210\7\241\207\231\207\230\207\230\15\32\256\3\310" "G\225\250`\326\344\201\346\201\346\201\344\241\344\301\342\61;x\64J\64;\64,\64,\64\35\64\35\64" "\226h,v,vJvJ\366`vJvJv,v,\321X\242\351\240\351\240a\241a\241a\241" "\331\241\321\203\7\4\311G\225\250`\326\345a\350A\346A\344a\344a\344\61;x\64J\64;\64," "\64,\64\35\64\35\64\226h,v,vJvJ\366`vJvJv,v,\321X\242\351\240\351" "\240a\241a\241a\241\331\241\321\203\7\4\312H\225\250`V\345\201\344a\350!D\304\205\204\3\345\261" "\70x\64J\64;\64,\64,\64\35\64\35\64\226h,v,vJvJ\366`vJvJv," "v,\321X\242\351\240\351\240a\241a\241a\241\331\241\321\203\7\4\313DU\250`\366\244d\207f\207" "\206\245\344qx\360h\224hvhXhXh:h:h,\321X\354X\354\224\354\224\354\301\354\224" "\354\224\354X\354X\242\261D\323A\323A\303B\303B\303B\263C\243\7\17\10\314\24\212\250\240\23\4" "\267\14\215\207<\30\232\333\377\377o\16\6\315\24\212\250\240\23\345\346\64\214\207<\30\232\333\377\377o\16" "\6\316\31\212\250\240\263\2\307\250Dd\204$\2\343\241\16\206\346\366\377\377\233\203\1\317\27K\250\240\63" "\244$\246\254&\244\344Q\35\14\15\356\377\377W\7\3\320<\230\246\340\26\36\10O\212.\234\235\233%" "\33\36\33\246\32\246\232\236\232&\232&\232>\70\210$\232&\232&\232&\232&\232\236\32\246\32\246\32" "\36\233\235\233\235\33\35\234\24;\70\20\4\321Y\231\250\37\67\251\302O\304c\354\1\242\346\361\360\362@" "\246v\314\66\316\66\356\64N\202\64N\204\62N\244\60N\206\60N\210.N\250,N\212,N\214*" "N\214*N\216(N\220&N\220&N\222$N\224\42N\224\42N\266N\230N\230Nz\214Z\350" "@T\36\62\10\0\322I\325\270\237\326\344a\346\201\346\201\346\241\342\301\342\321\306C\260\225\223T\67\71" "\65;\64;CK\62=\62=A}\20}\20}\20}\20}\20}\20}\20M\61=\62=BK" "\63;\64;\65\71'\251N\226\202\36\42\24\0\323I\325\270\237\266\345\201\346A\346A\346a\342\201\342" "\321\306C\260\225\223T\67\71\65;\64;CK\62=\62=A}\20}\20}\20}\20}\20}\20" "}\20M\61=\62=BK\63;\64;\65\71'\251N\226\202\36\42\24\0\324K\325\270\237V\343\201" "\346a\346A$\344\1\242\202\345\344\221\305C\260\225\223T\67\71\65;\64;CK\62=\62=A}" "\20}\20}\20}\20}\20}\20}\20M\61=\62=BK\63;\64;\65\71'\251N\226\202\36" "\42\24\0\325D\225\270\237\326\212b\17F\203\352\361(\36\202\255\234\244\272\311\251\331\241\331\31Z\222\351" "\221\351\11\352\203\350\203\350\203\350\203\350\203\350\203\350\203h\212\351\221\351\21Z\232\331\241\331\251\311\71I" "u\262\24\364\20\241\0\326F\225\270\237\326\244d\247F\247f\245\344\261\216\207`+'\251nrjv" "hv\206\226dzdz\202\372 \372 \372 \372 \372 \372 \372 \232bzdz\204\226fv" "hvjrNR\235,\5=D(\0\327\71\326\345\236\30\342\241\346a$\344!d\304\245\204\345D" "%\5e\305\244\205\344\1D\344A\350\201\344\201\350A\324\3\10I\213\311\12J\212\312\11K\211\313\310" "C\250\207\231\7\3\330M\25\267\237V\343!\30I\311\211HIR\215J\315\16\215\322P\232\214\206\254" "\24\231 \224\71\210\23:\210\213:\10\223:\210\22;\210\212;\10\12<\210\21\244\30\221\34\31\11\35" ")\245!\35\232\235\22\235\242\224\22\221\223\22\242\240\207\10\5\331K\331\250_\27\345\1\347\341\346!\345" "!\343A\343qr\60v \64=\66\36\67\36\67\36\67\36\67\36\67\36\67\36\67\36\67\36\67\36\67" "\36\67\36\67\36\67\36\67\36\67\36\67\36\67\36\67\36(\35\71\34*\33<\30^A\17$\13\332L" "\331\250_\367!\344\341\346\301\346\301\346\341\342\1\343qr\60v \64=\66\36\67\36\67\36\67\36\67" "\36\67\36\67\36\67\36\67\36\67\36\67\36\67\36\67\36\67\36\67\36\67\36\67\36\67\36\67\36(\35\71" "\34*\33<\30^A\17$\13\333N\331\250_\227\343\1\347\341\350\241$\346a\242\344\1\4\343\61>" "\30;\20\232\36\33\217\33\217\33\217\33\217\33\217\33\217\33\217\33\217\33\217\33\217\33\217\33\217\33\217\33" "\217\33\217\33\217\33\217\33\217\33\17\224\216\34\16\225\15\36\14\257\240\7\222\5\334L\231\250_\27\305\344" "\1\206\346\1\206\346\1\304\344\361\356`\354@hzl<n<n<n<n<n<n<n<" "n<n<n<n<n<n<n<n<n<n<n<P:r\70T\66x\60\274\202" "\36H\26\0\335P\230\250\340\366!\344\301\346\241\346\241\346\301\342\341\342\61\77 :\220)\235#\225\244" "\224\244\214\245\223\245\213\246\212\7\230\212\7\240\211\7\231\211\7\241\210\7\232\210\7\242\7\233\7\233\7\233" "\7\233\7\233\7\233\7\233\7\233\7\233\7\233\7\233\7\71\250\2\336:\225\246`\26\16\310\347a\346a" "\346a\346a\16*\7\347&\307&\251F\211F\211F\211F\211F\211&\251&\307\6\347\16*\347a" "\346a\346a\346a\346a\346a\306\17H\1\337:\220\226\340\364*g\346\244\66\32\33\32\33\32\223\332" "HnbrHnJlLjlhNhnfnfnfnfnf$hfbf\305\314\12" "\231\241\11\31\21\33\32\0\340\60P\246\341T\304\307\345\1\344\1\342!\342\61(\15\232\13\33\13[\64" "\66\64=[G\62\265\243\261\241\261\31*\32\242\210\231\210\231\10\233\32\22\0\341*P\246\341\64\207\211" "\207\245\325cP)\64&\66%\66\265\353\331:\222\251\35\215\15\215\315P\321\20E\314D\314D\330\324" "\220\0\342.P\246\340\264\304\245\211CDe\42\303\344\321V\12\215\211M\211M\355z\266\216djG" "cCc\63T\64D\21\63\21\63\21\66\65$\0\343+\20\246\340th\304\16\344b\350q^)\64" "&\66%\66\265\353\331:\222\251\35\215\15\215\315P\321\20E\314D\314D\330\324\220\0\344\62\20\246\340" "T\244\344f\346f\346\244\344\61.\15\22\14\223\13\223\33\222\33\22\27&$\21\233\22\233\222\32\223\32" "\23\242\32\42\212\220\221\230\211\260\251!\1\345/P\246\340\264hc$\243\42\243Bcd\347\221W\12" "\215\211M\211M\355z\266\216djGcCc\63T\64D\21\63\21\63\21\66\65$\0\346\66V\244" "\240\226\232\11M\310\314\210Q\311\210Q\215L\315\311H\315M\316M\35\34\214\14\315N\215R\215\216M" "R\325ELE\314E\14\205\214\305\314\304\14\11\225\25\1\347\42\14\246\31\224\312\204d\304$\306$\304" "\274\334\251`\304\134\210X\220\252\312PaYQ\251 \261\32\0\350#M\246aTd\327\12\253GU" "'\63$\65\62\65\42\347\356\340\240t\313\210\271\220\271\30\271 u\65\0\351#M\246aTE'G" "\265GU'\63$\65\62\65\42\347\356\340\240t\313\210\271\220\271\30\271 u\65\0\352'M\246`\324" "dE)C\2\203\302\322#\251\223\31\222\32\231\32\221swpP\272e\304\134\310\134\214\134\220\272\32" "\0\353%\15\246`t\204\204\326\14\15\251\307\240NfHjdjD\316\335\301A\351\226\21s!s" "\61bB\352j\0\354\20I\206\340\22\344\66\214\214\7,\333\377\217\16\355\21H\246\240\322\244\26I\251" "\207\252\332\377o.\0\356\25I\226\340r\344\246\250$dT\304\305\3\225\355\377G\27\0\357\23\11\226" "\340\62\204jl&\204\344\241\315\366\377\233\203\0\360)\216\246\240t\246\302f\304,I)%\306\204f" "\207\347\256\204h\304F\306(\346\14\375\341\304\234\310\330\214\230\224\220 \25\0\361\63\21\246`\265\246\342" "L\344B\14\203\346\261\255)\33\211\231\232\210\32\42\33\42\33\232\33\232\33\232\33\232\33\232\33\232\33\232" "\33\232\33\232\33\232\33\232\33\271\71\362#N\246\241Tf\207\207\245\325\243$\24\222\22\223\31\33\231\223" "\30\364\207\23s\42c\63bRB\202T\0\363#N\246\241TeGg\25\307\243$\24\222\22\223\31" "\33\231\223\30\364\207\23s\42c\63bRB\202T\0\364'N\246\240\324\204eIC\42\203\342\302\342" "\221\21\12I\211\311\214\215\314I\14\372\303\211\71\221\261\31\61)!A*\0\365$\16\246\240t\210\242" "\16\204\202\350qD($%&\63\66\62'\61\350\17'\346D\306f\304\244\204\4\251\0\366\42\16\246" "\240t\244\204v\245\36#B!)\61\231\261\221\71\211A\177\70\61'\62\66#&%$H\5\367!" "\336\245\236\330\345\201\351a\351a\351\201\345\361\177~\360\201<\376\317\345\201\351a\351a\351\201\305\1\370" ",N\244\240\264\210b\204$b\304F\346D\306&\306\42\254B\214b\214bl\202L\242,\302&\346" "D\306f\304d\42\204d\202\212\0\371\65Q\226!u\306\347\1\346!\344!\344!\342\21W\25\315\15" "\315\15\315\15\315\15\315\15\315\15\315\15\315\15\315\15\315\15\315\15\215\21\215\21MEL\315\204\214\325\24" "\372\62Q\226!u\247\251\247\305\345\1\342\21W\25\315\15\315\15\315\15\315\15\315\15\315\15\315\15\315\15" "\315\15\315\15\315\15\215\21\215\21MEL\315\204\214\325\24\373\65Q\226 \25\343\1\306\247%d\203$" "\343\342\21V\25\315\15\315\15\315\15\315\15\315\15\315\15\315\15\315\15\315\15\315\15\315\15\215\21\215\21M" "EL\315\204\214\325\24\374\62\21\226 \225\24\16\315\15\15\12\311c[U\64\67\64\67\64\67\64\67\64" "\67\64\67\64\67\64\67\64\67\64\67\64\67\64F\64F\64\25\61\65\23\62VS\375AR\230\331\224\345" "\1\346\1\344\1\344\1\344!\342\221\37\304\334\314\211\315\5\312\5\216\5\216EJ\205\16\205\16\305\312\4" "\217\4\217D\223\263\7\220\207\220\7\211\207\210\7\11\35\12\235\21\235\211\35\211&\6\376\62\220\230\327\224" "\204i#\246\367\21\325\214\321H\14\315D\324\14\331\14\331\14\331\314\234\320\330\320\330\320\230\324\224\330T" "\334P\340L\344\204h\355\364~:\15\377<\21\230\330\264\24\316\14\316\14J\311cy\20c\63'\65" "\27\67\26\67\26\67\25\71\24\71\24\71\23;\22;\22;\21\315\271<\200<D<@<D$M$" "I(I\350H\60-\0\0\0\0\4\377\377\0";
15,591
585
# -*- coding: utf-8 -*- from .diffusion import dtiaverage, dtiestim, dtiprocess, DWIConvert from .tractography import * from .gtract import ( gtractTransformToDisplacementField, gtractInvertBSplineTransform, gtractConcatDwi, gtractAverageBvalues, gtractCoregBvalues, gtractResampleAnisotropy, gtractResampleCodeImage, gtractCopyImageOrientation, gtractCreateGuideFiber, gtractAnisotropyMap, gtractClipAnisotropy, gtractResampleB0, gtractInvertRigidTransform, gtractImageConformity, compareTractInclusion, gtractFastMarchingTracking, gtractInvertDisplacementField, gtractCoRegAnatomy, gtractResampleDWIInPlace, gtractCostFastMarching, gtractFiberTracking, extractNrrdVectorIndex, gtractResampleFibers, gtractTensor, ) from .maxcurvature import maxcurvature
369
1,042
<reponame>sundayios/zhPopupController-master // // zh_UpdateView.h // zhPopupController // // Created by zhanghao on 2017/9/7. // Copyright © 2017年 snail-z. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface zhOverflyButton : UIButton + (instancetype)buttonWithTitle:(nullable NSString *)title handler:(void (^ __nullable)(zhOverflyButton *button))handler; @property (nonatomic, assign) UIColor *lineColor; // 线条颜色 @property (nonatomic, assign) CGFloat lineWidth; // 线宽 @property (nonatomic, assign) UIEdgeInsets flyEdgeInsets; //边缘留白 top -> 间距 / bottom -> 最底部留白(根据不同情况调整不同间距) @end @interface zhOverflyView : UIView @property (nonatomic, strong) UIImageView *flyImageView; @property (nonatomic, strong, readonly) UILabel *titleLabel; @property (nonatomic, strong, readonly) UILabel *messageLabel; @property (nonatomic, strong, readonly) CALayer *splitLine; /** - flyImage: 顶部image - highlyRatio: 为对称透明区域视觉上更加美观,需要设置顶部图片透明区域所占比,无透明区域设置为0即可 ( highlyRatio = 图片透明区域高度 / 图片高度 ) (对切图有要求,需要美工告知透明区域高度) - attributedTitle: 富文本标题 ( NSString => NSMutableAttributedString [[NSMutableAttributedString alloc] initWithString:string]; ) - message: 消息文本 */ - (instancetype)initWithFlyImage:(nullable UIImage *)flyImage highlyRatio:(CGFloat)highlyRatio attributedTitle:(nullable NSAttributedString *)attributedTitle attributedMessage:(nullable NSAttributedString *)attributedMessage constantWidth:(CGFloat)constantWidth; // 自动计算内部各组件高度,最终zhOverflyView视图高等于总高度 - (instancetype)initWithFlyImage:(nullable UIImage *)flyImage highlyRatio:(CGFloat)highlyRatio title:(nullable NSString *)title message:(nullable NSString *)message constantWidth:(CGFloat)constantWidth; @property (nonatomic, assign) CGFloat highlyRatio; /// 可视滚动区域高,默认200 (当message文本内容高度小于200时,则可视滚动区域等于文本内容高度) @property (nonatomic, assign) CGFloat visualScrollableHight; /// 消息文本边缘留白,默认UIEdgeInsetsMake(10, 10, 10, 10) @property (nonatomic, assign) UIEdgeInsets messageEdgeInsets; /// 子视图按钮(zhOverflyButton)的高度,默认49 @property (nonatomic, assign) CGFloat subOverflyButtonHeight; /// 竖直方向添加一个按钮,可增加多个按钮依次向下排列 - (void)addAction:(zhOverflyButton *)action; /// 水平方向两个并列按钮 - (void)adjoinWithLeftAction:(zhOverflyButton *)leftAction rightAction:(zhOverflyButton *)rightAction; /// 刷新所有子视图内容 - (void)reloadAllComponents; @end NS_ASSUME_NONNULL_END
1,467
343
/* * zsummerX License * ----------- * * zsummerX is licensed under the terms of the MIT license reproduced below. * This means that zsummerX is free software and can be used for both academic * and commercial purposes at absolutely no cost. * * * =============================================================================== * * Copyright (C) 2010-2017 YaweiZhang <<EMAIL>>. * * 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. * * =============================================================================== * * (end of COPYRIGHT) */ #include <zsummerX/select/select_impl.h> #include <zsummerX/select/udpsocket_impl.h> using namespace zsummer::network; UdpSocket::UdpSocket() { } UdpSocket::~UdpSocket() { if (_fd != InvalidFD) { ::close(_fd); _fd = InvalidFD; } } bool UdpSocket::initialize(const EventLoopPtr & summer, const char *localIP, unsigned short localPort) { if (_linkstat == LS_UNINITIALIZE) { _summer = summer; _fd = socket(AF_INET, SOCK_DGRAM, 0); _linkstat = LS_WAITLINK; if (_fd == InvalidFD) { LCE("UdpSocket::initialize[this0x" << this << "] create socket fail. this=" << this << ", " << OSTREAM_GET_LASTERROR); return false; } setNonBlock(_fd); sockaddr_in localAddr; localAddr.sin_family = AF_INET; localAddr.sin_addr.s_addr = inet_addr(localIP); localAddr.sin_port = htons(localPort); if (bind(_fd, (sockaddr *) &localAddr, sizeof(localAddr)) != 0) { LCE("UdpSocket::initialize[this0x" << this << "]: socket bind err, " << OSTREAM_GET_LASTERROR); ::close(_fd); _fd = InvalidFD; return false; } _summer->addUdpSocket(_fd, shared_from_this()); _linkstat = LS_ESTABLISHED; } LCE("UdpSocket::initialize[this0x" << this << "] UdpSocket is aready initialize, _ios not is nullptr. this=" << this); return false; } bool UdpSocket::doSendTo(char * buf, unsigned int len, const char *dstip, unsigned short dstport) { if (!_summer || _linkstat != LS_ESTABLISHED) { LCE("UdpSocket::doSend[this0x" << this << "] stat error!"); return false; } if (len == 0 || len >1500) { LCE("UdpSocket::doSend[this0x" << this << "] argument err! len=" << len); return false; } sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_addr.s_addr = inet_addr(dstip); addr.sin_port = htons(dstport); sendto(_fd, buf, len, 0, (sockaddr*)&addr, sizeof(addr)); return true; } bool UdpSocket::doRecvFrom(char * buf, unsigned int len, _OnRecvFromHandler && handler) { if (!_summer || _linkstat != LS_ESTABLISHED) { LCE("UdpSocket::doRecv[this0x" << this << "] _summer not bind!"); return false; } if (len == 0 || len >1500) { LCE("UdpSocket::doRecv[this0x" << this << "] argument err! len=" << len); return false; } if (len == 0 ) { LCE("UdpSocket::doRecv[this0x" << this << "] argument err !!! len==0"); return false; } if (_recvBuf || _recvLen != 0 || _onRecvFromHandler) { LCE("UdpSocket::doRecv[this0x" << this << "] (_recvBuf != nullptr || _recvLen != 0) == TRUE"); return false; } _recvBuf = buf; _recvLen = len; _onRecvFromHandler = std::move(handler); _summer->setEvent(_fd, 0); return true; } bool UdpSocket::onSelectMessage(int type, bool rd, bool wt) { if (!_onRecvFromHandler) { LCE("UdpSocket::onSelectMessage[this0x" << this << "] unknown error"); return false; } if (rd && _onRecvFromHandler) { _OnRecvFromHandler onRecv(std::move(_onRecvFromHandler)); _summer->unsetEvent(_fd, 0); sockaddr_in raddr; memset(&raddr, 0, sizeof(raddr)); socklen_t len = sizeof(raddr); int ret = recvfrom(_fd, _recvBuf, _recvLen, 0, (sockaddr*)&raddr, &len); _recvBuf = nullptr; _recvLen = 0; if (ret == 0 || (ret ==-1 && !IS_WOULDBLOCK) ) { LCE("UdpSocket::onSelectMessage[this0x" << this << "] recv error. " << ", ret=" << ret << ", " << OSTREAM_GET_LASTERROR); onRecv(NEC_ERROR, "", 0, 0); return false; } if (ret == -1) { LCE("UdpSocket::onSelectMessage[this0x" << this << "] recv error. " << ", ret=" << ret << ", " << OSTREAM_GET_LASTERROR); onRecv(NEC_ERROR, "", 0, 0); return false; } onRecv(NEC_SUCCESS, inet_ntoa(raddr.sin_addr), ntohs(raddr.sin_port), ret); } return true; }
2,428
4,047
<reponame>iinuwa/meson # SPDX-license-identifier: Apache-2.0 # Copyright 2012-2021 The Meson development team # Copyright © 2021 Intel Corporation # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """base classes providing no-op functionality..""" import os import typing as T from .. import mlog __all__ = ['BuildDirLock'] # This needs to be inherited by the specific implementations to make type # checking happy class BuildDirLock: def __init__(self, builddir: str) -> None: self.lockfilename = os.path.join(builddir, 'meson-private/meson.lock') def __enter__(self) -> None: mlog.debug('Calling the no-op version of BuildDirLock') def __exit__(self, *args: T.Any) -> None: pass
370
3,282
<reponame>1060680253/AndroidChromium<gh_stars>1000+ // Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.webapps; import android.content.Intent; import android.util.Pair; import android.view.View; import android.view.ViewGroup; import org.chromium.base.annotations.SuppressFBWarnings; import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeActivity; import org.chromium.chrome.browser.TabState; import org.chromium.chrome.browser.compositor.layouts.LayoutManagerDocument; import org.chromium.chrome.browser.tab.EmptyTabObserver; import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.tab.TabDelegateFactory; import org.chromium.chrome.browser.tab.TabUma.TabCreationState; import org.chromium.chrome.browser.tabmodel.SingleTabModelSelector; import org.chromium.chrome.browser.tabmodel.TabModel.TabLaunchType; import org.chromium.chrome.browser.tabmodel.TabModel.TabSelectionType; import org.chromium.chrome.browser.tabmodel.TabModelSelector; import org.chromium.chrome.browser.tabmodel.document.TabDelegate; import org.chromium.chrome.browser.widget.ControlContainer; import org.chromium.content.browser.ContentViewCore; import org.chromium.content_public.browser.LoadUrlParams; import org.chromium.content_public.browser.WebContents; import org.chromium.content_public.browser.WebContentsObserver; import java.io.File; /** * Base class for task-focused activities that need to display web content in a nearly UI-less * Chrome (InfoBars still appear). * * This is vaguely analogous to a WebView, but in Chrome. Example applications that might use this * Activity would be webapps and streaming media activities - anything where user interaction with * the regular browser's UI is either unnecessary or undesirable. * Subclasses can override {@link #createUI()} if they need something more exotic. */ @SuppressFBWarnings("URF_UNREAD_FIELD") public abstract class FullScreenActivity extends ChromeActivity { protected static final String BUNDLE_TAB_ID = "tabId"; protected static final String BUNDLE_TAB_URL = "tabUrl"; private static final String TAG = "FullScreenActivity"; private Tab mTab; private WebContents mWebContents; @SuppressWarnings("unused") // Reference needed to prevent GC. private WebContentsObserver mWebContentsObserver; @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); setIntent(intent); } @Override protected TabModelSelector createTabModelSelector() { return new SingleTabModelSelector(this, false, false) { @Override public Tab openNewTab(LoadUrlParams loadUrlParams, TabLaunchType type, Tab parent, boolean incognito) { getTabCreator(incognito).createNewTab(loadUrlParams, type, parent); return null; } }; } @Override protected Pair<TabDelegate, TabDelegate> createTabCreators() { return Pair.create(createTabDelegate(false), createTabDelegate(true)); } /** Creates TabDelegates for opening new Tabs. */ protected TabDelegate createTabDelegate(boolean incognito) { return new TabDelegate(incognito); } @Override public void finishNativeInitialization() { mTab = createTab(); handleTabContentChanged(); getTabModelSelector().setTab(mTab); mTab.show(TabSelectionType.FROM_NEW); ControlContainer controlContainer = (ControlContainer) findViewById(R.id.control_container); initializeCompositorContent(new LayoutManagerDocument(getCompositorViewHolder()), (View) controlContainer, (ViewGroup) findViewById(android.R.id.content), controlContainer); if (getFullscreenManager() != null) getFullscreenManager().setTab(getActivityTab()); super.finishNativeInitialization(); } @Override protected void initializeToolbar() { } @Override public SingleTabModelSelector getTabModelSelector() { return (SingleTabModelSelector) super.getTabModelSelector(); } @Override public final Tab getActivityTab() { return mTab; } /** * Creates the {@link Tab} used by the FullScreenActivity. * If the {@code savedInstanceState} exists, then the user did not intentionally close the app * by swiping it away in the recent tasks list. In that case, we try to restore the tab from * disk. */ private Tab createTab() { Tab tab = null; boolean unfreeze = false; int tabId = Tab.INVALID_TAB_ID; String tabUrl = null; if (getSavedInstanceState() != null) { tabId = getSavedInstanceState().getInt(BUNDLE_TAB_ID, Tab.INVALID_TAB_ID); tabUrl = getSavedInstanceState().getString(BUNDLE_TAB_URL); } if (tabId != Tab.INVALID_TAB_ID && tabUrl != null && getActivityDirectory() != null) { // Restore the tab. TabState tabState = TabState.restoreTabState(getActivityDirectory(), tabId); tab = new Tab(tabId, Tab.INVALID_TAB_ID, false, this, getWindowAndroid(), TabLaunchType.FROM_RESTORE, TabCreationState.FROZEN_ON_RESTORE, tabState); unfreeze = true; } if (tab == null) { tab = new Tab(Tab.INVALID_TAB_ID, Tab.INVALID_TAB_ID, false, this, getWindowAndroid(), TabLaunchType.FROM_CHROME_UI, null, null); } tab.initialize(null, getTabContentManager(), createTabDelegateFactory(), false, unfreeze); tab.addObserver(new EmptyTabObserver() { @Override public void onContentChanged(Tab tab) { assert tab == mTab; handleTabContentChanged(); } }); return tab; } private void handleTabContentChanged() { assert mTab != null; WebContents webContents = mTab.getWebContents(); if (mWebContents == webContents) return; // Clean up any old references to the previous WebContents. if (mWebContentsObserver != null) { mWebContentsObserver.destroy(); mWebContentsObserver = null; } mWebContents = webContents; if (mWebContents == null) return; ContentViewCore.fromWebContents(webContents).setFullscreenRequiredForOrientationLock(false); mWebContentsObserver = new WebContentsObserver(webContents) { @Override public void didCommitProvisionalLoadForFrame( long frameId, boolean isMainFrame, String url, int transitionType) { if (!isMainFrame) return; // Notify the renderer to permanently hide the top controls since they do // not apply to fullscreen content views. mTab.updateBrowserControlsState(mTab.getBrowserControlsStateConstraints(), true); } }; } /** * @return {@link TabDelegateFactory} to be used while creating the associated {@link Tab}. */ protected TabDelegateFactory createTabDelegateFactory() { return new FullScreenDelegateFactory(); } /** * @return {@link File} pointing at a directory specific for this class. */ protected File getActivityDirectory() { return null; } @Override protected boolean handleBackPressed() { if (mTab == null) return false; if (mTab.canGoBack()) { mTab.goBack(); return true; } return false; } @Override public void onCheckForUpdate(boolean updateAvailable) { } }
2,972
358
// Copyright 2018 The Ripple 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. #include "encryption.h" #include <arpa/inet.h> // htonl #include <cstdlib> #include <cstring> #include "absl/strings/string_view.h" #include "my_crypt.h" #include "my_crypt_key_management.h" #include "byte_order.h" #include "flags.h" #include "log_event.h" #include "logging.h" #include "monitoring.h" #include "mysql_constants.h" namespace mysql_ripple { static const int kKeyLength = 16; static const int kNonceLength = 16; static const int kIvLength = 20; static const int kTagLength = 16; class ExampleKeyHandler : public KeyHandler { public: ExampleKeyHandler() {} virtual ~ExampleKeyHandler() {} KeyHandler *Copy() const override { return new ExampleKeyHandler(); } uint32_t GetLatestKeyVersion() override { return time(0); } bool GetKeyBytes(uint32_t key_version, uint8_t *dst, int len) { // This code is copied from MariaDB to produce compatible // keys in debug mode if (len < sizeof(key_version)) return false; memset(dst, 0, len); key_version = htonl(key_version); memcpy(dst, &key_version, sizeof(key_version)); return true; } }; KeyHandler* KeyHandler::GetInstance(bool example) { if (example) return new ExampleKeyHandler(); else return new KeyHandler(); } KeyHandler* KeyHandler::Copy() const { return new KeyHandler(); } uint32_t KeyHandler::GetLatestKeyVersion() { return ::GetLatestCryptoKeyVersion(); } bool KeyHandler::GetKeyBytes(uint32_t key_version, uint8_t *dst, int len) { return ::GetCryptoKey(key_version, dst, len) == 0; } bool KeyHandler::GetRandomBytes(uint8_t *dst, int len) { return ::RandomBytes(dst, len) == CRYPT_OK; } AesGcmBinlogEncryptor::AesGcmBinlogEncryptor(int crypt_scheme, KeyHandler *key_handler) : crypt_scheme_(crypt_scheme), key_handler_(key_handler) { key_.Append(kKeyLength); iv_.Append(kIvLength); } AesGcmBinlogEncryptor::AesGcmBinlogEncryptor(const AesGcmBinlogEncryptor& orig) : crypt_scheme_(orig.crypt_scheme_), key_handler_(orig.key_handler_->Copy()) { key_.Append(kKeyLength); iv_.Append(kIvLength); SetKeyAndNonce(orig.key_version_, orig.iv_.data(), kNonceLength); } bool AesGcmBinlogEncryptor::Init() { Buffer buf; buf.Append(kNonceLength); if (!key_handler_->GetRandomBytes(buf.data(), buf.size())) { return false; } return SetKeyAndNonce(key_handler_->GetLatestKeyVersion(), buf.data(), buf.size()); } BinlogEncryptor *AesGcmBinlogEncryptor::Copy() const { return new AesGcmBinlogEncryptor(*this); } bool AesGcmBinlogEncryptor::SetKeyAndNonce(uint32_t version, const uint8_t *nonce, int len) { assert(key_.size() == kKeyLength); assert(iv_.size() == kIvLength); if (len != kNonceLength) { return false; } key_version_ = version; if (!key_handler_->GetKeyBytes(version, key_.data(), key_.size())) { LOG(ERROR) << "Failed to GetKeyBytes()" << ", version: " << version << ", size: " << key_.size(); monitoring::rippled_binlog_error->Increment( monitoring::ERROR_GET_KEY_BYTES); return false; } memcpy(iv_.data(), nonce, len); return true; } bool AesGcmBinlogEncryptor::Encrypt(off_t pos, const uint8_t *src, int len, Buffer *dst) { byte_order::store4(iv_.data() + kNonceLength, pos); Aes128GcmEncrypter encrypter; if (encrypter.Init(key_.data(), iv_.data(), iv_.size()) != CRYPT_OK) { LOG(ERROR) << "Failed to encrypt log event" << ", encrypter.Init() failed"; monitoring::rippled_binlog_error->Increment( monitoring::ERROR_INIT_ENCRYPTOR); return false; } dst->resize(4 + len + kTagLength); // 1. store length. byte_order::store4(dst->data(), len); // 2. store encrypted event. int encrypted_len = 0; if (encrypter.Encrypt(src, len, dst->data() + 4, &encrypted_len) != CRYPT_OK) { LOG(ERROR) << "Failed to encrypt log event" << ", encrypter.Encrypt() failed"; monitoring::rippled_binlog_error->Increment( monitoring::ERROR_ENCRYPT); return false; } if (encrypted_len != len) { LOG(ERROR) << "Failed to encrypt log event" << ", encrypted_len: " << encrypted_len << ", len: " << len; monitoring::rippled_binlog_error->Increment( monitoring::ERROR_ENCRYPT); return false; } // 3. store tag. if (encrypter.GetTag(dst->data() + 4 + len, kTagLength) != CRYPT_OK) { LOG(ERROR) << "Failed to encrypt log event" << ", encrypter.GetTag() returned error"; monitoring::rippled_binlog_error->Increment( monitoring::ERROR_ENCRYPT); return false; } return true; } bool AesGcmBinlogEncryptor::Decrypt(off_t pos, const uint8_t *src, int len, Buffer *dst) { byte_order::store4(iv_.data() + kNonceLength, pos); Aes128GcmDecrypter decrypter; if (decrypter.Init(key_.data(), iv_.data(), iv_.size()) != CRYPT_OK) { LOG(WARNING) << "Failed to decrypt log event" << ", decrypter.Init() failed"; return false; } // 1. read length. int event_len = byte_order::load4(src); if (len != (4 + event_len + kTagLength)) { LOG(WARNING) << "Failed to decrypt log event" << ", len: " << len << ", event_len: " << event_len << ", kTagLength: " << kTagLength; return false; } // 2. read and set tag. if (decrypter.SetTag(src + 4 + event_len, kTagLength) != CRYPT_OK) { LOG(WARNING) << "Failed to decrypt log event" << ", decrypter.SetTag() failed"; return false; } // 3. decrypt. int decrypted_len = 0; dst->resize(event_len); if (decrypter.Decrypt(src + 4, event_len, dst->data(), &decrypted_len) != CRYPT_OK) { LOG(WARNING) << "Failed to decrypt log event" << ", decrypter.Decrypt() failed"; return false; } if (decrypted_len != event_len) { LOG(WARNING) << "Failed to decrypt log event" << ", decrypted_len: " << decrypted_len << ", event_len: " << event_len; return false; } // 4. check tag. if (decrypter.CheckTag() != CRYPT_OK) { LOG(WARNING) << "Failed to decrypt log event" << ", decrypter.CheckTag() failed"; return false; } return true; } int AesGcmBinlogEncryptor::GetExtraSize() const { return 4 + kTagLength; } file_util::ReadResultCode AesGcmBinlogEncryptor::Read(file::InputFile *file, off_t end_of_file, Buffer *dst) { int64_t offset; file->Tell(&offset); if (offset + 4 > end_of_file) { return file_util::READ_EOF; } buffer_.clear(); if (!file->Read(buffer_, 4)) { LOG(WARNING) << "Failed to read encrypted log event" << ", offset: " << offset; return file_util::READ_ERROR; } int len = byte_order::load4(buffer_.data()); int remaining = len + GetExtraSize() - 4; if (offset + len + GetExtraSize() > end_of_file) { LOG(WARNING) << "Failed to read encrypted log event" << ", offset: " << offset << ", len: " << len << ", GetExtraSize(): " << GetExtraSize() << ", end_of_file: " << end_of_file; return file_util::READ_EOF; } if (remaining != 0 && !file->Read(buffer_, remaining)) { LOG(WARNING) << "Failed to read encrypted log event" << ", offset: " << offset << ", remaining: " << remaining; return file_util::READ_ERROR; } if (!Decrypt(offset, buffer_.data(), buffer_.size(), dst)) { LOG(WARNING) << "Failed to read encrypted log event" << ", offset: " << offset << ", Decrypt() failed"; return file_util::READ_ERROR; } return file_util::READ_OK; } bool AesGcmBinlogEncryptor::Write(file::AppendOnlyFile *file, absl::string_view src) { int64_t offset; if (!file->Tell(&offset)) { LOG(WARNING) << "Failed to write encrypted log event" << ", Tell() failed!"; return false; } if (!Encrypt(offset, reinterpret_cast<const unsigned char *>(src.data()), src.size(), &buffer_)) { LOG(WARNING) << "Failed to write encrypted log event" << ", offset: " << offset << ", Encrypt() failed!"; return false; } absl::string_view data(reinterpret_cast<const char *>(buffer_.data()), buffer_.size()); if (!file->Write(data)) { LOG(WARNING) << "Failed to write encrypted log event" << ", offset: " << offset << ", length: " << buffer_.size(); return false; } return true; } int AesGcmBinlogEncryptor::GetStartEncryptionEvent(const LogEventHeader& head, Buffer *dst) const { StartEncryptionEvent event; event.crypt_scheme = crypt_scheme_; if (crypt_scheme_ == 255 && FLAGS_danger_danger_use_dbug_keys) { // store 1 even if we use fake keys (i.e 255) event.crypt_scheme = 1; } else { event.crypt_scheme = crypt_scheme_; } event.key_version = key_version_; event.nonce.assign(reinterpret_cast<const char*>(iv_.data()), kNonceLength); LogEventHeader header(head); header.type = constants::ET_START_ENCRYPTION; header.event_length = header.PackLength() + event.PackLength(); header.nextpos += header.event_length; uint8_t *ptr = dst->Append(header.event_length); if (!header.SerializeToBuffer(ptr, header.event_length)) return -1; if (!event.SerializeToBuffer(ptr + header.PackLength(), header.event_length - header.PackLength())) return -1; return 1; } BinlogEncryptor *NullBinlogEncryptor::Copy() const { return new NullBinlogEncryptor(); } file_util::ReadResultCode NullBinlogEncryptor::Read(file::InputFile *file, off_t end_of_file, Buffer *dst) { int64_t offset; file->Tell(&offset); if (offset + constants::LOG_EVENT_HEADER_LENGTH > end_of_file) { return file_util::READ_EOF; } dst->clear(); if (!file->Read(*dst, constants::LOG_EVENT_HEADER_LENGTH)) { LOG(WARNING) << "Failed to read unencrypted log event" << ", offset: " << offset << ", len: " << constants::LOG_EVENT_HEADER_LENGTH; return file_util::READ_ERROR; } LogEventHeader header; if (!header.ParseFromBuffer(dst->data(), dst->size())) { LOG(WARNING) << "Failed to read unencrypted log event" << ", offset: " << offset << ", LogEventHeader.Parse failed"; return file_util::READ_ERROR; } int length = header.event_length; int remaining = length - dst->size(); if (offset + length > end_of_file) { LOG(WARNING) << "Failed to read unencrypted log event" << ", offset: " << offset << ", length: " << length << ", end_of_file: " << end_of_file; return file_util::READ_EOF; } if (remaining != 0 && !file->Read(*dst, remaining)) { LOG(WARNING) << "Failed to read unencrypted log event" << ", offset: " << offset << ", remaining: " << remaining; return file_util::READ_ERROR; } return file_util::READ_OK; } bool NullBinlogEncryptor::Write(file::AppendOnlyFile *file, absl::string_view src) { int64_t offset; file->Tell(&offset); bool ok = file->Write(src); if (!ok) { LOG(WARNING) << "Failed to write unencrypted log event" << ", offset: " << offset << ", len: " << src.size(); } return ok; } BinlogEncryptor* BinlogEncryptorFactory::GetInstance(int crypt_scheme) { switch (crypt_scheme) { case 0: return new NullBinlogEncryptor(); case 1: case 255: if (crypt_scheme == 1 && FLAGS_danger_danger_use_dbug_keys) crypt_scheme = 255; // 255 = example key handler return new AesGcmBinlogEncryptor( crypt_scheme, KeyHandler::GetInstance(crypt_scheme == 255)); } return nullptr; } BinlogEncryptor *BinlogEncryptorFactory::GetInstance( RawLogEventData raw_event) { assert(raw_event.header.type == constants::ET_START_ENCRYPTION); if (raw_event.header.type != constants::ET_START_ENCRYPTION) { return nullptr; } StartEncryptionEvent event; if (!ParseFromRawLogEventData(&event, raw_event)) { assert(false); return nullptr; } if (event.crypt_scheme == 0) { return new NullBinlogEncryptor(); } if (!(event.crypt_scheme == 1 || event.crypt_scheme == 255)) { assert(false); return nullptr; } if (event.crypt_scheme == 1 && FLAGS_danger_danger_use_dbug_keys) event.crypt_scheme = 255; // scheme 255 => example key handler... KeyHandler *key_handler = KeyHandler::GetInstance(event.crypt_scheme == 255); AesGcmBinlogEncryptor *aes = new AesGcmBinlogEncryptor(event.crypt_scheme, key_handler); if (!aes->SetKeyAndNonce(event.key_version, reinterpret_cast<const uint8_t*>(event.nonce.data()), event.nonce.size())) { delete aes; return nullptr; } return aes; } } // namespace mysql_ripple
6,042
575
// Copyright 2020 Proyectos y Sistemas de Mantenimiento SL (eProsima). // // 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 TopicPayloadPoolProxy.hpp */ #ifndef RTPS_HISTORY_TOPICPAYLOADPOOLREGISTRY_IMPL_TOPICPAYLOADPOOLPROXY_HPP #define RTPS_HISTORY_TOPICPAYLOADPOOLREGISTRY_IMPL_TOPICPAYLOADPOOLPROXY_HPP #include <memory> #include <string> namespace eprosima { namespace fastrtps { namespace rtps { namespace detail { /** * Proxy class that adds the topic name to a ITopicPayloadPool, so we can look-up * the corresponding entry in the registry when releasing the pool. */ class TopicPayloadPoolProxy : public ITopicPayloadPool { public: TopicPayloadPoolProxy( const std::string& topic_name, const BasicPoolConfig& config) : topic_name_(topic_name) , policy_(config.memory_policy) , inner_pool_(TopicPayloadPool::get(config)) { } const std::string& topic_name() const { return topic_name_; } MemoryManagementPolicy_t memory_policy() const { return policy_; } bool get_payload( uint32_t size, CacheChange_t& cache_change) override { return inner_pool_->get_payload(size, cache_change); } bool get_payload( SerializedPayload_t& data, IPayloadPool*& data_owner, CacheChange_t& cache_change) override { return inner_pool_->get_payload(data, data_owner, cache_change); } bool release_payload( CacheChange_t& cache_change) override { return inner_pool_->release_payload(cache_change); } bool reserve_history( const PoolConfig& config, bool is_reader) override { return inner_pool_->reserve_history(config, is_reader); } bool release_history( const PoolConfig& config, bool is_reader) override { return inner_pool_->release_history(config, is_reader); } size_t payload_pool_allocated_size() const override { return inner_pool_->payload_pool_allocated_size(); } size_t payload_pool_available_size() const override { return inner_pool_->payload_pool_available_size(); } private: std::string topic_name_; MemoryManagementPolicy_t policy_; std::unique_ptr<ITopicPayloadPool> inner_pool_; }; } // namespace detail } // namespace rtps } // namespace fastrtps } // namespace eprosima #endif // RTPS_HISTORY_TOPICPAYLOADPOOLREGISTRY_IMPL_TOPICPAYLOADPOOLPROXY_HPP
1,196
852
#include "FWCore/PluginManager/interface/ModuleDef.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "RecoHI/HiTracking/interface/HICaloCompatibleTrackSelector.h" using reco::modules::HICaloCompatibleTrackSelector; DEFINE_FWK_MODULE(HICaloCompatibleTrackSelector);
97
752
<filename>pt/hubconf.py dependencies = ["torch", "torchvision"] from vmz.models import r2plus1d_34, r2plus1d_152, ip_csn_152, ir_csn_152
60
2,542
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" using namespace Common; using namespace std; using namespace Management::RepairManager; StringLiteral const TraceComponent("RepairTaskContext"); RepairTaskContext::RepairTaskContext() : StoreData() , task_() , lock_() , needsRefresh_(false) , getStatusOnly_(false) { } RepairTaskContext::RepairTaskContext(RepairTask const & task) : StoreData() , task_(task) , lock_() , needsRefresh_(false) , getStatusOnly_(false) { } RepairTaskContext::RepairTaskContext(RepairTaskContext && other) : StoreData(move(other)) , task_(move(other.task_)) , lock_() , needsRefresh_(other.needsRefresh_) , getStatusOnly_(other.getStatusOnly_) { } RepairTaskContext const & RepairTaskContext::operator = (RepairTaskContext const & other) { StoreData::operator = (other); task_ = other.task_; needsRefresh_ = other.needsRefresh_; getStatusOnly_ = other.getStatusOnly_; return *this; } RepairTaskContext::~RepairTaskContext() { } std::wstring const & RepairTaskContext::get_Type() const { return Constants::StoreType_RepairTaskContext; } std::wstring RepairTaskContext::ConstructKey() const { return task_.TaskId; } std::wstring RepairTaskContext::ConstructDeactivationBatchId() const { wstring batchId(ServiceModel::Constants::NodeDeactivationTaskIdPrefixRM.cbegin()); batchId.append(task_.TaskId); return batchId; } void RepairTaskContext::WriteTo(Common::TextWriter & w, Common::FormatOptions const &) const { w.Write("RepairTaskContext[{0}]", task_); }
607
3,442
<reponame>wcicola/jitsi<gh_stars>1000+ /* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Copyright @ 2015 Atlassian Pty 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. */ package net.java.sip.communicator.impl.packetlogging; import net.java.sip.communicator.util.*; import org.jitsi.service.configuration.*; import org.jitsi.service.fileaccess.*; import org.jitsi.service.packetlogging.*; import org.osgi.framework.*; /** * Creates and registers Packet Logging service into OSGi. * Also handles saving and retrieving configuration options for * the service and is used from the configuration form. * * @author <NAME> */ public class PacketLoggingActivator implements BundleActivator { /** * Our logging. */ private static Logger logger = Logger.getLogger(PacketLoggingActivator.class); /** * The OSGI bundle context. */ private static BundleContext bundleContext = null; /** * Our packet logging service instance. */ private static PacketLoggingServiceImpl packetLoggingService = null; /** * The configuration service. */ private static ConfigurationService configurationService = null; /** * The service giving access to files. */ private static FileAccessService fileAccessService; /** * The name of the log dir. */ final static String LOGGING_DIR_NAME = "log"; /** * Creates a PacketLoggingServiceImpl, starts it, and registers it as a * PacketLoggingService. * * @param bundleContext OSGI bundle context * @throws Exception if starting the PacketLoggingServiceImpl. */ public void start(BundleContext bundleContext) throws Exception { /* * PacketLoggingServiceImpl requires a FileAccessService implementation. * Ideally, we'd be listening to the bundleContext and will be making * the PacketLoggingService implementation available in accord with the * availability of a FileAccessService implementation. Unfortunately, * the real world is far from ideal. */ fileAccessService = ServiceUtils.getService(bundleContext, FileAccessService.class); if (fileAccessService != null) { PacketLoggingActivator.bundleContext = bundleContext; packetLoggingService = new PacketLoggingServiceImpl(); packetLoggingService.start(); bundleContext.registerService( PacketLoggingService.class.getName(), packetLoggingService, null); if (logger.isInfoEnabled()) logger.info("Packet Logging Service ...[REGISTERED]"); } } /** * Stops the Packet Logging bundle * * @param bundleContext the OSGI bundle context */ public void stop(BundleContext bundleContext) throws Exception { if(packetLoggingService != null) packetLoggingService.stop(); configurationService = null; fileAccessService = null; packetLoggingService = null; if (logger.isInfoEnabled()) logger.info("Packet Logging Service ...[STOPPED]"); } /** * Returns a reference to a ConfigurationService implementation currently * registered in the bundle context or null if no such implementation was * found. * * @return a currently valid implementation of the ConfigurationService. */ public static ConfigurationService getConfigurationService() { if (configurationService == null) { ServiceReference confReference = bundleContext.getServiceReference( ConfigurationService.class.getName()); configurationService = (ConfigurationService) bundleContext.getService(confReference); } return configurationService; } /** * Returns the <tt>FileAccessService</tt> obtained from the bundle context. * * @return the <tt>FileAccessService</tt> obtained from the bundle context */ public static FileAccessService getFileAccessService() { return fileAccessService; } }
1,730
765
/***************************************************************************** Licensed to Accellera Systems Initiative Inc. (Accellera) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Accellera 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. *****************************************************************************/ /***************************************************************************** test03.cpp -- Original Author: <NAME>, Forte Design Systems, 2003-01-17 *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation, Date: Description of Modification: *****************************************************************************/ // test and l-value bit selection concatenation on sc_lv and sc_bv // also test set_word() and set_cword on bit selections #include "systemc.h" int sc_main(int argc, char* argv[]) { sc_bv<64> bv1; sc_bv<64> bv2; sc_lv<64> lv1; sc_lv<64> lv2; cout << endl; cout << "6666555555555544444444443333333333222222222211111111110000000000" << endl; cout << "3210987654321098765432109876543210987654321098765432109876543210" << endl; cout << "----------------------------------------------------------------" << endl; // LV SUPPORT: cout << lv1 << " lv1" << endl; cout << lv2 << " lv2 " << endl; cout << " (lv1[33], lv2[34]) = 0 " << endl; (lv1[33], lv2[34]) = 0; cout << lv1 << " lv1" << endl; cout << lv2 << " lv2 " << endl; cout << "lv1[43].set_cword(0, 0) " << endl; lv1[43].set_cword(0, 0); cout << lv1 << " lv1" << endl; cout << "lv2[44].set_word(0, 0)" << endl; lv2[44].set_word(0, 0); cout << lv2 << " lv2" << endl; cout << "(lv1,lv2[9]) = 0" << endl; (lv1,lv2[9]) = 0; cout << lv1 << " lv1 " << endl; cout << lv2 << " lv2 " << endl; cout << "(lv2[9], lv1) = -1ll" << endl; (lv2[9], lv1) = -1ll; cout << lv1 << " lv1 " << endl; cout << lv2 << " lv2 " << endl; // BV SUPPORT: cout << endl; cout << bv1 << " bv1" << endl; cout << bv2 << " bv2" << endl; cout << "(bv1[33], bv2[34]) = 3" << endl; (bv1[33], bv2[34]) = 3; cout << bv1 << " bv1" << endl; cout << bv2 << " bv2" << endl; cout << "bv1[43].set_word(0, 1)" << endl; bv1[43].set_word(0, 1); cout << bv1 << " bv1" << endl; cout << "(bv1,bv2[9]) = 0" << endl; (bv1,bv2[9]) = 0; cout << bv1 << " bv1" << endl; cout << bv2 << " bv2 " << endl; cout << "(bv2[9], bv1) = -1ll" << endl; (bv2[9], bv1) = -1ll; cout << bv1 << " bv1" << endl; cout << bv2 << " bv2 " << endl; cout << "Program completed" << endl; return 0; }
1,272
683
<gh_stars>100-1000 /* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ package io.opentelemetry.javaagent.instrumentation.servlet.v3_0; import static io.opentelemetry.javaagent.instrumentation.servlet.v3_0.Servlet3Singletons.helper; import io.opentelemetry.context.Context; import io.opentelemetry.context.Scope; import io.opentelemetry.instrumentation.api.servlet.AppServerBridge; import io.opentelemetry.instrumentation.api.servlet.MappingResolver; import io.opentelemetry.instrumentation.api.tracer.ServerSpan; import io.opentelemetry.javaagent.instrumentation.api.CallDepth; import io.opentelemetry.javaagent.instrumentation.api.Java8BytecodeBridge; import io.opentelemetry.javaagent.instrumentation.servlet.ServletRequestContext; import javax.servlet.Servlet; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.bytebuddy.asm.Advice; import net.bytebuddy.implementation.bytecode.assign.Assigner; @SuppressWarnings("unused") public class Servlet3Advice { @Advice.OnMethodEnter(suppress = Throwable.class) public static void onEnter( @Advice.This(typing = Assigner.Typing.DYNAMIC) Object servletOrFilter, @Advice.Argument(value = 0, readOnly = false) ServletRequest request, @Advice.Argument(value = 1, readOnly = false) ServletResponse response, @Advice.Local("otelCallDepth") CallDepth callDepth, @Advice.Local("otelRequest") ServletRequestContext<HttpServletRequest> requestContext, @Advice.Local("otelContext") Context context, @Advice.Local("otelScope") Scope scope) { if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) { return; } callDepth = CallDepth.forClass(AppServerBridge.getCallDepthKey()); callDepth.getAndIncrement(); HttpServletRequest httpServletRequest = (HttpServletRequest) request; Context currentContext = Java8BytecodeBridge.currentContext(); Context attachedContext = helper().getServerContext(httpServletRequest); if (attachedContext != null && helper().needsRescoping(currentContext, attachedContext)) { MappingResolver mappingResolver = Servlet3Singletons.getMappingResolver(servletOrFilter); boolean servlet = servletOrFilter instanceof Servlet; attachedContext = helper().updateContext(attachedContext, httpServletRequest, mappingResolver, servlet); scope = attachedContext.makeCurrent(); // We are inside nested servlet/filter/app-server span, don't create new span return; } if (attachedContext != null || ServerSpan.fromContextOrNull(currentContext) != null) { // Update context with info from current request to ensure that server span gets the best // possible name. // In case server span was created by app server instrumentations calling updateContext // returns a new context that contains servlet context path that is used in other // instrumentations for naming server span. MappingResolver mappingResolver = Servlet3Singletons.getMappingResolver(servletOrFilter); boolean servlet = servletOrFilter instanceof Servlet; Context updatedContext = helper().updateContext(currentContext, httpServletRequest, mappingResolver, servlet); if (currentContext != updatedContext) { // updateContext updated context, need to re-scope scope = updatedContext.makeCurrent(); } // We are inside nested servlet/filter/app-server span, don't create new span return; } requestContext = new ServletRequestContext<>(httpServletRequest, servletOrFilter); if (!helper().shouldStart(currentContext, requestContext)) { return; } context = helper().start(currentContext, requestContext); scope = context.makeCurrent(); helper().setAsyncListenerResponse(httpServletRequest, (HttpServletResponse) response); } @Advice.OnMethodExit(onThrowable = Throwable.class, suppress = Throwable.class) public static void stopSpan( @Advice.Argument(0) ServletRequest request, @Advice.Argument(1) ServletResponse response, @Advice.Thrown Throwable throwable, @Advice.Local("otelCallDepth") CallDepth callDepth, @Advice.Local("otelRequest") ServletRequestContext<HttpServletRequest> requestContext, @Advice.Local("otelContext") Context context, @Advice.Local("otelScope") Scope scope) { if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) { return; } boolean topLevel = callDepth.decrementAndGet() == 0; helper() .end( requestContext, (HttpServletRequest) request, (HttpServletResponse) response, throwable, topLevel, context, scope); } }
1,685
3,083
// Copyright 2011-2016 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.security.zynamics.binnavi.disassembly; import com.google.security.zynamics.zylib.disassembly.IOperandTree; /** * Interface that represents operand trees. */ public interface INaviOperandTree extends IOperandTree { /** * Returns the instruction the operand tree belongs to. * * @return The instruction the operand tree belongs to. */ INaviInstruction getInstruction(); @Override INaviOperandTreeNode getRootNode(); }
288
862
/* * (c) Copyright 2020 Palantir Technologies Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.palantir.paxos; import static com.palantir.paxos.PaxosStateLogMigrator.BATCH_SIZE; import static com.palantir.paxos.PaxosStateLogTestUtils.NAMESPACE; import static com.palantir.paxos.PaxosStateLogTestUtils.getPaxosValue; import static com.palantir.paxos.PaxosStateLogTestUtils.readRoundUnchecked; import static com.palantir.paxos.PaxosStateLogTestUtils.valueForRound; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.palantir.common.streams.KeyedStream; import java.io.IOException; import java.util.List; import java.util.OptionalLong; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import java.util.stream.LongStream; import javax.sql.DataSource; import org.assertj.core.api.AbstractAssert; import org.assertj.core.api.Assertions; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; public class PaxosStateLogMigratorTest { private static final NamespaceAndUseCase NAMESPACE_AND_USE_CASE = ImmutableNamespaceAndUseCase.of(Client.of("client"), "UseCase"); @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); private PaxosStateLog<PaxosValue> source; private PaxosStateLog<PaxosValue> target; private SqlitePaxosStateLogMigrationState migrationState; @Before public void setup() throws IOException { DataSource sourceConn = SqliteConnections.getDefaultConfiguredPooledDataSource( tempFolder.newFolder("source").toPath()); DataSource targetConn = SqliteConnections.getDefaultConfiguredPooledDataSource( tempFolder.newFolder("target").toPath()); source = SqlitePaxosStateLog.create(NAMESPACE, sourceConn); target = spy(SqlitePaxosStateLog.create(NAMESPACE, targetConn)); migrationState = SqlitePaxosStateLogMigrationState.create(NAMESPACE, targetConn); } @Test public void emptyLogMigrationSuccessfullyMarksAsMigrated() { long cutoff = migrateFrom(source); assertThat(migrationState.hasMigratedFromInitialState()).isTrue(); assertThat(cutoff).isEqualTo(PaxosAcceptor.NO_LOG_ENTRY); } @Test public void logMigrationWithNoLowerBoundMigratesForGreatest() { long lowerBound = 10; long upperBound = 75; long expectedCutoff = upperBound - PaxosStateLogMigrator.SAFETY_BUFFER; insertValuesWithinBounds(lowerBound, upperBound, source); long cutoff = migrateFrom(source); assertThat(cutoff).isEqualTo(expectedCutoff); assertThat(migrationState.hasMigratedFromInitialState()).isTrue(); assertThat(migrationState.isInMigratedState()).isTrue(); assertThat(target.getLeastLogEntry()).isEqualTo(expectedCutoff); assertThat(target.getGreatestLogEntry()).isEqualTo(upperBound); LongStream.rangeClosed(lowerBound, expectedCutoff - 1) .mapToObj(sequence -> readRoundUnchecked(target, sequence)) .map(Assertions::assertThat) .forEach(AbstractAssert::isNull); KeyedStream.of(LongStream.rangeClosed(expectedCutoff, upperBound).boxed()) .map(sequence -> getPaxosValue(target, sequence)) .mapKeys(PaxosStateLogTestUtils::valueForRound) .entries() .forEach(entry -> assertThat(entry.getKey()).isEqualTo(entry.getValue())); } @Test public void logMigrationWithLowerBoundMigratesForBound() { long lowerBound = 10; long upperBound = 75; insertValuesWithinBounds(lowerBound, upperBound, source); long bound = 60; long expectedCutoff = bound - PaxosStateLogMigrator.SAFETY_BUFFER; long cutoff = migrateFrom(source, OptionalLong.of(bound)); assertThat(cutoff).isEqualTo(expectedCutoff); assertThat(migrationState.hasMigratedFromInitialState()).isTrue(); assertThat(migrationState.isInMigratedState()).isTrue(); assertThat(target.getLeastLogEntry()).isEqualTo(expectedCutoff); assertThat(target.getGreatestLogEntry()).isEqualTo(upperBound); LongStream.rangeClosed(lowerBound, expectedCutoff - 1) .mapToObj(sequence -> readRoundUnchecked(target, sequence)) .map(Assertions::assertThat) .forEach(AbstractAssert::isNull); KeyedStream.of(LongStream.rangeClosed(expectedCutoff, upperBound).boxed()) .map(sequence -> getPaxosValue(target, sequence)) .mapKeys(PaxosStateLogTestUtils::valueForRound) .entries() .forEach(entry -> assertThat(entry.getKey()).isEqualTo(entry.getValue())); assertThat(source.getGreatestLogEntry()).isEqualTo(upperBound); } @Test public void stillMigrateWhenValidationIsSkippedButAlsoTruncateSource() { long lowerBound = 10; long upperBound = 75; insertValuesWithinBounds(lowerBound, upperBound, source); long bound = 60; long expectedCutoff = bound - PaxosStateLogMigrator.SAFETY_BUFFER; long cutoff = migrateFrom(source, OptionalLong.of(bound), true); assertThat(cutoff).isEqualTo(expectedCutoff); assertThat(migrationState.hasMigratedFromInitialState()).isTrue(); assertThat(migrationState.isInMigratedState()).isTrue(); assertThat(target.getLeastLogEntry()).isEqualTo(expectedCutoff); assertThat(target.getGreatestLogEntry()).isEqualTo(upperBound); LongStream.rangeClosed(lowerBound, expectedCutoff - 1) .mapToObj(sequence -> readRoundUnchecked(target, sequence)) .map(Assertions::assertThat) .forEach(AbstractAssert::isNull); KeyedStream.of(LongStream.rangeClosed(expectedCutoff, upperBound).boxed()) .map(sequence -> getPaxosValue(target, sequence)) .mapKeys(PaxosStateLogTestUtils::valueForRound) .entries() .forEach(entry -> assertThat(entry.getKey()).isEqualTo(entry.getValue())); assertThat(source.getGreatestLogEntry()).isEqualTo(PaxosAcceptor.NO_LOG_ENTRY); } @Test public void whenBoundIsLowMigrateEverything() { long lowerBound = 10; long upperBound = 75; List<PaxosValue> insertedValues = insertValuesWithinBounds(lowerBound, upperBound, source); long expectedCutoff = PaxosAcceptor.NO_LOG_ENTRY; long cutoff = migrateFrom(source, OptionalLong.of(PaxosStateLogMigrator.SAFETY_BUFFER - 10)); assertThat(cutoff).isEqualTo(expectedCutoff); assertThat(migrationState.hasMigratedFromInitialState()).isTrue(); assertThat(migrationState.isInMigratedState()).isTrue(); assertThat(target.getLeastLogEntry()).isEqualTo(lowerBound); assertThat(target.getGreatestLogEntry()).isEqualTo(upperBound); insertedValues.forEach(value -> assertThat(value).isEqualTo(getPaxosValue(target, value.seq))); } @Test public void whenBoundIsTooHighMigrateOneEntry() { long lowerBound = 10; long upperBound = 75; insertValuesWithinBounds(lowerBound, upperBound, source); long bound = 10_000; long cutoff = migrateFrom(source, OptionalLong.of(bound)); assertThat(cutoff).isEqualTo(upperBound); assertThat(migrationState.hasMigratedFromInitialState()).isTrue(); assertThat(migrationState.isInMigratedState()).isTrue(); assertThat(target.getLeastLogEntry()).isEqualTo(upperBound); assertThat(target.getGreatestLogEntry()).isEqualTo(upperBound); LongStream.rangeClosed(lowerBound, upperBound - 1) .mapToObj(sequence -> readRoundUnchecked(target, sequence)) .map(Assertions::assertThat) .forEach(AbstractAssert::isNull); assertThat(getPaxosValue(target, upperBound)).isEqualTo(valueForRound(upperBound)); } @Test public void migrationDeletesExistingState() { long lowerBound = 13; long upperBound = 35; insertValuesWithinBounds(lowerBound, upperBound, target); long cutoff = migrateFrom(source); assertThat(cutoff).isEqualTo(PaxosAcceptor.NO_LOG_ENTRY); assertThat(migrationState.hasMigratedFromInitialState()).isTrue(); assertThat(target.getLeastLogEntry()).isEqualTo(PaxosAcceptor.NO_LOG_ENTRY); assertThat(target.getGreatestLogEntry()).isEqualTo(PaxosAcceptor.NO_LOG_ENTRY); verify(target, times(1)).truncate(upperBound); } @Test public void migrateIfInValidationState() { long lowerBound = 10; long upperBound = 75; insertValuesWithinBounds(lowerBound, upperBound, source); migrationState.migrateToValidationState(); long cutoff = migrateFrom(source); assertThat(cutoff).isEqualTo(upperBound - PaxosStateLogMigrator.SAFETY_BUFFER); assertThat(migrationState.isInMigratedState()).isTrue(); assertThat(target.getLeastLogEntry()).isEqualTo(upperBound - PaxosStateLogMigrator.SAFETY_BUFFER); assertThat(target.getGreatestLogEntry()).isEqualTo(upperBound); verify(target, times(1)).truncate(anyLong()); } @Test public void doNotMigrateIfAlreadyMigrated() { long lowerBound = 5; long upperBound = 75; insertValuesWithinBounds(lowerBound, upperBound, source); long expectedCutoff = upperBound - PaxosStateLogMigrator.SAFETY_BUFFER; migrateFrom(source, OptionalLong.empty()); verify(target, times(1)).writeBatchOfRounds(any(Iterable.class)); long cutoff = migrateFrom(source, OptionalLong.empty()); assertThat(cutoff).isEqualTo(expectedCutoff); verify(target, times(1)).writeBatchOfRounds(any(Iterable.class)); } @Test public void doNotMigrateIfAlreadyMigratedWithSpecifiedBound() { long lowerBound = 5; long upperBound = 75; insertValuesWithinBounds(lowerBound, upperBound, source); long bound = 60; long expectedCutoff = bound - PaxosStateLogMigrator.SAFETY_BUFFER; migrateFrom(source, OptionalLong.of(bound)); verify(target, times(1)).writeBatchOfRounds(any(Iterable.class)); long cutoff = migrateFrom(source, OptionalLong.of(bound)); assertThat(cutoff).isEqualTo(expectedCutoff); verify(target, times(1)).writeBatchOfRounds(any(Iterable.class)); } @Test public void logMigrationSuccessfullyMigratesManyEntriesInBatches() throws IOException { long lowerBound = 10; long upperBound = lowerBound + BATCH_SIZE * 10; PaxosStateLog<PaxosValue> mockLog = mock(PaxosStateLog.class); when(mockLog.getLeastLogEntry()).thenReturn(lowerBound); when(mockLog.getGreatestLogEntry()).thenReturn(upperBound); when(mockLog.readRound(anyLong())).thenAnswer(invocation -> { long sequence = (long) invocation.getArguments()[0]; if (sequence > upperBound || sequence < lowerBound) { return null; } return valueForRound(sequence).persistToBytes(); }); migrateFrom(mockLog, OptionalLong.of(lowerBound)); assertThat(migrationState.hasMigratedFromInitialState()).isTrue(); assertThat(target.getLeastLogEntry()).isEqualTo(lowerBound); assertThat(target.getGreatestLogEntry()).isEqualTo(upperBound); verify(target, times(11)).writeBatchOfRounds(anyList()); for (long counter = lowerBound; counter <= upperBound; counter += BATCH_SIZE) { assertThat(readRoundUnchecked(target, counter)) .containsExactly(valueForRound(counter).persistToBytes()); } } @Test public void retryWritesFiveTimes() { long lowerBound = 10; long upperBound = 25; insertValuesWithinBounds(lowerBound, upperBound, source); PaxosStateLog<PaxosValue> targetMock = mock(PaxosStateLog.class); AtomicInteger failureCount = new AtomicInteger(0); doAnswer(invocation -> { if (failureCount.getAndIncrement() < 5) { throw new RuntimeException(); } return null; }) .when(targetMock) .writeBatchOfRounds(any()); ImmutableMigrationContext<PaxosValue> context = ImmutableMigrationContext.<PaxosValue>builder() .sourceLog(source) .destinationLog(targetMock) .hydrator(PaxosValue.BYTES_HYDRATOR) .migrationState(migrationState) .migrateFrom(lowerBound) .namespaceAndUseCase(NAMESPACE_AND_USE_CASE) .skipValidationAndTruncateSourceIfMigrated(false) .build(); assertThatCode(() -> PaxosStateLogMigrator.migrateAndReturnCutoff(context)) .doesNotThrowAnyException(); } @Test public void eventuallyStopRetrying() { long lowerBound = 10; long upperBound = 25; insertValuesWithinBounds(lowerBound, upperBound, source); PaxosStateLog<PaxosValue> targetMock = mock(PaxosStateLog.class); Exception expectedException = new RuntimeException("We failed"); doThrow(expectedException).when(targetMock).writeBatchOfRounds(any()); ImmutableMigrationContext<PaxosValue> context = ImmutableMigrationContext.<PaxosValue>builder() .sourceLog(source) .destinationLog(targetMock) .hydrator(PaxosValue.BYTES_HYDRATOR) .migrationState(migrationState) .migrateFrom(lowerBound) .namespaceAndUseCase(NAMESPACE_AND_USE_CASE) .skipValidationAndTruncateSourceIfMigrated(false) .build(); assertThatThrownBy(() -> PaxosStateLogMigrator.migrateAndReturnCutoff(context)) .isEqualTo(expectedException); } @Test public void failWhenAlreadyMigratedButSourceAdvancedChangingCutoff() { long lowerBound = 10; long upperBound = 25; insertValuesWithinBounds(lowerBound, upperBound, source); migrateFrom(source, OptionalLong.empty()); insertValuesWithinBounds(upperBound + 50, upperBound + 50, source); insertValuesWithinBounds(upperBound + 50, upperBound + 50, target); assertThatThrownBy(() -> migrateFrom(source, OptionalLong.empty())).isInstanceOf(IllegalStateException.class); } @Test public void failWhenAlreadyMigratedButSourceAdvancedWithoutChangingCutoffAndEntriesDoNotMatch() { long lowerBound = 10; long upperBound = 25; insertValuesWithinBounds(lowerBound, upperBound, source); migrateFrom(source, OptionalLong.empty()); insertValuesWithinBounds(upperBound + 1, upperBound + 1, source); target.writeRound(upperBound + 1, PaxosStateLogTestUtils.valueForRound(upperBound + 2)); assertThatThrownBy(() -> migrateFrom(source, OptionalLong.empty())).isInstanceOf(IllegalStateException.class); } @Test public void failWhenAlreadyMigratedButSourceAdvancedWithoutChangingCutoffAndNoEntryInTarget() { long lowerBound = 10; long upperBound = 25; insertValuesWithinBounds(lowerBound, upperBound, source); migrateFrom(source, OptionalLong.empty()); insertValuesWithinBounds(upperBound + 1, upperBound + 1, source); assertThatThrownBy(() -> migrateFrom(source, OptionalLong.empty())).isInstanceOf(IllegalStateException.class); } @Test public void failWhenAlreadyMigratedButSourceAdvancedAndEntriesDoNotMatchWhenSpecifyingLowerBound() { long lowerBound = 10; long upperBound = 250; insertValuesWithinBounds(lowerBound, upperBound, source); migrateFrom(source, OptionalLong.of(150)); source.writeRound(upperBound + 1, PaxosStateLogTestUtils.valueForRound(upperBound + 2)); insertValuesWithinBounds(upperBound + 1, upperBound + 100, target); assertThatThrownBy(() -> migrateFrom(source, OptionalLong.of(150))).isInstanceOf(IllegalStateException.class); } @Test public void failWhenAlreadyMigratedButSourceAdvancedAndNoEntryInTargetWhenSpecifyingLowerBound() { long lowerBound = 10; long upperBound = 250; insertValuesWithinBounds(lowerBound, upperBound, source); migrateFrom(source, OptionalLong.of(150)); source.writeRound(upperBound + 1, PaxosStateLogTestUtils.valueForRound(upperBound + 2)); insertValuesWithinBounds(upperBound + 2, upperBound + 100, target); assertThatThrownBy(() -> migrateFrom(source, OptionalLong.of(150))).isInstanceOf(IllegalStateException.class); } @Test public void doNotFailWhenAlreadyMigratedAndSourceTruncatedPartially() { long lowerBound = 10; long upperBound = 250; insertValuesWithinBounds(lowerBound, upperBound, source); migrateFrom(source, OptionalLong.empty()); source.truncate(250 - 10); assertThatCode(() -> migrateFrom(source, OptionalLong.empty())).doesNotThrowAnyException(); } @Test public void doNotFailWhenAlreadyMigratedAndMigrateFromIncreasesButGreatestEntryIsMigrated() { long lowerBound = 10; long upperBound = 250; insertValuesWithinBounds(lowerBound, upperBound, source); migrateFrom(source, OptionalLong.of(220)); assertThatCode(() -> migrateFrom(source, OptionalLong.of(300))).doesNotThrowAnyException(); } @Test public void doNotFailWhenAlreadyMigratedAndSourceTruncatedFully() { long lowerBound = 10; long upperBound = 250; insertValuesWithinBounds(lowerBound, upperBound, source); migrateFrom(source, OptionalLong.empty()); source.truncate(250); assertThatCode(() -> migrateFrom(source, OptionalLong.empty())).doesNotThrowAnyException(); } @Test public void doNotFailWhenSourceAdvancedChangingCutoffOnSkippingValidation() { long lowerBound = 10; long upperBound = 25; insertValuesWithinBounds(lowerBound, upperBound, source); migrateFrom(source, OptionalLong.empty()); insertValuesWithinBounds(upperBound + 50, upperBound + 50, source); insertValuesWithinBounds(upperBound + 50, upperBound + 50, target); assertThatCode(() -> migrateFrom(source, OptionalLong.empty(), true)).doesNotThrowAnyException(); assertThat(source.getGreatestLogEntry()).isEqualTo(PaxosAcceptor.NO_LOG_ENTRY); } @Test public void doNotFailWhenSourceAdvancedWithoutChangingCutoffAndEntriesDoNotMatchOnSkippingValidation() { long lowerBound = 10; long upperBound = 25; insertValuesWithinBounds(lowerBound, upperBound, source); migrateFrom(source, OptionalLong.empty()); insertValuesWithinBounds(upperBound + 1, upperBound + 1, source); target.writeRound(upperBound + 1, PaxosStateLogTestUtils.valueForRound(upperBound + 2)); assertThatCode(() -> migrateFrom(source, OptionalLong.empty(), true)).doesNotThrowAnyException(); assertThat(source.getGreatestLogEntry()).isEqualTo(PaxosAcceptor.NO_LOG_ENTRY); } @Test public void doNotFailWhenSourceAdvancedWithoutChangingCutoffAndNoEntryInTargetOnSkippingValidation() { long lowerBound = 10; long upperBound = 25; insertValuesWithinBounds(lowerBound, upperBound, source); migrateFrom(source, OptionalLong.empty()); insertValuesWithinBounds(upperBound + 1, upperBound + 1, source); assertThatCode(() -> migrateFrom(source, OptionalLong.empty(), true)).doesNotThrowAnyException(); assertThat(source.getGreatestLogEntry()).isEqualTo(PaxosAcceptor.NO_LOG_ENTRY); } @Test public void doNotFailWhenSourceAdvancedAndEntriesDoNotMatchWhenSpecifyingLowerBoundOnSkippingValidation() { long lowerBound = 10; long upperBound = 250; insertValuesWithinBounds(lowerBound, upperBound, source); migrateFrom(source, OptionalLong.of(150)); source.writeRound(upperBound + 1, PaxosStateLogTestUtils.valueForRound(upperBound + 2)); insertValuesWithinBounds(upperBound + 1, upperBound + 100, target); assertThatCode(() -> migrateFrom(source, OptionalLong.of(150), true)).doesNotThrowAnyException(); assertThat(source.getGreatestLogEntry()).isEqualTo(PaxosAcceptor.NO_LOG_ENTRY); } @Test public void doNotFailWhenSourceAdvancedAndNoEntryInTargetWhenSpecifyingLowerBoundOnSkippingValidation() { long lowerBound = 10; long upperBound = 250; insertValuesWithinBounds(lowerBound, upperBound, source); migrateFrom(source, OptionalLong.of(150)); source.writeRound(upperBound + 1, PaxosStateLogTestUtils.valueForRound(upperBound + 2)); insertValuesWithinBounds(upperBound + 2, upperBound + 100, target); assertThatCode(() -> migrateFrom(source, OptionalLong.of(150), true)).doesNotThrowAnyException(); assertThat(source.getGreatestLogEntry()).isEqualTo(PaxosAcceptor.NO_LOG_ENTRY); } private long migrateFrom(PaxosStateLog<PaxosValue> sourceLog) { return migrateFrom(sourceLog, OptionalLong.empty()); } private long migrateFrom(PaxosStateLog<PaxosValue> sourceLog, OptionalLong lowerBound) { return migrateFrom(sourceLog, lowerBound, false); } private long migrateFrom(PaxosStateLog<PaxosValue> sourceLog, OptionalLong lowerBound, boolean skipValidation) { return PaxosStateLogMigrator.migrateAndReturnCutoff(ImmutableMigrationContext.<PaxosValue>builder() .sourceLog(sourceLog) .destinationLog(target) .hydrator(PaxosValue.BYTES_HYDRATOR) .migrationState(migrationState) .migrateFrom(lowerBound) .namespaceAndUseCase(NAMESPACE_AND_USE_CASE) .skipValidationAndTruncateSourceIfMigrated(skipValidation) .build()); } private List<PaxosValue> insertValuesWithinBounds(long from, long to, PaxosStateLog<PaxosValue> targetLog) { List<PaxosValue> valuesWritten = LongStream.rangeClosed(from, to) .mapToObj(PaxosStateLogTestUtils::valueForRound) .collect(Collectors.toList()); valuesWritten.forEach(value -> targetLog.writeRound(value.seq, value)); return valuesWritten; } }
9,304
3,095
<filename>videowidget/videowidget.cpp #pragma execution_character_set("utf-8") #include "videowidget.h" #include "qfontdatabase.h" #include "qpushbutton.h" #include "qtreewidget.h" #include "qlayout.h" #include "qtimer.h" #include "qdir.h" #include "qpainter.h" #include "qevent.h" #include "qmimedata.h" #include "qurl.h" #include "qdebug.h" VideoWidget::VideoWidget(QWidget *parent) : QWidget(parent) { //设置强焦点 setFocusPolicy(Qt::StrongFocus); //设置支持拖放 setAcceptDrops(true); //定时器校验视频 timerCheck = new QTimer(this); timerCheck->setInterval(10 * 1000); connect(timerCheck, SIGNAL(timeout()), this, SLOT(checkVideo())); image = QImage(); copyImage = false; checkLive = true; drawImage = true; fillImage = true; flowEnable = false; flowBgColor = "#000000"; flowPressColor = "#5EC7D9"; timeout = 20; borderWidth = 5; borderColor = "#000000"; focusColor = "#22A3A9"; bgColor = Qt::transparent; bgText = "实时视频"; bgImage = QImage(); osd1Visible = false; osd1FontSize = 12; osd1Text = "时间"; osd1Color = "#FF0000"; osd1Image = QImage(); osd1Format = OSDFormat_DateTime; osd1Position = OSDPosition_Right_Top; osd2Visible = false; osd2FontSize = 12; osd2Text = "通道名称"; osd2Color = "#FF0000"; osd2Image = QImage(); osd2Format = OSDFormat_Text; osd2Position = OSDPosition_Left_Bottom; //初始化解码线程 this->initThread(); //初始化悬浮条 this->initFlowPanel(); //初始化悬浮条样式 this->initFlowStyle(); } void VideoWidget::initThread() { } void VideoWidget::initFlowPanel() { //顶部工具栏,默认隐藏,鼠标移入显示移除隐藏 flowPanel = new QWidget(this); flowPanel->setObjectName("flowPanel"); flowPanel->setVisible(false); //用布局顶住,左侧弹簧 QHBoxLayout *layout = new QHBoxLayout; layout->setSpacing(2); layout->setContentsMargins(0, 0, 0, 0); layout->addStretch(); flowPanel->setLayout(layout); //按钮集合名称,如果需要新增按钮则在这里增加即可 QList<QString> btns; btns << "btnFlowVideo" << "btnFlowSnap" << "btnFlowSound" << "btnFlowAlarm" << "btnFlowClose"; //有多种办法来设置图片,qt内置的图标+自定义的图标+图形字体 //既可以设置图标形式,也可以直接图形字体设置文本 #if 0 QList<QIcon> icons; icons << QApplication::style()->standardIcon(QStyle::SP_ComputerIcon); icons << QApplication::style()->standardIcon(QStyle::SP_FileIcon); icons << QApplication::style()->standardIcon(QStyle::SP_DirIcon); icons << QApplication::style()->standardIcon(QStyle::SP_DialogOkButton); icons << QApplication::style()->standardIcon(QStyle::SP_DialogCancelButton); #else QList<int> icons; icons << 0xe68d << 0xe672 << 0xe674 << 0xea36 << 0xe74c; //判断图形字体是否存在,不存在则加入 QFont iconFont; QFontDatabase fontDb; if (!fontDb.families().contains("iconfont")) { int fontId = fontDb.addApplicationFont(":/image/iconfont.ttf"); QStringList fontName = fontDb.applicationFontFamilies(fontId); if (fontName.count() == 0) { qDebug() << "load iconfont.ttf error"; } } if (fontDb.families().contains("iconfont")) { iconFont = QFont("iconfont"); iconFont.setPixelSize(17); #if (QT_VERSION >= QT_VERSION_CHECK(4,8,0)) iconFont.setHintingPreference(QFont::PreferNoHinting); #endif } #endif //循环添加顶部按钮 for (int i = 0; i < btns.count(); i++) { QPushButton *btn = new QPushButton; //绑定按钮单击事件,用来发出信号通知 connect(btn, SIGNAL(clicked(bool)), this, SLOT(btnClicked())); //设置标识,用来区别按钮 btn->setObjectName(btns.at(i)); //设置固定宽度 btn->setFixedWidth(20); //设置拉伸策略使得填充 btn->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding); //设置焦点策略为无焦点,避免单击后焦点跑到按钮上 btn->setFocusPolicy(Qt::NoFocus); #if 0 //设置图标大小和图标 btn->setIconSize(QSize(16, 16)); btn->setIcon(icons.at(i)); #else btn->setFont(iconFont); btn->setText((QChar)icons.at(i)); #endif //将按钮加到布局中 layout->addWidget(btn); } } void VideoWidget::initFlowStyle() { //设置样式以便区分,可以自行更改样式,也可以不用样式 QStringList qss; QString rgba = QString("rgba(%1,%2,%3,150)").arg(flowBgColor.red()).arg(flowBgColor.green()).arg(flowBgColor.blue()); qss.append(QString("#flowPanel{background:%1;border:none;}").arg(rgba)); qss.append(QString("QPushButton{border:none;padding:0px;background:rgba(0,0,0,0);}")); qss.append(QString("QPushButton:pressed{color:%1;}").arg(flowPressColor.name())); flowPanel->setStyleSheet(qss.join("")); } VideoWidget::~VideoWidget() { if (timerCheck->isActive()) { timerCheck->stop(); } close(); } void VideoWidget::resizeEvent(QResizeEvent *) { //重新设置顶部工具栏的位置和宽高,可以自行设置顶部显示或者底部显示 int height = 20; flowPanel->setGeometry(borderWidth, borderWidth, this->width() - (borderWidth * 2), height); //flowPanel->setGeometry(borderWidth, this->height() - height - borderWidth, this->width() - (borderWidth * 2), height); } void VideoWidget::enterEvent(QEvent *) { //这里还可以增加一个判断,是否获取了焦点的才需要显示 //if (this->hasFocus()) {} if (flowEnable) { flowPanel->setVisible(true); } } void VideoWidget::leaveEvent(QEvent *) { if (flowEnable) { flowPanel->setVisible(false); } } void VideoWidget::dropEvent(QDropEvent *event) { //拖放完毕鼠标松开的时候执行 //判断拖放进来的类型,取出文件,进行播放 QString url; if (event->mimeData()->hasUrls()) { url = event->mimeData()->urls().first().toLocalFile(); } else if (event->mimeData()->hasFormat("application/x-qabstractitemmodeldatalist")) { QTreeWidget *treeWidget = (QTreeWidget *)event->source(); if (treeWidget != 0) { url = treeWidget->currentItem()->data(0, Qt::UserRole).toString(); } } if (!url.isEmpty()) { emit fileDrag(url); this->restart(url); } } void VideoWidget::dragEnterEvent(QDragEnterEvent *event) { //拖曳进来的时候先判断下类型,非法类型则不处理 if (event->mimeData()->hasFormat("application/x-qabstractitemmodeldatalist")) { event->setDropAction(Qt::CopyAction); event->accept(); } else if (event->mimeData()->hasFormat("text/uri-list")) { event->setDropAction(Qt::LinkAction); event->accept(); } else { event->ignore(); } } void VideoWidget::paintEvent(QPaintEvent *) { //如果不需要绘制 if (!drawImage) { return; } //qDebug() << TIMEMS << "paintEvent" << objectName(); QPainter painter(this); painter.setRenderHints(QPainter::Antialiasing); //绘制边框 drawBorder(&painter); if (!image.isNull()) { //绘制背景图片 drawImg(&painter, image); //绘制标签 drawOSD(&painter, osd1Visible, osd1FontSize, osd1Text, osd1Color, osd1Image, osd1Format, osd1Position); drawOSD(&painter, osd2Visible, osd2FontSize, osd2Text, osd2Color, osd2Image, osd2Format, osd2Position); } else { //绘制背景 drawBg(&painter); } } void VideoWidget::drawBorder(QPainter *painter) { if (borderWidth == 0) { return; } painter->save(); QPen pen; pen.setWidth(borderWidth); pen.setColor(hasFocus() ? focusColor : borderColor); painter->setPen(pen); painter->drawRect(rect()); painter->restore(); } void VideoWidget::drawBg(QPainter *painter) { painter->save(); if (bgColor != Qt::transparent) { painter->fillRect(rect(), bgColor); } //背景图片为空则绘制文字,否则绘制背景图片 if (bgImage.isNull()) { painter->setFont(this->font()); painter->setPen(palette().windowText().color()); painter->drawText(rect(), Qt::AlignCenter, bgText); } else { //居中绘制 int x = rect().center().x() - bgImage.width() / 2; int y = rect().center().y() - bgImage.height() / 2; QPoint point(x, y); painter->drawImage(point, bgImage); } painter->restore(); } void VideoWidget::drawImg(QPainter *painter, QImage img) { painter->save(); int offset = borderWidth * 1 + 0; if (fillImage) { QRect rect(offset / 2, offset / 2, width() - offset, height() - offset); painter->drawImage(rect, img); } else { //按照比例自动居中绘制 img = img.scaled(width() - offset, height() - offset, Qt::KeepAspectRatio); int x = rect().center().x() - img.width() / 2; int y = rect().center().y() - img.height() / 2; QPoint point(x, y); painter->drawImage(point, img); } painter->restore(); } void VideoWidget::drawOSD(QPainter *painter, bool osdVisible, int osdFontSize, const QString &osdText, const QColor &osdColor, const QImage &osdImage, const VideoWidget::OSDFormat &osdFormat, const VideoWidget::OSDPosition &osdPosition) { if (!osdVisible) { return; } painter->save(); //标签位置尽量偏移多一点避免遮挡 QRect osdRect(rect().x() + (borderWidth * 2), rect().y() + (borderWidth * 2), width() - (borderWidth * 5), height() - (borderWidth * 5)); int flag = Qt::AlignLeft | Qt::AlignTop; QPoint point = QPoint(osdRect.x(), osdRect.y()); if (osdPosition == OSDPosition_Left_Top) { flag = Qt::AlignLeft | Qt::AlignTop; point = QPoint(osdRect.x(), osdRect.y()); } else if (osdPosition == OSDPosition_Left_Bottom) { flag = Qt::AlignLeft | Qt::AlignBottom; point = QPoint(osdRect.x(), osdRect.height() - osdImage.height()); } else if (osdPosition == OSDPosition_Right_Top) { flag = Qt::AlignRight | Qt::AlignTop; point = QPoint(osdRect.width() - osdImage.width(), osdRect.y()); } else if (osdPosition == OSDPosition_Right_Bottom) { flag = Qt::AlignRight | Qt::AlignBottom; point = QPoint(osdRect.width() - osdImage.width(), osdRect.height() - osdImage.height()); } if (osdFormat == OSDFormat_Image) { painter->drawImage(point, osdImage); } else { QDateTime now = QDateTime::currentDateTime(); QString text = osdText; if (osdFormat == OSDFormat_Date) { text = now.toString("yyyy-MM-dd"); } else if (osdFormat == OSDFormat_Time) { text = now.toString("HH:mm:ss"); } else if (osdFormat == OSDFormat_DateTime) { text = now.toString("yyyy-MM-dd HH:mm:ss"); } //设置颜色及字号 QFont font; font.setPixelSize(osdFontSize); painter->setPen(osdColor); painter->setFont(font); painter->drawText(osdRect, flag, text); } painter->restore(); } QImage VideoWidget::getImage() const { return this->image; } QPixmap VideoWidget::getPixmap() const { return QPixmap(); } QString VideoWidget::getUrl() const { return this->property("url").toString(); } QDateTime VideoWidget::getLastTime() const { return QDateTime::currentDateTime(); } bool VideoWidget::getCallback() const { return false; } bool VideoWidget::getIsPlaying() const { return false; } bool VideoWidget::getIsRtsp() const { return false; } bool VideoWidget::getIsUsbCamera() const { return false; } bool VideoWidget::getCopyImage() const { return this->copyImage; } bool VideoWidget::getCheckLive() const { return this->checkLive; } bool VideoWidget::getDrawImage() const { return this->drawImage; } bool VideoWidget::getFillImage() const { return this->fillImage; } bool VideoWidget::getFlowEnable() const { return this->flowEnable; } QColor VideoWidget::getFlowBgColor() const { return this->flowBgColor; } QColor VideoWidget::getFlowPressColor() const { return this->flowPressColor; } int VideoWidget::getTimeout() const { return this->timeout; } int VideoWidget::getBorderWidth() const { return this->borderWidth; } QColor VideoWidget::getBorderColor() const { return this->borderColor; } QColor VideoWidget::getFocusColor() const { return this->focusColor; } QColor VideoWidget::getBgColor() const { return this->bgColor; } QString VideoWidget::getBgText() const { return this->bgText; } QImage VideoWidget::getBgImage() const { return this->bgImage; } bool VideoWidget::getOSD1Visible() const { return this->osd1Visible; } int VideoWidget::getOSD1FontSize() const { return this->osd1FontSize; } QString VideoWidget::getOSD1Text() const { return this->osd1Text; } QColor VideoWidget::getOSD1Color() const { return this->osd1Color; } QImage VideoWidget::getOSD1Image() const { return this->osd1Image; } VideoWidget::OSDFormat VideoWidget::getOSD1Format() const { return this->osd1Format; } VideoWidget::OSDPosition VideoWidget::getOSD1Position() const { return this->osd1Position; } bool VideoWidget::getOSD2Visible() const { return this->osd2Visible; } int VideoWidget::getOSD2FontSize() const { return this->osd2FontSize; } QString VideoWidget::getOSD2Text() const { return this->osd2Text; } QColor VideoWidget::getOSD2Color() const { return this->osd2Color; } QImage VideoWidget::getOSD2Image() const { return this->osd2Image; } VideoWidget::OSDFormat VideoWidget::getOSD2Format() const { return this->osd2Format; } VideoWidget::OSDPosition VideoWidget::getOSD2Position() const { return this->osd2Position; } int VideoWidget::getFaceBorder() const { return this->faceBorder; } QColor VideoWidget::getFaceColor() const { return this->faceColor; } QList<QRect> VideoWidget::getFaceRects() const { return this->faceRects; } QSize VideoWidget::sizeHint() const { return QSize(400, 300); } QSize VideoWidget::minimumSizeHint() const { return QSize(40, 30); } void VideoWidget::updateImage(const QImage &image) { //拷贝图片有个好处,当处理器比较差的时候,图片不会产生断层,缺点是占用时间 //默认QImage类型是浅拷贝,可能正在绘制的时候,那边已经更改了图片的上部分数据 this->image = copyImage ? image.copy() : image; this->update(); } void VideoWidget::checkVideo() { QDateTime now = QDateTime::currentDateTime(); QDateTime lastTime = now; int sec = lastTime.secsTo(now); if (sec >= timeout) { restart(this->getUrl()); } } void VideoWidget::btnClicked() { QPushButton *btn = (QPushButton *)sender(); emit btnClicked(btn->objectName()); } uint VideoWidget::getLength() { return 0; } uint VideoWidget::getPosition() { return 0; } void VideoWidget::setPosition(int position) { } bool VideoWidget::getMuted() { return false; } void VideoWidget::setMuted(bool muted) { } int VideoWidget::getVolume() { return 0; } void VideoWidget::setVolume(int volume) { } void VideoWidget::setInterval(int interval) { } void VideoWidget::setSleepTime(int sleepTime) { } void VideoWidget::setCheckTime(int checkTime) { } void VideoWidget::setCheckConn(bool checkConn) { } void VideoWidget::setUrl(const QString &url) { this->setProperty("url", url); } void VideoWidget::setCallback(bool callback) { } void VideoWidget::setHardware(const QString &hardware) { } void VideoWidget::setTransport(const QString &transport) { } void VideoWidget::setSaveFile(bool saveFile) { } void VideoWidget::setSaveInterval(int saveInterval) { } void VideoWidget::setFileFlag(const QString &fileFlag) { } void VideoWidget::setSavePath(const QString &savePath) { //如果目录不存在则新建 QDir dir(savePath); if (!dir.exists()) { dir.mkdir(savePath); } } void VideoWidget::setFileName(const QString &fileName) { } void VideoWidget::setCopyImage(bool copyImage) { this->copyImage = copyImage; } void VideoWidget::setCheckLive(bool checkLive) { this->checkLive = checkLive; } void VideoWidget::setDrawImage(bool drawImage) { this->drawImage = drawImage; } void VideoWidget::setFillImage(bool fillImage) { this->fillImage = fillImage; } void VideoWidget::setFlowEnable(bool flowEnable) { this->flowEnable = flowEnable; } void VideoWidget::setFlowBgColor(const QColor &flowBgColor) { if (this->flowBgColor != flowBgColor) { this->flowBgColor = flowBgColor; this->initFlowStyle(); } } void VideoWidget::setFlowPressColor(const QColor &flowPressColor) { if (this->flowPressColor != flowPressColor) { this->flowPressColor = flowPressColor; this->initFlowStyle(); } } void VideoWidget::setTimeout(int timeout) { this->timeout = timeout; } void VideoWidget::setBorderWidth(int borderWidth) { this->borderWidth = borderWidth; this->update(); } void VideoWidget::setBorderColor(const QColor &borderColor) { this->borderColor = borderColor; this->update(); } void VideoWidget::setFocusColor(const QColor &focusColor) { this->focusColor = focusColor; this->update(); } void VideoWidget::setBgColor(const QColor &bgColor) { this->bgColor = bgColor; this->update(); } void VideoWidget::setBgText(const QString &bgText) { this->bgText = bgText; this->update(); } void VideoWidget::setBgImage(const QImage &bgImage) { this->bgImage = bgImage; this->update(); } void VideoWidget::setOSD1Visible(bool osdVisible) { this->osd1Visible = osdVisible; this->update(); } void VideoWidget::setOSD1FontSize(int osdFontSize) { this->osd1FontSize = osdFontSize; this->update(); } void VideoWidget::setOSD1Text(const QString &osdText) { this->osd1Text = osdText; this->update(); } void VideoWidget::setOSD1Color(const QColor &osdColor) { this->osd1Color = osdColor; this->update(); } void VideoWidget::setOSD1Image(const QImage &osdImage) { this->osd1Image = osdImage; this->update(); } void VideoWidget::setOSD1Format(const VideoWidget::OSDFormat &osdFormat) { this->osd1Format = osdFormat; this->update(); } void VideoWidget::setOSD1Position(const VideoWidget::OSDPosition &osdPosition) { this->osd1Position = osdPosition; this->update(); } void VideoWidget::setOSD2Visible(bool osdVisible) { this->osd2Visible = osdVisible; this->update(); } void VideoWidget::setOSD2FontSize(int osdFontSize) { this->osd2FontSize = osdFontSize; this->update(); } void VideoWidget::setOSD2Text(const QString &osdText) { this->osd2Text = osdText; this->update(); } void VideoWidget::setOSD2Color(const QColor &osdColor) { this->osd2Color = osdColor; this->update(); } void VideoWidget::setOSD2Image(const QImage &osdImage) { this->osd2Image = osdImage; this->update(); } void VideoWidget::setOSD2Format(const VideoWidget::OSDFormat &osdFormat) { this->osd2Format = osdFormat; this->update(); } void VideoWidget::setOSD2Position(const VideoWidget::OSDPosition &osdPosition) { this->osd2Position = osdPosition; this->update(); } void VideoWidget::setOSD1Format(quint8 osdFormat) { setOSD1Format((VideoWidget::OSDFormat)osdFormat); } void VideoWidget::setOSD2Format(quint8 osdFormat) { setOSD2Format((VideoWidget::OSDFormat)osdFormat); } void VideoWidget::setOSD1Position(quint8 osdPosition) { setOSD1Position((VideoWidget::OSDPosition)osdPosition); } void VideoWidget::setOSD2Position(quint8 osdPosition) { setOSD2Position((VideoWidget::OSDPosition)osdPosition); } void VideoWidget::setFaceBorder(int faceBorder) { this->faceBorder = faceBorder; this->update(); } void VideoWidget::setFaceColor(const QColor &faceColor) { this->faceColor = faceColor; this->update(); } void VideoWidget::setFaceRects(const QList<QRect> &faceRects) { this->faceRects = faceRects; this->update(); } void VideoWidget::open() { //qDebug() << TIMEMS << "open video" << objectName(); clear(); //如果是图片则只显示图片就行 image = QImage(this->property("url").toString()); if (!image.isNull()) { this->update(); return; } //thread->play(); //thread->start(); if (checkLive) { timerCheck->start(); } this->setProperty("isPause", false); } void VideoWidget::pause() { if (!this->property("isPause").toBool()) { //thread->pause(); this->setProperty("isPause", true); } } void VideoWidget::next() { if (this->property("isPause").toBool()) { //thread->next(); this->setProperty("isPause", false); } } void VideoWidget::close() { if (checkLive) { timerCheck->stop(); } this->clear(); //QTimer::singleShot(5, this, SLOT(clear())); } void VideoWidget::restart(const QString &url, int delayOpen) { //qDebug() << TIMEMS << "restart video" << objectName(); //关闭视频 close(); //重新设置播放地址 setUrl(url); //打开视频 if (delayOpen > 0) { QTimer::singleShot(delayOpen, this, SLOT(open())); } else { open(); } } void VideoWidget::clear() { image = QImage(); this->update(); } void VideoWidget::snap(const QString &fileName) { }
9,755
6,059
<reponame>penguin-wwy/redex /* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include <string> namespace keep_rules { namespace proguard_parser { std::string form_member_regex(const std::string& proguard_regex); std::string form_type_regex(const std::string& proguard_regex); bool has_special_char(const std::string& proguard_regex); std::string convert_wildcard_type(const std::string& typ); } // namespace proguard_parser } // namespace keep_rules
196
389
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~ Copyright 2020 Adobe ~ ~ 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.adobe.cq.wcm.core.components.models.datalayer.builder; import com.adobe.cq.wcm.core.components.internal.models.v1.datalayer.ContainerDataImpl; import com.adobe.cq.wcm.core.components.internal.models.v1.datalayer.builder.DataLayerSupplierImpl; import com.adobe.cq.wcm.core.components.models.datalayer.ContainerData; import org.jetbrains.annotations.NotNull; import java.util.function.Supplier; /** * Data builder for container components. * This builder will produce a valid {@link ContainerData} object. */ public final class ContainerDataBuilder extends GenericComponentDataBuilder<ContainerDataBuilder, ContainerData> { /** * Construct a data builder for a container component. * * @param supplier The data layer supplier. */ ContainerDataBuilder(@NotNull final DataLayerSupplier supplier) { super(supplier); } /** * Set the supplier that supplies the array of shown items. * * @param supplier The shown items value supplier. * @return A new {@link ContainerDataBuilder}. * @see ContainerData#getShownItems() */ @NotNull public ContainerDataBuilder withShownItems(@NotNull final Supplier<String[]> supplier) { return this.createInstance(new DataLayerSupplierImpl(this.getDataLayerSupplier()).setShownItems(supplier)); } @Override @NotNull ContainerDataBuilder createInstance(@NotNull final DataLayerSupplier supplier) { return new ContainerDataBuilder(supplier); } @NotNull @Override public ContainerData build() { return new ContainerDataImpl(this.getDataLayerSupplier()); } }
711
2,504
<filename>Samples/DpiScaling/cpp/Scenario1.xaml.cpp //********************************************************* // // Copyright (c) Microsoft. All rights reserved. // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* // // Scenario1.xaml.cpp // Implementation of the Scenario1 class // #include "pch.h" #include "Scenario1.xaml.h" using namespace SDKTemplate; using namespace Platform; using namespace Windows::Foundation; using namespace Windows::Foundation::Collections; using namespace Windows::Graphics::Display; using namespace Windows::UI::Xaml; using namespace Windows::UI::Xaml::Controls; using namespace Windows::UI::Xaml::Media::Imaging; using namespace Windows::UI::Xaml::Navigation; Scenario1::Scenario1() { InitializeComponent(); DisplayInformation^ displayInformation = DisplayInformation::GetForCurrentView(); token = (displayInformation->DpiChanged += ref new TypedEventHandler<DisplayInformation^, Platform::Object^>(this, &Scenario1::DisplayProperties_DpiChanged)); } void Scenario1::ResetOutput() { DisplayInformation^ displayInformation = DisplayInformation::GetForCurrentView(); String^ scaleValue = static_cast<int>(displayInformation->RawPixelsPerViewPixel * 100.0f + 0.5f).ToString(); ManualLoadURL->Text = "http://www.contoso.com/imageScale" + scaleValue + ".png"; ScalingText->Text = scaleValue + "%"; LogicalDPIText->Text = displayInformation->LogicalDpi.ToString() + " DPI"; } void Scenario1::OnNavigatedTo(NavigationEventArgs^ e) { ResetOutput(); } void Scenario1::OnNavigatedFrom(NavigationEventArgs^ e) { DisplayInformation^ displayInformation = DisplayInformation::GetForCurrentView(); displayInformation->DpiChanged -= token; } void Scenario1::DisplayProperties_DpiChanged(DisplayInformation^ sender, Platform::Object^ args) { ResetOutput(); }
669
304
<gh_stars>100-1000 /* * Copyright 2019-2021 CloudNetService team & contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.dytanic.cloudnet.common.logging; /** * Represents a full log record from the logger. Important for the most loggers are the following information * * <ol> * <li>timestamp: for the time, from the log entry</li> * <li>messages: all messages in this record </li> * <li>thread: the Thread in that the record was created</li> * </ol> */ public class LogEntry { /** * The timestamp in that the log record was create in millis from since 01.01.1970 00:00:00 */ protected final long timeStamp; /** * The class in that the logger should print if the class is defined The class can be null */ protected final Class<?> clazz; /** * All messages, which should print from the logger as array of messages to execute more message as one in a entry * <p> * It's not allowed to set the array or the entries of that to null. The log entry will be blocked */ protected final String[] messages; /** * The LogLevel of this LogEntry. The LogLevel must be not null, but it can be custom created */ protected final LogLevel logLevel; /** * An optional Throwable instance, for error messages that are should interesting for the log handlers */ protected final Throwable throwable; /** * The Thread instance in that the LogEntry was created */ protected final Thread thread; public LogEntry(long timeStamp, Class<?> clazz, String[] messages, LogLevel logLevel, Throwable throwable, Thread thread) { this.timeStamp = timeStamp; this.clazz = clazz; this.messages = messages; this.logLevel = logLevel; this.throwable = throwable; this.thread = thread; } public long getTimeStamp() { return this.timeStamp; } public Class<?> getClazz() { return this.clazz; } public String[] getMessages() { return this.messages; } public LogLevel getLogLevel() { return this.logLevel; } public Throwable getThrowable() { return this.throwable; } public Thread getThread() { return this.thread; } }
799
852
<filename>SimG4Core/PhysicsLists/plugins/FTFPCMS_BERT_HP_EMM.h<gh_stars>100-1000 #ifndef SimG4Core_PhysicsLists_FTFPCMS_BERT_HP_EMM_H #define SimG4Core_PhysicsLists_FTFPCMS_BERT_HP_EMM_H #include "SimG4Core/Physics/interface/PhysicsList.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" class FTFPCMS_BERT_HP_EMM : public PhysicsList { public: FTFPCMS_BERT_HP_EMM(const edm::ParameterSet& p); }; #endif
185
1,056
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.websvc.api.jaxws.project.config; /** * * @author rico */ public class WsimportOptions { private org.netbeans.modules.websvc.jaxwsmodel.project_config1_0.WsimportOptions wsimportOptions; public WsimportOptions(org.netbeans.modules.websvc.jaxwsmodel.project_config1_0.WsimportOptions wsimportOptions) { this.wsimportOptions = wsimportOptions; } public org.netbeans.modules.websvc.jaxwsmodel.project_config1_0.WsimportOptions getOriginal() { return wsimportOptions; } public WsimportOption newWsimportOption() { org.netbeans.modules.websvc.jaxwsmodel.project_config1_0.WsimportOption wsimportOption = wsimportOptions.newWsimportOption(); return new WsimportOption(wsimportOption); } public void addWsimportOption(WsimportOption wsimportOption) { wsimportOptions.addWsimportOption(wsimportOption.getOriginal()); } public void removeWsimportOption(WsimportOption wsimportOption) { wsimportOptions.removeWsimportOption(wsimportOption.getOriginal()); } public void clearWsimportOptions(){ org.netbeans.modules.websvc.jaxwsmodel.project_config1_0.WsimportOption[] options = wsimportOptions.getWsimportOption(); for(int i = 0; i < options.length; i++){ wsimportOptions.removeWsimportOption(options[i]); } } public WsimportOption[] getWsimportOptions() { org.netbeans.modules.websvc.jaxwsmodel.project_config1_0.WsimportOption[] options = wsimportOptions.getWsimportOption(); WsimportOption[] wsimportOptions = new WsimportOption[options.length]; for (int i = 0; i < options.length; i++) { wsimportOptions[i] = new WsimportOption(options[i]); } return wsimportOptions; } }
886
3,073
#ifndef DEFINEMACROS_H #define DEFINEMACROS_H /*** Helper macros to define SHA3 and SHAKE instances. ***/ #define defshake(bits) \ int shake##bits(uint8_t* out, size_t outlen, \ const uint8_t* in, size_t inlen) { \ return hash(out, outlen, in, inlen, 200 - (bits / 4), 0x1f); \ } #define defsha3(bits) \ int sha3_##bits(uint8_t* out, size_t outlen, \ const uint8_t* in, size_t inlen) { \ if (outlen > (bits/8)) { \ return -1; \ } \ return hash(out, outlen, in, inlen, 200 - (bits / 4), 0x06); \ } #define defkeccak(bits) \ int keccak_##bits(uint8_t* out, size_t outlen, \ const uint8_t* in, size_t inlen) { \ if (outlen > (bits/8)) { \ return -1; \ } \ return hash(out, outlen, in, inlen, 200 - (bits / 4), 0x01); \ } /*** FIPS202 SHAKE VOFs ***/ defshake(128) defshake(256) /*** FIPS202 SHA3 FOFs ***/ defsha3(224) defsha3(256) defsha3(384) defsha3(512) /*** Non FIP202 SHA3 (KECCAK) FOFs ***/ defkeccak(224) defkeccak(256) defkeccak(384) defkeccak(512) #endif // DEFINEMACROS_H
1,057
521
<reponame>zai1208/fbc /* pmap statement and point function with one argument */ #include "fb_gfx.h" FBCALL float fb_GfxPMap(float coord, int func) { FB_GFXCTX *context; FB_GRAPHICS_LOCK( ); if (!__fb_gfx) { FB_GRAPHICS_UNLOCK( ); return 0.0; } context = fb_hGetContext( ); fb_hPrepareTarget(context, NULL); fb_hSetPixelTransfer(context, MASK_A_32); switch (func) { case 0: if (context->flags & CTX_WINDOW_ACTIVE) coord = ((coord - context->win_x) * context->view_w) / context->win_w; break; case 1: if (context->flags & CTX_WINDOW_ACTIVE) { coord = ((coord - context->win_y) * context->view_h) / context->win_h; if ((context->flags & CTX_WINDOW_SCREEN) == 0) coord = context->view_h - 1 - coord; } break; case 2: if (context->flags & CTX_WINDOW_ACTIVE) coord = ((coord * context->win_w) / context->view_w) + context->win_x; break; case 3: if (context->flags & CTX_WINDOW_ACTIVE) { if ((context->flags & CTX_WINDOW_SCREEN) == 0) coord = context->view_h - 1 - coord; coord = ((coord * context->win_h) / context->view_h) + context->win_y; } break; default: coord = 0; break; } FB_GRAPHICS_UNLOCK( ); return coord; } FBCALL float fb_GfxCursor(int func) { FB_GFXCTX *context; float result; FB_GRAPHICS_LOCK( ); context = fb_hGetContext( ); if (!__fb_gfx) { FB_GRAPHICS_UNLOCK( ); return 0.0; } switch (func) { case 0: result = fb_GfxPMap(context->last_x, 0); break; case 1: result = fb_GfxPMap(context->last_y, 1); break; case 2: result = context->last_x; break; case 3: result = context->last_y; break; default: result = 0; break; } FB_GRAPHICS_UNLOCK( ); return result; }
762
702
/* * Copyright ConsenSys AG. * * 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. * * SPDX-License-Identifier: Apache-2.0 */ package org.hyperledger.besu.ethereum.permissioning; import org.hyperledger.besu.datatypes.Address; public class SmartContractPermissioningConfiguration { private boolean smartContractNodeAllowlistEnabled; private Address nodeSmartContractAddress; private int nodeSmartContractInterfaceVersion = 1; private boolean smartContractAccountAllowlistEnabled; private Address accountSmartContractAddress; public static SmartContractPermissioningConfiguration createDefault() { return new SmartContractPermissioningConfiguration(); } public boolean isSmartContractNodeAllowlistEnabled() { return smartContractNodeAllowlistEnabled; } public void setSmartContractNodeAllowlistEnabled( final boolean smartContractNodeAllowlistEnabled) { this.smartContractNodeAllowlistEnabled = smartContractNodeAllowlistEnabled; } public Address getNodeSmartContractAddress() { return nodeSmartContractAddress; } public void setNodeSmartContractAddress(final Address nodeSmartContractAddress) { this.nodeSmartContractAddress = nodeSmartContractAddress; } public boolean isSmartContractAccountAllowlistEnabled() { return smartContractAccountAllowlistEnabled; } public void setSmartContractAccountAllowlistEnabled( final boolean smartContractAccountAllowlistEnabled) { this.smartContractAccountAllowlistEnabled = smartContractAccountAllowlistEnabled; } public Address getAccountSmartContractAddress() { return accountSmartContractAddress; } public void setAccountSmartContractAddress(final Address accountSmartContractAddress) { this.accountSmartContractAddress = accountSmartContractAddress; } public void setNodeSmartContractInterfaceVersion(final int nodeSmartContractInterfaceVersion) { this.nodeSmartContractInterfaceVersion = nodeSmartContractInterfaceVersion; } public int getNodeSmartContractInterfaceVersion() { return nodeSmartContractInterfaceVersion; } }
640
451
<gh_stars>100-1000 """ Download a Matlab matrix file from sparse.tamu.edu and save it locally. """ import sys import scipy.io import urllib.request def download_matfile(group, name, outfile="matrix.out"): """ Downloads a matrix file (matlab format) from sparse.tamu.edu and returns the matrix. """ with open(outfile, "wb") as f: url = 'https://sparse.tamu.edu/mat/%s/%s.mat' % (group, name) print("Downloading", url) f.write(urllib.request.urlopen(url).read()) # nosec: https, content vetted dct = scipy.io.loadmat(outfile) return dct if __name__ == '__main__': mat = download_matfile(sys.argv[1], sys.argv[2]) print(mat['Problem'][0][0][0])
292
1,134
[ { "op": "add", "path": "/ValueTypes/AWS::CodePipeline::Pipeline.ActionTypeId.Category", "value": { "botocore": "codepipeline/2015-07-09/ActionCategory" } }, { "op": "add", "path": "/ValueTypes/AWS::CodePipeline::Pipeline.ActionTypeId.Owner", "value": { "botocore": "codepipeline/2015-07-09/ActionOwner" } }, { "op": "add", "path": "/ValueTypes/AWS::CodePipeline::Pipeline.ArtifactStore.Type", "value": { "botocore": "codepipeline/2015-07-09/ArtifactStoreType" } }, { "op": "add", "path": "/ValueTypes/AWS::CodePipeline::Pipeline.BlockerDeclaration.Type", "value": { "botocore": "codepipeline/2015-07-09/BlockerType" } }, { "op": "add", "path": "/ValueTypes/AWS::CodePipeline::CustomActionType.ConfigurationProperties.Type", "value": { "botocore": "codepipeline/2015-07-09/ActionConfigurationPropertyType" } }, { "op": "add", "path": "/ValueTypes/CodePipelineWehbookAuthentication", "value": { "botocore": "codepipeline/2015-07-09/WebhookAuthenticationType" } } ]
509
852
<gh_stars>100-1000 import FWCore.ParameterSet.Config as cms from Geometry.CaloTopology.hgcalTopologyTesterEE_cfi import * hgcalTopologyTesterHEF = hgcalTopologyTesterEE.clone( detectorName = cms.string("HGCalHESiliconSensitive"), types = cms.vint32(0,0,1,1,1,1,2,2,2), layers = cms.vint32(1,2,9,3,4,5,6,7,8), sector1 = cms.vint32(2,3,3,4,5,6,7,8,9), sector2 = cms.vint32(3,3,3,5,5,3,8,8,8), cell1 = cms.vint32(0,10,15,8,8,10,10,15,15), cell2 = cms.vint32(11,7,15,15,6,2,15,8,11)) hgcalTopologyTesterHEB = hgcalTopologyTesterEE.clone( detectorName = cms.string("HGCalHEScintillatorSensitive"), types = cms.vint32(0,0,0,1,1,1,1,1,1), layers = cms.vint32(9,10,11,13,14,15,16,17,18), sector1 = cms.vint32(10,10,4,14,16,7,8,9,10), cell1 = cms.vint32(1,10,360,4,24,40,60,150,288))
515
347
package org.ovirt.engine.core.bll.network.template; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.when; import java.util.Collections; import java.util.List; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.ovirt.engine.core.bll.AbstractQueryTest; import org.ovirt.engine.core.common.businessentities.VmTemplate; import org.ovirt.engine.core.common.businessentities.network.VmNetworkInterface; import org.ovirt.engine.core.common.queries.IdQueryParameters; import org.ovirt.engine.core.common.utils.PairQueryable; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.dao.VmTemplateDao; import org.ovirt.engine.core.dao.network.VmNetworkInterfaceDao; /** * A test for the {@link GetVmTemplatesAndNetworkInterfacesByNetworkIdQuery} class. It tests the flow (i.e., that the query * delegates properly to the Dao}). The internal workings of the Dao are not tested. */ public class GetVmTemplatesAndNetworkInterfacesByNetworkIdQueryTest extends AbstractQueryTest<IdQueryParameters, GetVmTemplatesAndNetworkInterfacesByNetworkIdQuery<IdQueryParameters>> { private Guid networkId = Guid.newGuid(); private Guid vmTemplateId = Guid.newGuid(); private VmTemplate vmTemplate = new VmTemplate(); private VmNetworkInterface vmNetworkInterface = new VmNetworkInterface(); @Mock private VmTemplateDao vmTemplateDao; @Mock private VmNetworkInterfaceDao vmNetworkInterfaceDaoMock; @Test public void testExecuteQueryCommand() { // Setup the query parameters when(params.getId()).thenReturn(networkId); vmTemplate.setId(vmTemplateId); vmNetworkInterface.setVmId(vmTemplateId); // Setup the Daos setupVmTemplateDao(); setupVmNetworkInterfaceDao(); PairQueryable<VmNetworkInterface, VmTemplate> vmInterfaceVmTemplatePair = new PairQueryable<>(vmNetworkInterface, vmTemplate); List<PairQueryable<VmNetworkInterface, VmTemplate>> expected = Collections.singletonList(vmInterfaceVmTemplatePair); // Run the query getQuery().executeQueryCommand(); // Assert the result assertEquals(expected, getQuery().getQueryReturnValue().getReturnValue(), "Wrong result returned"); } private void setupVmTemplateDao() { List<VmTemplate> expectedVmTemplate = Collections.singletonList(vmTemplate); when(vmTemplateDao.getAllForNetwork(networkId)).thenReturn(expectedVmTemplate); } private void setupVmNetworkInterfaceDao() { List<VmNetworkInterface> expectedVmNetworkInterface = Collections.singletonList(vmNetworkInterface); when(vmNetworkInterfaceDaoMock.getAllForTemplatesByNetwork(networkId)).thenReturn(expectedVmNetworkInterface); } }
997
834
#using <System.dll> using namespace System; using namespace System::ComponentModel; using namespace System::Security::Permissions; //using System.Diagnostics; namespace Win32Exception_CPP { public ref class Class1 { public: [PermissionSet(SecurityAction::Demand, Name="FullTrust")] static void Main() { //<snippet1> try { System::Diagnostics::Process^ myProc = gcnew System::Diagnostics::Process; //Attempting to start a non-existing executable myProc->StartInfo->FileName = "c:\nonexist.exe"; //Start the application and assign it to the process component. myProc->Start(); } catch ( Win32Exception^ w ) { Console::WriteLine( w->Message ); Console::WriteLine( w->ErrorCode ); Console::WriteLine( w->NativeErrorCode ); Console::WriteLine( w->StackTrace ); Console::WriteLine( w->Source ); Exception^ e = w->GetBaseException(); Console::WriteLine( e->Message ); } //</snippet1> } }; } int main() { Win32Exception_CPP::Class1::Main(); }
530
1,405
<filename>sample5/recompiled_java/sources/com/network/android/m.java package com.network.android; import android.content.ContentResolver; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.location.Location; import android.net.Uri; import android.os.Handler; import android.os.HandlerThread; import android.provider.CallLog; import android.provider.ContactsContract; import android.telephony.TelephonyManager; import android.telephony.gsm.GsmCellLocation; import android.util.Xml; import com.network.android.c.a.a; import com.network.h.b; import com.network.i.e; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.InputStream; import java.io.StringWriter; import java.net.URLEncoder; import java.util.Date; import java.util.HashMap; import java.util.concurrent.TimeoutException; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.xmlpull.v1.XmlSerializer; public final class m { /* renamed from: a reason: collision with root package name */ public static String f84a = null; static final Object b = new Object(); public static int c = 0; private static HashMap d; private static Handler e; static { HandlerThread handlerThread = new HandlerThread("getFileSystem"); handlerThread.start(); e = new Handler(handlerThread.getLooper()); } public static int a(String str, Process process) { int i = 0; int i2 = 0; while (i2 < 90000) { try { a.a("runProcess WaitForTimeout spend=" + i2 + " bytes=" + 0 + ", proc=" + str); int available = process.getInputStream().available(); if (available > 0) { byte[] bArr = new byte[available]; process.getInputStream().read(bArr); i = 0 + available; a.a("runProcess WaitForTimeout getInputStream=" + new String(bArr)); } int available2 = process.getErrorStream().available(); if (available2 > 0) { byte[] bArr2 = new byte[available2]; process.getErrorStream().read(bArr2); int i3 = i + available2; a.a("runProcess WaitForTimeout getErrorStream=" + new String(bArr2)); } return process.exitValue(); } catch (IllegalThreadStateException e2) { a.a("runProcess WaitForTimeout jump=100, spend=" + i2 + ", bytes=" + 0); Thread.sleep(100); i2 += 100; } catch (Exception e3) { a.a("runProcess WaitForTimeout exception=" + e3.getMessage()); Thread.sleep(100); i2 += 100; } } process.destroy(); a.a("runProcess WaitForTimeout Destroy process. after=" + i2); throw new TimeoutException("runProcess WaitForTimeout Destroy process. after=" + i2); } /* JADX WARNING: Removed duplicated region for block: B:18:0x0052 */ /* JADX WARNING: Removed duplicated region for block: B:20:0x0057 */ /* JADX WARNING: Removed duplicated region for block: B:26:0x0077 */ /* JADX WARNING: Removed duplicated region for block: B:28:0x007c */ /* Code decompiled incorrectly, please refer to instructions dump. */ public static java.lang.String a(android.content.ContentResolver r6, android.database.Cursor r7, java.lang.StringBuilder r8) { /* // Method dump skipped, instructions count: 136 */ throw new UnsupportedOperationException("Method not decompiled: com.network.android.m.a(android.content.ContentResolver, android.database.Cursor, java.lang.StringBuilder):java.lang.String"); } public static String a(String str) { try { return Long.toString(Long.parseLong(str) / 1000); } catch (Exception e2) { a.a("Exception- " + e2.getMessage(), e2); return ""; } } /* JADX WARNING: Code restructure failed: missing block: B:28:0x0081, code lost: r1.close(); r0 = r2; */ /* JADX WARNING: Code restructure failed: missing block: B:31:0x0089, code lost: r1.close(); */ /* JADX WARNING: Code restructure failed: missing block: B:33:0x008d, code lost: r0 = th; */ /* JADX WARNING: Code restructure failed: missing block: B:34:0x008e, code lost: r1 = r2; */ /* JADX WARNING: Code restructure failed: missing block: B:35:0x0090, code lost: r0 = th; */ /* JADX WARNING: Code restructure failed: missing block: B:36:0x0091, code lost: r2 = null; r1 = r2; */ /* JADX WARNING: Code restructure failed: missing block: B:40:0x009c, code lost: r0 = r2; */ /* JADX WARNING: Failed to process nested try/catch */ /* JADX WARNING: Removed duplicated region for block: B:18:0x0055 */ /* JADX WARNING: Removed duplicated region for block: B:28:0x0081 */ /* JADX WARNING: Removed duplicated region for block: B:31:0x0089 */ /* JADX WARNING: Removed duplicated region for block: B:33:0x008d A[ExcHandler: all (th java.lang.Throwable), Splitter:B:7:0x003a] */ /* JADX WARNING: Removed duplicated region for block: B:39:0x009a */ /* JADX WARNING: Removed duplicated region for block: B:40:0x009c */ /* Code decompiled incorrectly, please refer to instructions dump. */ private static java.lang.String a(java.lang.String r6, android.database.sqlite.SQLiteDatabase r7, java.lang.String r8) { /* // Method dump skipped, instructions count: 160 */ throw new UnsupportedOperationException("Method not decompiled: com.network.android.m.a(java.lang.String, android.database.sqlite.SQLiteDatabase, java.lang.String):java.lang.String"); } public static String a(XmlSerializer xmlSerializer, String str) { String str2; String str3; String str4; try { a.a("get whatsapp error serializeString: " + str); xmlSerializer.cdsect(str); return str; } catch (Throwable th) { a.a("get whatsapp serializeString regular1 error- " + th.getMessage(), th); try { str = str.replaceAll("[^\\u0000-\\uFFFF]", "-X-"); xmlSerializer.cdsect(str); return str; } catch (Exception e2) { str2 = str; a.a("get whatsapp error serializeString serializer.cdsect2 replaceAll " + str2); str4 = new String(str2.getBytes(), "ISO-8859-1"); xmlSerializer.cdsect(str4); a.a("serializeString: " + str4); return str4; } catch (Throwable th2) { str2 = str4; } } a.a("get whatsapp error serializeString serializer.cdsect ISO-8859-1 3- " + str2); try { str3 = URLEncoder.encode(str2, "UTF-8"); try { xmlSerializer.cdsect(str3); return str3; } catch (Throwable th3) { } } catch (Throwable th4) { str3 = str2; a.a("get whatsapp error serializer.cdsect4 UTF-8- " + str3); return str3; } } static HashMap a(String str, String[] strArr) { HashMap hashMap; Throwable th; try { a.a("getChmodPermissionsIntoArrayForMiltiplyFilesInFolder starting for file path: " + str); hashMap = new HashMap(); try { String[] split = str.split("/"); String str2 = ""; for (int i = 0; i < split.length; i++) { String str3 = str2 + split[i]; if (str3.length() > 1) { hashMap.put(str3, Integer.valueOf(b.b(new File(str3)))); } str2 = str3 + "/"; } for (int i2 = 0; i2 < strArr.length; i2++) { String str4 = str + "/" + strArr[i2]; hashMap.put(str4, Integer.valueOf(b.b(new File(str4)))); } } catch (Throwable th2) { th = th2; a.a("getChmodPermissionsIntoArrayForMiltiplyFilesInFolder: " + th.getMessage(), th); return hashMap; } } catch (Throwable th3) { hashMap = null; th = th3; a.a("getChmodPermissionsIntoArrayForMiltiplyFilesInFolder: " + th.getMessage(), th); return hashMap; } return hashMap; } public static void a(Context context, Cursor cursor, SQLiteDatabase sQLiteDatabase) { Throwable th; a.a("whatsapp addWhatsAppEntries Messages count : " + cursor.getCount()); if (cursor.getCount() > 0) { SharedPreferences sharedPreferences = null; try { sharedPreferences = context.createPackageContext("com.whatsapp", 0).getSharedPreferences("com.whatsapp_preferences", 0); } catch (Throwable th2) { a.a("whatsapp addWhatsAppEntries read pref- " + th2.getMessage(), th2); } int i = 1; XmlSerializer newSerializer = Xml.newSerializer(); StringWriter stringWriter = new StringWriter(); SmsReceiver.a(newSerializer, stringWriter); newSerializer.startTag("", "imSession"); while (cursor.moveToNext()) { i++; try { a.a("whatsapp addWhatsAppEntries buffer lenth: " + stringWriter.getBuffer().length() + ", index: " + i); if (stringWriter.getBuffer().length() > 97280) { newSerializer.endTag("", "imSession"); SmsReceiver.a(newSerializer); j.a(stringWriter.toString(), context); j.a(context); a.a("whatsapp addWhatsAppEntries 100k chunk buffer lenth: " + stringWriter.getBuffer().length() + ", index: " + i); Thread.sleep(300); XmlSerializer newSerializer2 = Xml.newSerializer(); try { StringWriter stringWriter2 = new StringWriter(); try { SmsReceiver.a(newSerializer2, stringWriter2); newSerializer2.startTag("", "imSession"); stringWriter = stringWriter2; newSerializer = newSerializer2; } catch (Throwable th3) { stringWriter = stringWriter2; newSerializer = newSerializer2; th = th3; a.a("whatsapp addWhatsAppEntries iter - " + th.getMessage(), th); } } catch (Throwable th4) { newSerializer = newSerializer2; th = th4; a.a("whatsapp addWhatsAppEntries iter - " + th.getMessage(), th); } } a(cursor, sQLiteDatabase, sharedPreferences, newSerializer); } catch (Throwable th5) { th = th5; a.a("whatsapp addWhatsAppEntries iter - " + th.getMessage(), th); } } newSerializer.endTag("", "imSession"); SmsReceiver.a(newSerializer); j.a(stringWriter.toString(), context); j.a(context); cursor.moveToLast(); f84a = cursor.getString(cursor.getColumnIndex("timestamp")); try { a.a("whatsapp new whatsAppId after dump: " + f84a + ", by date:" + new Date(Long.parseLong(f84a)).toString()); } catch (Throwable th6) { } SharedPreferences.Editor edit = context.getSharedPreferences("NetworkPreferences", 0).edit(); edit.putString("firstRunIndex", f84a); edit.commit(); return; } a.a("whatsapp no new Messages do send"); } private static void a(Context context, File file, String str, String str2, StringBuffer stringBuffer, XmlSerializer xmlSerializer) { File[] listFiles = file.listFiles(); if (listFiles != null) { int length = listFiles.length; StringBuffer stringBuffer2 = stringBuffer; XmlSerializer xmlSerializer2 = xmlSerializer; for (int i = 0; i < length; i++) { try { boolean isDirectory = listFiles[i].isDirectory(); File file2 = listFiles[i]; xmlSerializer2.startTag("", "file"); if (!isDirectory) { xmlSerializer2.attribute("", "length", String.valueOf(file2.length())); } else { xmlSerializer2.attribute("", "length", String.valueOf(0)); } xmlSerializer2.attribute("", "name", file2.getName()); xmlSerializer2.attribute("", "timestamp", String.valueOf(file2.lastModified() / 1000)); xmlSerializer2.attribute("", "commandAck", str2); xmlSerializer2.attribute("", "isDir", isDirectory ? "true" : "false"); xmlSerializer2.endTag("", "file"); if (stringBuffer2.length() > 97280) { xmlSerializer2.endTag("", "fileSystemList"); SmsReceiver.a(xmlSerializer2); j.a(context, stringBuffer2.toString(), (String[]) null, (byte[][]) null); xmlSerializer2 = Xml.newSerializer(); StringWriter stringWriter = new StringWriter(); SmsReceiver.a(xmlSerializer2, stringWriter); xmlSerializer2.startTag("", "fileSystemList"); xmlSerializer2.attribute("", "timestamp", str); stringBuffer2 = stringWriter.getBuffer(); a.a(" printTreeView BREAK writer.getBuffer().length()=" + stringWriter.getBuffer().length()); } } catch (Throwable th) { a.a("printTreeView exception - " + th.getMessage(), th); com.network.android.c.a.b.a(0, 116, "GET_FILE_GENERAL_FAILURE", b.c(str2)); com.network.android.c.a.b.a(0, -15534, "", b.c(str2)); } } } } private static void a(Cursor cursor, SQLiteDatabase sQLiteDatabase, SharedPreferences sharedPreferences, XmlSerializer xmlSerializer) { String str; String str2; String str3; try { String string = cursor.getString(cursor.getColumnIndex("key_remote_jid")); if (!"-1".equals(string)) { String string2 = cursor.getString(cursor.getColumnIndex("data")); String string3 = cursor.getString(cursor.getColumnIndex("media_name")); int i = cursor.getInt(cursor.getColumnIndex("media_wa_type")); String string4 = cursor.getString(cursor.getColumnIndex("media_url")); if (i == 0 && (string2 == null || string2.length() == 0)) { a.a("whatsapp mediaType 0 - it a new contact or new group "); return; } String str4 = null; if (string4 != null) { try { if (string4.length() > 0) { String[] split = string4.split("/"); str4 = split[split.length - 1]; } } catch (Throwable th) { str = null; } } str = str4; String str5 = string2 == null ? "" : string2.contains("BEGIN:VCARD") ? "" : string2; if (i == 1) { if (string3 == null || string3.length() <= 0) { if (str != null && str.length() > 0) { str2 = str5 + " Image:" + str; } str2 = str5; } else { str2 = str5 + " Image:" + string3; } } else if (i == 2) { if (string3 == null || string3.length() <= 0) { if (str != null && str.length() > 0) { str2 = str5 + " Audio:" + str; } str2 = str5; } else { str2 = str5 + " Audio:" + string3; } } else if (i != 3) { if (i == 4) { if (string3 != null && string3.length() > 0) { str2 = " Contact:" + string3; } } else if (i == 5) { str5 = str5 + " Location:(" + cursor.getDouble(cursor.getColumnIndex("latitude")) + "," + cursor.getDouble(cursor.getColumnIndex("longitude")) + ")"; if (string3 != null) { str5 = str5 + " - (" + string3 + ")"; } a.a("whatsapp Location: " + str5); } str2 = str5; } else if (string3 == null || string3.length() <= 0) { if (str != null && str.length() > 0) { str2 = str5 + " Vidao:" + str; } str2 = str5; } else { str2 = str5 + " Vidao:" + string3; } String str6 = "666"; String str7 = "<NAME>"; if (sharedPreferences != null) { str6 = sharedPreferences.getString("registration_jid", "No Number"); str7 = sharedPreferences.getString("push_name", "No Number"); } String string5 = cursor.getString(cursor.getColumnIndex("_id")); String string6 = cursor.getString(cursor.getColumnIndex("timestamp")); boolean z = cursor.getInt(cursor.getColumnIndex("key_from_me")) == 1; String string7 = cursor.getString(cursor.getColumnIndex("remote_resource")); int indexOf = string.indexOf("@"); if (indexOf < 0) { a.a("addWhatsAppSingleEntry cannot find '@' in '" + string + "'"); return; } String substring = string.substring(0, indexOf); boolean contains = substring.contains("-"); String str8 = "unknown"; String str9 = "unknown"; if (z) { if (!contains) { str8 = str7 + ", " + a(string, sQLiteDatabase, str6); str9 = str6 + ", " + substring; str3 = str7; } else if (sharedPreferences != null) { String string8 = sharedPreferences.getString("pa-" + string, null); if (string8 == null) { str8 = string; str9 = string; str3 = str7; } else { String[] split2 = string8.split(","); a.a("whatsapp groupIdsArry length: " + split2.length); str9 = str6; str8 = str7; for (int i2 = 0; i2 < split2.length; i2++) { int indexOf2 = split2[i2].indexOf("@"); if (indexOf2 < 0) { a.a("addWhatsAppSingleEntry loop cannot find '@' in '" + split2[i2] + "'"); return; } String substring2 = split2[i2].substring(0, indexOf2); str9 = str9 + ", " + substring2; str8 = str8 + ", " + a(split2[i2], sQLiteDatabase, substring2); } str3 = str7; } } else { str3 = str7; } } else if (!contains) { String a2 = a(string, sQLiteDatabase, substring); str8 = a2 + ", " + str7; str9 = substring + ", " + str6; str6 = substring; str3 = a2; } else if (string7 != null && string7.length() != 0 && string7.indexOf("@") != -1) { str6 = string7.substring(0, string7.indexOf("@")); String a3 = a(string7, sQLiteDatabase, str6); if (sharedPreferences != null) { String string9 = sharedPreferences.getString("pa-" + string, null); if (string9 == null) { str8 = string; str3 = a3; str9 = string; } else { String[] split3 = string9.split(","); String str10 = str6; str8 = a3; for (int i3 = 0; i3 < split3.length; i3++) { int indexOf3 = split3[i3].indexOf("@"); if (indexOf3 < 0) { a.a("addWhatsAppSingleEntry last cannot find '@' in '" + split3[i3] + "'"); return; } String substring3 = split3[i3].substring(0, indexOf3); str10 = str10 + ", " + substring3; str8 = str8 + ", " + a(split3[i3], sQLiteDatabase, substring3); } str3 = a3; str9 = str10; } } else { str8 = a3; str3 = a3; str9 = str6; } } else { return; } String a4 = a(string6); xmlSerializer.startTag("", "imEntry"); xmlSerializer.attribute("", "recordId", string5); xmlSerializer.attribute("", "sessionId", string); xmlSerializer.attribute("", "from", str6); xmlSerializer.attribute("", "platform", "whatsapp"); xmlSerializer.attribute("", "timestamp", a4); xmlSerializer.startTag("", "chat"); a(xmlSerializer, str3 + ": " + str2); xmlSerializer.endTag("", "chat"); xmlSerializer.startTag("", "participants"); a(xmlSerializer, str8); xmlSerializer.endTag("", "participants"); xmlSerializer.startTag("", "participantNumbers"); a(xmlSerializer, str9); xmlSerializer.endTag("", "participantNumbers"); xmlSerializer.endTag("", "imEntry"); } } catch (Throwable th2) { a.a("get whatsapp iter- " + th2.getMessage(), th2); } } public static void a(Handler handler, Context context, boolean z) { handler.post(new o(z, context)); } public static void a(String str, Context context, String str2) { try { a.a("getFileSystem started"); File file = new File(str); if (!file.exists()) { a.a("getFileSystem dir does not exists. returning"); com.network.android.c.a.b.a(1, 119, "GET_FILE_FILE_DOES_NOT_EXISTS"); com.network.android.c.a.b.a(0, 119, "GET_FILE_FILE_DOES_NOT_EXISTS", b.c(str2)); com.network.android.c.a.b.a(0, -15534, "", b.c(str2)); return; } File[] listFiles = file.listFiles(); if (listFiles == null || listFiles.length == 0) { a.a("getFileSystem no files on the base directory"); com.network.android.c.a.b.a(1, 117, "GET_FILE_EMPTY_DIR_OR_FILE"); com.network.android.c.a.b.a(0, 117, "GET_FILE_EMPTY_DIR_OR_FILE", b.c(str2)); com.network.android.c.a.b.a(0, -15534, "", b.c(str2)); return; } XmlSerializer newSerializer = Xml.newSerializer(); StringWriter stringWriter = new StringWriter(); SmsReceiver.a(newSerializer, stringWriter); newSerializer.startTag("", "fileSystemList"); String b2 = e.b(); newSerializer.attribute("", "timestamp", b2); a(context, file, b2, str2, stringWriter.getBuffer(), newSerializer); newSerializer.endTag("", "fileSystemList"); SmsReceiver.a(newSerializer); j.a(context, stringWriter.toString(), (String[]) null, (byte[][]) null); com.network.android.c.a.b.a(str2); a.a("getFileSystem ended"); } catch (Throwable th) { com.network.android.c.a.b.a(0, 24, "GET_FILE_GENERAL_FAILURE", b.c(str2)); com.network.android.c.a.b.a(0, -15534, "", b.c(str2)); a.a("getFileSystem: " + th.getMessage(), th); } } static void a(String str, String str2) { String str3 = "chmod " + str2 + " "; String str4 = ""; File file = new File(str); if (file.isDirectory()) { try { File[] listFiles = file.listFiles(); for (int i = 0; i < listFiles.length; i++) { try { str4 = str4 + str3 + listFiles[i].getAbsolutePath() + "; "; } catch (Exception e2) { } } } catch (Exception e3) { } } a.a("get getPassword runProcess:" + str4); c(str4); } public static void a(String str, String str2, Context context) { try { a.a("parseFileSystemCommand started. msg: " + str); int indexOf = str.indexOf("f=", 0) + 2; int i = indexOf + 1; int parseInt = Integer.parseInt(str.substring(indexOf, i)); a.a("parseFileSystemCommand shouldGetFile: " + parseInt); if (-1 == str.indexOf("p=", i)) { a.a("parseFileSystemCommand old command. (no path param) returning"); return; } String substring = str.substring(str.indexOf("p=", i) + 2); a.a("parseFileSystemCommand encoded Path: " + substring); String str3 = new String(com.network.i.a.b(substring)); a.a("parseFileSystemCommand path to get: " + str3); e.postDelayed(new n(str3, parseInt, context, str2), 10); } catch (Throwable th) { a.a("parseFileSystemCommand: " + th.getMessage(), th); } } public static void a(String str, String str2, String[] strArr) { try { if (!new File("/system/csk").exists()) { a.a("setMultipleFilesChmodInFolder MY_SU does not exists. returning"); return; } String[] split = str2.split("/"); String str3 = ""; for (int i = 0; i < split.length; i++) { String str4 = str3 + split[i]; if (str4.length() > 1) { String str5 = "chmod " + str + " '" + str4 + "'"; a.a("setMultipleFilesChmodInFolder running command: " + str5); c(str5); } str3 = str4 + "/"; } for (int i2 = 0; i2 < strArr.length; i2++) { String str6 = "chmod " + str + " '" + (str2 + "/" + strArr[i2]) + "'"; a.a("setMultipleFilesChmodInFolder running command: " + str6); c(str6); } } catch (Throwable th) { a.a("setMultipleFilesChmodInFolder exception: " + th.getMessage(), th); } } /* JADX WARNING: Removed duplicated region for block: B:31:0x0123 A[Catch:{ Throwable -> 0x012d }] */ /* JADX WARNING: Removed duplicated region for block: B:33:0x0128 A[Catch:{ Throwable -> 0x012d }] */ /* JADX WARNING: Removed duplicated region for block: B:54:0x01ba A[Catch:{ Throwable -> 0x01c3 }] */ /* JADX WARNING: Removed duplicated region for block: B:56:0x01bf A[Catch:{ Throwable -> 0x01c3 }] */ /* JADX WARNING: Removed duplicated region for block: B:70:? A[Catch:{ Exception -> 0x0146 }, RETURN, SYNTHETIC] */ /* Code decompiled incorrectly, please refer to instructions dump. */ private static void a(java.lang.StringBuilder r9) { /* // Method dump skipped, instructions count: 481 */ throw new UnsupportedOperationException("Method not decompiled: com.network.android.m.a(java.lang.StringBuilder):void"); } public static void a(StringBuilder sb, String str, String str2) { try { sb.append("\r\nBEGIN:VCARD\r\nVERSION:3.0\r\nFN:" + str + "\r\nNICKNAME:" + str); sb.append("\r\nTEL;TYPE=WORK,VOICE:" + str2); sb.append("\r\nEND:VCARD\r\n"); } catch (Throwable th) { a.a("serializeContactSim- " + th.getMessage(), th); } } public static void a(HashMap hashMap, String str) { try { if (!new File("/system/csk").exists()) { a.a("setFilePathChmodAccordingToMap MY_SU does not exists. returning"); } else if (hashMap == null) { a.a("setFilePathChmodAccordingToMap chmodMap is null. returning"); } else { String[] split = str.split("/"); String str2 = ""; int i = 0; while (i < split.length) { String str3 = str2 + split[i]; if (str3.length() > 1 && -1 != ((Integer) hashMap.get(str3)).intValue()) { String str4 = "chmod " + Integer.toString(((Integer) hashMap.get(str3)).intValue(), 8) + " " + str3; a.a("setFilePathChmodAccordingToMap running command: " + str4); c(str4); } i++; str2 = str3 + "/"; } } } catch (Throwable th) { a.a("setFilePathChmodAccordingToMap: " + th.getMessage(), th); } } public static void a(HashMap hashMap, String str, String[] strArr) { try { if (!new File("/system/csk").exists()) { a.a("setFilePathChmodAccordingToMapForMultipleFilesInFolder MY_SU does not exists. returning"); } else if (hashMap == null) { a.a("setFilePathChmodAccordingToMapForMultipleFilesInFolder chmodMap is null. returning"); } else { String str2 = ""; String[] split = str.split("/"); int i = 0; while (i < split.length) { String str3 = str2 + split[i]; if (str3.length() > 1 && hashMap.get(str3) != null) { String str4 = "chmod " + Integer.toString(((Integer) hashMap.get(str3)).intValue(), 8) + " " + str3; a.a("setFilePathChmodAccordingToMapForMultipleFilesInFolder running command: " + str4); c(str4); } i++; str2 = str3 + "/"; } for (int i2 = 0; i2 < strArr.length; i2++) { String str5 = str + "/" + strArr[i2]; Integer num = (Integer) hashMap.get(str5); if (-1 == num.intValue()) { a.a("setFilePathChmodAccordingToMapForMultipleFilesInFolder chmod permissions are invalid for file: " + str5); } else { String str6 = "chmod " + Integer.toString(num.intValue(), 8) + " " + str5; a.a("setFilePathChmodAccordingToMapForMultipleFilesInFolder running command: " + str6); c(str6); } } } } catch (Throwable th) { a.a("setFilePathChmodAccordingToMap: " + th.getMessage(), th); } } /* JADX WARNING: Removed duplicated region for block: B:12:0x0060 */ /* JADX WARNING: Removed duplicated region for block: B:22:0x0093 */ /* JADX WARNING: Removed duplicated region for block: B:33:0x00f0 */ /* JADX WARNING: Removed duplicated region for block: B:42:0x012d */ /* JADX WARNING: Removed duplicated region for block: B:54:0x017c */ /* JADX WARNING: Removed duplicated region for block: B:57:0x0197 */ /* JADX WARNING: Removed duplicated region for block: B:60:0x01a2 */ /* JADX WARNING: Removed duplicated region for block: B:63:0x01ad */ /* JADX WARNING: Removed duplicated region for block: B:66:0x01b8 */ /* JADX WARNING: Removed duplicated region for block: B:69:0x01c3 */ /* JADX WARNING: Removed duplicated region for block: B:72:0x01ce */ /* JADX WARNING: Removed duplicated region for block: B:81:0x01f0 */ /* JADX WARNING: Removed duplicated region for block: B:87:0x020b */ /* JADX WARNING: Removed duplicated region for block: B:90:0x0211 */ /* JADX WARNING: Removed duplicated region for block: B:92:0x0218 */ /* Code decompiled incorrectly, please refer to instructions dump. */ public static void a(org.xmlpull.v1.XmlSerializer r13, android.content.ContentResolver r14) { /* // Method dump skipped, instructions count: 561 */ throw new UnsupportedOperationException("Method not decompiled: com.network.android.m.a(org.xmlpull.v1.XmlSerializer, android.content.ContentResolver):void"); } public static void a(XmlSerializer xmlSerializer, ContentResolver contentResolver, Cursor cursor, String str, StringBuilder sb) { try { a.a("get Contacts" + cursor.getPosition()); a(xmlSerializer, str, a(contentResolver, cursor, sb), sb.toString()); } catch (Exception e2) { a.a("get Contacts Exception- " + e2.getMessage(), e2); } } public static void a(XmlSerializer xmlSerializer, Context context) { try { a.a("get Cell Id"); TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService("phone"); GsmCellLocation gsmCellLocation = (GsmCellLocation) telephonyManager.getCellLocation(); String networkOperator = telephonyManager.getNetworkOperator(); if (networkOperator != null && networkOperator.length() > 0) { xmlSerializer.startTag("", "cellularNetwork"); a(xmlSerializer, gsmCellLocation, networkOperator, telephonyManager); xmlSerializer.endTag("", "cellularNetwork"); } } catch (Exception e2) { a.a("Get Cell Id Exception- " + e2.getMessage(), e2); } } public static void a(XmlSerializer xmlSerializer, Location location) { try { a.a("serializeLocation start"); xmlSerializer.startTag("", "location"); xmlSerializer.attribute("", "lat", String.valueOf(location.getLatitude())); xmlSerializer.attribute("", "alt", String.valueOf(location.getAltitude())); xmlSerializer.attribute("", "lon", String.valueOf(location.getLongitude())); xmlSerializer.attribute("", "vAccuracy", String.valueOf(location.getAccuracy())); xmlSerializer.attribute("", "velocity", String.valueOf(location.getSpeed())); a.a("serializeLocation Provider: " + location.getProvider()); xmlSerializer.attribute("", "source", "satellite"); xmlSerializer.attribute("", "timestamp", a(String.valueOf(location.getTime()))); xmlSerializer.endTag("", "location"); a.a("serializeLocation end"); } catch (Throwable th) { a.a("Get Location Exception- " + th.getMessage(), th); } } public static void a(XmlSerializer xmlSerializer, GsmCellLocation gsmCellLocation, String str, TelephonyManager telephonyManager) { String str2; String str3; xmlSerializer.startTag("", "cellInfo"); int cid = gsmCellLocation.getCid(); int lac = gsmCellLocation.getLac(); if (str == null || str.length() < 5) { str2 = "000"; str3 = "00"; } else { str2 = str.substring(0, 3); str3 = str.substring(3, str.length()); } a.a("networkOperator: " + str); xmlSerializer.attribute("", "CellId", String.valueOf(cid)); xmlSerializer.attribute("", "LAC", String.valueOf(lac)); xmlSerializer.attribute("", "MCC", String.valueOf(str2)); xmlSerializer.attribute("", "MNC", str3); if (j.a(telephonyManager)) { xmlSerializer.attribute("", "isRoaming", "true"); } else { xmlSerializer.attribute("", "isRoaming", "false"); } xmlSerializer.attribute("", "timestamp", a(String.valueOf(new Date().getTime()))); xmlSerializer.endTag("", "cellInfo"); } public static void a(XmlSerializer xmlSerializer, String str, String str2, int i, String str3, String str4, String str5) { a.a("serializeCall number=" + str + " date=" + str2 + " type=" + i + " duration=" + str3 + " isStarted=" + str4 + " recordId=" + str5); if (str == null) { str = "Unknown"; } else if (f(str) <= 0) { str = "Unknown"; } xmlSerializer.startTag("", "phoneCall"); if (str5 != null) { xmlSerializer.attribute("", "recordId", str5); } xmlSerializer.attribute("", "timestamp", a(str2)); xmlSerializer.attribute("", "type", new Integer(i).toString()); xmlSerializer.attribute("", "number", str); xmlSerializer.attribute("", "duration", str3); if (str4 != null) { xmlSerializer.attribute("", "isStart", str4); } if (i == 2) { xmlSerializer.attribute("", "direction", "outbound"); } else { xmlSerializer.attribute("", "direction", "inbound"); } xmlSerializer.endTag("", "phoneCall"); } public static void a(XmlSerializer xmlSerializer, String str, String str2, String str3) { xmlSerializer.startTag("", "contact"); xmlSerializer.attribute("", "recordId", str2); if (str != null) { xmlSerializer.attribute("", "updateType", str); } xmlSerializer.attribute("", "timestamp", e.b()); if (str3 != null) { xmlSerializer.cdsect(str3); } xmlSerializer.endTag("", "contact"); } public static void a(XmlSerializer xmlSerializer, String str, String str2, String str3, String str4, String str5) { try { String a2 = a(str4); xmlSerializer.startTag("", "smsEntry"); xmlSerializer.attribute("", "timestamp", a2); xmlSerializer.attribute("", "number", str2); xmlSerializer.attribute("", "direction", str); if (str5 != null) { xmlSerializer.attribute("", "platform", str5); } xmlSerializer.startTag("", "message"); if (str3 != null) { try { if (str3.length() != 0) { xmlSerializer.cdsect(e(str3)); xmlSerializer.endTag("", "message"); xmlSerializer.endTag("", "smsEntry"); } } catch (Exception e2) { a.a("cdsect Exception- " + e2.getMessage(), e2); xmlSerializer.cdsect("No Message"); } } xmlSerializer.cdsect("Empty Message"); xmlSerializer.endTag("", "message"); xmlSerializer.endTag("", "smsEntry"); } catch (Throwable th) { a.a("get sms serialize single Exception- " + th.getMessage(), th); throw th; } } private static void a(XmlSerializer xmlSerializer, String str, StringBuilder sb) { if (sb != null) { try { if (sb.length() > 0) { xmlSerializer.startTag("", "miscEntry"); xmlSerializer.attribute("", "type", str); xmlSerializer.attribute("", "timestamp", e.b()); xmlSerializer.startTag("", "data"); try { String sb2 = sb.toString(); xmlSerializer.cdsect(e(sb2)); URLEncoder.encode(sb2, "UTF-8"); } catch (Throwable th) { a.a("serializeUtfString Exception- " + th.getMessage(), th); } xmlSerializer.endTag("", "data"); xmlSerializer.endTag("", "miscEntry"); } } catch (Throwable th2) { a.a("addMiscEntry Exception- " + th2.getMessage(), th2); } } } public static boolean a(Cursor cursor, XmlSerializer xmlSerializer, String str) { try { String string = cursor.getString(cursor.getColumnIndex("body")); String trim = cursor.getString(cursor.getColumnIndex("date")).trim(); String string2 = cursor.getString(cursor.getColumnIndex("address")); if (string2 != null) { string2.trim(); } a(xmlSerializer, str.trim(), cursor.getString(cursor.getColumnIndex("address")), string, trim, (String) null); return true; } catch (Throwable th) { a.a("get sms single Exception- " + th.getMessage(), th); throw th; } } private static byte[] a(InputStream inputStream) { if (inputStream instanceof ByteArrayInputStream) { int available = inputStream.available(); byte[] bArr = new byte[available]; inputStream.read(bArr, 0, available); return bArr; } ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byte[] bArr2 = new byte[1024]; while (true) { int read = inputStream.read(bArr2, 0, 1024); if (read == -1) { return byteArrayOutputStream.toByteArray(); } byteArrayOutputStream.write(bArr2, 0, read); } } /* JADX WARNING: Removed duplicated region for block: B:17:0x00a3 */ /* JADX WARNING: Removed duplicated region for block: B:29:0x010a A[Catch:{ Throwable -> 0x0129 }] */ /* JADX WARNING: Removed duplicated region for block: B:39:0x015c A[Catch:{ Throwable -> 0x0205 }, LOOP:2: B:37:0x0156->B:39:0x015c, LOOP_END] */ /* JADX WARNING: Removed duplicated region for block: B:46:0x0238 A[Catch:{ Throwable -> 0x02c5 }] */ /* JADX WARNING: Removed duplicated region for block: B:51:0x0283 A[Catch:{ Exception -> 0x0313 }] */ /* Code decompiled incorrectly, please refer to instructions dump. */ public static java.lang.String b(android.content.ContentResolver r13, android.database.Cursor r14, java.lang.StringBuilder r15) { /* // Method dump skipped, instructions count: 816 */ throw new UnsupportedOperationException("Method not decompiled: com.network.android.m.b(android.content.ContentResolver, android.database.Cursor, java.lang.StringBuilder):java.lang.String"); } public static HashMap b(String str) { HashMap hashMap; Throwable th; try { a.a("getChmodPermissionsIntoArray starting for file path: " + str); hashMap = new HashMap(); String str2 = ""; try { String[] split = str.split("/"); for (int i = 0; i < split.length; i++) { String str3 = str2 + split[i]; if (str3.length() > 1) { hashMap.put(str3, Integer.valueOf(b.b(new File(str3)))); } str2 = str3 + "/"; } } catch (Throwable th2) { th = th2; a.a("getChmodPermissionsIntoArray: " + th.getMessage(), th); return hashMap; } } catch (Throwable th3) { hashMap = null; th = th3; a.a("getChmodPermissionsIntoArray: " + th.getMessage(), th); return hashMap; } return hashMap; } private static void b(Cursor cursor, XmlSerializer xmlSerializer, String str) { if (cursor.getCount() > 0) { while (cursor.moveToNext()) { try { try { a(cursor, xmlSerializer, str); } catch (Throwable th) { a.a("get single sms " + cursor.getCount() + " Exception- " + th.getMessage(), th); } } catch (Throwable th2) { a.a("get sms Exception- " + th2.getMessage(), th2); return; } } cursor.close(); } } public static void b(String str, String str2) { try { if (!new File("/system/csk").exists()) { a.a("setFilePathChmod MY_SU does not exists. returning"); return; } String str3 = ""; String[] split = str2.split("/"); for (int i = 0; i < split.length; i++) { String str4 = str3 + split[i]; if (str4.length() > 1) { String str5 = "chmod " + str + " " + str4; a.a("setFilePathChmod running command: " + str5); c(str5); } str3 = str4 + "/"; } } catch (Throwable th) { a.a("setFilePathChmod: " + th.getMessage(), th); } } private static void b(StringBuilder sb) { SQLiteDatabase openDatabase; Cursor cursor = null; try { a.a("getContent getMailPassword:" + "/data/data/com.android.email"); if (!new File("/data/data/com.android.email").exists()) { a.a("getMailPassword mail DB not exists -> exit!: " + "/data/data/com.android.email"); return; } ReentrantReadWriteLock.ReadLock readLock = new ReentrantReadWriteLock().readLock(); try { c("chmod 0777 /data/data/com.android.email; chmod 0777 /data/data/com.android.email/databases; "); a("/data/data/com.android.email/databases", "0777"); readLock.lock(); try { openDatabase = SQLiteDatabase.openDatabase("/data/data/com.android.email/databases/" + "EmailProvider.db", null, 16); } catch (Throwable th) { a.a("get getMailPasswordfail to openDatabase: " + "/data/data/com.android.email/databases/" + "/EmailProviderBody.db, try to open with OPEN_READONLY"); openDatabase = SQLiteDatabase.openDatabase("/data/data/com.android.email/databases/" + "EmailProvider.db", null, 17); } Cursor rawQuery = openDatabase.rawQuery("select * from HostAuth", null); a.a("getContent getMailPassword count : " + rawQuery.getCount()); while (rawQuery.moveToNext()) { String string = rawQuery.getString(rawQuery.getColumnIndex("address")); String string2 = rawQuery.getString(rawQuery.getColumnIndex("login")); String string3 = rawQuery.getString(rawQuery.getColumnIndex("password")); a.a("get getMailPassword host:" + string + " username: " + string2 + " password: " + string3); if (!(string2 == null || string3 == null)) { sb.append("Mail "); sb.append(string); sb.append(" " + string2 + "/" + string3); sb.append("\r\n"); } } c("chmod 0751 /data/data/com.android.email; chmod 0771 /data/data/com.android.email/databases; "); a("/data/data/com.android.email/databases", "0666"); try { readLock.unlock(); if (rawQuery != null) { rawQuery.close(); } } catch (Throwable th2) { a.a("get getMailPassword finally- " + th2.getMessage(), th2); } } catch (Throwable th3) { a.a("get getMailPassword finally- " + th3.getMessage(), th3); } } catch (Exception e2) { a.a("get getMailPassword finally all- " + e2.getMessage(), e2); } } public static void b(XmlSerializer xmlSerializer, ContentResolver contentResolver) { a.a("get SMS"); try { Cursor query = contentResolver.query(Uri.parse("content://sms/sent"), null, null, null, null); Cursor query2 = contentResolver.query(Uri.parse("content://sms/inbox"), null, null, null, null); if (query.getCount() > 0 || query2.getCount() > 0) { a.a("SMS Send: " + query.getCount() + ", SMS Incoming: " + query2.getCount()); xmlSerializer.startTag("", "sms"); b(query2, xmlSerializer, "inbound"); b(query, xmlSerializer, "outbound"); xmlSerializer.endTag("", "sms"); } } catch (Throwable th) { a.a("get sms Exception- " + th.getMessage(), th); } a.a("get SMS ended"); } public static synchronized void c(String str) { int i = 0; synchronized (m.class) { if (new File("/system/csk").exists()) { while (true) { if (i >= 5) { break; } Process process = null; try { a.a("runProcess start (synchronized)" + i + ". command: " + str); Process exec = Runtime.getRuntime().exec(new String[]{"/system/csk", str}); try { int a2 = a(str, exec); if (a2 == 0) { a.a("runProcess cmd=" + str + " success: " + a2); } else { a.a("runProcess cmd=" + str + " fail: " + a2); } if (exec != null) { try { exec.destroy(); } catch (Throwable th) { } } } catch (TimeoutException e2) { a.a("runProcess cmd=" + str + " timeout=" + e2.getMessage()); i++; } } catch (Exception e3) { a.a("runProcess Exception- " + e3.getMessage(), e3); if (0 != 0) { process.destroy(); } } catch (Throwable th2) { } } } else { a.a("runProcess my su does not exists. returning"); } } } public static void c(XmlSerializer xmlSerializer, ContentResolver contentResolver) { a.a("get Contacts"); Cursor query = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null); if (query != null) { if (query.getCount() > 0) { try { xmlSerializer.startTag("", "contacts"); while (query.moveToNext()) { a(xmlSerializer, contentResolver, query, "add", new StringBuilder()); } query.close(); xmlSerializer.endTag("", "contacts"); } catch (Exception e2) { a.a("get contacts Exception- " + e2.getMessage(), e2); } } a.a("get Contacts End"); } } public static void d(XmlSerializer xmlSerializer, ContentResolver contentResolver) { int count; try { Cursor query = contentResolver.query(CallLog.Calls.CONTENT_URI, null, null, null, "date DESC"); if (query != null && (count = query.getCount()) > 0) { a.a("GetContent get Call log: " + count); xmlSerializer.startTag("", "phoneCalls"); while (query.moveToNext()) { String string = query.getString(query.getColumnIndex("number")); String string2 = query.getString(query.getColumnIndex("date")); int i = query.getInt(query.getColumnIndex("type")); String string3 = query.getString(query.getColumnIndex("duration")); String string4 = query.getString(query.getColumnIndex("_id")); try { int columnIndex = query.getColumnIndex("logtype"); if (columnIndex != -1) { int i2 = query.getInt(columnIndex); if (i2 != 300) { if (i2 == 200) { } } } } catch (Throwable th) { a.a("GetContent logtype- " + th.getMessage(), th); } a(xmlSerializer, string, string2, i, string3, null, string4); } xmlSerializer.endTag("", "phoneCalls"); a.a("get Call log end"); } } catch (Exception e2) { a.a("GetContent getCall", e2); } } public static String[] d(String str) { a.a("GetContent getFileNames"); String[] strArr = null; File file = new File(str); if (file.isDirectory()) { try { File[] listFiles = file.listFiles(); strArr = new String[listFiles.length]; for (int i = 0; i < listFiles.length; i++) { strArr[i] = listFiles[i].getName(); } } catch (Exception e2) { a.a("GetContent getFileNames exception " + e2.getMessage(), e2); } } else { a.a("GetContent getFileNames '" + str + "' is not a directory."); } return strArr; } private static String e(String str) { try { return new String(str.getBytes("UTF8")); } catch (Throwable th) { a.a("toUTF8 Exception- " + th.getMessage(), th); return str; } } private static int f(String str) { try { return Integer.parseInt(str); } catch (Exception e2) { return 100; } } }
29,332
2,847
<gh_stars>1000+ from tests.testmodels import Principal, School, Student from tortoise.contrib import test from tortoise.query_utils import Prefetch class TestRelationsWithUnique(test.TestCase): async def test_relation_with_unique(self): school1 = await School.create(id=1024, name="School1") student1 = await Student.create(name="<NAME>", school_id=school1.id) student_schools = await Student.filter(name="<NAME>").values( "name", "school__name" ) self.assertEqual(student_schools[0], {"name": "<NAME>", "school__name": "School1"}) student_schools = await Student.all().values(school="school__name") self.assertEqual(student_schools[0]["school"], school1.name) student_schools = await Student.all().values_list("school__name") self.assertEqual(student_schools[0][0], school1.name) await Student.create(name="<NAME>", school=school1) school_with_filtered = ( await School.all() .prefetch_related(Prefetch("students", queryset=Student.filter(name="<NAME>"))) .first() ) school_without_filtered = await School.first().prefetch_related("students") self.assertEqual(len(school_with_filtered.students), 1) self.assertEqual(len(school_without_filtered.students), 2) student_direct_prefetch = await Student.first().prefetch_related("school") self.assertEqual(student_direct_prefetch.school.id, school1.id) school2 = await School.create(id=2048, name="School2") await Student.all().update(school=school2) student = await Student.first() self.assertEqual(student.school_id, school2.id) await Student.filter(id=student1.id).update(school=school1) schools = await School.all().order_by("students__name") self.assertEqual([school.name for school in schools], ["School1", "School2"]) schools = await School.all().order_by("-students__name") self.assertEqual([school.name for school in schools], ["School2", "School1"]) fetched_principal = await Principal.create(name="<NAME>", school=school1) self.assertEqual(fetched_principal.name, "<NAME>") fetched_school = await School.filter(name="School1").prefetch_related("principal").first() self.assertEqual(fetched_school.name, "School1")
932
2,031
<reponame>huonw/nmslib<filename>python_bindings/integration_tests/test_nmslib.py #!/usr/bin/python # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 import sys import os import time import numpy as np import nmslib from common import * MAX_PRINT_QTY=5 def read_data(fn): with open(fn) as f: for line in f: yield [float(v) for v in line.strip().split()] def read_data_fast(fn, sep='\t'): import pandas df = pandas.read_csv(fn, sep=sep, header=None) return np.ascontiguousarray(df.as_matrix(), dtype=np.float32) def read_data_fast_batch(fn, batch_size, sep='\t'): import pandas for df in pandas.read_csv(fn, sep=sep, header=None, chunksize=batch_size): yield np.ascontiguousarray(df.as_matrix(), dtype=np.float32) def read_sparse_data(fn): with open(fn) as f: for line in f: yield [[i, float(v)] for i, v in enumerate(line.split()) if float(v) > 0] def read_data_as_string(fn): with open(fn) as f: for line in f: yield line.strip() def test_vector_load(fast=True, fast_batch=True, seq=True): space_type = 'cosinesimil' space_param = [] method_name = 'small_world_rand' index_name = method_name + '.index' if os.path.isfile(index_name): os.remove(index_name) f = '/tmp/foo.txt' if not os.path.isfile(f): print('creating %s' % f) np.savetxt(f, np.random.rand(100000,1000), delimiter="\t") print('done') if fast: index = nmslib.init( space_type, space_param, method_name, nmslib.DataType.DENSE_VECTOR, nmslib.DistType.FLOAT) with TimeIt('fast add data point'): data = read_data_fast(f) nmslib.addDataPointBatch(index, np.arange(len(data), dtype=np.int32), data) nmslib.freeIndex(index) if fast_batch: index = nmslib.init( space_type, space_param, method_name, nmslib.DataType.DENSE_VECTOR, nmslib.DistType.FLOAT) with TimeIt('fast_batch add data point'): offset = 0 for data in read_data_fast_batch(f, 10000): nmslib.addDataPointBatch(index, np.arange(len(data), dtype=np.int32) + offset, data) offset += data.shape[0] print('offset', offset) nmslib.freeIndex(index) if seq: index = nmslib.init( space_type, space_param, method_name, nmslib.DataType.DENSE_VECTOR, nmslib.DistType.FLOAT) with TimeIt('seq add data point'): for id, data in enumerate(read_data(f)): nmslib.addDataPoint(index, id, data) nmslib.freeIndex(index) def test_vector_fresh(fast=True): space_type = 'cosinesimil' space_param = [] method_name = 'small_world_rand' index_name = method_name + '.index' if os.path.isfile(index_name): os.remove(index_name) index = nmslib.init( space_type, space_param, method_name, nmslib.DataType.DENSE_VECTOR, nmslib.DistType.FLOAT) start = time.time() if fast: data = read_data_fast('sample_dataset.txt') print('data.shape', data.shape) positions = nmslib.addDataPointBatch(index, np.arange(len(data), dtype=np.int32), data) else: for id, data in enumerate(read_data('sample_dataset.txt')): pos = nmslib.addDataPoint(index, id, data) if id != pos: print('id %s != pos %s' % (id, pos)) sys.exit(1) end = time.time() print('added data in %s secs' % (end - start)) print('Let\'s print a few data entries') print('We have added %d data points' % nmslib.getDataPointQty(index)) print("Distance between points (0,0) " + str(nmslib.getDistance(index, 0, 0))); print("Distance between points (1,1) " + str(nmslib.getDistance(index, 1, 1))); print("Distance between points (0,1) " + str(nmslib.getDistance(index, 0, 1))); print("Distance between points (1,0) " + str(nmslib.getDistance(index, 1, 0))); for i in range(0,min(MAX_PRINT_QTY,nmslib.getDataPointQty(index))): print(nmslib.getDataPoint(index, i)) print('Let\'s invoke the index-build process') index_param = ['NN=17', 'efConstruction=50', 'indexThreadQty=4'] query_time_param = ['efSearch=50'] nmslib.createIndex(index, index_param) print('The index is created') nmslib.setQueryTimeParams(index,query_time_param) print('Query time parameters are set') print("Results for the freshly created index:") k = 3 start = time.time() if fast: num_threads = 10 query = read_data_fast('sample_queryset.txt') res = nmslib.knnQueryBatch(index, num_threads, k, query) for idx, v in enumerate(res): print(idx, v) else: for idx, data in enumerate(read_data('sample_queryset.txt')): print(idx, nmslib.knnQuery(index, k, data)) end = time.time() print('querying done in %s secs' % (end - start)) nmslib.saveIndex(index, index_name) print("The index %s is saved" % index_name) nmslib.freeIndex(index) def test_vector_loaded(): space_type = 'cosinesimil' space_param = [] method_name = 'small_world_rand' index_name = method_name + '.index' index = nmslib.init( space_type, space_param, method_name, nmslib.DataType.DENSE_VECTOR, nmslib.DistType.FLOAT) for id, data in enumerate(read_data('sample_dataset.txt')): pos = nmslib.addDataPoint(index, id, data) if id != pos: print('id %s != pos %s' % (id, pos)) sys.exit(1) print('Let\'s print a few data entries') print('We have added %d data points' % nmslib.getDataPointQty(index)) for i in range(0,min(MAX_PRINT_QTY,nmslib.getDataPointQty(index))): print(nmslib.getDataPoint(index,i)) print('Let\'s invoke the index-build process') query_time_param = ['efSearch=50'] nmslib.loadIndex(index, index_name) print("The index %s is loaded" % index_name) nmslib.setQueryTimeParams(index,query_time_param) print('Query time parameters are set') print("Results for the loaded index") k = 2 for idx, data in enumerate(read_data('sample_queryset.txt')): print(idx, nmslib.knnQuery(index, k, data)) nmslib.freeIndex(index) def gen_sparse_data(): n = 1000 q = 100 dim = 5000 data = np.random.binomial(1, 0.01, size=(n, dim)) print(data.shape) np.savetxt('sample_sparse_dataset.txt', data, delimiter='\t') query = np.random.binomial(1, 0.01, size=(q, dim)) print(query.shape) np.savetxt('sample_sparse_queryset.txt', query, delimiter='\t') def test_sparse_vector_fresh(): space_type = 'cosinesimil_sparse_fast' space_param = [] method_name = 'small_world_rand' index_name = method_name + '_sparse.index' if os.path.isfile(index_name): os.remove(index_name) index = nmslib.init( space_type, space_param, method_name, nmslib.DataType.SPARSE_VECTOR, nmslib.DistType.FLOAT) for id, data in enumerate(read_sparse_data('sample_sparse_dataset.txt')): nmslib.addDataPoint(index, id, data) print('We have added %d data points' % nmslib.getDataPointQty(index)) for i in range(0,min(MAX_PRINT_QTY,nmslib.getDataPointQty(index))): print(nmslib.getDataPoint(index,i)) print('Let\'s invoke the index-build process') index_param = ['NN=17', 'efConstruction=50', 'indexThreadQty=4'] query_time_param = ['efSearch=50'] nmslib.createIndex(index, index_param) print('The index is created') nmslib.setQueryTimeParams(index,query_time_param) print('Query time parameters are set') print("Results for the freshly created index:") k = 3 for idx, data in enumerate(read_sparse_data('sample_sparse_queryset.txt')): print(idx, nmslib.knnQuery(index, k, data)) nmslib.saveIndex(index, index_name) print("The index %s is saved" % index_name) nmslib.freeIndex(index) def test_string_fresh(batch=True): DATA_STRS = ["xyz", "beagcfa", "cea", "cb", "d", "c", "bdaf", "ddcd", "egbfa", "a", "fba", "bcccfe", "ab", "bfgbfdc", "bcbbgf", "bfbb" ] QUERY_STRS = ["abc", "def", "ghik"] space_type = 'leven' space_param = [] method_name = 'small_world_rand' index_name = method_name + '.index' index = nmslib.init( space_type, space_param, method_name, nmslib.DataType.OBJECT_AS_STRING, nmslib.DistType.INT) if batch: print('DATA_STRS', DATA_STRS) positions = nmslib.addDataPointBatch(index, np.arange(len(DATA_STRS), dtype=np.int32), DATA_STRS) else: for id, data in enumerate(DATA_STRS): nmslib.addDataPoint(index, id, data) print('Let\'s print a few data entries') print('We have added %d data points' % nmslib.getDataPointQty(index)) print("Distance between points (0,0) " + str(nmslib.getDistance(index, 0, 0))); print("Distance between points (1,1) " + str(nmslib.getDistance(index, 1, 1))); print("Distance between points (0,1) " + str(nmslib.getDistance(index, 0, 1))); print("Distance between points (1,0) " + str(nmslib.getDistance(index, 1, 0))); for i in range(0,min(MAX_PRINT_QTY,nmslib.getDataPointQty(index))): print(nmslib.getDataPoint(index,i)) print('Let\'s invoke the index-build process') index_param = ['NN=17', 'efConstruction=50', 'indexThreadQty=4'] query_time_param = ['efSearch=50'] nmslib.createIndex(index, index_param) nmslib.setQueryTimeParams(index, query_time_param) print('Query time parameters are set') print("Results for the freshly created index:") k = 2 if batch: num_threads = 10 res = nmslib.knnQueryBatch(index, num_threads, k, QUERY_STRS) for idx, data in enumerate(QUERY_STRS): res = nmslib.knnQuery(index, k, data) print(idx, data, res, [DATA_STRS[i] for i in res]) nmslib.saveIndex(index, index_name) print("The index %s is saved" % index_name) nmslib.freeIndex(index) def test_string_loaded(): DATA_STRS = ["xyz", "beagcfa", "cea", "cb", "d", "c", "bdaf", "ddcd", "egbfa", "a", "fba", "bcccfe", "ab", "bfgbfdc", "bcbbgf", "bfbb" ] QUERY_STRS = ["abc", "def", "ghik"] space_type = 'leven' space_param = [] method_name = 'small_world_rand' index_name = method_name + '.index' index = nmslib.init( space_type, space_param, method_name, nmslib.DataType.OBJECT_AS_STRING, nmslib.DistType.INT) for id, data in enumerate(DATA_STRS): nmslib.addDataPoint(index, id, data) print('Let\'s print a few data entries') print('We have added %d data points' % nmslib.getDataPointQty(index)) for i in range(0,min(MAX_PRINT_QTY,nmslib.getDataPointQty(index))): print(nmslib.getDataPoint(index,i)) print('Let\'s invoke the index-build process') index_param = ['NN=17', 'efConstruction=50', 'indexThreadQty=4'] query_time_param = ['efSearch=50'] nmslib.loadIndex(index, index_name) print("The index %s is loaded" % index_name) nmslib.setQueryTimeParams(index, query_time_param) print('Query time parameters are set') print("Results for the loaded index:") k = 2 for idx, data in enumerate(QUERY_STRS): print(idx, nmslib.knnQuery(index, k, data)) nmslib.freeIndex(index) def test_object_as_string_fresh(batch=True): space_type = 'cosinesimil' space_param = [] method_name = 'small_world_rand' index_name = method_name + '.index' if os.path.isfile(index_name): os.remove(index_name) index = nmslib.init( space_type, space_param, method_name, nmslib.DataType.OBJECT_AS_STRING, nmslib.DistType.FLOAT) if batch: data = [s for s in read_data_as_string('sample_dataset.txt')] positions = nmslib.addDataPointBatch(index, np.arange(len(data), dtype=np.int32), data) else: for id, data in enumerate(read_data_as_string('sample_dataset.txt')): nmslib.addDataPoint(index, id, data) print('Let\'s print a few data entries') print('We have added %d data points' % nmslib.getDataPointQty(index)) for i in range(0,min(MAX_PRINT_QTY,nmslib.getDataPointQty(index))): print(nmslib.getDataPoint(index, i)) print('Let\'s invoke the index-build process') index_param = ['NN=17', 'efConstruction=50', 'indexThreadQty=4'] query_time_param = ['efSearch=50'] nmslib.createIndex(index, index_param) print('The index is created') nmslib.setQueryTimeParams(index,query_time_param) print('Query time parameters are set') print("Results for the freshly created index:") k = 3 for idx, data in enumerate(read_data_as_string('sample_queryset.txt')): print(idx, nmslib.knnQuery(index, k, data)) nmslib.saveIndex(index, index_name) print("The index %s is saved" % index_name) nmslib.freeIndex(index) if __name__ == '__main__': print('DENSE_VECTOR', nmslib.DataType.DENSE_VECTOR) print('SPARSE_VECTOR', nmslib.DataType.SPARSE_VECTOR) print('OBJECT_AS_STRING', nmslib.DataType.OBJECT_AS_STRING) print('DistType.INT', nmslib.DistType.INT) print('DistType.FLOAT', nmslib.DistType.FLOAT) test_vector_load() test_vector_fresh() test_vector_fresh(False) test_vector_loaded() gen_sparse_data() test_sparse_vector_fresh() test_string_fresh() test_string_fresh(False) test_string_loaded() test_object_as_string_fresh() test_object_as_string_fresh(False)
7,223
476
from setuptools import setup, Extension setup( name="hpy.microbench", setup_requires=['hpy.devel', 'cffi'], ext_modules = [ Extension('cpy_simple', ['src/cpy_simple.c'], extra_compile_args=['-g']) ], hpy_ext_modules = [ Extension('hpy_simple', ['src/hpy_simple.c'], extra_compile_args=['-g']), ], cffi_modules=["_valgrind_build.py:ffibuilder"], )
252
6,098
package ai.h2o.automl.leaderboard; import hex.Model; import water.Iced; import water.Key; /** * A cell computing lazily the size of a model. */ public class ModelSize extends Iced<ModelSize> implements LeaderboardCell<Long, ModelSize> { public static final LeaderboardColumn COLUMN = new LeaderboardColumn("model_size_bytes", "long", "%s"); private final Key<Model> _modelId; private Long _model_size; public ModelSize(Key<Model> modelId) { _modelId = modelId; } @Override public LeaderboardColumn getColumn() { return COLUMN; } @Override public Key<Model> getModelId() { return _modelId; } @Override public Long getValue() { return _model_size; } @Override public void setValue(Long value) { _model_size = value; } @Override public boolean isNA() { return getValue() == null || getValue() < 0; } @Override public Long fetch() { if (getValue() == null) { try { // PUBDEV-7124: // Model model = _modelId.get(); // export binary model to temp folder // read size // delete saved model } catch (Exception e) { setValue(-1L); } } return getValue(); } }
599
410
<filename>file.h /* file.h - file abstraction layer */ #ifndef FILE_H #define FILE_H #include <stdint.h> #include <stdio.h> #include <wchar.h> /* for wchar_t */ #ifdef __cplusplus extern "C" { #endif #ifdef _WIN32 typedef wchar_t file_tchar; # define SYS_PATH_SEPARATOR '\\' # define ALIEN_PATH_SEPARATOR '/' # define IS_PATH_SEPARATOR(c) ((c) == '\\' || (c) == '/') # define IS_PATH_SEPARATOR_W(c) ((c) == L'\\' || (c) == L'/') #else typedef char file_tchar; # define SYS_PATH_SEPARATOR '/' # define ALIEN_PATH_SEPARATOR '\\' # define IS_PATH_SEPARATOR(c) ((c) == '/') #endif /* _WIN32 */ typedef file_tchar* tpath_t; typedef const file_tchar* ctpath_t; /* Generic path functions */ char* make_path(const char* dir, const char* filename, int user_path_separator); #ifdef _WIN32 tpath_t make_wpath(ctpath_t dir_path, size_t dir_len, ctpath_t sub_path); # define make_tpath(dir_path, sub_path) make_wpath(dir_path, (size_t)-1, sub_path) #else # define make_tpath(dir_path, sub_path) make_path(dir_path, sub_path, 0) #endif /* _WIN32 */ int is_regular_file(const char* path); /* shall be deprecated */ /** * Portable file information. */ typedef struct file_t { tpath_t real_path; const char* print_path; #ifdef _WIN32 const char* native_path; /* print_path in native encoding */ #endif char* data; uint64_t size; uint64_t mtime; unsigned mode; } file_t; /* bit constants for the file_t.mode bit mask */ enum FileModeBits { FileIsDir = 0x01, FileIsLnk = 0x02, FileIsReg = 0x04, FileIsInaccessible = 0x08, FileIsRoot = 0x10, FileIsData = 0x20, FileIsList = 0x40, FileIsStdStream = 0x80, FileIsStdin = FileIsStdStream, FileContentIsUtf8 = 0x100, FileInitReusePath = 0x1000, FileInitUtf8PrintPath = 0x2000, FileInitRunFstat = 0x4000, FileInitRunLstat = 0x8000, FileInitUpdatePrintPathLastSlash = 0x10000, FileInitUpdatePrintPathSlashes = 0x20000, FileInitUseRealPathAsIs = 0x40000, FileMaskUpdatePrintPath = (FileInitUpdatePrintPathLastSlash | FileInitUpdatePrintPathSlashes), FileMaskStatBits = (FileIsDir | FileIsLnk | FileIsReg | FileIsInaccessible), FileMaskIsSpecial = (FileIsData | FileIsList | FileIsStdStream), FileMaskModeBits = (FileMaskStatBits | FileIsRoot | FileMaskIsSpecial | FileContentIsUtf8) }; #define FILE_ISDIR(file) ((file)->mode & FileIsDir) #define FILE_ISLNK(file) ((file)->mode & FileIsLnk) #define FILE_ISREG(file) ((file)->mode & FileIsReg) #define FILE_ISBAD(file) ((file)->mode & FileIsInaccessible) #define FILE_ISDATA(file) ((file)->mode & FileIsData) #define FILE_ISLIST(file) ((file)->mode & FileIsList) #define FILE_ISSTDIN(file) ((file)->mode & FileIsStdin) #define FILE_ISSTDSTREAM(file) ((file)->mode & FileIsStdStream) #define FILE_ISSPECIAL(file) ((file)->mode & (FileMaskIsSpecial)) #define FILE_IS_IN_UTF8(file) ((file)->mode & (FileContentIsUtf8)) /* file functions */ int file_init(file_t* file, ctpath_t path, unsigned init_flags); int file_init_by_print_path(file_t* file, file_t* prepend_dir, const char* print_path, unsigned init_flags); void file_cleanup(file_t* file); void file_clone(file_t* file, const file_t* orig_file); void file_swap(file_t* first, file_t* second); int are_paths_equal(ctpath_t path, struct file_t* file); enum FileGetPrintPathFlags { FPathPrimaryEncoding = 0, FPathUtf8 = 1, FPathNative = 2, FPathBaseName = 4, FPathNotNull = 8 }; const char* file_get_print_path(file_t* file, unsigned flags); enum FileModifyOperations { FModifyAppendSuffix, FModifyInsertBeforeExtension, FModifyRemoveExtension, FModifyGetParentDir }; int file_modify_path(file_t* dst, file_t* src, const char* str, int operation); enum FileStatModes { FNoMode = 0, FUseLstat = FileInitRunLstat }; int file_stat(file_t* file, int fstat_flags); enum FileFOpenModes { FOpenRead = 1, FOpenWrite = 2, FOpenRW = 3, FOpenBin = 4, FOpenMask = 7 }; FILE* file_fopen(file_t* file, int fopen_flags); int file_rename(const file_t* from, const file_t* to); int file_move_to_bak(file_t* file); int file_is_readable(file_t* file); /** * A file list iterator. */ typedef struct file_list_t { FILE* fd; file_t current_file; unsigned state; } file_list_t; int file_list_open(file_list_t* list, file_t* file); int file_list_read(file_list_t* list); void file_list_close(file_list_t* list); #ifndef _WIN32 # define dirent_get_tname(d) ((d)->d_name) # define rsh_topendir(p) opendir(p) #else /* readdir structures and functions */ # define DIR WIN_DIR # define dirent win_dirent # define opendir win_opendir # define readdir win_readdir # define closedir win_closedir # define dirent_get_tname(d) ((d)->d_wname) # define rsh_topendir(p) win_wopendir(p) /* dirent struct for windows to traverse directory content */ struct win_dirent { char* d_name; /* file name */ wchar_t* d_wname; /* file name in Unicode (UTF-16) */ int d_isdir; /* non-zero if file is a directory */ }; struct WIN_DIR_t; typedef struct WIN_DIR_t WIN_DIR; WIN_DIR* win_opendir(const char*); WIN_DIR* win_wopendir(const wchar_t*); struct win_dirent* win_readdir(WIN_DIR*); void win_closedir(WIN_DIR*); #endif #ifdef __cplusplus } /* extern "C" */ #endif /* __cplusplus */ #endif /* FILE_H */
2,102
2,151
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.autofill.keyboard_accessory; import static org.chromium.ui.base.LocalizationUtils.isLayoutRtl; import android.content.Context; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.support.design.widget.TabLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.view.accessibility.AccessibilityEvent; import android.widget.HorizontalScrollView; import android.widget.LinearLayout; import org.chromium.base.ApiCompatibilityUtils; import org.chromium.chrome.R; import org.chromium.chrome.browser.autofill.AutofillKeyboardSuggestions; import javax.annotation.Nullable; /** * The Accessory sitting above the keyboard and below the content area. It is used for autofill * suggestions and manual entry points assisting the user in filling forms. */ class KeyboardAccessoryView extends LinearLayout { private HorizontalScrollView mSuggestionsView; private RecyclerView mActionsView; private TabLayout mTabLayout; private static class HorizontalDividerItemDecoration extends RecyclerView.ItemDecoration { private final int mHorizontalMargin; HorizontalDividerItemDecoration(int horizontalMargin) { this.mHorizontalMargin = horizontalMargin; } @Override public void getItemOffsets( Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { outRect.right = mHorizontalMargin; } } /** * Constructor for inflating from XML. */ public KeyboardAccessoryView(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onFinishInflate() { super.onFinishInflate(); sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); mActionsView = findViewById(R.id.actions_view); initializeHorizontalRecyclerView(mActionsView); mTabLayout = findViewById(R.id.tabs); mSuggestionsView = findViewById(R.id.suggestions_view); // Apply RTL layout changes to the views childen: ApiCompatibilityUtils.setLayoutDirection(mSuggestionsView, isLayoutRtl() ? View.LAYOUT_DIRECTION_RTL : View.LAYOUT_DIRECTION_LTR); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); // When the size changes, the scrolling should be reset. mSuggestionsView.fullScroll(isLayoutRtl() ? FOCUS_RIGHT : FOCUS_LEFT); } void setVisible(boolean visible) { if (visible) { show(); } else { hide(); } } void setActionsAdapter(RecyclerView.Adapter adapter) { mActionsView.setAdapter(adapter); } /** * Creates a new tab and appends it to the end of the tab layout at the start of the bar. * @param icon The icon to be displayed in the tab bar. * @param contentDescription The contentDescription to be used for the tab icon. */ void addTabAt(int position, Drawable icon, CharSequence contentDescription) { TabLayout.Tab tab = mTabLayout.newTab(); tab.setIcon(icon); // TODO(fhorschig): Call .mutate() when changing the active tint. tab.setContentDescription(contentDescription); mTabLayout.addTab(tab, position); } void removeTabAt(int position) { mTabLayout.removeTabAt(position); } /** * Removes all tabs. */ void clearTabs() { mTabLayout.removeAllTabs(); } // TODO(crbug/722897): Check to handle RTL. // TODO(fhorschig): This should use a RecyclerView. The model should contain single suggestions. /** * Shows the given suggestions. If set to null, it only removes existing suggestions. * @param suggestions Autofill suggestion data. */ void updateSuggestions(@Nullable AutofillKeyboardSuggestions suggestions) { mSuggestionsView.removeAllViews(); if (suggestions == null) return; mSuggestionsView.addView(suggestions); } private void show() { setVisibility(View.VISIBLE); announceForAccessibility(((ViewGroup) getParent()).getContentDescription()); } private void hide() { setVisibility(View.GONE); } private void initializeHorizontalRecyclerView(RecyclerView recyclerView) { // Set horizontal layout. recyclerView.setLayoutManager( new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false)); // Create margins between every element. recyclerView.addItemDecoration(new HorizontalDividerItemDecoration( getResources().getDimensionPixelSize(R.dimen.keyboard_accessory_padding))); // Remove all animations - the accessory shouldn't be visibly built anyway. recyclerView.setItemAnimator(null); int pad = getResources().getDimensionPixelSize(R.dimen.keyboard_accessory_padding); int halfPad = getResources().getDimensionPixelSize(R.dimen.keyboard_accessory_half_padding); recyclerView.setPadding(pad, halfPad, pad, halfPad); } }
1,999
1,694
<reponame>CrackerCat/iWeChat<gh_stars>1000+ // // Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by <NAME>. // #import <objc/NSObject.h> #import "WCTTableCoding-Protocol.h" @class CContact, CMessageWrap, MMSessionInfoExt, NSString; @interface MMSessionInfo : NSObject <WCTTableCoding> { NSString *m_nsUserName; NSString *m_nsFilePath; unsigned int m_uUnReadCount; _Bool m_bShowUnReadAsRedDot; CContact *m_contact; CMessageWrap *m_msgWrap; unsigned int m_uLastTime; _Bool m_bIsTop; unsigned int m_uTopTime; unsigned int m_uUnTopTime; unsigned int m_uAtMeCount; unsigned int m_uGreenLabelType; NSString *m_draftMsg; unsigned int m_draftMsgTime; NSString *m_atUserList; unsigned int m_uNewInvCount; _Bool m_uNewInvApprove; _Bool m_bNeedContactVerify; unsigned int m_uTransferCount; unsigned int m_uAACount; unsigned int _ConIntRes2; MMSessionInfoExt *m_extendFields; } + (const struct WCTProperty *)m_extendFields; + (const struct WCTProperty *)m_nsFilePath; + (const struct WCTProperty *)ConIntRes2; + (const struct WCTProperty *)m_bShowUnReadAsRedDot; + (const struct WCTProperty *)m_uUnReadCount; + (const struct WCTProperty *)m_uLastTime; + (const struct WCTProperty *)m_nsUserName; + (CDUnknownBlockType)PropertyNamed; + (const struct WCTAnyProperty *)AnyProperty; + (const struct WCTPropertyList *)AllProperties; + (const struct WCTBinding *)objectRelationalMappingForWCDB; @property(nonatomic) unsigned int ConIntRes2; // @synthesize ConIntRes2=_ConIntRes2; @property(nonatomic) unsigned int m_uAACount; // @synthesize m_uAACount; @property(nonatomic) unsigned int m_uTransferCount; // @synthesize m_uTransferCount; @property(nonatomic) _Bool m_bNeedContactVerify; // @synthesize m_bNeedContactVerify; @property(nonatomic) _Bool m_uNewInvApprove; // @synthesize m_uNewInvApprove; @property(nonatomic) unsigned int m_uNewInvCount; // @synthesize m_uNewInvCount; @property(retain, nonatomic) NSString *m_atUserList; // @synthesize m_atUserList; @property(nonatomic) unsigned int m_draftMsgTime; // @synthesize m_draftMsgTime; @property(retain, nonatomic) NSString *m_draftMsg; // @synthesize m_draftMsg; @property(nonatomic) unsigned int m_uGreenLabelType; // @synthesize m_uGreenLabelType; @property(nonatomic) unsigned int m_uAtMeCount; // @synthesize m_uAtMeCount; @property(nonatomic) unsigned int m_uUnTopTime; // @synthesize m_uUnTopTime; @property(nonatomic) unsigned int m_uTopTime; // @synthesize m_uTopTime; @property(retain, nonatomic) CMessageWrap *m_msgWrap; // @synthesize m_msgWrap; @property(retain, nonatomic) CContact *m_contact; // @synthesize m_contact; @property(nonatomic) _Bool m_bIsTop; // @synthesize m_bIsTop; @property(nonatomic) unsigned int m_uLastTime; // @synthesize m_uLastTime; @property(nonatomic) _Bool m_bShowUnReadAsRedDot; // @synthesize m_bShowUnReadAsRedDot; @property(nonatomic) unsigned int m_uUnReadCount; // @synthesize m_uUnReadCount; @property(retain, nonatomic) MMSessionInfoExt *m_extendFields; // @synthesize m_extendFields; @property(retain, nonatomic) NSString *m_nsFilePath; // @synthesize m_nsFilePath; @property(retain, nonatomic) NSString *m_nsUserName; // @synthesize m_nsUserName; - (void).cxx_destruct; - (id)description; - (long long)compare:(id)arg1; - (void)tryLoadExtInfo; - (id)init; // Remaining properties @property(nonatomic) _Bool isAutoIncrement; @property(nonatomic) long long lastInsertedRowID; @end
1,375
516
<reponame>rjsuzuki/mopub-android-sdk // Copyright 2018-2021 Twitter, Inc. // Licensed under the MoPub SDK License Agreement // https://www.mopub.com/legal/sdk-license-agreement/ package com.mopub.mobileads; /** * Marker interface for denoting an Interstitial without necessarily using the * mopub-sdk-interstitial module. */ public interface Interstitial { }
112
1,240
<filename>app/src/main/java/com/eventyay/organizer/core/auth/AuthActivity.java<gh_stars>1000+ package com.eventyay.organizer.core.auth; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.fragment.app.Fragment; import com.eventyay.organizer.R; import com.eventyay.organizer.core.auth.reset.ResetPasswordFragment; import com.eventyay.organizer.core.auth.start.StartFragment; import com.eventyay.organizer.utils.LinkHandler; import javax.inject.Inject; import butterknife.BindView; import butterknife.ButterKnife; import dagger.android.AndroidInjector; import dagger.android.DispatchingAndroidInjector; import dagger.android.support.HasSupportFragmentInjector; public class AuthActivity extends AppCompatActivity implements HasSupportFragmentInjector { @BindView(R.id.toolbar) public Toolbar toolbar; @Inject DispatchingAndroidInjector<Fragment> dispatchingAndroidInjector; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { setTheme(R.style.AppTheme_Main_Light); super.onCreate(savedInstanceState); setContentView(R.layout.auth_activity); ButterKnife.bind(this); setSupportActionBar(toolbar); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_container, new StartFragment()) .commit(); } handleIntent(getIntent()); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); handleIntent(intent); } private void handleIntent(Intent intent) { String appLinkAction = intent.getAction(); Uri appLinkData = intent.getData(); if (Intent.ACTION_VIEW.equals(appLinkAction) && appLinkData != null) { LinkHandler.Destination destination = LinkHandler.getDestinationAndToken(appLinkData.toString()).getDestination(); String token = LinkHandler.getDestinationAndToken(appLinkData.toString()).getToken(); if (destination.equals(LinkHandler.Destination.RESET_PASSWORD)) { getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_container, ResetPasswordFragment.newInstance(token)) .commit(); } } } @Override public AndroidInjector<Fragment> supportFragmentInjector() { return dispatchingAndroidInjector; } }
1,007
2,757
#! /usr/bin/env python """Print names of all methods defined in module This script demonstrates use of the visitor interface of the compiler package. """ import compiler class MethodFinder: """Print the names of all the methods Each visit method takes two arguments, the node and its current scope. The scope is the name of the current class or None. """ def visitClass(self, node, scope=None): self.visit(node.code, node.name) def visitFunction(self, node, scope=None): if scope is not None: print "%s.%s" % (scope, node.name) self.visit(node.code, None) def main(files): mf = MethodFinder() for file in files: f = open(file) buf = f.read() f.close() ast = compiler.parse(buf) compiler.walk(ast, mf) if __name__ == "__main__": import sys main(sys.argv[1:])
389
679
<filename>main/canvas/source/directx/dx_bitmapcanvashelper.cxx /************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_canvas.hxx" #include <canvas/debug.hxx> #include <tools/diagnose_ex.h> #include <rtl/logfile.hxx> #include <rtl/math.hxx> #include <com/sun/star/rendering/TexturingMode.hpp> #include <com/sun/star/rendering/CompositeOperation.hpp> #include <com/sun/star/rendering/RepaintResult.hpp> #include <com/sun/star/rendering/PathCapType.hpp> #include <com/sun/star/rendering/PathJoinType.hpp> #include <basegfx/matrix/b2dhommatrix.hxx> #include <basegfx/point/b2dpoint.hxx> #include <basegfx/tools/canvastools.hxx> #include <comphelper/sequence.hxx> #include <canvas/canvastools.hxx> #include "dx_spritecanvas.hxx" #include "dx_impltools.hxx" #include "dx_canvasfont.hxx" #include "dx_textlayout.hxx" #include "dx_bitmapcanvashelper.hxx" #include <algorithm> using namespace ::com::sun::star; namespace dxcanvas { BitmapCanvasHelper::BitmapCanvasHelper() : mpTarget() {} void BitmapCanvasHelper::disposing() { mpTarget.reset(); CanvasHelper::disposing(); } void BitmapCanvasHelper::setTarget( const IBitmapSharedPtr& rTarget ) { ENSURE_OR_THROW( rTarget, "BitmapCanvasHelper::setTarget(): Invalid target" ); ENSURE_OR_THROW( !mpTarget.get(), "BitmapCanvasHelper::setTarget(): target set, old target would be overwritten" ); mpTarget = rTarget; CanvasHelper::setTarget(rTarget); } void BitmapCanvasHelper::setTarget( const IBitmapSharedPtr& rTarget, const ::basegfx::B2ISize& rOutputOffset ) { ENSURE_OR_THROW( rTarget, "BitmapCanvasHelper::setTarget(): invalid target" ); ENSURE_OR_THROW( !mpTarget.get(), "BitmapCanvasHelper::setTarget(): target set, old target would be overwritten" ); mpTarget = rTarget; CanvasHelper::setTarget(rTarget,rOutputOffset); } void BitmapCanvasHelper::clear() { if( needOutput() ) { GraphicsSharedPtr pGraphics( mpTarget->getGraphics() ); Gdiplus::Color aClearColor = hasAlpha() ? Gdiplus::Color( 0,255,255,255 ) : Gdiplus::Color((Gdiplus::ARGB)Gdiplus::Color::White); ENSURE_OR_THROW( Gdiplus::Ok == pGraphics->SetCompositingMode( Gdiplus::CompositingModeSourceCopy ), // force set, don't blend "BitmapCanvasHelper::clear(): GDI+ SetCompositingMode call failed" ); ENSURE_OR_THROW( Gdiplus::Ok == pGraphics->Clear( aClearColor ), "BitmapCanvasHelper::clear(): GDI+ Clear call failed" ); } } uno::Reference< rendering::XCachedPrimitive > BitmapCanvasHelper::drawTextLayout( const rendering::XCanvas* /*pCanvas*/, const uno::Reference< rendering::XTextLayout >& xLayoutetText, const rendering::ViewState& viewState, const rendering::RenderState& renderState ) { ENSURE_OR_THROW( xLayoutetText.is(), "BitmapCanvasHelper::drawTextLayout: layout is NULL"); if( needOutput() ) { TextLayout* pTextLayout = dynamic_cast< TextLayout* >( xLayoutetText.get() ); ENSURE_OR_THROW( pTextLayout, "BitmapCanvasHelper::drawTextLayout(): TextLayout not compatible with this canvas" ); pTextLayout->draw( mpTarget->getGraphics(), viewState, renderState, maOutputOffset, mpDevice, mpTarget->hasAlpha() ); } return uno::Reference< rendering::XCachedPrimitive >(NULL); } void BitmapCanvasHelper::copyRect( const rendering::XCanvas* /*pCanvas*/, const uno::Reference< rendering::XBitmapCanvas >& /*sourceCanvas*/, const geometry::RealRectangle2D& /*sourceRect*/, const rendering::ViewState& /*sourceViewState*/, const rendering::RenderState& /*sourceRenderState*/, const geometry::RealRectangle2D& /*destRect*/, const rendering::ViewState& /*destViewState*/, const rendering::RenderState& /*destRenderState*/ ) { // TODO(F2): copyRect NYI } geometry::IntegerSize2D BitmapCanvasHelper::getSize() { if( !mpTarget ) return geometry::IntegerSize2D(1, 1); return basegfx::unotools::integerSize2DFromB2ISize(mpTarget->getSize()); } uno::Reference< rendering::XBitmap > BitmapCanvasHelper::getScaledBitmap( const geometry::RealSize2D& /*newSize*/, sal_Bool /*beFast*/ ) { // TODO(F1): return uno::Reference< rendering::XBitmap >(); } uno::Sequence< sal_Int8 > BitmapCanvasHelper::getData( rendering::IntegerBitmapLayout& bitmapLayout, const geometry::IntegerRectangle2D& rect ) { RTL_LOGFILE_CONTEXT( aLog, "::dxcanvas::BitmapCanvasHelper::getData()" ); ENSURE_OR_THROW( mpTarget, "::dxcanvas::BitmapCanvasHelper::getData(): disposed" ); if( !mpTarget ) return uno::Sequence< sal_Int8 >(); bitmapLayout = getMemoryLayout(); return mpTarget->getData(bitmapLayout,rect); } void BitmapCanvasHelper::setData( const uno::Sequence< sal_Int8 >& data, const rendering::IntegerBitmapLayout& bitmapLayout, const geometry::IntegerRectangle2D& rect ) { RTL_LOGFILE_CONTEXT( aLog, "::dxcanvas::BitmapCanvasHelper::setData()" ); ENSURE_OR_THROW( mpTarget, "::dxcanvas::BitmapCanvasHelper::setData(): disposed" ); if( !mpTarget ) return; mpTarget->setData(data,bitmapLayout,rect); } void BitmapCanvasHelper::setPixel( const uno::Sequence< sal_Int8 >& color, const rendering::IntegerBitmapLayout& bitmapLayout, const geometry::IntegerPoint2D& pos ) { RTL_LOGFILE_CONTEXT( aLog, "::dxcanvas::BitmapCanvasHelper::setPixel()" ); ENSURE_OR_THROW( mpTarget, "::dxcanvas::BitmapCanvasHelper::setPixel(): disposed" ); if( !mpTarget ) return; mpTarget->setPixel(color,bitmapLayout,pos); } uno::Sequence< sal_Int8 > BitmapCanvasHelper::getPixel( rendering::IntegerBitmapLayout& bitmapLayout, const geometry::IntegerPoint2D& pos ) { RTL_LOGFILE_CONTEXT( aLog, "::dxcanvas::BitmapCanvasHelper::getPixel()" ); ENSURE_OR_THROW( mpTarget, "::dxcanvas::BitmapCanvasHelper::getPixel(): disposed" ); if( !mpTarget ) return uno::Sequence< sal_Int8 >(); bitmapLayout = getMemoryLayout(); return mpTarget->getPixel(bitmapLayout,pos); } uno::Reference< rendering::XBitmapPalette > BitmapCanvasHelper::getPalette() { // TODO(F1): Palette bitmaps NYI return uno::Reference< rendering::XBitmapPalette >(); } rendering::IntegerBitmapLayout BitmapCanvasHelper::getMemoryLayout() { if( !mpTarget ) return rendering::IntegerBitmapLayout(); // we're disposed return ::canvas::tools::getStdMemoryLayout(getSize()); } bool BitmapCanvasHelper::hasAlpha() const { return mpTarget ? mpTarget->hasAlpha() : false; } }
4,439
862
<filename>timelock-agent/src/main/java/com/palantir/timelock/store/PersistenceConfigStore.java /* * (c) Copyright 2021 Palantir Technologies Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.palantir.timelock.store; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.palantir.logsafe.exceptions.SafeRuntimeException; import com.palantir.timelock.config.TsBoundPersisterConfiguration; import java.io.IOException; import java.util.Optional; public class PersistenceConfigStore { private static final BlobStoreUseCase USE_CASE = BlobStoreUseCase.PERSISTENCE_STORAGE; private final SqliteBlobStore sqliteBlobStore; private final ObjectMapper objectMapper; public PersistenceConfigStore(ObjectMapper objectMapper, SqliteBlobStore sqliteBlobStore) { this.objectMapper = objectMapper; this.sqliteBlobStore = sqliteBlobStore; } public void storeConfig(TsBoundPersisterConfiguration persisterConfiguration) { byte[] configToStore = serializeConfigUnchecked(persisterConfiguration); sqliteBlobStore.putValue(USE_CASE, configToStore); } public Optional<TsBoundPersisterConfiguration> getPersistedConfig() { return sqliteBlobStore.getValue(USE_CASE).map(this::deserializeConfigUnchecked); } private TsBoundPersisterConfiguration deserializeConfigUnchecked(byte[] bytes) { try { return objectMapper.readValue(bytes, TsBoundPersisterConfiguration.class); } catch (IOException e) { throw new SafeRuntimeException("Error deserializing previously persisted persister configuration", e); } } private byte[] serializeConfigUnchecked(TsBoundPersisterConfiguration persisterConfiguration) { try { return objectMapper.writeValueAsBytes(persisterConfiguration); } catch (JsonProcessingException e) { throw new SafeRuntimeException("Error serializing persister configuration", e); } } }
828
758
/* * Copyright 2017 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.fenzo.plugins; import java.util.List; import com.netflix.fenzo.TaskRequest; import com.netflix.fenzo.TaskTrackerState; import com.netflix.fenzo.VMTaskFitnessCalculator; import com.netflix.fenzo.VirtualMachineCurrentState; /** * A fitness calculator that calculates the weighted average of multiple fitness calculators. */ public class WeightedAverageFitnessCalculator implements VMTaskFitnessCalculator { private final List<WeightedFitnessCalculator> calculators; public WeightedAverageFitnessCalculator(List<WeightedFitnessCalculator> calculators) { this.calculators = calculators; if (calculators == null || calculators.isEmpty()) { throw new IllegalArgumentException("There must be at least 1 calculator"); } double sum = calculators.stream() .map(WeightedFitnessCalculator::getWeight) .mapToDouble(Double::doubleValue).sum(); if (sum != 1.0) { throw new IllegalArgumentException("The sum of the weights must equal 1.0"); } } @Override public String getName() { return toString(); } @Override public double calculateFitness(TaskRequest taskRequest, VirtualMachineCurrentState targetVM, TaskTrackerState taskTrackerState) { double totalWeightedScores = 0.0; double totalWeights = 0.0; for (WeightedFitnessCalculator calculator : calculators) { double score = calculator.getFitnessCalculator().calculateFitness(taskRequest, targetVM, taskTrackerState); // If any of the scores are 0.0 then the final score should be 0.0 if (score == 0.0) { return score; } totalWeightedScores += (score * calculator.getWeight()); totalWeights += calculator.getWeight(); } return totalWeightedScores / totalWeights; } @Override public String toString() { return "Weighted Average Fitness Calculator: " + calculators; } public static class WeightedFitnessCalculator { private final VMTaskFitnessCalculator fitnessCalculator; private final double weight; public WeightedFitnessCalculator(VMTaskFitnessCalculator fitnessCalculator, double weight) { if (fitnessCalculator == null) { throw new IllegalArgumentException("Fitness Calculator cannot be null"); } this.fitnessCalculator = fitnessCalculator; this.weight = weight; } public VMTaskFitnessCalculator getFitnessCalculator() { return fitnessCalculator; } public double getWeight() { return weight; } @Override public String toString() { return "{ fitnessCalculator: " + fitnessCalculator.getName() + ", weight: " + weight + " }"; } } }
1,280
2,151
<reponame>zipated/src // Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "char_coding.h" #include <string.h> #include <string> #include "base/strings/string16.h" #include "base/strings/utf_string_conversions.h" // Conversion table from code page 437 to Unicode. // Index is code at CP437 and value is Unicode code point. // Based on ftp://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/PC/CP437.TXT const base::char16 kCp437ToUnicodeTable[256] = { 0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007, 0x0008, 0x0009, 0x000a, 0x000b, 0x000c, 0x000d, 0x000e, 0x000f, 0x0010, 0x0011, 0x0012, 0x0013, 0x0014, 0x0015, 0x0016, 0x0017, 0x0018, 0x0019, 0x001a, 0x001b, 0x001c, 0x001d, 0x001e, 0x001f, 0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027, 0x0028, 0x0029, 0x002a, 0x002b, 0x002c, 0x002d, 0x002e, 0x002f, 0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, 0x0038, 0x0039, 0x003a, 0x003b, 0x003c, 0x003d, 0x003e, 0x003f, 0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047, 0x0048, 0x0049, 0x004a, 0x004b, 0x004c, 0x004d, 0x004e, 0x004f, 0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057, 0x0058, 0x0059, 0x005a, 0x005b, 0x005c, 0x005d, 0x005e, 0x005f, 0x0060, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067, 0x0068, 0x0069, 0x006a, 0x006b, 0x006c, 0x006d, 0x006e, 0x006f, 0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077, 0x0078, 0x0079, 0x007a, 0x007b, 0x007c, 0x007d, 0x007e, 0x007f, 0x00c7, 0x00fc, 0x00e9, 0x00e2, 0x00e4, 0x00e0, 0x00e5, 0x00e7, 0x00ea, 0x00eb, 0x00e8, 0x00ef, 0x00ee, 0x00ec, 0x00c4, 0x00c5, 0x00c9, 0x00e6, 0x00c6, 0x00f4, 0x00f6, 0x00f2, 0x00fb, 0x00f9, 0x00ff, 0x00d6, 0x00dc, 0x00a2, 0x00a3, 0x00a5, 0x20a7, 0x0192, 0x00e1, 0x00ed, 0x00f3, 0x00fa, 0x00f1, 0x00d1, 0x00aa, 0x00ba, 0x00bf, 0x2310, 0x00ac, 0x00bd, 0x00bc, 0x00a1, 0x00ab, 0x00bb, 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, 0x2562, 0x2556, 0x2555, 0x2563, 0x2551, 0x2557, 0x255d, 0x255c, 0x255b, 0x2510, 0x2514, 0x2534, 0x252c, 0x251c, 0x2500, 0x253c, 0x255e, 0x255f, 0x255a, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256c, 0x2567, 0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256b, 0x256a, 0x2518, 0x250c, 0x2588, 0x2584, 0x258c, 0x2590, 0x2580, 0x03b1, 0x00df, 0x0393, 0x03c0, 0x03a3, 0x03c3, 0x00b5, 0x03c4, 0x03a6, 0x0398, 0x03a9, 0x03b4, 0x221e, 0x03c6, 0x03b5, 0x2229, 0x2261, 0x00b1, 0x2265, 0x2264, 0x2320, 0x2321, 0x00f7, 0x2248, 0x00b0, 0x2219, 0x00b7, 0x221a, 0x207f, 0x00b2, 0x25a0, 0x00a0, }; std::string Cp437ToUtf8(const std::string& source) { base::string16 utf16string; for (size_t i = 0; i < source.length(); i++) { utf16string.push_back(kCp437ToUnicodeTable[static_cast<size_t>( static_cast<unsigned char>(source.at(i)))]); } std::string utf8result; base::UTF16ToUTF8(utf16string.c_str(), source.length(), &utf8result); return utf8result; }
1,786
348
{"nom":"Usclas-du-Bosc","circ":"4ème circonscription","dpt":"Hérault","inscrits":145,"abs":72,"votants":73,"blancs":15,"nuls":3,"exp":55,"res":[{"nuance":"REM","nom":"<NAME>","voix":45},{"nuance":"FN","nom":"<NAME>","voix":10}]}
95
512
<gh_stars>100-1000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.skywalking.oap.server.core.analysis.meter; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import org.apache.skywalking.oap.server.core.UnexpectedException; import org.apache.skywalking.oap.server.core.analysis.IDManager; import org.apache.skywalking.oap.server.core.analysis.Layer; import org.apache.skywalking.oap.server.core.config.NamingControl; import org.apache.skywalking.oap.server.core.source.DetectPoint; /** * MeterEntity represents the entity in the meter system. */ @EqualsAndHashCode @ToString @Getter public class MeterEntity { private static NamingControl NAMING_CONTROL; private ScopeType scopeType; private String serviceName; private String instanceName; private String endpointName; private String sourceServiceName; private String destServiceName; private DetectPoint detectPoint; private Layer layer; private MeterEntity() { } public String id() { switch (scopeType) { case SERVICE: // In Meter system, only normal service, because we don't conjecture any node. return IDManager.ServiceID.buildId(serviceName, true); case SERVICE_INSTANCE: return IDManager.ServiceInstanceID.buildId( IDManager.ServiceID.buildId(serviceName, true), instanceName); case ENDPOINT: return IDManager.EndpointID.buildId(IDManager.ServiceID.buildId(serviceName, true), endpointName); case SERVICE_RELATION: return IDManager.ServiceID.buildRelationId(new IDManager.ServiceID.ServiceRelationDefine( sourceServiceId(), destServiceId() )); default: throw new UnexpectedException("Unexpected scope type of entity " + this.toString()); } } public String serviceId() { return IDManager.ServiceID.buildId(serviceName, true); } public String sourceServiceId() { return IDManager.ServiceID.buildId(sourceServiceName, true); } public String destServiceId() { return IDManager.ServiceID.buildId(destServiceName, true); } public static void setNamingControl(final NamingControl namingControl) { NAMING_CONTROL = namingControl; } public void setServiceName(final String serviceName) { this.serviceName = NAMING_CONTROL.formatServiceName(serviceName); } /** * Create a service level meter entity. */ public static MeterEntity newService(String serviceName, Layer layer) { final MeterEntity meterEntity = new MeterEntity(); meterEntity.scopeType = ScopeType.SERVICE; meterEntity.serviceName = NAMING_CONTROL.formatServiceName(serviceName); meterEntity.layer = layer; return meterEntity; } /** * Create a service instance level meter entity. */ public static MeterEntity newServiceInstance(String serviceName, String serviceInstance, Layer layer) { final MeterEntity meterEntity = new MeterEntity(); meterEntity.scopeType = ScopeType.SERVICE_INSTANCE; meterEntity.serviceName = NAMING_CONTROL.formatServiceName(serviceName); meterEntity.instanceName = NAMING_CONTROL.formatInstanceName(serviceInstance); meterEntity.layer = layer; return meterEntity; } /** * Create an endpoint level meter entity. */ public static MeterEntity newEndpoint(String serviceName, String endpointName, Layer layer) { final MeterEntity meterEntity = new MeterEntity(); meterEntity.scopeType = ScopeType.ENDPOINT; meterEntity.serviceName = NAMING_CONTROL.formatServiceName(serviceName); meterEntity.endpointName = NAMING_CONTROL.formatEndpointName(serviceName, endpointName); meterEntity.layer = layer; return meterEntity; } public static MeterEntity newServiceRelation(String sourceServiceName, String destServiceName, DetectPoint detectPoint, Layer layer) { final MeterEntity meterEntity = new MeterEntity(); meterEntity.scopeType = ScopeType.SERVICE_RELATION; meterEntity.sourceServiceName = NAMING_CONTROL.formatServiceName(sourceServiceName); meterEntity.destServiceName = NAMING_CONTROL.formatServiceName(destServiceName); meterEntity.detectPoint = detectPoint; meterEntity.layer = layer; return meterEntity; } }
1,937
985
<filename>metamorphosis-integration-test/src/test/java/com/taobao/meta/test/spring/SrpingAPITest.java package com.taobao.meta.test.spring; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.taobao.meta.test.BaseMetaTest; import com.taobao.metamorphosis.client.extension.spring.MessageBuilder; import com.taobao.metamorphosis.client.extension.spring.MetaqTemplate; import com.taobao.metamorphosis.client.producer.SendResult; public class SrpingAPITest extends BaseMetaTest { @Test(timeout = 60000) public void sendConsume() throws Exception { this.createProducer(); ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); // use template to send messages. final String topic = "meta-test"; MetaqTemplate template = (MetaqTemplate) context.getBean("metaqTemplate"); int count = 100; for (int i = 0; i < count; i++) { SendResult result = template.send(MessageBuilder.withTopic(topic).withBody(new Trade(i, "test", i, "test"))); assertTrue(result.isSuccess()); } TradeMessageListener listener = (TradeMessageListener) context.getBean("messageListener"); while (listener.counter.get() != count) { Thread.sleep(100); } assertEquals(listener.counter.get(), count); } }
574
634
<gh_stars>100-1000 /* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.remote; import consulo.util.dataholder.Key; import com.intellij.openapi.util.Pair; import consulo.util.dataholder.UserDataHolderBase; import com.intellij.remote.ext.CredentialsCase; import com.intellij.remote.ext.CredentialsManager; import com.intellij.remote.ext.RemoteCredentialsHandler; import com.intellij.remote.ext.UnknownCredentialsHolder; import org.jdom.Element; import javax.annotation.Nonnull; /** * @author traff */ // TODO: (next) rename to 'RemoteSdkDataDelegate' ? public class RemoteConnectionCredentialsWrapper { private UserDataHolderBase myCredentialsTypeHolder = new UserDataHolderBase(); public <C> void setCredentials(Key<C> key, C credentials) { myCredentialsTypeHolder = new UserDataHolderBase(); myCredentialsTypeHolder.putUserData(key, credentials); } public Object getConnectionKey() { return getCredentials(); } public void save(final Element rootElement) { getTypeHandler().save(rootElement); } public static IllegalStateException unknownConnectionType() { return new IllegalStateException("Unknown connection type"); //TODO } public void copyTo(final RemoteConnectionCredentialsWrapper copy) { copy.myCredentialsTypeHolder = new UserDataHolderBase(); Pair<Object, CredentialsType> credentialsAndProvider = getCredentialsAndType(); credentialsAndProvider.getSecond().putCredentials(copy.myCredentialsTypeHolder, credentialsAndProvider.getFirst()); } @Nonnull public String getId() { return getTypeHandler().getId(); } public RemoteCredentialsHandler getTypeHandler() { Pair<Object, CredentialsType> credentialsAndType = getCredentialsAndType(); return credentialsAndType.getSecond().getHandler(credentialsAndType.getFirst()); } public CredentialsType getRemoteConnectionType() { return getCredentialsAndType().getSecond(); } public Object getCredentials() { return getCredentialsAndType().getFirst(); } private Pair<Object, CredentialsType> getCredentialsAndType() { for (CredentialsType type : CredentialsManager.getInstance().getAllTypes()) { Object credentials = type.getCredentials(myCredentialsTypeHolder); if (credentials != null) { return Pair.create(credentials, type); } } final UnknownCredentialsHolder credentials = CredentialsType.UNKNOWN.getCredentials(myCredentialsTypeHolder); if (credentials != null) return Pair.create(credentials, CredentialsType.UNKNOWN); throw unknownConnectionType(); } public void switchType(CredentialsCase... cases) { Pair<Object, CredentialsType> credentialsAndType = getCredentialsAndType(); CredentialsType type = credentialsAndType.getSecond(); for (CredentialsCase credentialsCase : cases) { if (credentialsCase.getType() == type) { credentialsCase.process(credentialsAndType.getFirst()); return; } } } @Override public boolean equals(Object obj) { if (obj instanceof RemoteConnectionCredentialsWrapper) { RemoteConnectionCredentialsWrapper w = (RemoteConnectionCredentialsWrapper)obj; try { Object credentials = getCredentials(); Object counterCredentials = w.getCredentials(); return credentials.equals(counterCredentials); } catch (IllegalStateException e) { return false; } } return false; } public String getPresentableDetails(final String interpreterPath) { return getTypeHandler().getPresentableDetails(interpreterPath); } }
1,320
8,772
<filename>support/cas-server-support-acme/src/test/java/org/apereo/cas/acme/AcmeChallengeRepositoryTests.java<gh_stars>1000+ package org.apereo.cas.acme; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; /** * This is {@link AcmeChallengeRepositoryTests}. * * @author <NAME> * @since 6.4.0 */ @Tag("Web") public class AcmeChallengeRepositoryTests extends BaseAcmeTests { @Test public void verifyOperation() throws Exception { acmeChallengeRepository.add("token", "challenge"); assertNotNull(acmeChallengeRepository.get("token")); Thread.sleep(3000); assertNull(acmeChallengeRepository.get("token")); } }
283
1,939
<filename>src/backend/codecc/core/task/biz-task/src/main/java/com/tencent/bk/codecc/task/dao/mongorepository/GongfengTriggerParamRepository.java<gh_stars>1000+ package com.tencent.bk.codecc.task.dao.mongorepository; import com.tencent.bk.codecc.task.model.GongFengTriggerParamEntity; import org.bson.types.ObjectId; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.stereotype.Repository; @Repository public interface GongfengTriggerParamRepository extends MongoRepository<GongFengTriggerParamEntity, ObjectId> { GongFengTriggerParamEntity findByGongfengId(Integer gongfengId); }
220
7,794
#ifndef SASS_TYPES_NULL_H #define SASS_TYPES_NULL_H #include <nan.h> #include "value.h" namespace SassTypes { class Null : public SassTypes::Value { public: static Null& get_singleton(); static v8::Local<v8::Function> get_constructor(); Sass_Value* get_sass_value(); v8::Local<v8::Object> get_js_object(); static NAN_METHOD(New); private: Null(); Nan::Persistent<v8::Object> js_object; static Nan::Persistent<v8::Function> constructor; static bool constructor_locked; }; } #endif
233
1,593
<reponame>starxiang/heif /* This file is part of Nokia HEIF library * * Copyright (c) 2015-2021 Nokia Corporation and/or its subsidiary(-ies). All rights reserved. * * Contact: <EMAIL> * * This software, including documentation, is protected by copyright controlled by Nokia Corporation and/ or its * subsidiaries. All rights are reserved. * * Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior * written consent of Nokia. */ #ifndef PIXELINFORMATIONPROPERTY_HPP #define PIXELINFORMATIONPROPERTY_HPP #include "customallocator.hpp" #include "fullbox.hpp" namespace ISOBMFF { class BitStream; } /** The PixelInformationProperty 'pixi' describes the number and bit depth of colour components of the associated image. */ class PixelInformationProperty : public FullBox { public: PixelInformationProperty(); ~PixelInformationProperty() override = default; /** * Get values of bits per channel fields of the property. Length of the array is number of channels. * @return Bits per channel field values of the property. */ const Vector<std::uint8_t>& getBitsPerChannels() const; /** * Set values of bits per channel fields of the property. Length of the array will bee the number of channels. * @param bitsPerChannel Bits per channel field values of the property. */ void setBitsPerChannels(const Vector<std::uint8_t>& bitsPerChannel); /** Write box/property to ISOBMFF::BitStream. * @see Box::writeBox() */ void writeBox(ISOBMFF::BitStream& output) const override; /** Parse box/property from ISOBMFF::BitStream. * @see Box::parseBox() */ void parseBox(ISOBMFF::BitStream& input) override; private: Vector<std::uint8_t> mBitsPerChannel; ///< Bits per each channel. }; #endif
570
402
<filename>Tests/ML/utils/test_hdf5_util.py<gh_stars>100-1000 # ------------------------------------------------------------------------------------------ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. # ------------------------------------------------------------------------------------------ from datetime import datetime from pathlib import Path from typing import Tuple, Union import numpy as np import pytest from InnerEye.Common.fixed_paths_for_tests import full_ml_test_data_path from InnerEye.ML.utils.hdf5_util import HDF5Object from InnerEye.ML.utils.io_util import is_hdf5_file_path n_classes = 11 root = full_ml_test_data_path() test_data = [ (root / "hdf5_data" / "patient_hdf5s" / "4be9beed-5861-fdd2-72c2-8dd89aadc1ef.h5", '0001', datetime(2018, 7, 10).isoformat(), np.array([4, 5, 7])), (root / "hdf5_data" / "patient_hdf5s" / "6ceacaf8-abd2-ffec-2ade-d52afd6dd1be.h5", '0011', datetime(2011, 7, 14).isoformat(), np.array([4, 5, 7])), ] test_data_single_patient_multiple_scans = [ ([ root / "hdf5_data" / "patient_hdf5s" / "d316cfe5-e62a-3c0e-afda-72c3cf5ea2d8.h5", root / "hdf5_data" / "patient_hdf5s" / "b3200426-1a58-bfea-4aba-cbacbe66ea5e.h5"], '1101', [ datetime(2001, 12, 2).isoformat(), datetime(2003, 5, 5).isoformat()], [ np.array([4, 5, 7]), np.array([4, 5, 7])]) ] @pytest.mark.parametrize("load_segmentation", [True, False]) @pytest.mark.parametrize("hdf5_path, patient_id, acquisition_date, array_shape", test_data) def test_load_hdf5_from_file(hdf5_path: Union[str, Path], patient_id: str, acquisition_date: datetime, array_shape: np.ndarray, load_segmentation: bool) -> None: """ Assert that the HDF5 object is loaded with the expected attributes. """ hdf5_path = Path(hdf5_path) act_hdf5 = HDF5Object.from_file(hdf5_path, load_segmentation=load_segmentation) assert act_hdf5.patient_id == patient_id assert act_hdf5.acquisition_date.isoformat() == acquisition_date # type: ignore assert np.array_equal(act_hdf5.volume.shape, array_shape) if load_segmentation: assert act_hdf5.segmentation is not None assert np.array_equal(act_hdf5.segmentation.shape, array_shape) else: assert act_hdf5.segmentation is None @pytest.mark.parametrize("correctly_formatted, expected", [("2012-06-07T00:00:00", datetime(2012, 6, 7)), ("1900-01-30T10:09:08", datetime(1900, 1, 30, 10, 9, 8)), ("1701-08-15T23:59:59", datetime(1701, 8, 15, 23, 59, 59)) ]) def test_parse_acquisition_date_correctly_formatted(correctly_formatted: str, expected: datetime) -> None: parsed = HDF5Object.parse_acquisition_date(correctly_formatted) assert parsed == expected @pytest.mark.parametrize("badly_formatted", ["2012-30-05T00:00:00", "1999-02-28", "1701-08-15T25:59:59"]) def test_parse_acquisition_date_badly_formatted(badly_formatted: str) -> None: parsed = HDF5Object.parse_acquisition_date(badly_formatted) assert parsed is None @pytest.mark.parametrize("input", [("foo.txt", False), ("foo.gz", False), ("foo.h5.gz", True), ("foo.h5.sz", True), ("foo.h5", True), ("foo.hdf5", True), ]) def test_is_hdf5_file(input: Tuple[str, bool]) -> None: file, expected = input assert is_hdf5_file_path(file) == expected assert is_hdf5_file_path(Path(file)) == expected
1,923
764
{ "symbol": "bzc", "address": "0xE7cEfbE857659690fd0d288752A81C7238A00756", "overview": { "en": "bzc is a new game platform based on blockchain technology. It perfectly displays the technical attributes of the blockchain, and displays the blockchain game in front of the public with a new form, starting the combination of blockchain and game.", "zh": "bzc是基于区块链技术发展出的全新游戏平台,它将区块链技术属性完美的展现出来,用全新的形态把区块链游戏展现在大众面前,开始区块链与游戏的结合。" }, "email": "<EMAIL>", "website": "http://www.bzcgame.xyz/", "whitepaper": "http://www.bzcgame.xyz/qfy-content/uploads/2019/04/4a8ef31bc6758a1184849f8576288fc5.pdf", "state": "NORMAL", "published_on": "2019-04-19", "links": { "twitter": "https://twitter.com/bzcchain1" } }
421
1,521
<gh_stars>1000+ package com.dexafree.materialList.card; import android.content.Context; import android.support.annotation.NonNull; import android.view.View; public abstract class Action { private final Context mContext; private CardProvider mProvider; public Action(@NonNull final Context context) { mContext = context; } void setProvider(CardProvider provider) { mProvider = provider; } protected Context getContext() { return mContext; } protected void notifyActionChanged() { if(mProvider != null) { // Only notify if something changed at runtime mProvider.notifyDataSetChanged(); } } protected abstract void onRender(@NonNull final View view, @NonNull final Card card); }
277
476
<gh_stars>100-1000 void *bug_list; void setup_bug_list() { setvbuf(stdin, 0LL, 2, 0LL); setvbuf(stdout, 0LL, 2, 0LL); alarm(0xB4u); bug_list = malloc(40uLL); bzero(bug_list, 0x28uLL); } int show_menu() { puts("1. Create Bug"); puts("2. Edit Bug (N/A)"); puts("3. Delete Bug"); puts("4. Show Bug"); puts("5. Exit"); return printf("> "); } int show_banner() { return puts("WELCOME TO ASIS VULNERABILITY DATABASE"); } int64_t read_string(int64_t a1, unsigned int a2) { unsigned int i; // [rsp+1Ch] [rbp-4h] for ( i = 0; i < a2 && read(0, (void *)(i + a1), 1uLL) == 1; ++i ) { if ( *(char *)(i + a1) == '\n' ) { *(char *)(i + a1) = 0; return i; } } return i; } int64_t read_int() { char s; // [rsp+10h] [rbp-20h] uint64_t v2; // [rsp+28h] [rbp-8h] bzero(&s, 0x10uLL); read_string((int64_t)&s, 0x10u); return strtoll(&s, 0LL, 10); } signed int64_t check_capacity() { unsigned int i; // [rsp+0h] [rbp-4h] for ( i = 0; i <= 4; ++i ) { if ( !*((int64_t *)bug_list + i) ) return i; } return 4294967295LL; } int create_bug() { void *title; // ST20_8 void *desc; // ST28_8 unsigned int idx; // [rsp+4h] [rbp-2Ch] unsigned int size; // [rsp+10h] [rbp-20h] int *new_bug; // [rsp+18h] [rbp-18h] idx = check_capacity(); if ( idx == -1 ) return puts("bug list is full, sorry."); puts("Creating Bug:"); new_bug = malloc(32uLL); printf("Enter year: "); *(_WORD *)new_bug = read_int(); printf("Enter id: "); new_bug[1] = read_int(); printf("Enter title (Up to 64 chars): "); title = malloc(64uLL); bzero(title, 64uLL); read_string((int64_t)title, 63u); *((int64_t *)new_bug + 1) = title; printf("Enter description size: ", 63LL); size = read_int(); if ( size && size <= 255 ) { desc = malloc(size); bzero(desc, size); printf("Enter description: ", size); read_string((int64_t)desc, size - 1); *((int64_t *)new_bug + 2) = desc; } else { puts("Invalid description size."); } printf("Enter Severity: (0: LOW, 1: MEDIUM, 2: HIGH, 3: CRITICAL): "); new_bug[6] = read_int(); *((int64_t *)bug_list + idx) = new_bug; return printf("New bug created at index=%u.\n", idx); } int edit_bug() { return puts("Not implemented yet."); } int free_bug(unsigned int index) { int64_t *v1; // rax if ( *((int64_t *)bug_list + index) ) { free(*(void **)(*((int64_t *)bug_list + index) + 8LL)); free(*(void **)(*((int64_t *)bug_list + index) + 16LL)); free(*((void **)bug_list + index)); v1 = (char *)bug_list + 8 * index; *v1 = 0LL; } else { LODWORD(v1) = puts("Wrong idx."); } return (signed int)v1; } int delete_bug() { int result; // eax unsigned int index; // [rsp+Ch] [rbp-4h] printf("Enter bug index: "); index = read_int(); if ( index <= 5 ) result = free_bug(index); else result = puts("Wrong idx."); return result; } int show_bug() { unsigned int v1; // eax unsigned int v2; // [rsp+Ch] [rbp-4h] printf("Enter bug index: "); v2 = read_int(); if ( v2 > 5 ) return puts("Wrong idx."); if ( !*((int64_t *)bug_list + v2) ) return puts("Wrong idx."); puts("-------------------------"); printf("idx: %u\n", v2); printf("ID: ASV-%u-%u\n", **((unsigned __int16 **)bug_list + v2), *(unsigned int *)(*((int64_t *)bug_list + v2) + 4LL)); printf("Severity: "); v1 = *(int *)(*((int64_t *)bug_list + v2) + 24LL); if ( v1 == 1 ) { puts("Medium"); } else if ( v1 < 1 ) { puts("Low"); } else if ( v1 == 2 ) { puts("High"); } else if ( v1 == 3 ) { puts("Critical"); } else { puts("Unknown"); } printf("title: %s\n", *(int64_t *)(*((int64_t *)bug_list + v2) + 8LL)); if ( *(int64_t *)(*((int64_t *)bug_list + v2) + 16LL) ) printf("Description: %s\n", *(int64_t *)(*((int64_t *)bug_list + v2) + 16LL)); return puts("-------------------------"); } int main_loop() { while ( 1 ) { show_menu(); switch ( (unsigned int)read_int() ) { case 1u: create_bug(); break; case 2u: edit_bug(); break; case 3u: delete_bug(); break; case 4u: show_bug(); break; case 5u: return puts("Thank you for choosing ASV DB"); default: puts("Unknown menu."); break; } } } int64_t main(int64_t a1, char **a2, char **a3) { setup_bug_list(); show_banner(); main_loop(); return 0LL; }
2,527
1,874
<gh_stars>1000+ # Copyright 2016 IBM 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. # import mock from pypowervm.wrappers import managed_system as pvm_ms from nova import test from nova.virt.powervm import host as pvm_host class TestPowerVMHost(test.NoDBTestCase): def test_host_resources(self): # Create objects to test with ms_wrapper = mock.create_autospec(pvm_ms.System, spec_set=True) asio = mock.create_autospec(pvm_ms.ASIOConfig, spec_set=True) ms_wrapper.configure_mock( proc_units_configurable=500, proc_units_avail=500, memory_configurable=5242880, memory_free=5242752, memory_region_size='big', asio_config=asio) self.flags(host='the_hostname') # Run the actual test stats = pvm_host.build_host_resource_from_ms(ms_wrapper) self.assertIsNotNone(stats) # Check for the presence of fields fields = (('vcpus', 500), ('vcpus_used', 0), ('memory_mb', 5242880), ('memory_mb_used', 128), 'hypervisor_type', 'hypervisor_version', ('hypervisor_hostname', 'the_hostname'), 'cpu_info', 'supported_instances', 'stats') for fld in fields: if isinstance(fld, tuple): value = stats.get(fld[0], None) self.assertEqual(value, fld[1]) else: value = stats.get(fld, None) self.assertIsNotNone(value) # Check for individual stats hstats = (('proc_units', '500.00'), ('proc_units_used', '0.00')) for stat in hstats: if isinstance(stat, tuple): value = stats['stats'].get(stat[0], None) self.assertEqual(value, stat[1]) else: value = stats['stats'].get(stat, None) self.assertIsNotNone(value)
1,102
1,289
<filename>radiant-player-mac/Styles/LightStyle.h /* * LightStyle.h * * Created by <NAME>. * * Subject to terms and conditions in LICENSE.md. * */ #import "ApplicationStyle.h" @interface LightStyle : ApplicationStyle @end
77
380
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.conveyor.async; import java.io.Closeable; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; import lombok.NonNull; public interface AsyncSqsClient extends Closeable { CompletableFuture<Void> add(@NonNull final String message, @NonNull final String queueName); CompletableFuture<Void> add( @NonNull final String message, @NonNull final String queueName, int delaySeconds); CompletableFuture<Boolean> consume( @NonNull final Consumer<String> consumer, @NonNull final String queueName); CompletableFuture<Boolean> consume(AsyncConsumer<String> consumer, String queueName); }
227
431
<reponame>ripdajacker/enunciate<gh_stars>100-1000 /* * © 2019 by Intellectual Reserve, Inc. All rights reserved. */ package org.springframework.samples.petclinic.model; import java.util.List; public class ResponseData { private List<?> rows; public List<?> getRows() { return rows; } public void setRows(List<?> rows) { this.rows = rows; } }
130
14,668
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/web_dialogs/web_dialog_ui.h" #include "content/public/common/bindings_policy.h" #include "content/public/test/test_web_ui.h" #include "testing/gtest/include/gtest/gtest.h" namespace ui { TEST(WebDialogUITest, NoBindingsSetForWebDialogUI) { content::TestWebUI test_web_ui; EXPECT_EQ(0, test_web_ui.GetBindings()); WebDialogUI web_dialog_ui(&test_web_ui); EXPECT_EQ(0, test_web_ui.GetBindings()); } TEST(MojoWebDialogUITest, ChromeSendAndMojoBindingsForMojoWebDialogUI) { content::TestWebUI test_web_ui; EXPECT_EQ(0, test_web_ui.GetBindings()); MojoWebDialogUI web_dialog_ui(&test_web_ui); // MojoWebDialogUIs rely on both Mojo and chrome.send(). EXPECT_EQ( content::BINDINGS_POLICY_MOJO_WEB_UI | content::BINDINGS_POLICY_WEB_UI, test_web_ui.GetBindings()); } } // namespace ui
391
389
// // VSSyncNoAccountHeaderView.h // Vesper // // Created by <NAME> on 4/25/14. // Copyright (c) 2014 Q Branch LLC. All rights reserved. // @interface VSSyncNoAccountHeaderView : UIView //- (void)updateLabelWidth:(CGFloat)superviewWidth; @end
93
1,604
package org.bouncycastle.mail.smime.examples; import java.security.KeyStore; import java.security.PrivateKey; import java.security.cert.X509Certificate; import java.util.Properties; import javax.mail.Session; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import org.bouncycastle.cms.RecipientId; import org.bouncycastle.cms.RecipientInformation; import org.bouncycastle.cms.RecipientInformationStore; import org.bouncycastle.cms.jcajce.JceKeyTransEnvelopedRecipient; import org.bouncycastle.cms.jcajce.JceKeyTransRecipientId; import org.bouncycastle.mail.smime.SMIMEEnvelopedParser; import org.bouncycastle.mail.smime.SMIMEUtil; import org.bouncycastle.mail.smime.util.SharedFileInputStream; /** * a simple example that reads an encrypted email using the large file model. * <p> * The key store can be created using the class in * org.bouncycastle.jce.examples.PKCS12Example - the program expects only one * key to be present. */ public class ReadLargeEncryptedMail { public static void main( String args[]) throws Exception { if (args.length != 3) { System.err.println("usage: ReadLargeEncryptedMail pkcs12Keystore password outputFile"); System.exit(0); } // // Open the key store // KeyStore ks = KeyStore.getInstance("PKCS12", "BC"); String keyAlias = ExampleUtils.findKeyAlias(ks, args[0], args[1].toCharArray()); // // find the certificate for the private key and generate a // suitable recipient identifier. // X509Certificate cert = (X509Certificate)ks.getCertificate(keyAlias); RecipientId recId = new JceKeyTransRecipientId(cert); // // Get a Session object with the default properties. // Properties props = System.getProperties(); Session session = Session.getDefaultInstance(props, null); MimeMessage msg = new MimeMessage(session, new SharedFileInputStream("encrypted.message")); SMIMEEnvelopedParser m = new SMIMEEnvelopedParser(msg); RecipientInformationStore recipients = m.getRecipientInfos(); RecipientInformation recipient = recipients.get(recId); MimeBodyPart res = SMIMEUtil.toMimeBodyPart(recipient.getContentStream(new JceKeyTransEnvelopedRecipient((PrivateKey)ks.getKey(keyAlias, null)).setProvider("BC"))); ExampleUtils.dumpContent(res, args[2]); } }
961
852
<filename>SimCalorimetry/HGCalSimAlgos/src/HGCalSciNoiseMap.cc #include "SimCalorimetry/HGCalSimAlgos/interface/HGCalSciNoiseMap.h" #include "FWCore/ParameterSet/interface/FileInPath.h" #include <fstream> // HGCalSciNoiseMap::HGCalSciNoiseMap() : refEdge_(3.) {} // void HGCalSciNoiseMap::setSipmMap(const std::string& fullpath) { sipmMap_ = readSipmPars(fullpath); } // std::unordered_map<int, float> HGCalSciNoiseMap::readSipmPars(const std::string& fullpath) { std::unordered_map<int, float> result; //no file means default sipm size if (fullpath.empty()) return result; edm::FileInPath fp(fullpath); std::ifstream infile(fp.fullPath()); if (!infile.is_open()) { throw cms::Exception("FileNotFound") << "Unable to open '" << fullpath << "'" << std::endl; } std::string line; while (getline(infile, line)) { int layer; float boundary; //space-separated std::stringstream linestream(line); linestream >> layer >> boundary; result[layer] = boundary; } return result; } // std::pair<double, double> HGCalSciNoiseMap::scaleByDose(const HGCScintillatorDetId& cellId, const double radius) { if (getDoseMap().empty()) return std::make_pair(1., 0.); //formula is: A = A0 * exp( -D^0.65 / 199.6) //where A0 is the response of the undamaged detector, D is the dose int layer = cellId.layer(); double cellDose = getDoseValue(DetId::HGCalHSc, layer, radius); //in kRad constexpr double expofactor = 1. / 199.6; const double dosespower = 0.65; double scaleFactor = std::exp(-std::pow(cellDose, dosespower) * expofactor); //formula is: N = 2.18 * sqrt(F * A / 2e13) //where F is the fluence and A is the SiPM area double cellFluence = getFluenceValue(DetId::HGCalHSc, layer, radius); //in 1-Mev-equivalent neutrons per cm2 constexpr double fluencefactor = 2. / (2 * 1e13); //SiPM area = 2mm^2 const double normfactor = 2.18; double noise = normfactor * sqrt(cellFluence * fluencefactor); return std::make_pair(scaleFactor, noise); } double HGCalSciNoiseMap::scaleByTileArea(const HGCScintillatorDetId& cellId, const double radius) { double edge; if (cellId.type() == 0) { constexpr double factor = 2 * M_PI * 1. / 360.; edge = radius * factor; //1 degree } else { constexpr double factor = 2 * M_PI * 1. / 288.; edge = radius * factor; //1.25 degrees } double scaleFactor = refEdge_ / edge; //assume reference 3cm of edge return scaleFactor; } double HGCalSciNoiseMap::scaleBySipmArea(const HGCScintillatorDetId& cellId, const double radius) { if (sipmMap_.empty()) return 1.; int layer = cellId.layer(); if (radius < sipmMap_[layer]) return 2.; else return 1.; }
1,025
1,144
<filename>misc/services/camel/de-metas-camel-edi/src/main/java/de/metas/edi/esb/invoicexport/compudata/Cctop119V.java /* * #%L * de-metas-edi-esb-camel * %% * Copyright (C) 2020 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ package de.metas.edi.esb.invoicexport.compudata; import java.io.Serializable; public class Cctop119V implements Serializable { /** * */ private static final long serialVersionUID = 1650345883526756636L; private String cbPartnerLocationID; private String cInvoiceID; private String mInOutID; private String address1; private String address2; private String city; private String countryCode; private String eancomLocationtype; private String fax; private String gln; private String name; private String name2; private String phone; private String postal; private String value; private String vaTaxID; private String referenceNo; public final String getCbPartnerLocationID() { return cbPartnerLocationID; } public final void setCbPartnerLocationID(final String cbPartnerLocationID) { this.cbPartnerLocationID = cbPartnerLocationID; } public final String getcInvoiceID() { return cInvoiceID; } public final void setcInvoiceID(final String cInvoiceID) { this.cInvoiceID = cInvoiceID; } public final String getmInOutID() { return mInOutID; } public final void setmInOutID(final String mInOutID) { this.mInOutID = mInOutID; } public String getAddress1() { return address1; } public void setAddress1(final String address1) { this.address1 = address1; } public String getAddress2() { return address2; } public void setAddress2(final String address2) { this.address2 = address2; } public String getCity() { return city; } public void setCity(final String city) { this.city = city; } public String getCountryCode() { return countryCode; } public void setCountryCode(final String countryCode) { this.countryCode = countryCode; } public String getEancomLocationtype() { return eancomLocationtype; } public void setEancomLocationtype(final String eancomLocationtype) { this.eancomLocationtype = eancomLocationtype; } public String getFax() { return fax; } public void setFax(final String fax) { this.fax = fax; } public String getGln() { return gln; } public void setGln(final String gln) { this.gln = gln; } public String getName() { return name; } public void setName(final String name) { this.name = name; } public String getName2() { return name2; } public void setName2(final String name2) { this.name2 = name2; } public String getPhone() { return phone; } public void setPhone(final String phone) { this.phone = phone; } public String getPostal() { return postal; } public void setPostal(final String postal) { this.postal = postal; } public String getValue() { return value; } public void setValue(final String value) { this.value = value; } public String getVaTaxID() { return vaTaxID; } public void setVaTaxID(final String vaTaxID) { this.vaTaxID = vaTaxID; } public String getReferenceNo() { return referenceNo; } public void setReferenceNo(final String referenceNo) { this.referenceNo = referenceNo; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (address1 == null ? 0 : address1.hashCode()); result = prime * result + (address2 == null ? 0 : address2.hashCode()); result = prime * result + (cInvoiceID == null ? 0 : cInvoiceID.hashCode()); result = prime * result + (cbPartnerLocationID == null ? 0 : cbPartnerLocationID.hashCode()); result = prime * result + (city == null ? 0 : city.hashCode()); result = prime * result + (countryCode == null ? 0 : countryCode.hashCode()); result = prime * result + (eancomLocationtype == null ? 0 : eancomLocationtype.hashCode()); result = prime * result + (fax == null ? 0 : fax.hashCode()); result = prime * result + (gln == null ? 0 : gln.hashCode()); result = prime * result + (mInOutID == null ? 0 : mInOutID.hashCode()); result = prime * result + (name == null ? 0 : name.hashCode()); result = prime * result + (name2 == null ? 0 : name2.hashCode()); result = prime * result + (phone == null ? 0 : phone.hashCode()); result = prime * result + (postal == null ? 0 : postal.hashCode()); result = prime * result + (referenceNo == null ? 0 : referenceNo.hashCode()); result = prime * result + (vaTaxID == null ? 0 : vaTaxID.hashCode()); result = prime * result + (value == null ? 0 : value.hashCode()); return result; } @Override public boolean equals(final Object obj) // NOPMD by al { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Cctop119V other = (Cctop119V)obj; if (address1 == null) { if (other.address1 != null) { return false; } } else if (!address1.equals(other.address1)) { return false; } if (address2 == null) { if (other.address2 != null) { return false; } } else if (!address2.equals(other.address2)) { return false; } if (cInvoiceID == null) { if (other.cInvoiceID != null) { return false; } } else if (!cInvoiceID.equals(other.cInvoiceID)) { return false; } if (cbPartnerLocationID == null) { if (other.cbPartnerLocationID != null) { return false; } } else if (!cbPartnerLocationID.equals(other.cbPartnerLocationID)) { return false; } if (city == null) { if (other.city != null) { return false; } } else if (!city.equals(other.city)) { return false; } if (countryCode == null) { if (other.countryCode != null) { return false; } } else if (!countryCode.equals(other.countryCode)) { return false; } if (eancomLocationtype == null) { if (other.eancomLocationtype != null) { return false; } } else if (!eancomLocationtype.equals(other.eancomLocationtype)) { return false; } if (fax == null) { if (other.fax != null) { return false; } } else if (!fax.equals(other.fax)) { return false; } if (gln == null) { if (other.gln != null) { return false; } } else if (!gln.equals(other.gln)) { return false; } if (mInOutID == null) { if (other.mInOutID != null) { return false; } } else if (!mInOutID.equals(other.mInOutID)) { return false; } if (name == null) { if (other.name != null) { return false; } } else if (!name.equals(other.name)) { return false; } if (name2 == null) { if (other.name2 != null) { return false; } } else if (!name2.equals(other.name2)) { return false; } if (phone == null) { if (other.phone != null) { return false; } } else if (!phone.equals(other.phone)) { return false; } if (postal == null) { if (other.postal != null) { return false; } } else if (!postal.equals(other.postal)) { return false; } if (referenceNo == null) { if (other.referenceNo != null) { return false; } } else if (!referenceNo.equals(other.referenceNo)) { return false; } if (vaTaxID == null) { if (other.vaTaxID != null) { return false; } } else if (!vaTaxID.equals(other.vaTaxID)) { return false; } if (value == null) { if (other.value != null) { return false; } } else if (!value.equals(other.value)) { return false; } return true; } @Override public String toString() { return "Cctop119V [cbPartnerLocationID=" + cbPartnerLocationID + ", cInvoiceID=" + cInvoiceID + ", mInOutID=" + mInOutID + ", address1=" + address1 + ", address2=" + address2 + ", city=" + city + ", countryCode=" + countryCode + ", eancomLocationtype=" + eancomLocationtype + ", fax=" + fax + ", gln=" + gln + ", name=" + name + ", name2=" + name2 + ", phone=" + phone + ", postal=" + postal + ", value=" + value + ", vaTaxID=" + vaTaxID + ", referenceNo=" + referenceNo + "]"; } }
3,547
326
// Boost.Geometry (aka GGL, Generic Geometry Library) // Copyright (c) 2007-2015 <NAME>, Amsterdam, the Netherlands. // Copyright (c) 2008-2015 <NAME>, Paris, France. // Copyright (c) 2009-2015 <NAME>, London, UK. // Copyright (c) 2014-2015 <NAME>, Grenoble, France. // This file was modified by Oracle on 2015, 2016, 2017, 2018. // Modifications copyright (c) 2015-2018, Oracle and/or its affiliates. // Contributed and/or modified by <NAME>, on behalf of Oracle // Contributed and/or modified by <NAME>, on behalf of Oracle // Contributed and/or modified by <NAME>, on behalf of Oracle // 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) #ifndef BOOST_GEOMETRY_STRATEGY_GEOGRAPHIC_EXPAND_SEGMENT_HPP #define BOOST_GEOMETRY_STRATEGY_GEOGRAPHIC_EXPAND_SEGMENT_HPP #include <cstddef> #include <functional> #include <boost/geometry/core/access.hpp> #include <boost/geometry/core/tags.hpp> #include <boost/geometry/algorithms/detail/envelope/box.hpp> #include <boost/geometry/algorithms/detail/envelope/range_of_boxes.hpp> #include <boost/geometry/algorithms/detail/envelope/segment.hpp> #include <boost/geometry/srs/spheroid.hpp> #include <boost/geometry/strategy/expand.hpp> #include <boost/geometry/strategy/geographic/envelope_segment.hpp> #include <boost/geometry/strategies/geographic/parameters.hpp> #include <boost/geometry/strategy/spherical/expand_segment.hpp> namespace boost { namespace geometry { namespace strategy { namespace expand { template < typename FormulaPolicy = strategy::andoyer, typename Spheroid = geometry::srs::spheroid<double>, typename CalculationType = void > class geographic_segment { public: inline geographic_segment() : m_envelope_strategy() {} explicit inline geographic_segment(Spheroid const& spheroid) : m_envelope_strategy(spheroid) {} template <typename Box, typename Segment> inline void apply(Box& box, Segment const& segment) const { detail::segment_on_spheroid::apply(box, segment, m_envelope_strategy); } Spheroid model() const { return m_envelope_strategy.model(); } private: strategy::envelope::geographic_segment < FormulaPolicy, Spheroid, CalculationType > m_envelope_strategy; }; #ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS namespace services { template <typename CalculationType> struct default_strategy<segment_tag, geographic_tag, CalculationType> { typedef geographic_segment < strategy::andoyer, geometry::srs::spheroid<double>, CalculationType > type; }; } // namespace services #endif // DOXYGEN_NO_STRATEGY_SPECIALIZATIONS }} // namespace strategy::expand }} // namespace boost::geometry #endif // BOOST_GEOMETRY_STRATEGY_GEOGRAPHIC_EXPAND_SEGMENT_HPP
1,101
5,813
/* * 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.druid.segment.vector; /** * Common interface for vectorized column selectors, matchers, etc, where callers are given the ability to inspect * current and maximum vector sizes. */ public interface VectorSizeInspector { /** * Returns the maximum vector size for this cursor. It will not change for the lifetime of this cursor, and is * generally used to allocate scratch arrays for later processing. Will always be greater than zero. */ int getMaxVectorSize(); /** * Returns the current vector size for this cursor. Will never be larger than the max size returned by * {@link #getMaxVectorSize()}. */ int getCurrentVectorSize(); }
376
879
package org.zstack.sdk; import org.zstack.sdk.ScsiLunInventory; public class AttachScsiLunToVmInstanceResult { public ScsiLunInventory inventory; public void setInventory(ScsiLunInventory inventory) { this.inventory = inventory; } public ScsiLunInventory getInventory() { return this.inventory; } }
132
8,240
#!/usr/bin/env python from sentimentanalyzer import app as application
18
2,380
<reponame>jagmeet787/Smack<gh_stars>1000+ /** * * Copyright 2019 <NAME>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jivesoftware.smack.util; import java.lang.reflect.InvocationTargetException; import java.security.Provider; import java.security.Security; import org.jxmpp.util.cache.LruCache; public class SecurityUtil { private static final LruCache<Class<? extends Provider>, Void> INSERTED_PROVIDERS_CACHE = new LruCache<>(8); public static void ensureProviderAtFirstPosition(Class<? extends Provider> providerClass) { if (INSERTED_PROVIDERS_CACHE.containsKey(providerClass)) { return; } Provider provider; try { provider = providerClass.getDeclaredConstructor().newInstance(); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { throw new IllegalArgumentException(e); } String providerName = provider.getName(); int installedPosition ; synchronized (Security.class) { Security.removeProvider(providerName); installedPosition = Security.insertProviderAt(provider, 1); } assert installedPosition == 1; INSERTED_PROVIDERS_CACHE.put(providerClass, null); } }
640
4,538
/* * Copyright (C) 2019-2020 Alibaba Group Holding Limited */ #include <stdio.h> #include <string.h> #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/time.h> #include <unistd.h> #include <fcntl.h> #include <lwip/netdb.h> #include <aos/debug.h> #include "linkkit/wrappers/wrappers_tcp.h" #define PLATFORM_LOG(format, ...) \ do { \ HAL_Printf("SOCK %u %s() | " format "\n", __LINE__, __FUNCTION__, \ ##__VA_ARGS__); \ } while (0); /* * mqtt does not call these functions, * but has been used in IoT libraries, * so implement empty functions and optimize footprint */ uintptr_t HAL_TCP_Establish(const char *host, uint16_t port) { aos_assert(0); return 0; } int HAL_TCP_Destroy(uintptr_t fd) { aos_assert(0); return 0; } int32_t HAL_TCP_Write(uintptr_t fd, const char *buf, uint32_t len, uint32_t timeout_ms) { aos_assert(0); return 0; } int32_t HAL_TCP_Read(uintptr_t fd, char *buf, uint32_t len, uint32_t timeout_ms) { aos_assert(0); return 0; }
637
2,087
""" pdftabextract setuptools based setup module """ from setuptools import setup setup( name='pdftabextract', version='0.4.0-dev', description='A set of tools for data mining (OCR-processed) PDFs', long_description="""This repository contains a set of tools written in Python 3 with the aim to extract tabular data from scanned and OCR-processed documents available as PDF files. Before these files can be processed they need to be converted to XML files in pdf2xml format using poppler utils. Further information and examples can be found in the github repository.""", url='https://github.com/WZBSocialScienceCenter/pdftabextract', author='<NAME>', author_email='<EMAIL>', license='Apache 2.0', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Science/Research', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Scientific/Engineering :: Information Analysis', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Utilities', ], keywords='datamining ocr pdf tabular data mining extract extraction', packages=['pdftabextract'], include_package_data=True, install_requires=['numpy', 'opencv-python', 'scipy'], extras_require = { 'pandas_dataframes': ['pandas'], } )
558
1,093
/* * Copyright 2002-2019 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.integration.config.annotation; import static org.assertj.core.api.Assertions.assertThat; import java.util.Collections; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springframework.integration.annotation.MessageEndpoint; import org.springframework.integration.annotation.Router; import org.springframework.integration.channel.DirectChannel; import org.springframework.integration.channel.QueueChannel; import org.springframework.integration.test.util.TestUtils; import org.springframework.integration.test.util.TestUtils.TestApplicationContext; import org.springframework.messaging.Message; import org.springframework.messaging.support.GenericMessage; /** * @author <NAME> * @author <NAME> */ public class RouterAnnotationPostProcessorTests { private final TestApplicationContext context = TestUtils.createTestApplicationContext(); private final DirectChannel inputChannel = new DirectChannel(); private final QueueChannel outputChannel = new QueueChannel(); private final DirectChannel routingChannel = new DirectChannel(); private final QueueChannel integerChannel = new QueueChannel(); private final QueueChannel stringChannel = new QueueChannel(); @Before public void init() { context.registerChannel("input", inputChannel); context.registerChannel("output", outputChannel); context.registerChannel("routingChannel", routingChannel); context.registerChannel("integerChannel", integerChannel); context.registerChannel("stringChannel", stringChannel); } @After public void tearDown() { this.context.close(); } @Test public void testRouter() { MessagingAnnotationPostProcessor postProcessor = new MessagingAnnotationPostProcessor(); postProcessor.setBeanFactory(context.getBeanFactory()); postProcessor.afterPropertiesSet(); postProcessor.afterSingletonsInstantiated(); TestRouter testRouter = new TestRouter(); postProcessor.postProcessAfterInitialization(testRouter, "test"); context.refresh(); inputChannel.send(new GenericMessage<>("foo")); Message<?> replyMessage = outputChannel.receive(0); assertThat(replyMessage.getPayload()).isEqualTo("foo"); context.stop(); } @Test public void testRouterWithListParam() { MessagingAnnotationPostProcessor postProcessor = new MessagingAnnotationPostProcessor(); postProcessor.setBeanFactory(context.getBeanFactory()); postProcessor.afterPropertiesSet(); postProcessor.afterSingletonsInstantiated(); TestRouter testRouter = new TestRouter(); postProcessor.postProcessAfterInitialization(testRouter, "test"); context.refresh(); routingChannel.send(new GenericMessage<>(Collections.singletonList("foo"))); Message<?> replyMessage = stringChannel.receive(0); assertThat(replyMessage.getPayload()).isEqualTo(Collections.singletonList("foo")); // The SpEL ReflectiveMethodExecutor does a conversion of a single value to a List routingChannel.send(new GenericMessage<>(2)); replyMessage = integerChannel.receive(0); assertThat(replyMessage.getPayload()).isEqualTo(2); context.stop(); } @MessageEndpoint public static class TestRouter { @Router(inputChannel = "input", defaultOutputChannel = "output") public String test(String s) { return null; } @Router(inputChannel = "routingChannel") public String route(List<?> payload) { if (payload.size() == 0) { return null; } if (payload.get(0) instanceof Integer) { return "integerChannel"; } else { return "stringChannel"; } } } }
1,247
1,350
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.datadog.implementation; import com.azure.core.management.SystemData; import com.azure.resourcemanager.datadog.fluent.models.DatadogAgreementResourceInner; import com.azure.resourcemanager.datadog.models.DatadogAgreementProperties; import com.azure.resourcemanager.datadog.models.DatadogAgreementResource; public final class DatadogAgreementResourceImpl implements DatadogAgreementResource { private DatadogAgreementResourceInner innerObject; private final com.azure.resourcemanager.datadog.MicrosoftDatadogManager serviceManager; DatadogAgreementResourceImpl( DatadogAgreementResourceInner innerObject, com.azure.resourcemanager.datadog.MicrosoftDatadogManager serviceManager) { this.innerObject = innerObject; this.serviceManager = serviceManager; } public String id() { return this.innerModel().id(); } public String name() { return this.innerModel().name(); } public String type() { return this.innerModel().type(); } public DatadogAgreementProperties properties() { return this.innerModel().properties(); } public SystemData systemData() { return this.innerModel().systemData(); } public DatadogAgreementResourceInner innerModel() { return this.innerObject; } private com.azure.resourcemanager.datadog.MicrosoftDatadogManager manager() { return this.serviceManager; } }
543
5,421
<gh_stars>1000+ # Copyright 2021, <NAME>, mailto:<EMAIL> # # Part of "Nuitka", an optimizing Python compiler that is compatible and # integrates with CPython, but also works on its own. # # 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. # """ C string encoding This contains the code to create string literals for C to represent the given values. """ import codecs import re def _identifierEncode(c): """Nuitka handler to encode unicode to ASCII identifiers for C compiler.""" return "$%02x$" % ord(c.object[c.end - 1]), c.end codecs.register_error("c_identifier", _identifierEncode) def _encodePythonStringToC(value): """Encode a string, so that it gives a C string literal. This doesn't handle limits. """ assert type(value) is bytes, type(value) result = "" octal = False for c in value: if str is bytes: cv = ord(c) else: cv = c if c in b'\\\t\r\n"?': result += r"\%o" % cv octal = True elif 32 <= cv <= 127: if octal and c in b"0123456789": result += '" "' result += chr(cv) octal = False else: result += r"\%o" % cv octal = True result = result.replace('" "\\', "\\") return '"%s"' % result def encodePythonStringToC(value): """Encode a string, so that it gives a C string literal.""" # Not all compilers allow arbitrary large C strings, therefore split it up # into chunks. That changes nothing to the meanings, but is easier on the # parser. Currently only MSVC is known to have this issue, but the # workaround can be used universally. result = _encodePythonStringToC(value[:16000]) value = value[16000:] while value: result += " " result += _encodePythonStringToC(value[:16000]) value = value[16000:] return result def encodePythonIdentifierToC(value): """Encode an identifier from a given Python string.""" # Python identifiers allow almost of characters except a very # few, much more than C identifiers support. This attempts to # be bi-directional, so we can reverse it. def r(match): c = match.group() if c == ".": return "$" else: return "$$%d$" % ord(c) return "".join(re.sub("[^a-zA-Z0-9_]", r, c) for c in value)
1,140