repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
Verckolf/MyInterfaceTest
venv/Lib/site-packages/celery/tests/backends/test_database.py
<reponame>Verckolf/MyInterfaceTest from __future__ import absolute_import, unicode_literals from datetime import datetime from pickle import loads, dumps from celery import states from celery.exceptions import ImproperlyConfigured from celery.utils import uuid from celery.tests.case import ( AppCase, SkipTest, depends_on_current_app, mask_modules, skip_if_pypy, skip_if_jython, ) try: import sqlalchemy # noqa except ImportError: DatabaseBackend = Task = TaskSet = retry = None # noqa else: from celery.backends.database import DatabaseBackend, retry from celery.backends.database.models import Task, TaskSet class SomeClass(object): def __init__(self, data): self.data = data class test_DatabaseBackend(AppCase): @skip_if_pypy @skip_if_jython def setup(self): if DatabaseBackend is None: raise SkipTest('sqlalchemy not installed') self.uri = 'sqlite:///test.db' def test_retry_helper(self): from celery.backends.database import DatabaseError calls = [0] @retry def raises(): calls[0] += 1 raise DatabaseError(1, 2, 3) with self.assertRaises(DatabaseError): raises(max_retries=5) self.assertEqual(calls[0], 5) def test_missing_SQLAlchemy_raises_ImproperlyConfigured(self): with mask_modules('sqlalchemy'): from celery.backends.database import _sqlalchemy_installed with self.assertRaises(ImproperlyConfigured): _sqlalchemy_installed() def test_missing_dburi_raises_ImproperlyConfigured(self): self.app.conf.CELERY_RESULT_DBURI = None with self.assertRaises(ImproperlyConfigured): DatabaseBackend(app=self.app) def test_missing_task_id_is_PENDING(self): tb = DatabaseBackend(self.uri, app=self.app) self.assertEqual(tb.get_status('xxx-does-not-exist'), states.PENDING) def test_missing_task_meta_is_dict_with_pending(self): tb = DatabaseBackend(self.uri, app=self.app) self.assertDictContainsSubset({ 'status': states.PENDING, 'task_id': 'xxx-does-not-exist-at-all', 'result': None, 'traceback': None }, tb.get_task_meta('xxx-does-not-exist-at-all')) def test_mark_as_done(self): tb = DatabaseBackend(self.uri, app=self.app) tid = uuid() self.assertEqual(tb.get_status(tid), states.PENDING) self.assertIsNone(tb.get_result(tid)) tb.mark_as_done(tid, 42) self.assertEqual(tb.get_status(tid), states.SUCCESS) self.assertEqual(tb.get_result(tid), 42) def test_is_pickled(self): tb = DatabaseBackend(self.uri, app=self.app) tid2 = uuid() result = {'foo': 'baz', 'bar': SomeClass(12345)} tb.mark_as_done(tid2, result) # is serialized properly. rindb = tb.get_result(tid2) self.assertEqual(rindb.get('foo'), 'baz') self.assertEqual(rindb.get('bar').data, 12345) def test_mark_as_started(self): tb = DatabaseBackend(self.uri, app=self.app) tid = uuid() tb.mark_as_started(tid) self.assertEqual(tb.get_status(tid), states.STARTED) def test_mark_as_revoked(self): tb = DatabaseBackend(self.uri, app=self.app) tid = uuid() tb.mark_as_revoked(tid) self.assertEqual(tb.get_status(tid), states.REVOKED) def test_mark_as_retry(self): tb = DatabaseBackend(self.uri, app=self.app) tid = uuid() try: raise KeyError('foo') except KeyError as exception: import traceback trace = '\n'.join(traceback.format_stack()) tb.mark_as_retry(tid, exception, traceback=trace) self.assertEqual(tb.get_status(tid), states.RETRY) self.assertIsInstance(tb.get_result(tid), KeyError) self.assertEqual(tb.get_traceback(tid), trace) def test_mark_as_failure(self): tb = DatabaseBackend(self.uri, app=self.app) tid3 = uuid() try: raise KeyError('foo') except KeyError as exception: import traceback trace = '\n'.join(traceback.format_stack()) tb.mark_as_failure(tid3, exception, traceback=trace) self.assertEqual(tb.get_status(tid3), states.FAILURE) self.assertIsInstance(tb.get_result(tid3), KeyError) self.assertEqual(tb.get_traceback(tid3), trace) def test_forget(self): tb = DatabaseBackend(self.uri, backend='memory://', app=self.app) tid = uuid() tb.mark_as_done(tid, {'foo': 'bar'}) tb.mark_as_done(tid, {'foo': 'bar'}) x = self.app.AsyncResult(tid, backend=tb) x.forget() self.assertIsNone(x.result) def test_process_cleanup(self): tb = DatabaseBackend(self.uri, app=self.app) tb.process_cleanup() @depends_on_current_app def test_reduce(self): tb = DatabaseBackend(self.uri, app=self.app) self.assertTrue(loads(dumps(tb))) def test_save__restore__delete_group(self): tb = DatabaseBackend(self.uri, app=self.app) tid = uuid() res = {'something': 'special'} self.assertEqual(tb.save_group(tid, res), res) res2 = tb.restore_group(tid) self.assertEqual(res2, res) tb.delete_group(tid) self.assertIsNone(tb.restore_group(tid)) self.assertIsNone(tb.restore_group('xxx-nonexisting-id')) def test_cleanup(self): tb = DatabaseBackend(self.uri, app=self.app) for i in range(10): tb.mark_as_done(uuid(), 42) tb.save_group(uuid(), {'foo': 'bar'}) s = tb.ResultSession() for t in s.query(Task).all(): t.date_done = datetime.now() - tb.expires * 2 for t in s.query(TaskSet).all(): t.date_done = datetime.now() - tb.expires * 2 s.commit() s.close() tb.cleanup() def test_Task__repr__(self): self.assertIn('foo', repr(Task('foo'))) def test_TaskSet__repr__(self): self.assertIn('foo', repr(TaskSet('foo', None)))
manishksingh89/openairinterface5g
openair3/NAS/COMMON/NR_NAS_defs.h
<filename>openair3/NAS/COMMON/NR_NAS_defs.h /* * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The OpenAirInterface Software Alliance licenses this file to You under * the OAI Public License, Version 1.1 (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.openairinterface.org/?page_id=698 * * Author and copyright: <NAME>, open-cells.com * * 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. *------------------------------------------------------------------------------- * For more information about the OpenAirInterface (OAI) Software Alliance: * <EMAIL> */ #ifndef NR_NAS_DEFS_H #define NR_NAS_DEFS_H #include <common/utils/LOG/log.h> #include <openair3/UICC/usim_interface.h> #include <openair2/LAYER2/NR_MAC_gNB/nr_mac_gNB.h> /* TS 24.007 possible L3 formats: Table 11.1: Formats of information elements Format Meaning IEI present LI present Value part present T Type only yes no no V Value only no no yes TV Type and Value yes no yes LV Length and Value no yes yes TLV Type, Length and Value yes yes yes LV-E Length and Value no yes yes TLV-E Type, Length and Value yes yes yes */ /* Map task id to printable name. */ typedef struct { int id; char text[256]; } text_info_t; static inline const char * idToText(const text_info_t* table, int size, int id) { for(int i=0; i<size; i++) if (table[i].id==id) return table[i].text; LOG_E(NAS,"impossible id %x\n", id); return "IMPOSSIBLE"; } #define idStr(TaBle, iD) idToText(TaBle, sizeof(TaBle)/sizeof(text_info_t), iD) #define TO_TEXT(LabEl, nUmID) {nUmID, #LabEl}, #define TO_ENUM(LabEl, nUmID ) LabEl = nUmID, //TS 24.501, chap 9.2 => TS 24.007 typedef enum { SGSsessionmanagementmessages=0x2e, //LTEbox: 0xC0 ??? SGSmobilitymanagementmessages=0x7e, } Extendedprotocoldiscriminator_t; #define FOREACH_TYPE(TYPE_DEF) \ TYPE_DEF( Registrationrequest,0x41 )\ TYPE_DEF( Registrationaccept,0x42 )\ TYPE_DEF( Registrationcomplete,0x43 )\ TYPE_DEF( Registrationreject,0x44 )\ TYPE_DEF( DeregistrationrequestUEoriginating,0x45 )\ TYPE_DEF( DeregistrationacceptUEoriginating,0x46 )\ TYPE_DEF( DeregistrationrequestUEterminated,0x47 )\ TYPE_DEF( DeregistrationacceptUEterminated,0x48 )\ TYPE_DEF( Servicerequest,0x4c )\ TYPE_DEF( Servicereject,0x4d )\ TYPE_DEF( Serviceaccept,0x4e )\ TYPE_DEF( Controlplaneservicerequest,0x4f )\ TYPE_DEF( Networkslicespecificauthenticationcommand,0x50 )\ TYPE_DEF( Networkslicespecificauthenticationcomplete,0x51 )\ TYPE_DEF( Networkslicespecificauthenticationresult,0x52 )\ TYPE_DEF( Configurationupdatecommand,0x54 )\ TYPE_DEF( Configurationupdatecomplete,0x55 )\ TYPE_DEF( Authenticationrequest,0x56 )\ TYPE_DEF( Authenticationresponse,0x57 )\ TYPE_DEF( Authenticationreject,0x58 )\ TYPE_DEF( Authenticationfailure,0x59 )\ TYPE_DEF( Authenticationresult,0x5a )\ TYPE_DEF( Identityrequest,0x5b )\ TYPE_DEF( Identityresponse,0x5c )\ TYPE_DEF( Securitymodecommand,0x5d )\ TYPE_DEF( Securitymodecomplete,0x5e )\ TYPE_DEF( Securitymodereject,0x5f )\ TYPE_DEF( SGMMstatus,0x64 )\ TYPE_DEF( Notification,0x65 )\ TYPE_DEF( Notificationresponse,0x66 )\ TYPE_DEF( ULNAStransport,0x67 )\ TYPE_DEF( DLNAStransport,0x68 )\ TYPE_DEF( PDUsessionestablishmentrequest,0xc1 )\ TYPE_DEF( PDUsessionestablishmentaccept,0xc2 )\ TYPE_DEF( PDUsessionestablishmentreject,0xc3 )\ TYPE_DEF( PDUsessionauthenticationcommand,0xc5 )\ TYPE_DEF( PDUsessionauthenticationcomplete,0xc6 )\ TYPE_DEF( PDUsessionauthenticationresult,0xc7 )\ TYPE_DEF( PDUsessionmodificationrequest,0xc9 )\ TYPE_DEF( PDUsessionmodificationreject,0xca )\ TYPE_DEF( PDUsessionmodificationcommand,0xcb )\ TYPE_DEF( PDUsessionmodificationcomplete,0xcc )\ TYPE_DEF( PDUsessionmodificationcommandreject,0xcd )\ TYPE_DEF( PDUsessionreleaserequest,0xd1 )\ TYPE_DEF( PDUsessionreleasereject,0xd2 )\ TYPE_DEF( PDUsessionreleasecommand,0xd3 )\ TYPE_DEF( PDUsessionreleasecomplete,0xd4 )\ TYPE_DEF( SGSMstatus,0xd6 )\ static const text_info_t message_text_info[] = { FOREACH_TYPE(TO_TEXT) }; //! Tasks id of each task typedef enum { FOREACH_TYPE(TO_ENUM) } SGSmobilitymanagementmessages_t; // TS 24.501 typedef enum { notsecurityprotected=0, Integrityprotected=1, Integrityprotectedandciphered=2, Integrityprotectedwithnew5GNASsecuritycontext=3, Integrityprotectedandcipheredwithnew5GNASsecuritycontext=4, } Security_header_t; typedef enum { SUCI=1, SGGUTI, IMEI, SGSTMSI, IMEISV, MACaddress, EUI64, } identitytype_t; // table 9.11.3.2.1 #define FOREACH_CAUSE(CAUSE_DEF) \ CAUSE_DEF(Illegal_UE,0x3 )\ CAUSE_DEF(PEI_not_accepted,0x5 )\ CAUSE_DEF(Illegal_ME,0x6 )\ CAUSE_DEF(SGS_services_not_allowed,0x7 )\ CAUSE_DEF(UE_identity_cannot_be_derived_by_the_network,0x9 )\ CAUSE_DEF(Implicitly_de_registered,0x0a )\ CAUSE_DEF(PLMN_not_allowed,0x0b )\ CAUSE_DEF(Tracking_area_not_allowed,0x0c )\ CAUSE_DEF(Roaming_not_allowed_in_this_tracking_area,0x0d )\ CAUSE_DEF(No_suitable_cells_in_tracking_area,0x0f )\ CAUSE_DEF(MAC_failure,0x14 )\ CAUSE_DEF(Synch_failure,0x15 )\ CAUSE_DEF(Congestion,0x16 )\ CAUSE_DEF(UE_security_capabilities_mismatch,0x17 )\ CAUSE_DEF(Security_mode_rejected_unspecified,0x18 )\ CAUSE_DEF(Non_5G_authentication_unacceptable,0x1a )\ CAUSE_DEF(N1_mode_not_allowed,0x1b )\ CAUSE_DEF(Restricted_service_area,0x1c )\ CAUSE_DEF(Redirection_to_EPC_required,0x1f )\ CAUSE_DEF(LADN_not_available,0x2b )\ CAUSE_DEF(No_network_slices_available,0x3e )\ CAUSE_DEF(Maximum_number_of_PDU_sessions_reached,0x41 )\ CAUSE_DEF(Insufficient_resources_for_specific_slice_and_DNN,0x43 )\ CAUSE_DEF(Insufficient_resources_for_specific_slice,0x45 )\ CAUSE_DEF(ngKSI_already_in_use,0x47 )\ CAUSE_DEF(Non_3GPP_access_to_5GCN_not_allowed,0x48 )\ CAUSE_DEF(Serving_network_not_authorized,0x49 )\ CAUSE_DEF(Temporarily_not_authorized_for_this_SNPN,0x4A )\ CAUSE_DEF(Permanently_not_authorized_for_this_SNPN,0x4b )\ CAUSE_DEF(Not_authorized_for_this_CAG_or_authorized_for_CAG_cells_only,0x4c )\ CAUSE_DEF(Wireline_access_area_not_allowed,0x4d )\ CAUSE_DEF(Payload_was_not_forwarded,0x5a )\ CAUSE_DEF(DNN_not_supported_or_not_subscribed_in_the_slice,0x5b )\ CAUSE_DEF(Insufficient_user_plane_resources_for_the_PDU_session,0x5c )\ CAUSE_DEF(Semantically_incorrect_message,0x5f )\ CAUSE_DEF(Invalid_mandatory_information,0x60 )\ CAUSE_DEF(Message_type_non_existent_or_not_implemented,0x61 )\ CAUSE_DEF(Message_type_not_compatible_with_the_protocol_state,0x62 )\ CAUSE_DEF(Information_element_non_existent_or_not_implemented,0x63 )\ CAUSE_DEF(Conditional_IE_error,0x64 )\ CAUSE_DEF(Message_not_compatible_with_the_protocol_state,0x65 )\ CAUSE_DEF(Protocol_error_unspecified,0x67 ) /* Map task id to printable name. */ #define CAUSE_TEXT(LabEl, nUmID) {nUmID, #LabEl}, static const text_info_t cause_text_info[] = { FOREACH_CAUSE(TO_TEXT) }; #define CAUSE_ENUM(LabEl, nUmID ) LabEl = nUmID, //! Tasks id of each task typedef enum { FOREACH_CAUSE(TO_ENUM) } cause_id_t; //_table_9.11.4.2.1:_5GSM_cause_information_element #define FOREACH_CAUSE_SECU(CAUSE_SECU_DEF) \ CAUSE_SECU_DEF(Security_Operator_determined_barring,0x08 )\ CAUSE_SECU_DEF(Security_Insufficient_resources,0x1a )\ CAUSE_SECU_DEF(Security_Missing_or_unknown_DNN,0x1b )\ CAUSE_SECU_DEF(Security_Unknown_PDU_session_type,0x1c )\ CAUSE_SECU_DEF(Security_User_authentication_or_authorization_failed,0x1d )\ CAUSE_SECU_DEF(Security_Request_rejected_unspecified,0x1f )\ CAUSE_SECU_DEF(Security_Service_option_not_supported,0x20 )\ CAUSE_SECU_DEF(Security_Requested_service_option_not_subscribed,0x21 )\ CAUSE_SECU_DEF(Security_Service_option_temporarily_out_of_order,0x22 )\ CAUSE_SECU_DEF(Security_PTI_already_in_use,0x23 )\ CAUSE_SECU_DEF(Security_Regular_deactivation,0x24 )\ CAUSE_SECU_DEF(Security_Network_failure,0x26 )\ CAUSE_SECU_DEF(Security_Reactivation_requested,0x27 )\ CAUSE_SECU_DEF(Security_Semantic_error_in_the_TFT_operation,0x29 )\ CAUSE_SECU_DEF(Security_Syntactical_error_in_the_TFT_operation,0x2a )\ CAUSE_SECU_DEF(Security_Invalid_PDU_session_identity,0x2b )\ CAUSE_SECU_DEF(Security_Semantic_errors_in_packet_filter,0x2c )\ CAUSE_SECU_DEF(Security_Syntactical_error_in_packet_filter,0x2d )\ CAUSE_SECU_DEF(Security_Out_of_LADN_service_area,0x2e )\ CAUSE_SECU_DEF(Security_PTI_mismatch,0x2f )\ CAUSE_SECU_DEF(Security_PDU_session_type_IPv4_only_allowed,0x32 )\ CAUSE_SECU_DEF(Security_PDU_session_type_IPv6_only_allowed,0x33 )\ CAUSE_SECU_DEF(Security_PDU_session_does_not_exist,0x36 )\ CAUSE_SECU_DEF(Security_PDU_session_type_IPv4v6_only_allowed,0x39 )\ CAUSE_SECU_DEF(Security_PDU_session_type_Unstructured_only_allowed,0x3a )\ CAUSE_SECU_DEF(Security_PDU_session_type_Ethernet_only_allowed,0x3d )\ CAUSE_SECU_DEF(Security_Insufficient_resources_for_specific_slice_and_DNN,0x43 )\ CAUSE_SECU_DEF(Security_Not_supported_SSC_mode,0x44 )\ CAUSE_SECU_DEF(Security_Insufficient_resources_for_specific_slice,0x45 )\ CAUSE_SECU_DEF(Security_Missing_or_unknown_DNN_in_a_slice,0x46 )\ CAUSE_SECU_DEF(Security_Invalid_PTI_value,0x51 )\ CAUSE_SECU_DEF(Security_Maximum_data_rate_per_UE_for_user_plane_integrity_protection_is_too_low,0x52 )\ CAUSE_SECU_DEF(Security_Semantic_error_in_the_QoS_operation,0x53 )\ CAUSE_SECU_DEF(Security_Syntactical_error_in_the_QoS_operation,0x54 )\ CAUSE_SECU_DEF(Security_Invalid_mapped_EPS_bearer_identity,0x55 )\ CAUSE_SECU_DEF(Security_Semantically_incorrect_message,0x5f )\ CAUSE_SECU_DEF(Security_Invalid_mandatory_information,0x60 )\ CAUSE_SECU_DEF(Security_Message_type_non_existent_or_not_implemented,0x61 )\ CAUSE_SECU_DEF(Security_Message_type_not_compatible_with_the_protocol_state,0x62 )\ CAUSE_SECU_DEF(Security_Information_element_non_existent_or_not_implemented,0x63 )\ CAUSE_SECU_DEF(Security_Conditional_IE_error,0x64 )\ CAUSE_SECU_DEF(Security_Message_not_compatible_with_the_protocol_state,0x65 )\ CAUSE_SECU_DEF(Security_Protocol_error_unspecified,0x6f ) static const text_info_t cause_secu_text_info[] = { FOREACH_CAUSE_SECU(TO_TEXT) }; //! Tasks id of each task typedef enum { FOREACH_CAUSE_SECU(TO_ENUM) } cause_secu_id_t; // IEI (information element identifier) are spread in each message definition #define IEI_RAND 0x21 #define IEI_AUTN 0x20 #define IEI_EAP 0x78 #define IEI_AuthenticationResponse 0x2d //TS 24.501 sub layer states for UE // for network side, only 5GMMderegistered, 5GMMderegistered_initiated, 5GMMregistered, 5GMMservice_request_initiated are valid typedef enum { SGMMnull, SGMMderegistered, SGMMderegistered_initiated, SGMMregistered, SGMMregistered_initiated, SGMMservice_request_initiated, } SGMM_UE_states; typedef struct { Extendedprotocoldiscriminator_t epd:8; Security_header_t sh:8; SGSmobilitymanagementmessages_t mt:8; } SGScommonHeader_t; typedef struct { Extendedprotocoldiscriminator_t epd:8; Security_header_t sh:8; SGSmobilitymanagementmessages_t mt:8; identitytype_t it:8; } Identityrequest_t; // the message continues with the identity value, depending on identity type, see TS 14.501, 9.11.3.4 typedef struct __attribute__((packed)) { Extendedprotocoldiscriminator_t epd:8; Security_header_t sh:8; SGSmobilitymanagementmessages_t mt:8; uint16_t len; } Identityresponse_t; typedef struct __attribute__((packed)) { Identityresponse_t common; identitytype_t mi:8; unsigned int supiFormat:4; unsigned int identityType:4; unsigned int mcc1:4; unsigned int mcc2:4; unsigned int mcc3:4; unsigned int mnc3:4; unsigned int mnc1:4; unsigned int mnc2:4; unsigned int routing1:4; unsigned int routing2:4; unsigned int routing3:4; unsigned int routing4:4; unsigned int protectScheme:4; unsigned int spare:4; uint8_t hplmnId; } IdentityresponseIMSI_t; typedef struct __attribute__((packed)) { Extendedprotocoldiscriminator_t epd:8; Security_header_t sh:8; SGSmobilitymanagementmessages_t mt:8; unsigned int ngKSI:4; unsigned int spare:4; unsigned int ABBALen:8; unsigned int ABBA:16; uint8_t ieiRAND; uint8_t RAND[16]; uint8_t ieiAUTN; uint8_t AUTNlen; uint8_t AUTN[16]; } authenticationrequestHeader_t; typedef struct __attribute__((packed)) { Extendedprotocoldiscriminator_t epd:8; Security_header_t sh:8; SGSmobilitymanagementmessages_t mt:8; uint8_t iei; uint8_t RESlen; uint8_t RES[16]; } authenticationresponse_t; //AUTHENTICATION RESULT typedef struct __attribute__((packed)) { Extendedprotocoldiscriminator_t epd:8; Security_header_t sh:8; SGSmobilitymanagementmessages_t mt:8; unsigned int selectedNASsecurityalgorithms; unsigned int ngKSI:4; //ngKSI NAS key set identifier 192.168.127.12 unsigned int spare:4; // LV 3-9 bytes Replayed UE security capabilities UE security capability 172.16.17.32 /* optional TV (E-, 1 byte) Oprional IMEISV request IMEISV request 192.168.127.12 TV (57, 2 bytes ) Selected EPS NAS security algorithms EPS NAS security algorithms 172.16.58.3 TLV (36, 3 bytes) Additional 5G security information Additional 5G security information 172.16.58.32 TLV-E (78,, 7-1503 bytes) EAP message EAP message 9.11.2.2 TLV (38, 4-n)ABBA ABBA 9.11.3.10 TLV (19, 4-7) Replayed S1 UE security capabilities S1 UE security capability 9.11.3.48A */ } securityModeCommand_t; typedef struct { uicc_t *uicc; } nr_user_nas_t; #define STATIC_ASSERT(test_for_true) _Static_assert((test_for_true), "(" #test_for_true ") failed") #define myCalloc(var, type) type * var=(type*)calloc(sizeof(type),1); #define arrayCpy(tO, FroM) STATIC_ASSERT(sizeof(tO) == sizeof(FroM)) ; memcpy(tO, FroM, sizeof(tO)) int resToresStar(uint8_t *msg, uicc_t* uicc); int identityResponse(void **msg, nr_user_nas_t *UE); int authenticationResponse(void **msg, nr_user_nas_t *UE); void UEprocessNAS(void *msg,nr_user_nas_t *UE); void SGSabortUE(void *msg, NRUEcontext_t *UE) ; void SGSregistrationReq(void *msg, NRUEcontext_t *UE); void SGSderegistrationUEReq(void *msg, NRUEcontext_t *UE); void SGSauthenticationResp(void *msg, NRUEcontext_t *UE); void SGSidentityResp(void *msg, NRUEcontext_t *UE); void SGSsecurityModeComplete(void *msg, NRUEcontext_t *UE); void SGSregistrationComplete(void *msg, NRUEcontext_t *UE); void processNAS(void *msg, NRUEcontext_t *UE); int identityRequest(void **msg, NRUEcontext_t *UE); int authenticationRequest(void **msg, NRUEcontext_t *UE); int securityModeCommand(void **msg, NRUEcontext_t *UE); void servingNetworkName(uint8_t *msg, char * imsiStr, int nmc_size); #endif
qsyttkx/geek_time_cpp
24/test04_scope_exit.cpp
#include <stdio.h> // fopen/perror/puts #include <boost/scope_exit.hpp> // BOOST_SCOPE_EXIT void test() { FILE* fp = fopen("../boost_test04_scope_exit.cpp", "r"); if (fp == NULL) { perror("Cannot open file"); } BOOST_SCOPE_EXIT(&fp) { if (fp) { fclose(fp); puts("File is closed"); } } BOOST_SCOPE_EXIT_END puts("Faking an exception"); throw 42; } int main() { try { test(); } catch (int) { puts("Exception received"); } }
abreu4/jina
tests/unit/executors/encoders/test_frameworks.py
import pytest from jina.excepts import ModelCheckpointNotExist from jina.executors.encoders.frameworks import BaseOnnxEncoder def test_raised_exception(): with pytest.raises(ModelCheckpointNotExist): BaseOnnxEncoder()
gudaoxuri/ez-framework
services/auth/src/main/scala/com/ecfront/ez/framework/service/auth/model/EZ_Resource.scala
package com.ecfront.ez.framework.service.auth.model import com.ecfront.common.Resp import com.ecfront.ez.framework.core.i18n.I18NProcessor.Impl import com.ecfront.ez.framework.service.auth.CacheManager import com.ecfront.ez.framework.service.jdbc._ import scala.beans.BeanProperty /** * 资源实体 */ @Entity("Resource") case class EZ_Resource() extends BaseModel with SecureModel { @Unique @Require @Desc("Code", 1000, 0) // method@uri @BeanProperty var code: String = _ @Index @Require @Desc("Method", 10, 0) @BeanProperty var method: String = _ @Index @Require @Desc("URI", 800, 0) @BeanProperty var uri: String = _ @Require @Desc("Name", 200, 0) @BeanProperty var name: String = _ } object EZ_Resource extends SecureStorage[EZ_Resource] { def apply(method: String, uri: String, name: String): EZ_Resource = { val res = EZ_Resource() res.method = method res.uri = uri res.name = name.x res } override def preSave(model: EZ_Resource): Resp[EZ_Resource] = { preSaveOrUpdate(model) } override def preUpdate(model: EZ_Resource): Resp[EZ_Resource] = { preSaveOrUpdate(model) } override def preSaveOrUpdate(model: EZ_Resource): Resp[EZ_Resource] = { if (model.method == null || model.method.trim.isEmpty || model.uri == null || model.uri.trim.isEmpty) { logger.warn(s"Require【method】and【uri】") Resp.badRequest("Require【method】and【uri】") } else { if (model.uri.contains(BaseModel.SPLIT)) { logger.warn(s"【uri】can't contains ${BaseModel.SPLIT}") Resp.badRequest(s"【uri】can't contains ${BaseModel.SPLIT}") } else { model.code = assembleCode(model.method, model.uri) super.preSaveOrUpdate(model) } } } override def postSave(saveResult: EZ_Resource, preResult: EZ_Resource): Resp[EZ_Resource] = { postAddExt(saveResult) super.postSave(saveResult, preResult) } override def postUpdate(updateResult: EZ_Resource, preResult: EZ_Resource): Resp[EZ_Resource] = { postAddExt(updateResult) super.postUpdate(updateResult, preResult) } override def postSaveOrUpdate(saveOrUpdateResult: EZ_Resource, preResult: EZ_Resource): Resp[EZ_Resource] = { postAddExt(saveOrUpdateResult) super.postSaveOrUpdate(saveOrUpdateResult, preResult) } override def preDeleteById(id: Any): Resp[Any] = { preRemoveExt(doGetById(id).body) super.preDeleteById(id) } override def preDeleteByUUID(uuid: String): Resp[String] = { preRemoveExt(doGetByUUID(uuid).body) super.preDeleteByUUID(uuid) } override def preDeleteByCond(condition: String, parameters: List[Any]): Resp[(String, List[Any])] = { doFind(condition, parameters).body.foreach(preRemoveExt) super.preDeleteByCond(condition, parameters) } def deleteByCode(code: String): Resp[Void] = { deleteByCond( s"""code = ?""", List(code)) } private def postAddExt(obj: EZ_Resource): Unit = { if (obj != null) { CacheManager.RBAC.addResource(obj) } } private def preRemoveExt(obj: EZ_Resource): Unit = { if (obj != null) { CacheManager.RBAC.removeResource(obj.code) } } override def preUpdateByCond(newValues: String, condition: String, parameters: List[Any]): Resp[(String, String, List[Any])] = Resp.notImplemented("") def assembleCode(method: String, uri: String): String = { method + BaseModel.SPLIT + uri } }
chris-blay/guillemot-core
rosWorkspace/mip_common/include/mip_common/mip_sdk_config.h
///////////////////////////////////////////////////////////////////////////// // //! @file mip_sdk_config.h //! @author <NAME> //! @version 1.0 // //! @description Target-Specific Configuration // // External dependencies: // // // //! @copyright 2011 Microstrain. // //!@section CHANGES //! // //!@section LICENSE //! //! THE PRESENT SOFTWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING //! CUSTOMERS WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER //! FOR THEM TO SAVE TIME. AS A RESULT, MICROSTRAIN SHALL NOT BE HELD LIABLE //! FOR ANY DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY //! CLAIMS ARISING FROM THE CONTENT OF SUCH SOFTWARE AND/OR THE USE MADE BY //! CUSTOMERS OF THE CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH //! THEIR PRODUCTS. // ///////////////////////////////////////////////////////////////////////////// #ifndef _MIP_SDK_CONFIG_H #define _MIP_SDK_CONFIG_H //////////////////////////////////////////////////////////////////////////////// // //Include Files // //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // // Defines // //////////////////////////////////////////////////////////////////////////////// //! @def /// //The MIP protocol is big-endian, if the user needs little-endian, MIP_SDK_CONFIG_BYTESWAP should be 1. /// #define MIP_SDK_CONFIG_BYTESWAP 1 /// //The maximum number of callbacks the interface structure can hold //Notes: // // Each callback takes up 9 bytes. Several loops search the callback list for // valid callbacks, increasing the number will result in slightly slower execution. // /// #define MIP_INTERFACE_MAX_CALLBACKS 10 /// //The maximum time (in milliseconds) the MIP interface will wait for bytes to become available on the port /// #define MIP_INTERFACE_PORT_READ_TIMEOUT_MS 10 /// //The maximum time the (in milliseconds) to wait for most command/response cycles to complete /// #define MIP_INTERFACE_DEFAULT_COMMAND_RESPONSE_TIMEOUT_MS 1000 /// //The maximum time the (in milliseconds) to wait for command/response cycles that require long processing on the device to complete //(e.g. turning sub-device power on/off, running a BIT, etc.) /// #define MIP_INTERFACE_LONG_COMMAND_RESPONSE_TIMEOUT_MS 10000 #endif
juturnas/go-sdk
secrets/option.go
package secrets import ( "net/http" "strconv" ) // Option a thing that we can do to modify a request. type Option func(req *http.Request) // Version adds a version to the request. func Version(version int) Option { return func(req *http.Request) { req.URL.Query().Add("version", strconv.Itoa(version)) } } // List adds a list parameter to the request. func List() Option { return func(req *http.Request) { req.URL.Query().Add("list", "true") } }
Robbbert/messui
src/mame/drivers/supduck.cpp
// license:BSD-3-Clause // copyright-holders:<NAME> /********************************************************************************* Super Duck (c) 1992 Comad hardware appears to be roughly based off Bionic Commando, close to the Tiger Road / F1-Dream based Pushman / Bouncing Balls. PCB Clocks as measured: Crystal 1: 8mhz Crystal 2: 24mhz All clock timing comes from crystal 1 68k - 8mhz Z80 - 2mhz OKI M6295 - 1mhz *********************************************************************************/ #include "emu.h" #include "cpu/z80/z80.h" #include "cpu/m68000/m68000.h" #include "machine/gen_latch.h" #include "sound/okim6295.h" #include "video/bufsprite.h" #include "video/tigeroad_spr.h" #include "emupal.h" #include "screen.h" #include "speaker.h" #include "tilemap.h" class supduck_state : public driver_device { public: supduck_state(const machine_config &mconfig, device_type type, const char *tag) : driver_device(mconfig, type, tag) , m_maincpu(*this, "maincpu") , m_audiocpu(*this, "audiocpu") , m_spriteram(*this, "spriteram") , m_text_videoram(*this, "textvideoram") , m_fore_videoram(*this, "forevideoram") , m_back_videoram(*this, "backvideoram") , m_gfxdecode(*this, "gfxdecode") , m_palette(*this, "palette") , m_spritegen(*this, "spritegen") , m_soundlatch(*this, "soundlatch") { } void supduck(machine_config &config); private: // devices required_device<cpu_device> m_maincpu; required_device<z80_device> m_audiocpu; // shared pointers required_device<buffered_spriteram16_device> m_spriteram; required_shared_ptr<uint16_t> m_text_videoram; required_shared_ptr<uint16_t> m_fore_videoram; required_shared_ptr<uint16_t> m_back_videoram; required_device<gfxdecode_device> m_gfxdecode; required_device<palette_device> m_palette; required_device<tigeroad_spr_device> m_spritegen; required_device<generic_latch_8_device> m_soundlatch; tilemap_t *m_text_tilemap; tilemap_t *m_fore_tilemap; tilemap_t *m_back_tilemap; uint32_t screen_update(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect); void text_videoram_w(offs_t offset, uint16_t data, uint16_t mem_mask = ~0); void fore_videoram_w(offs_t offset, uint16_t data, uint16_t mem_mask = ~0); void back_videoram_w(offs_t offset, uint16_t data, uint16_t mem_mask = ~0); void supduck_scroll_w(offs_t offset, uint16_t data, uint16_t mem_mask = ~0); void supduck_4000_w(uint16_t data); void supduck_4002_w(offs_t offset, uint16_t data, uint16_t mem_mask = ~0); TILEMAP_MAPPER_MEMBER(supduk_tilemap_scan); void okibank_w(uint8_t data); void main_map(address_map &map); void oki_map(address_map &map); void sound_map(address_map &map); // driver_device overrides virtual void machine_start() override; virtual void machine_reset() override; virtual void video_start() override; TILE_GET_INFO_MEMBER(get_text_tile_info); TILE_GET_INFO_MEMBER(get_fore_tile_info); TILE_GET_INFO_MEMBER(get_back_tile_info); }; TILEMAP_MAPPER_MEMBER(supduck_state::supduk_tilemap_scan) { // where does each page start? int pagesize = 0x8 * 0x8; int offset = ((col & ~0x7) / 0x8) * (pagesize); offset += ((row^0x3f) & 0x7)*0x8; offset += col & 0x7; offset &= 0x3ff; offset += (((row^0x3f) & ~0x7) / 0x8) * 0x400; return offset; } void supduck_state::video_start() { m_text_tilemap = &machine().tilemap().create(*m_gfxdecode, tilemap_get_info_delegate(*this, FUNC(supduck_state::get_text_tile_info)), TILEMAP_SCAN_ROWS, 8, 8, 32, 32); m_fore_tilemap = &machine().tilemap().create(*m_gfxdecode, tilemap_get_info_delegate(*this, FUNC(supduck_state::get_fore_tile_info)), tilemap_mapper_delegate(*this, FUNC(supduck_state::supduk_tilemap_scan)), 32, 32, 128,64); m_back_tilemap = &machine().tilemap().create(*m_gfxdecode, tilemap_get_info_delegate(*this, FUNC(supduck_state::get_back_tile_info)), tilemap_mapper_delegate(*this, FUNC(supduck_state::supduk_tilemap_scan)), 32, 32, 128,64); m_text_tilemap->set_transparent_pen(0x3); m_fore_tilemap->set_transparent_pen(0xf); m_text_tilemap->set_scrolldx(128, 128); m_text_tilemap->set_scrolldy( 6, 6); m_fore_tilemap->set_scrolldx(128, 128); m_fore_tilemap->set_scrolldy( 6, 6); m_back_tilemap->set_scrolldx(128, 128); m_back_tilemap->set_scrolldy( 6, 6); } uint32_t supduck_state::screen_update(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect) { bitmap.fill(m_palette->black_pen(), cliprect); m_back_tilemap->draw(screen, bitmap, cliprect, 0, 0); m_fore_tilemap->draw(screen, bitmap, cliprect, 0, 0); m_spritegen->draw_sprites(bitmap, cliprect, m_spriteram->buffer(), m_spriteram->bytes(), flip_screen(), true); m_text_tilemap->draw(screen, bitmap, cliprect, 0, 0); return 0; } void supduck_state::text_videoram_w(offs_t offset, uint16_t data, uint16_t mem_mask) { COMBINE_DATA(&m_text_videoram[offset]); m_text_tilemap->mark_tile_dirty(offset); } void supduck_state::fore_videoram_w(offs_t offset, uint16_t data, uint16_t mem_mask) { COMBINE_DATA(&m_fore_videoram[offset]); m_fore_tilemap->mark_tile_dirty(offset); } void supduck_state::back_videoram_w(offs_t offset, uint16_t data, uint16_t mem_mask) { COMBINE_DATA(&m_back_videoram[offset]); m_back_tilemap->mark_tile_dirty(offset); } TILE_GET_INFO_MEMBER(supduck_state::get_text_tile_info) // same as tigeroad.c { uint16_t *videoram = m_text_videoram; int data = videoram[tile_index]; int attr = data >> 8; int code = (data & 0xff) + ((attr & 0xc0) << 2) + ((attr & 0x20) << 5); int color = attr & 0x0f; int flags = (attr & 0x10) ? TILE_FLIPY : 0; tileinfo.set(0, code, color, flags); } TILE_GET_INFO_MEMBER(supduck_state::get_fore_tile_info) { uint16_t *videoram = m_fore_videoram; int data = videoram[tile_index]; int code = data & 0xff; if (data & 0x4000) code |= 0x100; if (data & 0x8000) code |= 0x200; int color = (data & 0x0f00)>>8; int flags = (data & 0x2000) ? TILE_FLIPX : 0; flags |=(data & 0x1000) ? TILE_FLIPY : 0; tileinfo.set(1, code, color, flags); } TILE_GET_INFO_MEMBER(supduck_state::get_back_tile_info) { uint16_t *videoram = m_back_videoram; int data = videoram[tile_index]; int code = data & 0xff; if (data & 0x4000) code |= 0x100; if (data & 0x8000) code |= 0x200; int color = (data & 0x0f00)>>8; int flags = (data & 0x2000) ? TILE_FLIPX : 0; flags |=(data & 0x1000) ? TILE_FLIPY : 0; tileinfo.set(2, code, color, flags); } void supduck_state::supduck_4000_w(uint16_t data) { } void supduck_state::supduck_4002_w(offs_t offset, uint16_t data, uint16_t mem_mask) { data &= mem_mask; m_soundlatch->write((data>>8)); m_audiocpu->set_input_line(0, HOLD_LINE); } void supduck_state::supduck_scroll_w(offs_t offset, uint16_t data, uint16_t mem_mask) { data &= mem_mask; switch (offset) { case 0: m_back_tilemap->set_scrollx(0, data); break; case 1: m_back_tilemap->set_scrolly(0, -data - 32 * 8); break; case 2: m_fore_tilemap->set_scrollx(0, data); break; case 3: m_fore_tilemap->set_scrolly(0, -data - 32 * 8); break; } } void supduck_state::main_map(address_map &map) { map(0x000000, 0x03ffff).rom().nopw(); map(0xfe0000, 0xfe1fff).ram().share("spriteram"); map(0xfe4000, 0xfe4001).portr("P1_P2").w(FUNC(supduck_state::supduck_4000_w)); map(0xfe4002, 0xfe4003).portr("SYSTEM").w(FUNC(supduck_state::supduck_4002_w)); map(0xfe4004, 0xfe4005).portr("DSW"); map(0xfe8000, 0xfe8007).w(FUNC(supduck_state::supduck_scroll_w)); map(0xfe800e, 0xfe800f).nopw(); // watchdog or irqack map(0xfec000, 0xfecfff).ram().w(FUNC(supduck_state::text_videoram_w)).share("textvideoram"); map(0xff0000, 0xff3fff).ram().w(FUNC(supduck_state::back_videoram_w)).share("backvideoram"); map(0xff4000, 0xff7fff).ram().w(FUNC(supduck_state::fore_videoram_w)).share("forevideoram"); map(0xff8000, 0xff87ff).ram().w(m_palette, FUNC(palette_device::write16)).share("palette"); map(0xffc000, 0xffffff).ram(); /* working RAM */ } void supduck_state::sound_map(address_map &map) { map(0x0000, 0x7fff).rom(); map(0x8000, 0x87ff).ram(); map(0x9000, 0x9000).w(FUNC(supduck_state::okibank_w)); map(0x9800, 0x9800).rw("oki", FUNC(okim6295_device::read), FUNC(okim6295_device::write)); map(0xa000, 0xa000).r(m_soundlatch, FUNC(generic_latch_8_device::read)); } void supduck_state::oki_map(address_map &map) { map(0x00000, 0x1ffff).rom(); map(0x20000, 0x3ffff).bankr("okibank"); } void supduck_state::okibank_w(uint8_t data) { // bit 0x80 is written on startup? membank("okibank")->set_entry(data&0x03); } static INPUT_PORTS_START( supduck ) PORT_START("P1_P2") PORT_BIT( 0x0001, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_4WAY PORT_PLAYER(1) PORT_BIT( 0x0002, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_4WAY PORT_PLAYER(1) PORT_BIT( 0x0004, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_4WAY PORT_PLAYER(1) PORT_BIT( 0x0008, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_4WAY PORT_PLAYER(1) PORT_BIT( 0x0010, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(1) PORT_BIT( 0x0020, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(1) PORT_BIT( 0x0040, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_PLAYER(1) PORT_BIT( 0x0080, IP_ACTIVE_LOW, IPT_BUTTON4 ) PORT_PLAYER(1) PORT_BIT( 0x0100, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_4WAY PORT_PLAYER(2) PORT_BIT( 0x0200, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_4WAY PORT_PLAYER(2) PORT_BIT( 0x0400, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_4WAY PORT_PLAYER(2) PORT_BIT( 0x0800, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_4WAY PORT_PLAYER(2) PORT_BIT( 0x1000, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(2) PORT_BIT( 0x2000, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(2) PORT_BIT( 0x4000, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_PLAYER(2) PORT_BIT( 0x8000, IP_ACTIVE_LOW, IPT_BUTTON4 ) PORT_PLAYER(2) PORT_START("SYSTEM") PORT_BIT( 0x00ff, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x0100, IP_ACTIVE_LOW, IPT_START1 ) PORT_BIT( 0x0200, IP_ACTIVE_LOW, IPT_START2 ) PORT_BIT( 0x0400, IP_ACTIVE_LOW, IPT_CUSTOM ) PORT_VBLANK("screen") /* not sure, probably wrong */ PORT_BIT( 0x0800, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x1000, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x2000, IP_ACTIVE_LOW, IPT_SERVICE1 ) PORT_BIT( 0x4000, IP_ACTIVE_LOW, IPT_COIN1 ) PORT_BIT( 0x8000, IP_ACTIVE_LOW, IPT_COIN2 ) PORT_START("DSW") PORT_DIPNAME( 0x0007, 0x0007, DEF_STR( Coinage ) ) PORT_DIPLOCATION("DIP-A:1,2,3") PORT_DIPSETTING( 0x0000, DEF_STR( 5C_1C ) ) PORT_DIPSETTING( 0x0001, DEF_STR( 4C_1C ) ) PORT_DIPSETTING( 0x0002, DEF_STR( 3C_1C ) ) PORT_DIPSETTING( 0x0003, DEF_STR( 2C_1C ) ) PORT_DIPSETTING( 0x0007, DEF_STR( 1C_1C ) ) PORT_DIPSETTING( 0x0006, DEF_STR( 1C_2C ) ) PORT_DIPSETTING( 0x0005, DEF_STR( 1C_3C ) ) PORT_DIPSETTING( 0x0004, DEF_STR( 1C_4C ) ) PORT_DIPNAME( 0x0008, 0x0008, DEF_STR( Unknown ) ) PORT_DIPLOCATION("DIP-A:4") PORT_DIPSETTING( 0x0008, DEF_STR( Off ) ) PORT_DIPSETTING( 0x0000, DEF_STR( On ) ) PORT_DIPNAME( 0x0010, 0x0010, DEF_STR( Demo_Sounds ) ) PORT_DIPLOCATION("DIP-A:5") PORT_DIPSETTING( 0x0000, DEF_STR( Off ) ) PORT_DIPSETTING( 0x0010, DEF_STR( On ) ) PORT_DIPNAME( 0x0020, 0x0020, "Game Sound" ) PORT_DIPLOCATION("DIP-A:6") /* Kills all sounds except for Coin-In */ PORT_DIPSETTING( 0x0000, DEF_STR( Off ) ) PORT_DIPSETTING( 0x0020, DEF_STR( On ) ) PORT_DIPNAME( 0x00c0, 0x0080, DEF_STR( Lives ) ) PORT_DIPLOCATION("DIP-A:7,8") PORT_DIPSETTING( 0x00c0, "2" ) PORT_DIPSETTING( 0x0080, "3" ) PORT_DIPSETTING( 0x0040, "4" ) PORT_DIPSETTING( 0x0000, "5" ) PORT_DIPNAME( 0x0100, 0x0100, DEF_STR( Unknown ) ) PORT_DIPLOCATION("DIP-B:1") PORT_DIPSETTING( 0x0100, DEF_STR( Off ) ) PORT_DIPSETTING( 0x0000, DEF_STR( On ) ) PORT_DIPNAME( 0x0200, 0x0200, DEF_STR( Unknown ) ) PORT_DIPLOCATION("DIP-B:2") PORT_DIPSETTING( 0x0200, DEF_STR( Off ) ) PORT_DIPSETTING( 0x0000, DEF_STR( On ) ) PORT_DIPNAME( 0x0400, 0x0400, DEF_STR( Unknown ) ) PORT_DIPLOCATION("DIP-B:3") PORT_DIPSETTING( 0x0400, DEF_STR( Off ) ) PORT_DIPSETTING( 0x0000, DEF_STR( On ) ) PORT_DIPNAME( 0x0800, 0x0800, DEF_STR( Unknown ) ) PORT_DIPLOCATION("DIP-B:4") PORT_DIPSETTING( 0x0800, DEF_STR( Off ) ) PORT_DIPSETTING( 0x0000, DEF_STR( On ) ) PORT_DIPNAME( 0x1000, 0x1000, DEF_STR( Unknown ) ) PORT_DIPLOCATION("DIP-B:5") PORT_DIPSETTING( 0x1000, DEF_STR( Off ) ) PORT_DIPSETTING( 0x0000, DEF_STR( On ) ) PORT_DIPNAME( 0x2000, 0x2000, DEF_STR( Unknown ) ) PORT_DIPLOCATION("DIP-B:6") PORT_DIPSETTING( 0x2000, DEF_STR( Off ) ) PORT_DIPSETTING( 0x0000, DEF_STR( On ) ) PORT_DIPNAME( 0x4000, 0x4000, "Character Test" ) PORT_DIPLOCATION("DIP-B:7") PORT_DIPSETTING( 0x4000, DEF_STR( Off ) ) PORT_DIPSETTING( 0x0000, DEF_STR( On ) ) PORT_SERVICE_DIPLOC( 0x8000, IP_ACTIVE_LOW, "DIP-B:8" ) INPUT_PORTS_END static const gfx_layout vramlayout= { 8,8, /* 8*8 characters */ RGN_FRAC(1,1), /* 1024 character */ 2, /* 2 bitplanes */ { 4,0 }, { STEP4(0,1), STEP4(4*2,1) }, { STEP8(0,4*2*2) }, 128 /* every character takes 128 consecutive bytes */ }; // same as the ROM tilemap layout from tigeroad static const gfx_layout tile_layout = { 32, 32, RGN_FRAC(1, 2), 4, { RGN_FRAC(1,2)+4, RGN_FRAC(1,2)+0, 4, 0 }, { STEP4(0,1), STEP4(4*2,1), STEP4(4*2*2*32,1), STEP4(4*2*2*32+4*2,1), STEP4(4*2*2*64,1), STEP4(4*2*2*64+4*2,1), STEP4(4*2*2*96,1), STEP4(4*2*2*96+4*2,1) }, { STEP32(0,4*2*2) }, 256 * 8 }; static GFXDECODE_START( gfx_supduck ) GFXDECODE_ENTRY( "gfx1", 0, vramlayout, 768, 64 ) /* colors 768-1023 */ GFXDECODE_ENTRY( "gfx2", 0, tile_layout, 0, 16 ) /* colors 0- 63 */ GFXDECODE_ENTRY( "gfx3", 0, tile_layout, 256, 16 ) /* colors 256- 319 */ GFXDECODE_END void supduck_state::machine_start() { membank("okibank")->configure_entries(0, 4, memregion("okibank")->base(), 0x20000); membank("okibank")->set_entry(0); } void supduck_state::machine_reset() { } void supduck_state::supduck(machine_config &config) { /* basic machine hardware */ M68000(config, m_maincpu, XTAL(8'000'000)); /* Verified on PCB */ m_maincpu->set_addrmap(AS_PROGRAM, &supduck_state::main_map); m_maincpu->set_vblank_int("screen", FUNC(supduck_state::irq2_line_hold)); // 2 & 4? Z80(config, m_audiocpu, XTAL(8'000'000)/4); /* 2MHz - verified on PCB */ m_audiocpu->set_addrmap(AS_PROGRAM, &supduck_state::sound_map); /* video hardware */ screen_device &screen(SCREEN(config, "screen", SCREEN_TYPE_RASTER)); screen.set_raw(6000000, 384, 128, 0, 262, 22, 246); // hsync is 50..77, vsync is 257..259 screen.set_screen_update(FUNC(supduck_state::screen_update)); screen.set_palette(m_palette); screen.screen_vblank().set(m_spriteram, FUNC(buffered_spriteram16_device::vblank_copy_rising)); BUFFERED_SPRITERAM16(config, m_spriteram); GFXDECODE(config, m_gfxdecode, m_palette, gfx_supduck); TIGEROAD_SPRITE(config, m_spritegen, 0); m_spritegen->set_palette(m_palette); m_spritegen->set_color_base(512); /* colors 512- 767 */ PALETTE(config, m_palette).set_format(palette_device::xRGBRRRRGGGGBBBB_bit4, 0x800/2); /* sound hardware */ SPEAKER(config, "mono").front_center(); GENERIC_LATCH_8(config, m_soundlatch); okim6295_device &oki(OKIM6295(config, "oki", XTAL(8'000'000)/8, okim6295_device::PIN7_HIGH)); // 1MHz - Verified on PCB, pin 7 not verified oki.add_route(ALL_OUTPUTS, "mono", 1.0); oki.set_addrmap(0, &supduck_state::oki_map); } /*************************************************************************** Game driver(s) ***************************************************************************/ ROM_START( supduck ) ROM_REGION( 0x40000, "maincpu", 0 ) /* 68000 code */ ROM_LOAD16_BYTE( "5.u16n", 0x00000, 0x20000, CRC(837a559a) SHA1(ed5ad744a4145dfbef56ad2e6eec3ff14c20de1c) ) ROM_LOAD16_BYTE( "6.u16l", 0x00001, 0x20000, CRC(508e9905) SHA1(2da3f12caa29066b4d54b22573cfdfcea8916f99) ) ROM_REGION( 0x10000, "audiocpu", 0 ) ROM_LOAD( "4.su6", 0x00000, 0x8000, CRC(d75863ea) SHA1(497d11b86f4f69134943fc3448d195c6e7acbe8f) ) ROM_REGION( 0x08000, "gfx1", 0 ) ROM_LOAD( "3.cu15", 0x00000, 0x8000, CRC(b1cacca4) SHA1(b4a486618197cf2b85a121b5640cd773b2d453fc) ) ROM_REGION( 0x80000, "gfx2", 0 ) ROM_LOAD( "7.uu29", 0x00000, 0x20000, CRC(f3251b20) SHA1(8ebb9b98324de14356c9a57ae8a77dc4118fb5c2) ) ROM_LOAD( "8.uu30", 0x20000, 0x20000, CRC(03c60cbd) SHA1(bf3be7161f69187350eb9d9d4209b93f8b67d0f1) ) ROM_LOAD( "9.uu31", 0x40000, 0x20000, CRC(9b6d3430) SHA1(ade2decc5bcf817498b1198a2244d1c65bc20bea) ) ROM_LOAD( "10.uu32", 0x60000, 0x20000, CRC(beed2616) SHA1(c077a3de4a6d451a568694ab70e85830d585a41d) ) ROM_REGION( 0x80000, "gfx3", 0 ) ROM_LOAD( "11.ul29", 0x00000, 0x20000, CRC(1b6958a4) SHA1(ca93f898702e14ece24d5cfced38d622d3596d0f) ) ROM_LOAD( "12.ul30", 0x20000, 0x20000, CRC(3e6bd24b) SHA1(f93b5c78d815bd30ecb9cfe2cd257548e467e852) ) ROM_LOAD( "13.ul31", 0x40000, 0x20000, CRC(bff7b7cd) SHA1(2f65cadcfcc02fe31ba721eea9f45d4a729e4374) ) ROM_LOAD( "14.ul32", 0x60000, 0x20000, CRC(97a7310b) SHA1(76b82bfea64b59890c0ba2e1688b7321507a4da7) ) ROM_REGION( 0x80000, "spritegen", 0 ) ROM_LOAD32_BYTE( "15.u1d", 0x00000, 0x20000, CRC(81bf1f27) SHA1(7a66630a2da85387904917d3c136880dffcb9649) ) ROM_LOAD32_BYTE( "16.u2d", 0x00001, 0x20000, CRC(9573d6ec) SHA1(9923be782bae47c49913d01554bcf3e5efb5395b) ) ROM_LOAD32_BYTE( "17.u1c", 0x00002, 0x20000, CRC(21ef14d4) SHA1(66e389aaa1186921a07da9a9a9eda88a1083ad42) ) ROM_LOAD32_BYTE( "18.u2c", 0x00003, 0x20000, CRC(33dd0674) SHA1(b95dfcc16d939bac77f338b8a8cada19328a1993) ) ROM_REGION( 0x80000, "oki", 0 ) ROM_LOAD( "2.su12", 0x00000, 0x20000, CRC(745d42fb) SHA1(f9aee3ddbad3cc2f3a7002ee0d762eb041967e1e) ) // static sample data ROM_REGION( 0x80000, "okibank", 0 ) ROM_LOAD( "1.su13", 0x00000, 0x80000, CRC(7fb1ed42) SHA1(77ec86a6454398e329066aa060e9b6a39085ce71) ) // banked sample data ROM_END GAME( 1992, supduck, 0, supduck, supduck, supduck_state, empty_init, ROT0, "Comad", "Super Duck", MACHINE_SUPPORTS_SAVE )
ben-manes/jOOQ
jOOQ-test/src/org/jooq/test/oracle/generatedclasses/test/routines/PArrays1.java
/** * This class is generated by jOOQ */ package org.jooq.test.oracle.generatedclasses.test.routines; /** * This class is generated by jOOQ. */ @java.lang.SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class PArrays1 extends org.jooq.impl.AbstractRoutine<java.lang.Void> { private static final long serialVersionUID = 601370280; /** * The parameter <code>TEST.P_ARRAYS1.IN_ARRAY</code>. */ public static final org.jooq.Parameter<org.jooq.test.oracle.generatedclasses.test.udt.records.UNumberArrayRecord> IN_ARRAY = createParameter("IN_ARRAY", org.jooq.impl.SQLDataType.INTEGER.asArrayDataType(org.jooq.test.oracle.generatedclasses.test.udt.records.UNumberArrayRecord.class)); /** * The parameter <code>TEST.P_ARRAYS1.OUT_ARRAY</code>. */ public static final org.jooq.Parameter<org.jooq.test.oracle.generatedclasses.test.udt.records.UNumberArrayRecord> OUT_ARRAY = createParameter("OUT_ARRAY", org.jooq.impl.SQLDataType.INTEGER.asArrayDataType(org.jooq.test.oracle.generatedclasses.test.udt.records.UNumberArrayRecord.class)); /** * Create a new routine call instance */ public PArrays1() { super("P_ARRAYS1", org.jooq.test.oracle.generatedclasses.test.Test.TEST); addInParameter(IN_ARRAY); addOutParameter(OUT_ARRAY); } /** * Set the <code>IN_ARRAY</code> parameter IN value to the routine */ public void setInArray(org.jooq.test.oracle.generatedclasses.test.udt.records.UNumberArrayRecord value) { setValue(org.jooq.test.oracle.generatedclasses.test.routines.PArrays1.IN_ARRAY, value); } /** * Get the <code>OUT_ARRAY</code> parameter OUT value from the routine */ public org.jooq.test.oracle.generatedclasses.test.udt.records.UNumberArrayRecord getOutArray() { return getValue(OUT_ARRAY); } }
MrPii2/atT_j1550
core/src/main/java/hudson/model/listeners/SCMPollListener.java
/* * The MIT License * * Copyright (c) 2011, <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package hudson.model.listeners; import hudson.ExtensionList; import hudson.ExtensionPoint; import hudson.scm.PollingResult; import jenkins.model.Jenkins; import hudson.model.AbstractProject; import hudson.model.TaskListener; import java.io.IOException; /** * A hook for listening to polling activities in Jenkins. * * @author <NAME> * @author <NAME> * @since 1.474 */ public abstract class SCMPollListener implements ExtensionPoint { /** * Called before the polling execution. * * @param project * Project that's about to run polling. * @param listener * Connected to the polling log. */ public void onBeforePolling( AbstractProject<?, ?> project, TaskListener listener ) {} /** * Called when the polling successfully concluded. * * @param result * The result of the polling. */ public void onPollingSuccess( AbstractProject<?, ?> project, TaskListener listener, PollingResult result) {} /** * Called when the polling concluded with an error. * * @param exception * The problem reported. This can include {@link InterruptedException} (that corresponds to the user cancelling it), * some anticipated problems like {@link IOException}, or bug in the code ({@link RuntimeException}) */ public void onPollingFailed( AbstractProject<?, ?> project, TaskListener listener, Throwable exception) {} public static void fireBeforePolling( AbstractProject<?, ?> project, TaskListener listener ) { for (SCMPollListener l : all()) { try { l.onBeforePolling(project, listener); } catch (Exception e) { /* Make sure, that the listeners do not have any impact on the actual poll */ } } } public static void firePollingSuccess( AbstractProject<?, ?> project, TaskListener listener, PollingResult result ) { for( SCMPollListener l : all() ) { try { l.onPollingSuccess(project, listener, result); } catch (Exception e) { /* Make sure, that the listeners do not have any impact on the actual poll */ } } } public static void firePollingFailed( AbstractProject<?, ?> project, TaskListener listener, Throwable exception ) { for( SCMPollListener l : all() ) { try { l.onPollingFailed(project, listener, exception); } catch (Exception e) { /* Make sure, that the listeners do not have any impact on the actual poll */ } } } /** * Returns all the registered {@link SCMPollListener}s. */ public static ExtensionList<SCMPollListener> all() { return Jenkins.getInstance().getExtensionList( SCMPollListener.class ); } }
clangen/autom8
libautom8/include/autom8/message/request_handler_factory.hpp
<gh_stars>1-10 #ifndef __C_AUTOM8_REQUEST_HANDLER_FACTORY_HPP__ #define __C_AUTOM8_REQUEST_HANDLER_FACTORY_HPP__ #include <autom8/message/request_handler.hpp> #include <boost/thread.hpp> #include <boost/shared_ptr.hpp> namespace autom8 { class session; class request_handler_factory; typedef boost::shared_ptr<request_handler_factory> request_handler_factory_ptr; class request_handler_factory { private: typedef std::vector<request_handler_ptr> request_handler_list; request_handler_factory(); // singleton public: static request_handler_factory_ptr instance(); bool handle_request(boost::shared_ptr<session>, message_ptr); void register_handler(request_handler_ptr); private: boost::mutex protect_handler_list_mutex_; request_handler_list request_handlers_; }; } #endif
karendolan/unitime
JavaSource/org/unitime/timetable/server/sectioning/SectioningReportTypesBackend.java
/* * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * The Apereo Foundation 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.unitime.timetable.server.sectioning; import java.util.Collection; import org.cpsolver.studentsct.report.DistanceConflictTable; import org.cpsolver.studentsct.report.RequestGroupTable; import org.cpsolver.studentsct.report.RequestPriorityTable; import org.cpsolver.studentsct.report.SectionConflictTable; import org.cpsolver.studentsct.report.TableauReport; import org.cpsolver.studentsct.report.TimeOverlapConflictTable; import org.cpsolver.studentsct.report.UnbalancedSectionsTable; import org.springframework.beans.factory.annotation.Autowired; import org.unitime.localization.impl.Localization; import org.unitime.timetable.gwt.client.sectioning.SectioningReports.ReportTypeInterface; import org.unitime.timetable.gwt.client.sectioning.SectioningReports.SectioningReportTypesRpcRequest; import org.unitime.timetable.gwt.command.client.GwtRpcResponseList; import org.unitime.timetable.gwt.command.server.GwtRpcImplementation; import org.unitime.timetable.gwt.command.server.GwtRpcImplements; import org.unitime.timetable.gwt.resources.StudentSectioningMessages; import org.unitime.timetable.reports.studentsct.CriticalCoursesReport; import org.unitime.timetable.reports.studentsct.IndividualStudentTimeOverlaps; import org.unitime.timetable.reports.studentsct.PerturbationsReport; import org.unitime.timetable.reports.studentsct.StudentAvailabilityConflicts; import org.unitime.timetable.reports.studentsct.UnasignedCourseRequests; import org.unitime.timetable.reports.studentsct.UnusedReservations; import org.unitime.timetable.security.SessionContext; import org.unitime.timetable.solver.service.SolverService; import org.unitime.timetable.solver.studentsct.StudentSolverProxy; /** * @author <NAME> */ @GwtRpcImplements(SectioningReportTypesRpcRequest.class) public class SectioningReportTypesBackend implements GwtRpcImplementation<SectioningReportTypesRpcRequest, GwtRpcResponseList<ReportTypeInterface>> { protected static final StudentSectioningMessages SCT_MSG = Localization.create(StudentSectioningMessages.class); @Autowired SolverService<StudentSolverProxy> studentSectioningSolverService; public static enum ReportType { TIME_CONFLICTS("Time Conflicts", SectionConflictTable.class.getName(), "type", "OVERLAPS", "overlapsIncludeAll", "true"), AVAILABLE_CONFLICTS("Availability Conflicts", SectionConflictTable.class.getName(), "type", "UNAVAILABILITIES", "overlapsIncludeAll", "true"), SECTION_CONFLICTS("Time & Availability Conflicts", SectionConflictTable.class.getName(), "type", "OVERLAPS_AND_UNAVAILABILITIES", "overlapsIncludeAll", "true"), UNBALANCED_SECTIONS("Unbalanced Classes", UnbalancedSectionsTable.class.getName()), DISTANCE_CONFLICTS("Distance Conflicts", DistanceConflictTable.class.getName()), TIME_OVERLAPS("Time Overlaps", TimeOverlapConflictTable.class.getName()), REQUEST_GROUPS("Request Groups", RequestGroupTable.class.getName()), PERTURBATIONS("Perturbations", PerturbationsReport.class.getName()), INDIVIDUAL_TIME_OVERLAPS("Individual Student Time Overlaps", IndividualStudentTimeOverlaps.class.getName()), NOT_ALLOWED_TIME_OVERLAPS("Not Allowed Time Overlaps", IndividualStudentTimeOverlaps.class.getName(), "includeAllowedOverlaps", "false"), INDIVIDUAL_TIME_OVERLAPS_BT("Individual Student Time Overlaps (Exclude Break Times)", IndividualStudentTimeOverlaps.class.getName(), "ignoreBreakTimeConflicts", "true"), NOT_ALLOWED_TIME_OVERLAPS_BT("Not Allowed Time Overlaps (Exclude Break Times)", IndividualStudentTimeOverlaps.class.getName(), "ignoreBreakTimeConflicts", "true", "includeAllowedOverlaps", "false"), TEACHING_CONFLICTS("Teaching Conflicts", StudentAvailabilityConflicts.class.getName()), TEACHING_CONFLICTS_NA("Teaching Conflicts (Exclude Allowed)", StudentAvailabilityConflicts.class.getName(), "includeAllowedOverlaps", "false"), NOT_ASSIGNED_COURSE_REQUESTS(SCT_MSG.reportUnassignedCourseRequests(), UnasignedCourseRequests.class.getName()), UNUSED_GROUP_RES(SCT_MSG.reportUnusedGroupReservations(), UnusedReservations.class.getName(), "type", "group"), UNUSED_INDIVIDUAL_RES(SCT_MSG.reportUnusedIndividualReservations(), UnusedReservations.class.getName(), "type", "individual"), UNUSED_OVERRIDE_RES(SCT_MSG.reportUnusedOverrideReservations(), UnusedReservations.class.getName(), "type", "override"), UNUSED_LC_RES(SCT_MSG.reportUnusedLearningCommunityReservations(), UnusedReservations.class.getName(), "type", "lc"), COURSE_REQUESTS(SCT_MSG.reportCourseRequestsWithPriorities(), RequestPriorityTable.class.getName(), "pritify", "false"), TABLEAU_REPORT(SCT_MSG.reportTableauReport(), TableauReport.class.getName(), "pritify", "false"), TABLEAU_SIMPLE(SCT_MSG.reportTableauSimpleReport(), TableauReport.class.getName(), "pritify", "false", "simple", "true"), CRITICAL(SCT_MSG.reportCriticalCoursesReport(), CriticalCoursesReport.class.getName(), "pritify", "false"), ; String iName, iImplementation; String[] iParameters; ReportType(String name, String implementation, String... params) { iName = name; iImplementation = implementation; iParameters = params; } public String getName() { return iName; } public String getImplementation() { return iImplementation; } public String[] getParameters() { return iParameters; } public ReportTypeInterface toReportTypeInterface() { return new ReportTypeInterface(name(), iName, iImplementation, iParameters); } } @Override public GwtRpcResponseList<ReportTypeInterface> execute(SectioningReportTypesRpcRequest request, SessionContext context) { GwtRpcResponseList<ReportTypeInterface> ret = new GwtRpcResponseList<ReportTypeInterface>(); for (ReportType type: ReportType.values()) ret.add(type.toReportTypeInterface()); if (!request.isOnline()) { StudentSolverProxy solver = studentSectioningSolverService.getSolver(); if (solver != null) { Collection<ReportTypeInterface> types = solver.getReportTypes(); if (types != null && !types.isEmpty()) ret.addAll(types); } } return ret; } }
fossabot/erbridge-home
src/components/LogoParticle.test.js
<gh_stars>0 import { shallow } from 'enzyme'; import React from 'react'; import LogoParticle from './LogoParticle'; it('renders correctly with all props', () => { expect( shallow( <LogoParticle groupBoundingRect={{ top: 100, right: 200 }} pointerPosition={{ x: 15, y: 25 }} radius={1} x={0} y={0} />, ), ).toMatchSnapshot(); }); it('renders correctly without optional props', () => { expect(shallow(<LogoParticle radius={1} x={0} y={0} />)).toMatchSnapshot(); });
skpatel20/spring-app-boot
spring-lemon-commons-mongo/src/main/java/com/naturalprogrammer/spring/lemon/commonsmongo/AbstractDocument.java
<gh_stars>100-1000 /* * Copyright 2020-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this artifact or 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 com.naturalprogrammer.spring.lemon.commonsmongo; import com.naturalprogrammer.spring.lemon.commons.security.PermissionEvaluatorEntity; import com.naturalprogrammer.spring.lemon.commons.security.UserDto; import lombok.Getter; import lombok.Setter; import org.springframework.data.annotation.*; import org.springframework.data.mongodb.core.mapping.Document; import java.io.Serializable; import java.util.Date; @Document @Getter @Setter public abstract class AbstractDocument<ID extends Serializable> implements PermissionEvaluatorEntity { @Id protected ID id; @CreatedBy private ID createdBy; @CreatedDate private Date createdDate; @LastModifiedBy private ID lastModifiedBy; @LastModifiedDate private Date lastModifiedDate; @Version private Long version; /** * Whether the given user has the given permission for * this entity. Override this method where you need. */ @Override public boolean hasPermission(UserDto currentUser, String permission) { return false; } }
thelostdeveloper/Conduit
src/main/java/systems/conduit/main/api/inventory/GUI.java
<gh_stars>0 package systems.conduit.main.api.inventory; import com.google.common.collect.ImmutableList; import systems.conduit.main.api.mixins.ServerPlayer; /** * @author Innectic * @since 12/11/2020 */ public interface GUI { void open(ServerPlayer player); void open(Iterable<ServerPlayer> player); void close(ServerPlayer player); void close(Iterable<ServerPlayer> player); ImmutableList<ServerPlayer> getActiveViewers(); }
huguanghui/StartGo
utils/color.go
package utils import ( "strconv" ) var ( Black, White *Color ) func init() { initColorCube() Black, _ = NewColor("#000000") White, _ = NewColor("#ffffff") } type Color struct { Red uint8 Green uint8 Blue uint8 } func NewColor(hex string) (*Color, error) { red, err := strconv.ParseUint(hex[0:2], 16, 8) if err != nil { return nil, err } green, err := strconv.ParseUint(hex[2:4], 16, 8) if err != nil { return nil, err } blue, err := strconv.ParseUint(hex[4:6], 16, 8) if err != nil { return nil, err } return &Color{ Red: uint8(red), Green: uint8(green), Blue: uint8(blue), }, nil } var x6colorIndexes = [6]uint8{0, 95, 135, 175, 215, 255} var x6colorCube [216]Color func initColorCube() { i := 0 for iR := 0; iR < 6; iR++ { for iG := 0; iG < 6; iG++ { for iB := 0; iB < 6; iB++ { x6colorCube[i] = Color{ x6colorIndexes[iR], x6colorIndexes[iG], x6colorIndexes[iB], } i++ } } } }
dairongpeng/leona
internal/apiserver/run.go
// Copyright 2021 dairongpeng <<EMAIL>>. 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 apiserver import "github.com/dairongpeng/leona/internal/apiserver/config" // Run runs the specified APIServer. This should never exit. func Run(cfg *config.Config) error { // the configuration used to create the HTTP/GRPC server according to the application configuration server, err := createAPIServer(cfg) if err != nil { return err } // PrepareRun for initializing the HTTP/GRPC server before it starts // Afterwards, the Run method is called to start the GRPC and HTTP server return server.PrepareRun().Run() }
j-zhen/UXAspects
src/ng1/directives/previewPanes/previewPane.module.js
<reponame>j-zhen/UXAspects<filename>src/ng1/directives/previewPanes/previewPane.module.js import PreviewPaneProvider from './previewPane.provider.js'; import PreviewPaneDirective from './previewPane/previewPane.directive.js'; import PreviewPaneController from './previewPane/previewPane.controller.js'; import PreviewPaneItemDirective from './previewPaneItem/previewPaneItem.directive.js'; import PreviewPaneItemController from './previewPaneItem/previewPaneItem.controller.js'; import PreviewPaneToggleDirective from './previewPaneToggle/previewPaneToggle.directive.js'; import PreviewPaneToggleController from './previewPaneToggle/previewPaneToggle.controller.js'; import PreviewPaneWindowDirective from './previewPaneWindow/previewPaneWindow.directive.js'; import '../../services/windowCommunicationService/windowCommunication.module.js'; import '../../services/keyboardService/keyboardService.module.js'; angular.module("ux-aspects.previewPanes", ['ux-aspects.windowCommunicationService', 'ux-aspects.keyboardService']) .provider('previewPaneProvider', PreviewPaneProvider) .directive('previewPane', PreviewPaneDirective) .controller('PreviewPaneCtrl', PreviewPaneController) .directive('previewPaneItem', PreviewPaneItemDirective) .controller('PreviewPaneItemCtrl', PreviewPaneItemController) .directive('previewPaneToggle', PreviewPaneToggleDirective) .controller('PreviewPaneToggleCtrl', PreviewPaneToggleController) .directive('previewPaneWindow', PreviewPaneWindowDirective);
Chun-Jie-Group/pipelines
pipelines/wdl-smRNA/miRNA_scripts/Main.py
#! /usr/bin/env python2.7 from __future__ import division import os,sys,re,argparse,collections,time,datetime,itertools,config_parser __author__='zhangq' __Email__ = '<EMAIL>' def get_analysis_option(): my_cmdparser = argparse.ArgumentParser(description='This py is used to generate dir and shell for miRNA analysis. Any problem please contact to zq, <EMAIL>') my_cmdparser.add_argument('-C','--config',action='store',dest='config',metavar='CONFIG',help='choose your miRNA config file') my_cmdparser.add_argument('--version',action='version',version='%(prog)s 1.0 ') options=my_cmdparser.parse_args() configure={i:getattr(options,i) for i in dir(options) if (i[0] != '_' and i not in ('ensure_value', 'read_file','read_module'))} if configure['config']: configure['config'] = os.path.abspath(configure['config']) CP = config_parser.parser_info() CP.get_config_info(configure['config']) CP.get_softwares_info('DB_SOFT_info','config') CP.modify_global_setting() else: print "CONFIG FILE LOST,PLEASE CHECK!" sys.exit() CP.config_info['RESULT']['shell_path']=os.path.join(CP.config_info['RESULT']['result_path'],'Shell') cf=CP.config_info cf['config_file'] = configure['config'] return cf def generate_shell_4_mir(cf): configure = {} configure['outdir']=cf['RESULT']['result_path'] configure['shell'] = os.path.join(configure['outdir'],'Shell') configure['cpu_number'] = cf['GLOBAL_SETTING']['single_sample_cpu_number'] configure['path'] = cf['DB_SOFT_info']['config'] configure['species'] = cf['GLOBAL_SETTING']['species'] configure['abbr'] = cf['GLOBAL_SETTING']['abbr'] configure['sample_info'] = cf['sample_info'] configure['diff_comapre'] = cf['diff_compare'] configure['setting_analysis']=cf['setting_analysis'] import filter_base,align_anno_predict analysis_sample=cf['sample_info'].keys() total_single_sh_name = os.path.join(configure['shell'],'1.SingleSample.sh') total_single_sh = open(total_single_sh_name,'w') total_single_sh.write('#! /usr/bin/env bash\n') for i in analysis_sample: single_sample_config={} sample_single_sh_list=[] single_sample_config['outdir'] = os.path.join(configure['outdir'],'1.Data',i) single_sample_config['config_file'] = cf['config_file'] single_sample_config['sample_name']=i if 'r2' in cf['sample_info'][i]: single_sample_config['reads']=','.join([cf['sample_info'][i]['r1'],cf['sample_info'][i]['r2']]) else: single_sample_config['reads'] = cf['sample_info'][i]['r1'] if 'adp' in cf['sample_info'][i]: single_sample_config['adaptor']=cf['sample_info'][i]['adp'] single_sample_config['shell'] = os.path.join(configure['shell'],'Single_Sample',i) single_sample_config['path'] = configure['path'] single_sample_config['cpu_number'] = configure['cpu_number'] if not 'species' in cf['sample_info'][i]: single_sample_config['species'] = configure['species'] single_sample_config['abbr'] = configure['abbr'] else: single_sample_config['species'] = cf['sample_info'][i]['species'] single_sample_config['abbr'] = cf['sample_info'][i]['abbr'] sample_main_sh_name = os.path.join(single_sample_config['shell'],'{0}.main.sh'.format(i)) sample_main_sh = open(sample_main_sh_name,'w') filter_flag = int(configure['setting_analysis']['filter_option']) filter_sh=filter_base.generate_cmd(single_sample_config,filter_flag) sample_single_sh_list.append(filter_sh) single_sample_config['outdir']= os.path.join(cf['RESULT']['result_path'],'2.Analysis_result') single_sample_config['reads']='{0}.fa'.format(os.path.join(configure['outdir'],'1.Data',i,'2.cleandata',i)) a_s_p_sh = align_anno_predict.get_align_anno_predict_shell(single_sample_config) sample_single_sh_list.extend(a_s_p_sh) sample_main_sh.write('sh '+"\nsh ".join(sample_single_sh_list)+'\n') sample_main_sh.close() total_single_sh.write('nohup sh {0} 1>{0}.log 2>{0}.err \n'.format(sample_main_sh_name)) total_single_sh.close() Multi_config = {} Multi_config['sample_name'] = ','.join(analysis_sample) Multi_config['indir'] = cf['RESULT']['result_path'] Multi_config['outdir'] = os.path.join(cf['RESULT']['result_path'],'2.Analysis_result','Multi_Sample') Multi_config['path']=cf['DB_SOFT_info']['config'] Multi_config['species'] = configure['species'] Multi_config['cpu_number'] = cf['GLOBAL_SETTING']['global_cpu_number'] Multi_config['shell'] = os.path.join(configure['shell'],'Multi_Sample') Multi_config['GLOBAL_SETTING'] = cf['GLOBAL_SETTING'] total_multi_sh_name = os.path.join(configure['shell'],'2.MultiSample.sh') total_multi_sh = open(total_multi_sh_name,'w') total_multi_sh.write('#! /usr/bin/env bash\n') import multi_sample_mir sample_exp_sh = multi_sample_mir.get_sample_exp(Multi_config) total_multi_sh.write('nohup sh '+'\n nohup sh '.join([sample_exp_sh])+'\n') # MAIN_SH.write('echo "run merge and exp start at `date`" && sh {0} && echo "run merge and exp end at `date`"\n'.format(total_multi_sh_name)) import diff_mir diff_config={} diff_config['outdir'] = cf['RESULT']['result_path'] diff_config['shell'] = os.path.join(configure['shell'],'Diff') diff_config['GLOBAL_SETTING'] = cf['GLOBAL_SETTING'] diff_config['path'] = cf['DB_SOFT_info']['config'] diff_config['sample_info'] = cf['sample_info'] diff_config['diff_compare'] = cf['diff_compare'] diff_compare_info = diff_mir.get_diff_info() diff_compare_info.get_compare_list(diff_config,'sRNA') diff_sh = diff_mir.run_diff(diff_config,diff_compare_info) diff_main_sh_name = os.path.join(configure['shell'],'3.Diff.sh') with open(diff_main_sh_name,'w') as df: df.write('sh '+'\n'.join(diff_sh)) def make_dirs_4_mir(sample_names,result_outdir,shell_dir,configure): dir_list = [] for i in sample_names: for j in ['0.QC','1.rawdata','2.cleandata']: if configure['setting_analysis']['filter_option']<2 and j =='0.QC':continue dir_list.append('{0}/1.Data/{1}/{2}/'.format(result_outdir,i,j)) for j in ['1.Align2DB','2.Anno','3.Predict']: dir_list.append('{0}/2.Analysis_result/Single_Sample/{1}/{2}/'.format(result_outdir,i,j)) dir_list.append('{0}/2.Analysis_result/Multi_Sample/'.format(result_outdir)) dir_list.append('{0}/2.Analysis_result/diff/'.format(result_outdir)) dir_list.append('{0}/2.Analysis_result/diff/sample_compare/'.format(result_outdir)) dir_list.append('{0}/2.Analysis_result/diff/group_compare/'.format(result_outdir)) shell_dir_list = [] for n,i in enumerate(['Single_Sample','Multi_Sample','Diff']): if n ==0: for j in sample_names: shell_dir_list.append('{0}/{1}/{2}/'.format(shell_dir,i,j)) shell_dir_list.append('{0}/{1}/'.format(shell_dir,i)) for i in itertools.chain(dir_list,shell_dir_list): if not os.path.isdir(i):os.makedirs(i) def generate_main_sh(cf): configure = {} configure['outdir']=cf['RESULT']['result_path'] configure['shell'] = os.path.join(configure['outdir'],'Shell') out_main_single_name = os.path.join(configure['shell'],'1.SingleSample.sh') out_main_Multi_name = os.path.join(configure['shell'],'2.MultiSample.sh') out_main_diff_name = os.path.join(configure['shell'],'3.Diff.sh') out_main_anno_name = os.path.join(configure['shell'],'4.anno.sh') analysis_sample=cf['sample_info'].keys() make_dirs_4_mir(analysis_sample,configure['outdir'],configure['shell'],cf) generate_shell_4_mir(cf) MAIN_SH_name = os.path.join(configure['shell'],'MAIN.sh') MAIN_SH = open(MAIN_SH_name,'w') MAIN_SH.write('nohup python {0} {1} '.format(cf['DB_SOFT_info']['config']['mutil_run'],cf['GLOBAL_SETTING']['global_cpu_number'])+'\nnohup python {0} {1} '.join([out_main_single_name,out_main_Multi_name,out_main_diff_name,out_main_anno_name]).format(cf['DB_SOFT_info']['config']['mutil_run'],cf['GLOBAL_SETTING']['global_cpu_number'])) if __name__ =='__main__': if len(sys.argv ) != 3: sys.argv.append('-h') get_analysis_option() sys.exit() else: cf = get_analysis_option() generate_main_sh(cf)
benjohnson/devspace
pkg/devspace/services/targetselector/waiting_strategy.go
package targetselector import ( "context" "github.com/loft-sh/devspace/pkg/devspace/kubectl" "github.com/loft-sh/devspace/pkg/devspace/kubectl/selector" "github.com/loft-sh/devspace/pkg/util/log" v1 "k8s.io/api/core/v1" ) // WaitingStrategy defines how the target selector should wait type WaitingStrategy interface { SelectContainer(ctx context.Context, client kubectl.Client, namespace string, containers []*selector.SelectedPodContainer, log log.Logger) (bool, *selector.SelectedPodContainer, error) SelectPod(ctx context.Context, client kubectl.Client, namespace string, pods []*v1.Pod, log log.Logger) (bool, *v1.Pod, error) }
automatejs/automate
src/directive/switch/switch-default.js
<reponame>automatejs/automate import { Directive } from '../../view'; import { directive } from '../../decorator'; @directive({ namespace: 'automate', key: 'switchDefault' }) class SwitchDefaultDirective extends Directive { constructor() { super(); this.switchCtrl = null; this.$placeholder = document.createComment('switch-default'); } afterLink() { this.switchCtrl = this.$seekUpDirective('switch'); if (this.switchCtrl == null) { throw new Error('Require m-switch directive'); } this.switchCtrl.matchDefault.on(() => { this[this.switchCtrl.defaultMatched ? '$appendElement' : '$removeElement'](); }); if(!this.switchCtrl.defaultMatched) { this.$removeElement(); } } }
linminglu/Fgame
cross/tulong/event/listener/biology_killed.go
<reponame>linminglu/Fgame<filename>cross/tulong/event/listener/biology_killed.go package listener import ( "fgame/fgame/core/event" "fgame/fgame/cross/tulong/pbutil" tulongscene "fgame/fgame/cross/tulong/scene" "fgame/fgame/cross/tulong/tulong" gameevent "fgame/fgame/game/event" sceneeventtypes "fgame/fgame/game/scene/event/types" "fgame/fgame/game/scene/scene" scenetypes "fgame/fgame/game/scene/types" tulongtemplate "fgame/fgame/game/tulong/template" ) //boss被杀 func battleObjectDead(target event.EventTarget, data event.EventData) (err error) { bo, ok := target.(scene.BattleObject) if !ok { return } npc, ok := bo.(scene.NPC) if !ok { return } attackId, ok := data.(int64) if !ok { return } pl := npc.GetScene().GetPlayer(attackId) if pl == nil { return } s := pl.GetScene() sd := s.SceneDelegate() if sd == nil { return } if s.MapTemplate().GetMapType() != scenetypes.SceneTypeCrossTuLong { return } scendData, ok := sd.(tulongscene.TuLongSceneData) if !ok { return } alliaceId := pl.GetAllianceId() if alliaceId == 0 { return } biologyTemplate := npc.GetBiologyTemplate() if biologyTemplate == nil { return } tuLongTemplate, flag := tulongtemplate.GetTuLongTemplateService().GetTuLongTemplateByBiologyId(int32(biologyTemplate.TemplateId())) if !flag { return } tulong.GetTuLongService().KillBoss(pl.GetServerId(), alliaceId, pl.GetAllianceName()) scendData.KillBoss(pl) //发邮件使用 biologyId := tuLongTemplate.BiologyId isTuLongKillBoss := pbutil.BuildISTuLongKillBoss(biologyId) pl.SendMsg(isTuLongKillBoss) return } func init() { gameevent.AddEventListener(sceneeventtypes.EventTypeBattleObjectDead, event.EventListenerFunc(battleObjectDead)) }
TheTHINGYEEE/ParkourPlugin
src/main/java/com/github/thethingyee/parkourplugin/listeners/ParkourLeaveListeners.java
package com.github.thethingyee.parkourplugin.listeners; import com.github.thethingyee.parkourplugin.ParkourPlugin; import com.github.thethingyee.parkourplugin.scoreboards.ArenaScoreboard; import com.github.thethingyee.parkourplugin.scoreboards.HubScoreboard; import com.github.thethingyee.parkourplugin.scoreboards.ParkourScoreboards; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.World; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.scheduler.BukkitRunnable; import java.util.UUID; public class ParkourLeaveListeners extends ParkourScoreboards implements Listener { public ParkourLeaveListeners(HubScoreboard hubScoreboard, ArenaScoreboard arenaScoreboard, ParkourPlugin parkourPlugin) { super(hubScoreboard, arenaScoreboard, parkourPlugin); } @EventHandler public void onLeave(PlayerQuitEvent event) { for(Player target : Bukkit.getOnlinePlayers()) { if(target.getLocation().getWorld().getUID().equals(UUID.fromString(this.getParkourPlugin().getConfig().getString("hubspawn.World")))) { new BukkitRunnable() { int counter = 0; @Override public void run() { counter++; if(counter > 1) { getHubScoreboard().access(target); this.cancel(); } } }.runTaskTimer(getParkourPlugin(), 0, 20); } try { for(String arenaWorlds : this.getParkourPlugin().getArenaConfig().getConfigurationSection("parkourarenas.worlds").getKeys(false)) { if(target.getLocation().getWorld().equals(Bukkit.getWorld(arenaWorlds))) { new BukkitRunnable() { int counter = 0; @Override public void run() { counter++; if(counter > 1) { getArenaScoreboard().access(target); this.cancel(); } } }.runTaskTimer(getParkourPlugin(), 0, 20); } } } catch(NullPointerException e) { Bukkit.getConsoleSender().sendMessage(getParkourPlugin().PREFIX + ChatColor.RED + "Catched error! No arenas found."); } } } }
steppat/caelum-stella
stella-nfe/src/main/java/br/com/caelum/stella/nfe/fluid/PISOutrasOperacoes.java
package br.com.caelum.stella.nfe.fluid; @net.vidageek.fluid.annotations.FluidClass(br.com.caelum.stella.nfe.modelo.PISOutr.class) public interface PISOutrasOperacoes<T> extends net.vidageek.fluid.FluidInterface<T> { @net.vidageek.fluid.annotations.FluidField("cst") PISOutrasOperacoes<T> withCst(java.lang.String cst); @net.vidageek.fluid.annotations.FluidField("vbc") PISOutrasOperacoes<T> withValorDaBaseDeCalculo(java.math.BigDecimal valorDaBaseDeCalculo); @net.vidageek.fluid.annotations.FluidField("ppis") PISOutrasOperacoes<T> withAliquota(java.math.BigDecimal aliquota); @net.vidageek.fluid.annotations.FluidField("qbcProd") PISOutrasOperacoes<T> withQuantidadeVendida(java.math.BigDecimal quantidadeVendida); @net.vidageek.fluid.annotations.FluidField("vAliqProd") PISOutrasOperacoes<T> withAliquotaDoProduto(java.math.BigDecimal aliquotaDoProduto); @net.vidageek.fluid.annotations.FluidField("vpis") PISOutrasOperacoes<T> withValor(java.math.BigDecimal valor); }
kadel/ocdev
tests/integration/devfile/cmd_logs_test.go
<reponame>kadel/ocdev package devfile import ( "path/filepath" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/redhat-developer/odo/tests/helper" ) var _ = Describe("odo logs command tests", func() { var componentName string var commonVar helper.CommonVar var _ = BeforeEach(func() { commonVar = helper.CommonBeforeEach() componentName = helper.RandString(6) helper.Chdir(commonVar.Context) Expect(helper.VerifyFileExists(".odo/env/env.yaml")).To(BeFalse()) }) var _ = AfterEach(func() { helper.CommonAfterEach(commonVar) }) When("directory is empty", func() { BeforeEach(func() { Expect(helper.ListFilesInDir(commonVar.Context)).To(HaveLen(0)) }) It("should error", func() { output := helper.Cmd("odo", "logs").ShouldFail().Err() Expect(output).To(ContainSubstring("this command cannot run in an empty directory")) }) }) When("component is created and odo logs is executed", func() { BeforeEach(func() { helper.CopyExample(filepath.Join("source", "nodejs"), commonVar.Context) helper.Cmd("odo", "init", "--name", componentName, "--devfile-path", helper.GetExamplePath("source", "devfiles", "nodejs", "devfile-deploy-functional-pods.yaml")).ShouldPass() Expect(helper.VerifyFileExists(".odo/env/env.yaml")).To(BeFalse()) }) When("running in Dev mode", func() { var devSession helper.DevSession var err error BeforeEach(func() { devSession, _, _, _, err = helper.StartDevMode() Expect(err).ToNot(HaveOccurred()) }) AfterEach(func() { devSession.Kill() devSession.WaitEnd() }) It("should successfully show logs of the running component", func() { // `odo logs` out := helper.Cmd("odo", "logs").ShouldPass().Out() helper.MatchAllInOutput(out, []string{"runtime:", "main:"}) // `odo logs --dev` out = helper.Cmd("odo", "logs", "--dev").ShouldPass().Out() helper.MatchAllInOutput(out, []string{"runtime:", "main:"}) // `odo logs --deploy` out = helper.Cmd("odo", "logs", "--deploy").ShouldPass().Out() Expect(out).To(ContainSubstring("no containers running in the specified mode for the component")) }) }) When("running in Deploy mode", func() { BeforeEach(func() { helper.Cmd("odo", "deploy").AddEnv("PODMAN_CMD=echo").ShouldPass() Eventually(func() string { return string(commonVar.CliRunner.Run("get", "pods", "-n", commonVar.Project).Out.Contents()) }).Should(Not(ContainSubstring("ContainerCreating"))) }) It("should successfully show logs of the running component", func() { // `odo logs` out := helper.Cmd("odo", "logs").ShouldPass().Out() helper.MatchAllInOutput(out, []string{"main:", "main[1]:", "main[2]:"}) // `odo logs --dev` out = helper.Cmd("odo", "logs", "--dev").ShouldPass().Out() Expect(out).To(ContainSubstring("no containers running in the specified mode for the component")) // `odo logs --deploy` out = helper.Cmd("odo", "logs", "--deploy").ShouldPass().Out() helper.MatchAllInOutput(out, []string{"main:", "main[1]:", "main[2]:"}) }) }) When("running in both Dev and Deploy mode", func() { var devSession helper.DevSession var err error BeforeEach(func() { devSession, _, _, _, err = helper.StartDevMode() Expect(err).ToNot(HaveOccurred()) helper.Cmd("odo", "deploy").AddEnv("PODMAN_CMD=echo").ShouldPass() Eventually(func() string { return string(commonVar.CliRunner.Run("get", "pods", "-n", commonVar.Project).Out.Contents()) }).Should(Not(ContainSubstring("ContainerCreating"))) }) AfterEach(func() { devSession.Kill() devSession.WaitEnd() }) It("should successfully show logs of the running component", func() { // `odo logs` out := helper.Cmd("odo", "logs").ShouldPass().Out() helper.MatchAllInOutput(out, []string{"runtime", "main:", "main[1]:", "main[2]:", "main[3]:"}) // `odo logs --dev` out = helper.Cmd("odo", "logs", "--dev").ShouldPass().Out() helper.MatchAllInOutput(out, []string{"runtime:", "main:"}) // `odo logs --deploy` out = helper.Cmd("odo", "logs", "--deploy").ShouldPass().Out() helper.MatchAllInOutput(out, []string{"main:", "main[1]:", "main[2]:"}) // `odo logs --dev --deploy` out = helper.Cmd("odo", "logs", "--deploy", "--dev").ShouldFail().Err() Expect(out).To(ContainSubstring("pass only one of --dev or --deploy flags; pass no flag to see logs for both modes")) }) }) }) })
luoyuan3471/hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/statistics/impl/IOStatisticsStoreBuilder.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.fs.statistics.impl; /** * Builder of the {@link IOStatisticsStore} implementation. */ public interface IOStatisticsStoreBuilder { /** * Declare a varargs list of counters to add. * @param keys names of statistics. * @return this builder. */ IOStatisticsStoreBuilder withCounters(String... keys); /** * Declare a varargs list of gauges to add. * @param keys names of statistics. * @return this builder. */ IOStatisticsStoreBuilder withGauges(String... keys); /** * Declare a varargs list of maximums to add. * @param keys names of statistics. * @return this builder. */ IOStatisticsStoreBuilder withMaximums(String... keys); /** * Declare a varargs list of minimums to add. * @param keys names of statistics. * @return this builder. */ IOStatisticsStoreBuilder withMinimums(String... keys); /** * Declare a varargs list of means to add. * @param keys names of statistics. * @return this builder. */ IOStatisticsStoreBuilder withMeanStatistics(String... keys); /** * Add a statistic in the counter, min, max and mean maps for each * declared statistic prefix. * @param prefixes prefixes for the stats. * @return this */ IOStatisticsStoreBuilder withDurationTracking( String... prefixes); /** * Build the collector. * @return a new collector. */ IOStatisticsStore build(); }
stpangst/onemall
pay-service-project/pay-service-app/src/main/java/cn/iocoder/mall/payservice/convert/transaction/TransactionConvert.java
<gh_stars>1-10 package cn.iocoder.mall.payservice.convert.transaction; import cn.iocoder.common.framework.vo.PageResult; import cn.iocoder.mall.payservice.dal.mysql.dataobject.transaction.TransactionDO; import cn.iocoder.mall.payservice.service.transaction.bo.TransactionBO; import cn.iocoder.mall.payservice.service.transaction.bo.TransactionCreateBO; import cn.iocoder.mall.payservice.service.transaction.bo.TransactionUpdateBO; import com.baomidou.mybatisplus.core.metadata.IPage; import org.mapstruct.Mapper; import org.mapstruct.Mappings; import org.mapstruct.factory.Mappers; import java.util.List; @Mapper public interface TransactionConvert { TransactionConvert INSTANCE = Mappers.getMapper(TransactionConvert.class); TransactionDO convert(TransactionUpdateBO updateBO); List<TransactionBO> convertList(List<TransactionDO> transactionDOs); PageResult<TransactionBO> convertPage(IPage<TransactionDO> transactionDOPage); TransactionDO convert(TransactionCreateBO createBO); TransactionBO convert(TransactionDO transactionDO); }
Cenfotec/ObjectOrientedProgramming
Classwork/Classwork 13/EstructuraDatos/src/org/bonilla/bl/PilaLibros.java
<filename>Classwork/Classwork 13/EstructuraDatos/src/org/bonilla/bl/PilaLibros.java package org.bonilla.bl; import org.bonilla.dl.Apilable; public class PilaLibros implements Apilable { private Libro[] libros; private int cabeza = -1; public PilaLibros() { } public PilaLibros(int size) { libros = new Libro[size]; } @Override public void agregar(Object obj) { if (obj instanceof Libro) { Libro tmpObject = (Libro) obj; cabeza++; libros[cabeza] = tmpObject; } } @Override public Object extraer() { Object tmpObject; tmpObject = libros[cabeza]; cabeza--; return tmpObject; } }
tangerstein/inspectit-oce
inspectit-ocelot-core/src/main/java/rocks/inspectit/ocelot/core/tags/ICommonTagsProvider.java
<reponame>tangerstein/inspectit-oce<filename>inspectit-ocelot-core/src/main/java/rocks/inspectit/ocelot/core/tags/ICommonTagsProvider.java<gh_stars>10-100 package rocks.inspectit.ocelot.core.tags; import rocks.inspectit.ocelot.config.model.InspectitConfig; import java.util.Map; public interface ICommonTagsProvider { /** * Get tags provided by this metrics providers. * * @return Get tags provided by this metrics providers. */ Map<String, String> getTags(InspectitConfig configuration); }
tankbing/dubbo-mock
mock_po/src/main/java/com/tony/test/mock/po/RegistryConfig.java
package com.tony.test.mock.po; import java.util.Date; public class RegistryConfig { private Integer id; private String registryProtocol; private String registryAddress; private Integer registryTimeout; private Date updateTime; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getRegistryProtocol() { return registryProtocol; } public void setRegistryProtocol(String registryProtocol) { this.registryProtocol = registryProtocol == null ? null : registryProtocol.trim(); } public String getRegistryAddress() { return registryAddress; } public void setRegistryAddress(String registryAddress) { this.registryAddress = registryAddress == null ? null : registryAddress.trim(); } public Integer getRegistryTimeout() { return registryTimeout; } public void setRegistryTimeout(Integer registryTimeout) { this.registryTimeout = registryTimeout; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } }
Devfast83/coinchart
src/containers/DurationTabs/index.js
import PropTypes from "prop-types"; import React from "react"; import { connect } from "react-redux"; import Tabs from "../../components/Tabs"; import { DEFAULT_PROPS, DURATION_LIST, PROPTYPES } from "../../constants"; import { SettingsActions, SettingsSelectors } from "../../store/settings"; const DurationTabs = ({ handleDurationChange, selectedDuration }) => { const options = DURATION_LIST.reduce((accumulator, { key, codename }) => { // eslint-disable-next-line no-param-reassign accumulator[key] = { listKey: codename, element: <span>{codename}</span>, }; return accumulator; }, {}); return <Tabs options={options} onChange={handleDurationChange} selectedKey={selectedDuration} />; }; const mapDispatchToProps = dispatch => ({ handleDurationChange: durationKey => { dispatch(SettingsActions.selectDuration(durationKey)); }, }); function mapStateToProps(state) { const selectedDuration = SettingsSelectors.getSelectedDuration(state); return { selectedDuration }; } DurationTabs.propTypes = { selectedDuration: PROPTYPES.DURATION, handleDurationChange: PropTypes.func.isRequired, }; DurationTabs.defaultProps = { selectedDuration: DEFAULT_PROPS.DURATION, }; // Use named export for tests export { DurationTabs as UnconnectedDurationTabs, mapDispatchToProps, mapStateToProps }; export default connect(mapStateToProps, mapDispatchToProps)(DurationTabs);
jbdelcuv/openenclave
enclave/core/optee/stubs.c
// Copyright (c) Open Enclave SDK contributors. // Licensed under the MIT License. #include <openenclave/enclave.h> #include <openenclave/internal/defs.h> /* These are functions referenced by libutee that are left out while compiling * it for inclusion in the SDK. */ void _oe_trace_set_level(int level) { OE_UNUSED(level); } void _oe_malloc_add_pool(void* buf, size_t len) { OE_UNUSED(buf); OE_UNUSED(len); } void oe__TEE_MathAPI_Init(void) { } OE_WEAK_ALIAS(_oe_trace_set_level, trace_set_level); OE_WEAK_ALIAS(_oe_malloc_add_pool, malloc_add_pool); OE_WEAK_ALIAS(oe__TEE_MathAPI_Init, _TEE_MathAPI_Init);
Masternode24/hubble
app/assets/javascripts/page/livepeer/report-show.js
$(document).ready(function() { if (!_.includes(App.mode, 'report-show')) { return; } new App.Livepeer.ReportTable($('.report-table')).render(); });
chrisprice/creating-d3-components
node_modules/d3fc/src/indicator/algorithm/calculator/percentageChange.js
(function(d3, fc) { 'use strict'; fc.indicator.algorithm.calculator.percentageChange = function() { var baseIndex = d3.functor(0), value = fc.util.fn.identity; var percentageChange = function(data) { if (data.length === 0) { return []; } var baseValue = value(data[baseIndex(data)]); return data.map(function(d, i) { return (value(d, i) - baseValue) / baseValue; }); }; percentageChange.baseIndex = function(x) { if (!arguments.length) { return baseIndex; } baseIndex = d3.functor(x); return percentageChange; }; percentageChange.value = function(x) { if (!arguments.length) { return value; } value = x; return percentageChange; }; return percentageChange; }; }(d3, fc));
BillMills/AutoQC
util/geo.py
<gh_stars>10-100 from datetime import datetime import numpy as np import math def haversine(theta): ''' haversine. ''' return math.sin(theta/2)**2 def arcHaversine(hs): ''' inverts haversine ''' sqrths = math.sqrt(hs) if sqrths > 1: sqrths = round(sqrths, 10) return 2 * math.asin(sqrths) def haversineDistance(lat1, lon1, lat2, lon2): """ Calculate the great circle distance in meters between two points on the earth (specified in decimal degrees) implementation from http://gis.stackexchange.com/questions/44064/how-to-calculate-distances-in-a-point-sequence """ # convert decimal degrees to radians lon1, lat1, lon2, lat2 = map(math.radians, [lon1, lat1, lon2, lat2]) # haversine formula dlon = lon2 - lon1 dlat = lat2 - lat1 a = haversine(dlat) + math.cos(lat1) * math.cos(lat2) * haversine(dlon) c = arcHaversine(a) km = 6367 * c assert km >= 0, 'haversine returned negative distance' return km*1000. def haversineAngle(lat1, lon1, lat2, lon2, lat3, lon3): ''' Calculate the angle subtended by the great circle passing through lat/lon1 and lat/lon2, with that passing through lat/lon2 and lat/lon3 return None if any required information is missing. ''' if None in [lat1, lon1, lat2, lon2, lat3, lon3]: return None a = haversineDistance(lat1, lon1, lat2, lon2) / 6367000. b = haversineDistance(lat2, lon2, lat3, lon3) / 6367000. c = haversineDistance(lat3, lon3, lat1, lon1) / 6367000. if a == 0 or b == 0: return 0 cosC = (math.cos(c) - math.cos(a)*math.cos(b))/math.sin(a)/math.sin(b) if cosC > 1: cosC = 1 if cosC < -1: cosC = -1 return math.acos(cosC) def deltaTime(earlier, later): ''' Calculate the time difference between two tuples (year, month, day, time), in seconds. return None if information is missing. ''' if None in [earlier[0], earlier[1], earlier[2], earlier[3]]: return None if None in [later[0], later[1], later[2], later[3]]: return None eHour, eMinute, eSecond = parseTime(earlier[3]) lHour, lMinute, lSecond = parseTime(later[3]) try: early = datetime(year=earlier[0], month=earlier[1], day=earlier[2], hour=eHour, minute=eMinute, second=eSecond ) late = datetime(year=later[0], month=later[1], day=later[2], hour=lHour, minute=lMinute, second=lSecond ) except: return None timeDiff = (late - early).total_seconds() assert timeDiff >= 0, 'early date {} is after later date {}'.format(early, late) return timeDiff def parseTime(time): ''' convert a WOD time on [0,24) to ints: hour [0,23], minute [0, 59], second [0, 59] ''' hour = np.floor(time) minute = np.floor(time*60) % 60 second = np.floor(time*3600) % 60 return int(hour), int(minute), int(second)
Alexhuszagh/funxx
pycpp/allocator/crt.h
// :copyright: (c) 2017 <NAME>. // :license: MIT, see licenses/mit.md for more details. /** * \addtogroup PyCPP * \brief C-runtime allocator. * * A shallow wrapper around `malloc` and `free`. This allocator * has poor performance, and therefore should be used sparingly. * * \synopsis * template <typename T> * struct crt_allocator * { * using value_type = T; * * crt_allocator() noexcept; * crt_allocator(const self_t&) noexcept; * template <typename U> crt_allocator(const crt_allocator<U>&) noexcept; * self_t& operator=(const self_t&) noexcept; * template <typename U> self_t& operator=(const crt_allocator<U>&) noexcept; * ~crt_allocator() = default; * * value_type* allocate(size_t n, const void* hint = nullptr); * value_type* reallocate(value_type* p, size_t old_size, size_t new_size, const void* hint = nullptr); * void deallocate(value_type* p, size_t n); * }; * * using crt_resource = resource_adaptor<crt_allocator<byte>>; * * template <typename T, typename U> * inline bool operator==(const crt_allocator<T>&, const crt_allocator<U>&) noexcept; * * template <typename T, typename U> * inline bool operator!=(const crt_allocator<T>&, const crt_allocator<U>&) noexcept */ #pragma once #include <pycpp/misc/safe_stdlib.h> #include <pycpp/stl/memory.h> #include <pycpp/stl/utility.h> #include <stddef.h> PYCPP_BEGIN_NAMESPACE // FORWARD // ------- template <typename T> struct crt_allocator; // DETAIL // ------ /** * \brief Base for crt memory allocator. */ struct crt_allocator_base { static void* allocate(size_t n, size_t size, const void* hint = nullptr); static void deallocate(void* p, size_t n); }; // is_relocatable<T>::value template <typename T> T* crt_reallocate_impl(T* p, size_t old_size, size_t new_size, const void* hint, true_type) { return reinterpret_cast<T*>(safe_realloc(p, new_size * sizeof(T))); } // !is_relocatable<T>::value template <typename T> T* crt_reallocate_impl(T* p, size_t old_size, size_t new_size, const void* hint, false_type) { T* ptr = reinterpret_cast<T*>(crt_allocator_base::allocate(new_size, sizeof(T), hint)); // use placement new to construct-in-place // Don't use `move`, since that move assigns into // uninitialized memory. for (size_t i = 0; i < old_size; ++i) { T& src = p[i]; T* dst = &ptr[i]; new (static_cast<void*>(dst)) T(move(src)); } crt_allocator_base::deallocate(p, old_size * sizeof(T)); return ptr; } // OBJECTS // ------- /** * \brief Standard memory allocator. */ template <typename T> struct crt_allocator: private crt_allocator_base { // MEMBER TYPES // ------------ using self_t = crt_allocator<T>; using value_type = T; #if defined(CPP11_PARTIAL_ALLOCATOR_TRAITS) using reference = value_type&; using const_reference = const value_type&; using pointer = value_type*; using const_pointer = const value_type*; using size_type = size_t; using difference_type = ptrdiff_t; template <typename U> struct rebind { using other = crt_allocator<U>; }; #endif // CPP11_PARTIAL_ALLOCATOR_TRAITS // MEMBER FUNCTIONS // ---------------- // CONSTRUCTORS crt_allocator() noexcept = default; crt_allocator(const self_t&) noexcept = default; self_t& operator=(const self_t&) noexcept = default; ~crt_allocator() = default; template <typename U> crt_allocator(const crt_allocator<U>&) noexcept {} template <typename U> self_t& operator=(const crt_allocator<U>&) noexcept { return *this; } // ALLOCATOR TRAITS value_type* allocate(size_t n, const void* hint = nullptr) { return reinterpret_cast<value_type*>(crt_allocator_base::allocate(n, sizeof(value_type), hint)); } value_type* reallocate(value_type* p, size_t old_size, size_t new_size, const void* hint = nullptr) { return reinterpret_cast<value_type*>(crt_reallocate_impl(p, old_size, new_size, hint, is_relocatable<T> {})); } void deallocate(value_type* p, size_t n) { crt_allocator_base::deallocate(p, sizeof(value_type) * n); } #if defined(CPP11_PARTIAL_ALLOCATOR_TRAITS) template <typename ... Ts> void construct(T* p, Ts&&... ts) { ::new (static_cast<void*>(p)) T(std::forward<Ts>(ts)...); } void destroy(T* p) { p->~T(); } size_type max_size() { return std::numeric_limits<size_type>::max(); } #endif // CPP11_PARTIAL_ALLOCATOR_TRAITS }; // ALIAS // ----- using crt_resource = resource_adaptor<crt_allocator<byte>>; // SPECIALIZATION // -------------- template <typename T> struct is_relocatable<crt_allocator<T>>: true_type {}; // NON-MEMBER FUNCTIONS // -------------------- template <typename T, typename U> inline bool operator==(const crt_allocator<T>&, const crt_allocator<U>&) noexcept { return true; } template <typename T, typename U> inline bool operator!=(const crt_allocator<T>& lhs, const crt_allocator<U>& rhs) noexcept { return !(lhs == rhs); } PYCPP_END_NAMESPACE
Yuunagi-Yu/NumberDisk
Project/Temp/StagingArea/Data/il2cppOutput/Mono_Security_Mono_Security_Protocol_Tls_Certificat989458295MethodDeclarations.h
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #include <assert.h> #include <exception> // Mono.Security.Protocol.Tls.CertificateValidationCallback struct CertificateValidationCallback_t989458295; // System.Object struct Il2CppObject; // System.Security.Cryptography.X509Certificates.X509Certificate struct X509Certificate_t283079845; // System.Int32[] struct Int32U5BU5D_t3030399641; // System.IAsyncResult struct IAsyncResult_t1999651008; // System.AsyncCallback struct AsyncCallback_t163412349; #include "codegen/il2cpp-codegen.h" #include "mscorlib_System_Object2689449295.h" #include "mscorlib_System_IntPtr2504060609.h" #include "mscorlib_System_Security_Cryptography_X509Certifica283079845.h" #include "mscorlib_System_AsyncCallback163412349.h" // System.Void Mono.Security.Protocol.Tls.CertificateValidationCallback::.ctor(System.Object,System.IntPtr) extern "C" void CertificateValidationCallback__ctor_m1298586051 (CertificateValidationCallback_t989458295 * __this, Il2CppObject * ___object0, IntPtr_t ___method1, const MethodInfo* method) IL2CPP_METHOD_ATTR; // System.Boolean Mono.Security.Protocol.Tls.CertificateValidationCallback::Invoke(System.Security.Cryptography.X509Certificates.X509Certificate,System.Int32[]) extern "C" bool CertificateValidationCallback_Invoke_m2500463874 (CertificateValidationCallback_t989458295 * __this, X509Certificate_t283079845 * ___certificate0, Int32U5BU5D_t3030399641* ___certificateErrors1, const MethodInfo* method) IL2CPP_METHOD_ATTR; // System.IAsyncResult Mono.Security.Protocol.Tls.CertificateValidationCallback::BeginInvoke(System.Security.Cryptography.X509Certificates.X509Certificate,System.Int32[],System.AsyncCallback,System.Object) extern "C" Il2CppObject * CertificateValidationCallback_BeginInvoke_m3625803269 (CertificateValidationCallback_t989458295 * __this, X509Certificate_t283079845 * ___certificate0, Int32U5BU5D_t3030399641* ___certificateErrors1, AsyncCallback_t163412349 * ___callback2, Il2CppObject * ___object3, const MethodInfo* method) IL2CPP_METHOD_ATTR; // System.Boolean Mono.Security.Protocol.Tls.CertificateValidationCallback::EndInvoke(System.IAsyncResult) extern "C" bool CertificateValidationCallback_EndInvoke_m2418808873 (CertificateValidationCallback_t989458295 * __this, Il2CppObject * ___result0, const MethodInfo* method) IL2CPP_METHOD_ATTR;
cheehieu/laser-stranger
software/firmware_nrf52/nRF5_SDK_15.0.0_a53641a/components/drivers_ext/elliegrid/ble_egs/ble_egs.h
<filename>software/firmware_nrf52/nRF5_SDK_15.0.0_a53641a/components/drivers_ext/elliegrid/ble_egs/ble_egs.h #ifndef BLE_EGS_H__ #define BLE_EGS_H__ #include <stdint.h> #include <stdbool.h> #include "ble.h" #include "ble_srv_common.h" #include "nrf_sdh_ble.h" #ifdef __cplusplus extern "C" { #endif /**@brief Macro for defining a ble_egs instance. * * @param _name Name of the instance. * @hideinitializer */ #define BLE_EGS_DEF(_name) \ ble_egs_t _name; \ NRF_SDH_BLE_OBSERVER(_name ## _obs, \ BLE_EGS_BLE_OBSERVER_PRIO, \ ble_egs_on_ble_evt, &_name) #define EGS_UUID_BASE {0x51, 0xBB, 0x06, 0x63, 0x51, 0x0B, 0xF4, 0x9A, \ 0x29, 0x4C, 0x40, 0xD4, 0x00, 0x00, 0x1E, 0xE1} #define EGS_UUID_SERVICE 0x0001 #define EGS_UUID_COMP_LED_CHAR 0x0002 #define EGS_UUID_STATUS_CHAR 0x0003 //global variable state for PGn, MAGn, CAPn, other interrupts, haptic enable, #define COMMAND_LEDS 0x1 #define COMMAND_SELECT_LEDS 0x2 #define COMMAND_AUDIO 0x3 #define COMMAND_AUDIO_NO_VOL_CHG 0x4 #define COMMAND_EASTER_EGG 0x5 #define COMMAND_ALARM_TRIGGER 0x6 #define COMMAND_ALARM_TAKEN 0x7 #define COMMAND_ALARM_SKIPPED 0x8 #define COMMAND_ALARM_MISSED 0x9 #define COMMAND_PILLBOX_STATE 0xA #define COMMAND_ALARM_SILENCED 0xB #define COMMAND_RICK 0x5249434B //'RICK' <--> 0x4B434952 #define COMMAND_LEDS_RAINBOW 0x50000001 #define COMMAND_LEDS_RAINBOW_CYCLE 0x50000002 #define COMMAND_LEDS_THEATER_CHASE 0x50000003 #define COMMAND_LEDS_THEATER_CHASE_RAINBOW 0x50000004 // STATUS NOTIFICATION (byte) = 0b0000-0-CHARGING-LID-BTN #define STATUS_BTN_PRESSED_MASK 0x01 #define STATUS_LID_OPEN_MASK 0x02 #define STATUS_CHARGING_MASK 0x04 // Forward declaration of the ble_egs_t type. typedef struct ble_egs_s ble_egs_t; typedef void (*ble_egs_led_write_handler_t) (uint16_t conn_handle, ble_egs_t * p_egs, uint8_t new_state); typedef void (*ble_egs_comp_led_write_handler_t)(uint16_t conn_handle, ble_egs_t *p_egs, uint32_t new_state); /** @brief LED Button Service init structure. This structure contains all options and data needed for * initialization of the service.*/ typedef struct { ble_egs_led_write_handler_t led_write_handler; /**< Event handler to be called when the LED Characteristic is written. */ ble_egs_comp_led_write_handler_t comp_led_write_handler; } ble_egs_init_t; /**@brief LED Button Service structure. This structure contains various status information for the service. */ struct ble_egs_s { uint16_t service_handle; /**< Handle of LED Button Service (as provided by the BLE stack). */ ble_gatts_char_handles_t led_char_handles; /**< Handles related to the LED Characteristic. */ ble_gatts_char_handles_t button_char_handles; /**< Handles related to the Button Characteristic. */ ble_gatts_char_handles_t comp_led_char_handles; uint8_t uuid_type; /**< UUID type for the LED Button Service. */ ble_egs_led_write_handler_t led_write_handler; /**< Event handler to be called when the LED Characteristic is written. */ ble_egs_comp_led_write_handler_t comp_led_write_handler; }; /**@brief Function for initializing the LED Button Service. * * @param[out] p_egs LED Button Service structure. This structure must be supplied by * the application. It is initialized by this function and will later * be used to identify this particular service instance. * @param[in] p_egs_init Information needed to initialize the service. * * @retval NRF_SUCCESS If the service was initialized successfully. Otherwise, an error code is returned. */ uint32_t ble_egs_init(ble_egs_t * p_egs, const ble_egs_init_t * p_egs_init); /**@brief Function for handling the application's BLE stack events. * * @details This function handles all events from the BLE stack that are of interest to the LED Button Service. * * @param[in] p_ble_evt Event received from the BLE stack. * @param[in] p_context LED Button Service structure. */ void ble_egs_on_ble_evt(ble_evt_t const * p_ble_evt, void * p_context); /**@brief Function for sending a button state notification. * ' @param[in] conn_handle Handle of the peripheral connection to which the button state notification will be sent. * @param[in] p_egs LED Button Service structure. * @param[in] button_state New button state. * * @retval NRF_SUCCESS If the notification was sent successfully. Otherwise, an error code is returned. */ uint32_t ble_egs_on_button_change(uint16_t conn_handle, ble_egs_t * p_egs, uint8_t button_state); #ifdef __cplusplus } #endif #endif // BLE_EGS_H__ /** @} */
kbiesiadecki141/roscfe
cfs_converter/relay_base/relay_app_base/fsw/src/convert/tf/LinearMath/MinMax.h
<reponame>kbiesiadecki141/roscfe /* ** ** Copyright (c) 2020 Japan Aerospace Exploration Agency. ** All Rights Reserved. ** ** This file is covered by the LICENSE.txt in the root of this project. ** */ #ifndef MIN_MAX_H #define MIN_MAX_H #include "cfe.h" template <class T> TFSIMD_FORCE_INLINE const T &tfMin(const T &a, const T &b) { return a < b ? a : b; } template <class T> TFSIMD_FORCE_INLINE const T &tfMax(const T &a, const T &b) { return a > b ? a : b; } template <class T> TFSIMD_FORCE_INLINE void tfSetMin(T &a, const T &b) { if (b < a) { a = b; } } template <class T> TFSIMD_FORCE_INLINE void tfSetMax(T &a, const T &b) { if (a < b) { a = b; } } #endif // MIN_MAX_H
laoxiaoo/learning
flowable/src/test/java/com/xiao/Test.java
package com.xiao; import com.greenpineyu.fel.FelEngine; import com.greenpineyu.fel.FelEngineImpl; import com.greenpineyu.fel.context.FelContext; /** * @author 肖杰 * @version 1. * @ClassName Test.java * @Description TODO * @createTime 2021年01月22日 14:34:00 */ public class Test { @org.junit.Test public void test2() { //测试SpringEL解析器 //String template = "#{#user}";//设置文字模板,其中#{}表示表达式的起止,#user是表达式字符串,表示引用一个变量。 String template= "#{#user}"; FelEngine fel = new FelEngineImpl(); FelContext ctx = fel.getContext(); ctx.set("单价", 1.5898); ctx.set("数量", 1); ctx.set("运费", 75); ctx.set("a1", 1); ctx.set("a2", 2); Object result = fel.eval("a1*"); System.out.println(result); } }
janniclas/phasar
test/llvm_test_code/constness/global/global_05.cpp
/* g, i | @g, %1 (ID: 0, 4) | mem2reg */ int *g; void foo() { *g = 99; } int main() { int i = 42; g = &i; foo(); return 0; }
richtermark/smeagonline
web/bundles/topxiaadmin/js/controller/open-course-analysis/referer.js
<filename>web/bundles/topxiaadmin/js/controller/open-course-analysis/referer.js define(function(require, exports, module) { require('echarts'); var EchartsConfig = require('./pie-charts-config'); exports.run = function() { var myChart = echarts.init(document.getElementById('echats-pie')); var config = new EchartsConfig(); myChart.setOption(config.option()); var triggerAction = function(action, selected) { legend = []; for (name in selected) { if (selected.hasOwnProperty(name)) { legend.push({ name: name }); } } myChart.dispatchAction({ type: action, batch: legend }); }; myChart.on('legendselectchanged', function(obj) { triggerAction('legendSelect', obj.selected); }); } });
copslock/o-ran_o-du_l2
src/du_app/du_msg_hdl.c
<filename>src/du_app/du_msg_hdl.c<gh_stars>0 /******************************************************************************* ################################################################################ # Copyright (c) [2017-2019] [Radisys] # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # ################################################################################ *******************************************************************************/ /* This file contains message handling functionality for DU cell management */ #include "du_sctp.h" #include "f1ap_msg_hdl.h" U8 rlcDlCfg = 0; U8 numRlcDlSaps = 0; U8 rlcUlCfg = 0; U8 numRlcMacSaps = 0; U8 macCfg = 0; U8 macCfgInst = 0; extern S16 cmPkLkwCfgReq(Pst *pst, KwMngmt *cfg); extern S16 cmPkLkwCntrlReq(Pst *pst, KwMngmt *cfg); extern S16 cmPkLrgCfgReq(Pst *pst, RgMngmt *cfg); /************************************************************************** * @brief Function to fill configs required by RLC * * @details * * Function : duBuildRlcCfg * * Functionality: * Initiates general Configs towards RLC * * @param[in] Inst Specifies if RLC UL or RLC DL instance * @return ROK - success * RFAILED - failure * ***************************************************************************/ S16 duBuildRlcCfg(Inst inst) { KwMngmt kwMngmt; KwGenCfg *genCfg = NULLP; Pst pst; DU_SET_ZERO(&kwMngmt, sizeof(KwMngmt)); DU_SET_ZERO(&pst, sizeof(Pst)); genCfg = &(kwMngmt.t.cfg.s.gen); /*----------- Fill General Configuration Parameters ---------*/ genCfg->maxUe = duCfgParam.maxUe; genCfg->maxKwuSaps = 2; genCfg->maxUdxSaps = 1; genCfg->rlcMode = (inst == RLC_UL_INST) ? LKW_RLC_MODE_UL : LKW_RLC_MODE_DL; genCfg->timeRes = 1; genCfg->maxRguSaps = DEFAULT_CELLS; /*----------- Fill lmPst * Parameters ---------*/ genCfg->lmPst.dstProcId = DU_PROC; genCfg->lmPst.srcProcId = DU_PROC; genCfg->lmPst.dstEnt = ENTDUAPP; genCfg->lmPst.dstInst = DU_INST; genCfg->lmPst.srcEnt = ENTKW; genCfg->lmPst.srcInst = inst; genCfg->lmPst.prior = PRIOR0; genCfg->lmPst.route = RTESPEC; genCfg->lmPst.region = (inst == RLC_UL_INST) ? RLC_UL_MEM_REGION:RLC_DL_MEM_REGION; genCfg->lmPst.pool = RLC_POOL; genCfg->lmPst.selector = DU_SELECTOR_LC; /* Fill Header */ kwMngmt.hdr.msgType = TCFG; kwMngmt.hdr.msgLen = 0; kwMngmt.hdr.entId.ent = ENTKW; kwMngmt.hdr.entId.inst = (Inst)0; kwMngmt.hdr.elmId.elmnt = STGEN; kwMngmt.hdr.seqNmb = 0; kwMngmt.hdr.version = 0; kwMngmt.hdr.transId = 0; kwMngmt.hdr.response.prior = PRIOR0; kwMngmt.hdr.response.route = RTESPEC; kwMngmt.hdr.response.mem.region = (inst == RLC_UL_INST) ? RLC_UL_MEM_REGION:RLC_DL_MEM_REGION; kwMngmt.hdr.response.mem.pool = DU_POOL; kwMngmt.hdr.response.selector = DU_SELECTOR_LC; /* Fill Pst */ pst.selector = DU_SELECTOR_LC; pst.srcEnt = ENTDUAPP; pst.dstEnt = ENTKW; pst.dstInst = inst; pst.dstProcId = DU_PROC; pst.srcProcId = DU_PROC; pst.region = duCb.init.region; printf("\nRLC Gen Cfg Req sent for inst %d", inst); /* Send the request to RLC */ cmPkLkwCfgReq(&pst, &kwMngmt); return ROK; } /************************************************************************** * @brief Function to fill configs required by RLC * * @details * * Function : duBuildRlcLsapCfg * * Functionality: * Initiates general Configs towards RLC * * @param[in] Inst Specifies if RLC UL or RLC DL instance * @return ROK - success * RFAILED - failure * ***************************************************************************/ S16 duBuildRlcLsapCfg(Ent ent, Inst inst, U8 lsapInst) { KwMngmt kwMngmt; KwSapCfg *lSap = NULLP; Pst pst; DU_SET_ZERO(&kwMngmt, sizeof(KwMngmt)); DU_SET_ZERO(&pst, sizeof(Pst)); /* Fill Header */ kwMngmt.hdr.msgType = TCFG; kwMngmt.hdr.entId.ent = ENTKW; kwMngmt.hdr.response.mem.region = (inst == RLC_UL_INST) ? RLC_UL_MEM_REGION:RLC_DL_MEM_REGION; kwMngmt.hdr.response.mem.pool = RLC_POOL; /* Fill Pst */ pst.selector = DU_SELECTOR_LC; pst.srcEnt = ENTDUAPP; pst.dstEnt = ENTKW; pst.dstProcId = DU_PROC; pst.dstInst = inst; pst.srcProcId = DU_PROC; pst.region = duCb.init.region; lSap = &(kwMngmt.t.cfg.s.sap); lSap->mem.region = (inst == RLC_UL_INST) ? RLC_UL_MEM_REGION:RLC_DL_MEM_REGION; lSap->mem.pool = RLC_POOL; lSap->mem.spare = 0; lSap->bndTmrIntvl = 10; lSap->priority = PRIOR0; lSap->route = RTESPEC; if (ent == ENTRG) { lSap->procId = DU_PROC; lSap->ent = ENTRG; lSap->inst = lsapInst; lSap->sapId = lsapInst; /* SapId will be stored as suId in MAC */ lSap->selector = (inst == RLC_UL_INST) ? DU_SELECTOR_LWLC : DU_SELECTOR_TC; kwMngmt.hdr.elmId.elmnt = STRGUSAP; printf("\nRLC MAC Lower Sap Cfg Req sent for inst %d", inst); } else { lSap->procId = DU_PROC; lSap->ent = ENTKW; lSap->inst = (inst == RLC_UL_INST) ? RLC_DL_INST : RLC_UL_INST; lSap->sapId = 0; lSap->selector = DU_SELECTOR_LC; kwMngmt.hdr.elmId.elmnt = STUDXSAP; printf("\nRLC DL/UL Lower Sap Cfg Req sent for inst %d", inst); } cmPkLkwCfgReq(&pst, &kwMngmt); return ROK; } /************************************************************************** * @brief Function to fill configs required by RLC * * @details * * Function : duBuildRlcUsapCfg * * Functionality: * Initiates general Configs towards RLC * * @param[in] Inst Specifies if RLC UL or RLC DL instance * @return ROK - success * RFAILED - failure * ***************************************************************************/ S16 duBuildRlcUsapCfg(U8 elemId, Ent ent, Inst inst) { KwMngmt kwMngmt; KwSapCfg *uSap = NULLP; Pst pst; DU_SET_ZERO(&kwMngmt, sizeof(KwMngmt)); DU_SET_ZERO(&pst, sizeof(Pst)); uSap = &(kwMngmt.t.cfg.s.sap); uSap->selector = DU_SELECTOR_LC; uSap->mem.region = (inst == RLC_UL_INST) ? RLC_UL_MEM_REGION:RLC_DL_MEM_REGION; uSap->mem.pool = RLC_POOL; uSap->mem.spare = 0; uSap->procId = DU_PROC; uSap->ent = ENTKW; uSap->sapId = 0; uSap->inst = (inst == RLC_UL_INST) ? RLC_DL_INST : RLC_UL_INST; uSap->bndTmrIntvl = 1000; uSap->priority = PRIOR0; uSap->route = RTESPEC; /* Fill Header */ kwMngmt.hdr.msgType = TCFG; kwMngmt.hdr.entId.ent = ENTKW; kwMngmt.hdr.elmId.elmnt = STUDXSAP; kwMngmt.hdr.response.mem.region = (inst == RLC_UL_INST) ? RLC_UL_MEM_REGION:RLC_DL_MEM_REGION; kwMngmt.hdr.response.mem.pool = RLC_POOL; /* Fill Pst */ pst.selector = DU_SELECTOR_LC; pst.srcEnt = ENTDUAPP; pst.dstEnt = ENTKW; pst.dstProcId = DU_PROC; pst.dstInst = inst; pst.srcProcId = DU_PROC; pst.region = duCb.init.region; printf("\nRLC Kwu Upper Sap Cfg Req sent for inst %d", inst); cmPkLkwCfgReq(&pst, &kwMngmt); return ROK; } /************************************************************************** * @brief Function to invoke DU Layer Configs * * @details * * Function : duSendRlcUlCfg * * Functionality: * Initiates Configs towards layers of DU * * @param[in] void * @return ROK - success * RFAILED - failure * ***************************************************************************/ S16 duSendRlcUlCfg() { U8 cellIdx; duBuildRlcCfg((Inst)RLC_UL_INST); for(cellIdx = 0; cellIdx < DEFAULT_CELLS; cellIdx++) { duBuildRlcLsapCfg(ENTRG, (Inst)RLC_UL_INST, cellIdx); } duBuildRlcLsapCfg(ENTKW, (Inst)RLC_UL_INST, 0); return ROK; } /************************************************************************** * @brief Function to invoke DU Layer Configs * * @details * * Function : duSendRlcDlCfg * * Functionality: * Initiates Configs towards layers of DU * * @param[in] void * @return ROK - success * RFAILED - failure * ***************************************************************************/ S16 duSendRlcDlCfg() { U8 cellIdx; duBuildRlcCfg((Inst)RLC_DL_INST); duBuildRlcUsapCfg(STUDXSAP, ENTKW, (Inst)RLC_DL_INST); for(cellIdx = 0; cellIdx < DEFAULT_CELLS; cellIdx++) { duBuildRlcLsapCfg(ENTRG, (Inst)RLC_DL_INST, cellIdx); } return ROK; } /************************************************************************** * @brief Function to handle Config Confirm from RLC * * @details * * Function : duHdlRlcCfgComplete * * Functionality: * Handles Gen Config Confirm from RLC * * @param[in] Pst *pst, Post structure of the primitive. * @param[in] KwMngmt *cfm, Unpacked primitive info received from RLC * @return ROK - success * RFAILED - failure * ***************************************************************************/ S16 duHdlRlcCfgComplete(Pst *pst, KwMngmt *cfm) { S16 ret = ROK; if (pst->srcInst == RLC_UL_INST) { ret = duProcRlcUlCfgComplete(pst, cfm); } else { ret = duProcRlcDlCfgComplete(pst, cfm); } return ret; } /************************************************************************** * @brief Function to handle Control Config Confirm from RLC * * @details * * Function : duHdlRlcCntrlCfgComplete * * Functionality: * Handles Control Config Confirm from RLC * * @param[in] Pst *pst, Post structure of the primitive. * @param[in] KwMngmt *cfm, Unpacked primitive info received from RLC * @return ROK - success * RFAILED - failure * ***************************************************************************/ S16 duHdlRlcCntrlCfgComplete(Pst *pst, KwMngmt *cntrl) { S16 ret = ROK; if (cntrl->cfm.status == LCM_PRIM_OK) { switch (cntrl->hdr.elmId.elmnt) { case STRGUSAP: { if (pst->srcInst == RLC_DL_INST) { printf("\nBIND OF RLC DL TO MAC (RGU) SAP SUCCESSFUL"); macCfgInst++; if(macCfgInst < DEFAULT_CELLS) { macCfgInst = 0; duBindUnbindRlcToMacSap((Inst) RLC_DL_INST, ABND); } else { duBindUnbindRlcToMacSap((Inst) RLC_UL_INST, ABND); } } else { printf("\nBIND OF RLC UL TO MAC (RGU) SAP SUCCESSFUL"); macCfgInst++; if(macCfgInst < DEFAULT_CELLS) { duBindUnbindRlcToMacSap((Inst) RLC_UL_INST, ABND); } else { duSctpStartReq(); } break; } } } } return ret; } /************************************************************************** * @brief Function to handle Config Confirm from RLC UL * * @details * * Function : duHdlRlcUlCfgComplete * * Functionality: * Handles Config Confirm from RLC UL * * @param[in] Pst *pst, Post structure of the primitive. * @param[in] KwMngmt *cfm, Unpacked primitive info received from RLC UL * @return ROK - success * RFAILED - failure * ***************************************************************************/ S16 duProcRlcUlCfgComplete(Pst *pst, KwMngmt *cfm) { S16 ret; printf("\nRLC UL Cfg Status %d", cfm->cfm.status); if (cfm->cfm.status == LCM_PRIM_OK) { switch(cfm->hdr.elmId.elmnt) { case STGEN: { rlcUlCfg |= RLC_GEN_CFG; break; } case STRGUSAP: { numRlcMacSaps++; if(numRlcMacSaps == DEFAULT_CELLS) { rlcUlCfg |= RLC_MAC_SAP_CFG; numRlcMacSaps = 0; } break; } case STUDXSAP: { rlcUlCfg |= RLC_UDX_SAP_CFG; break; } default: break; } printf("\n RLC UL Cfg Cfm received for the element %d ",cfm->hdr.elmId.elmnt); if(rlcUlCfg == DU_RLC_UL_CONFIGURED) { rlcUlCfg = 0; numRlcMacSaps = 0; //Start configuration of RLC DL duSendRlcDlCfg(); } } else { printf("\nConfig confirm NOK from RLC UL"); ret = RFAILED; } return ret; } /************************************************************************** * @brief Function to handle Config Confirm from RLC DL * * @details * * Function : duHdlRlcDlCfgComplete * * Functionality: * Handles Config Confirm from RLC DL * * @param[in] Pst *pst, Post structure of the primitive. * @param[in] KwMngmt *cfm, Unpacked primitive info received from RLC DL * @return ROK - success * RFAILED - failure * ***************************************************************************/ S16 duProcRlcDlCfgComplete(Pst *pst, KwMngmt *cfm) { printf("\nRLC DL Cfg Status %d", cfm->cfm.status); if (cfm->cfm.status == LCM_PRIM_OK) { switch(cfm->hdr.elmId.elmnt) { case STGEN: { rlcDlCfg |= RLC_GEN_CFG; break; } case STRGUSAP: { numRlcMacSaps++; if(numRlcMacSaps == DEFAULT_CELLS) { rlcDlCfg |= RLC_MAC_SAP_CFG; numRlcMacSaps = 0; } break; } case STUDXSAP: { rlcDlCfg |= RLC_UDX_SAP_CFG; break; } default: break; } printf("\n RLC DL Cfg Cfm received for the element %d ",cfm->hdr.elmId.elmnt); if(rlcDlCfg == DU_RLC_DL_CONFIGURED) { rlcDlCfg = 0; //Start configuration of MAC duSendMacCfg(); } } else { printf("\nConfig confirm NOK from RLC DL"); } return ROK; } /************************************************************************** * @brief Function to send configs to MAC * * @details * * Function : duSendMacCfg * * Functionality: * Initiates Configs towards MAC layer * * @param[in] void * @return ROK - success * RFAILED - failure * ***************************************************************************/ S16 duSendMacCfg() { duBuildMacGenCfg(); duBuildMacUsapCfg(RLC_UL_INST); duBuildMacUsapCfg(RLC_DL_INST); return ROK; } /************************************************************************** * @brief Function to fill gen config required by MAC * * @details * * Function : duBuildMacGenCfg * * Functionality: * Initiates general Configs towards MAC * * @param[in] void * @return ROK - success * RFAILED - failure * ***************************************************************************/ S16 duBuildMacGenCfg() { RgMngmt rgMngmt; RgGenCfg *genCfg=NULLP; Pst pst; DU_SET_ZERO(&pst, sizeof(Pst)); DU_SET_ZERO(&rgMngmt, sizeof(RgMngmt)); genCfg = &(rgMngmt.t.cfg.s.genCfg); /*----------- Fill General Configuration Parameters ---------*/ genCfg->mem.region = RG_MEM_REGION; genCfg->mem.pool = RG_POOL; genCfg->tmrRes = 10; genCfg->numRguSaps = 2; genCfg->lmPst.dstProcId = DU_PROC; genCfg->lmPst.srcProcId = DU_PROC; genCfg->lmPst.dstEnt = ENTDUAPP; genCfg->lmPst.dstInst = 0; genCfg->lmPst.srcEnt = ENTRG; genCfg->lmPst.srcInst = macCfgInst; genCfg->lmPst.prior = PRIOR0; genCfg->lmPst.route = RTESPEC; genCfg->lmPst.region = RG_MEM_REGION; genCfg->lmPst.pool = RG_POOL; genCfg->lmPst.selector = DU_SELECTOR_LC; /* Fill Header */ rgMngmt.hdr.msgType = TCFG; rgMngmt.hdr.msgLen = 0; rgMngmt.hdr.entId.ent = ENTRG; rgMngmt.hdr.entId.inst = (Inst)0; rgMngmt.hdr.elmId.elmnt = STGEN; rgMngmt.hdr.seqNmb = 0; rgMngmt.hdr.version = 0; rgMngmt.hdr.transId = 0; rgMngmt.hdr.response.prior = PRIOR0; rgMngmt.hdr.response.route = RTESPEC; rgMngmt.hdr.response.mem.region = RG_MEM_REGION; rgMngmt.hdr.response.mem.pool = RG_POOL; rgMngmt.hdr.response.selector = DU_SELECTOR_LC; /* Fill Pst */ pst.selector = DU_SELECTOR_LC; pst.srcEnt = ENTDUAPP; pst.dstEnt = ENTRG; pst.dstInst = macCfgInst; pst.dstProcId = DU_PROC; pst.srcProcId = DU_PROC; pst.region = duCb.init.region; printf("\nMAC Gen Cfg Req sent"); /* Send the request to MAC */ cmPkLrgCfgReq(&pst, &rgMngmt); return ROK; } /************************************************************************** * @brief Function to fill USAP config required by MAC * * @details * * Function : duBuildMacUsapCfg * * Functionality: * Initiates USAP Configs towards MAC * * @param[in] SpId Specifies if RLC UL or RLC DL instance * @return ROK - success * RFAILED - failure * ***************************************************************************/ S16 duBuildMacUsapCfg(SpId sapId) { RgMngmt rgMngmt; RgUpSapCfg *uSap = NULLP; Pst pst; DU_SET_ZERO(&pst, sizeof(Pst)); DU_SET_ZERO(&rgMngmt, sizeof(RgMngmt)); uSap = &(rgMngmt.t.cfg.s.rguSap); uSap->mem.region = RG_MEM_REGION; uSap->mem.pool = RG_POOL; uSap->suId = 0; uSap->spId = sapId; uSap->procId = DU_PROC; uSap->ent = ENTKW; uSap->inst = sapId; uSap->prior = PRIOR0; uSap->route = RTESPEC; uSap->selector = DU_SELECTOR_LC ; /* fill header */ rgMngmt.hdr.msgType = TCFG; rgMngmt.hdr.entId.ent = ENTRG; rgMngmt.hdr.entId.inst = (Inst)0; rgMngmt.hdr.elmId.elmnt = STRGUSAP; rgMngmt.hdr.response.mem.region = RG_MEM_REGION; rgMngmt.hdr.response.mem.pool = RG_POOL; /* fill pst */ pst.selector = DU_SELECTOR_LC; pst.srcEnt = ENTDUAPP; pst.dstEnt = ENTRG; pst.dstInst = macCfgInst; pst.dstProcId = DU_PROC; pst.srcProcId = DU_PROC; pst.region = duCb.init.region; printf("\nMAC Rgu USap Cfg Req sent"); /* Send the request to MAC */ cmPkLrgCfgReq(&pst, &rgMngmt); return ROK; } /************************************************************************** * @brief Function to handle Config Confirm from MAC * * @details * * Function : duHdlMacCfgComplete * * Functionality: * Handles Gen Config Confirm from MAC * * @param[in] Pst *pst, Post structure of the primitive. * @param[in] RgMngmt *cfm, Unpacked primitive info received from MAC * @return ROK - success * RFAILED - failure * ***************************************************************************/ S16 duHdlMacCfgComplete(Pst *pst, RgMngmt *cfm) { S16 ret = ROK; if (cfm->cfm.status == LCM_PRIM_OK) { switch (cfm->hdr.elmId.elmnt) { case STGEN: { macCfg |= MAC_GEN_CFG; break; } case STRGUSAP: { macCfg |= MAC_SAP_CFG; numRlcMacSaps++; break; } default: break; } printf("\n MAC Cfg Cfm received for the element %d ",cfm->hdr.elmId.elmnt); if(macCfg == MAC_CONFIGURED && numRlcMacSaps == MAX_MAC_SAP) { macCfg = 0; printf("\n Completed sending Configs"); macCfgInst = 0; duBindUnbindRlcToMacSap(RLC_DL_INST, ABND); } } else { printf("\nConfig confirm NOK from MAC"); ret = RFAILED; } return ret; } /************************************************************************** * @brief Function to bind/unbind RLC to MAC SAP * * @details * * Function : duBindUnbindRlcToMacSap * * Functionality: * Initiates Bind/Unbind from RLC to MAC * * @param[in] Inst Specifies if RLC UL or RLC DL instance * @param[in] action Specifies if action is bind or unbind * @return ROK - success * RFAILED - failure * ***************************************************************************/ S16 duBindUnbindRlcToMacSap(U8 inst, U8 action) { KwCntrl *cntrl = NULLP; KwMngmt kwMngmt; Pst pst; TRC2(smBindKwToRguSap) DU_SET_ZERO(&kwMngmt, sizeof(KwMngmt)); DU_SET_ZERO(&pst, sizeof(Pst)); if (action == ABND) { printf("\nCntrl Req to RLC inst %d to bind MAC sap", inst); } else { printf("\nCntrl Req to RLC inst %d to unbind MAC sap", inst); } cntrl = &(kwMngmt.t.cntrl); cntrl->action = action; cntrl->subAction = DU_ZERO_VAL; cntrl->s.sapCntrl.suId = macCfgInst; cntrl->s.sapCntrl.spId = inst; /* Fill header */ kwMngmt.hdr.msgType = TCNTRL; kwMngmt.hdr.entId.ent = ENTKW; kwMngmt.hdr.entId.inst = inst; kwMngmt.hdr.elmId.elmnt = 186; /* ambiguous defines in lkw.h and lrg.h so direct hardcoded*/ kwMngmt.hdr.response.mem.region = (inst == RLC_UL_INST) ? RLC_UL_MEM_REGION:RLC_DL_MEM_REGION; kwMngmt.hdr.response.mem.pool = RLC_POOL; /* Fill pst */ pst.selector = DU_SELECTOR_LC; pst.srcEnt = ENTDUAPP; pst.dstEnt = ENTKW; pst.dstProcId = DU_PROC; pst.dstInst = inst; pst.srcProcId = DU_PROC; pst.region = duCb.init.region; cmPkLkwCntrlReq(&pst, &kwMngmt); return ROK; } /******************************************************************* * * @brief Function to start SCTP * * @details * * Function : duSctpStartReq * * Functionality: * Function to start SCTP * * @params[in] * @return void * * ****************************************************************/ S16 duSctpStartReq() { Pst pst; Buffer *mBuf; cmMemset((U8 *)&(pst), 0, sizeof(Pst)); pst.srcEnt = (Ent)ENTDUAPP; pst.srcInst = (Inst)DU_INST; pst.srcProcId = DU_PROC; pst.dstEnt = (Ent)ENTSCTP; pst.dstInst = (Inst)SCTP_INST; pst.dstProcId = pst.srcProcId; pst.event = EVTSCTPSTRT; pst.selector = DU_SELECTOR_LC; pst.pool= DU_POOL; if(SGetMsg(DFLT_REGION, DU_POOL, &mBuf) != ROK) { printf("\nMemory allocation failed in duReadCfg"); return RFAILED; } SPstTsk(&pst, mBuf); RETVALUE(ROK); } /******************************************************************* * * @brief Handles SCTP notifications * * @details * * Function : duSctpNtfyHdl * * Functionality: * Handles SCTP notification * * @params[in] Message Buffer * SCTP notification * * @return ROK - success * RFAILED - failure * * ****************************************************************/ S16 duSctpNtfyHdl(Buffer *mBuf, CmInetSctpNotification *ntfy) { char *finalBuf; int i,j; switch(ntfy->header.nType) { case CM_INET_SCTP_ASSOC_CHANGE: switch(ntfy->u.assocChange.state) { case CM_INET_SCTP_COMM_UP: { printf("\nSCTP communication UP"); duCb.sctpStatus = TRUE; //Setup F1-C if(!duCb.f1Status) { /* Build and send F1 Setup response */ Buffer *f1SetupReq; MsgLen copyCnt; BuildF1SetupReq(); /* Reversing the encoded string */ if(SGetSBuf(1, 1, (Data **)&finalBuf, (Size)encBufSize) != ROK) { printf("Memory allocation failed"); RETVALUE(RFAILED); } for(i = 0, j = encBufSize-1; i<encBufSize; i++, j--) { finalBuf[j] = encBuf[i]; } if(SGetMsg(1, 1, &f1SetupReq) == ROK) { if(SCpyFixMsg((Data *)finalBuf, f1SetupReq, 0, encBufSize, &copyCnt) == ROK) { printf("\nSending F1 setup request"); SPrntMsg(f1SetupReq, 0,0); if(sctpOutMsgSend(f1SetupReq) != ROK) { printf("\nFailed Sending"); } } } } else { } break; } } break; } RETVALUE(ROK); } /********************************************************************** End of file **********************************************************************/
wuzhl2018/samples
DateTime/main.cpp
#include <iostream> #include "DateTime.hpp" int main() { std::string timeStr = DateTime::convert<std::string>(time(nullptr)); std::cout << timeStr << std::endl; std::cout << DateTime::convert<time_t>(timeStr) << std::endl; std::cout << DateTime::currentTime() << std::endl << std::endl; return 0; }
chrisRintjema/bugsnag-go
gin/gin_test.go
package bugsnaggin_test import ( "fmt" "net/http" "os" "testing" "time" "github.com/bitly/go-simplejson" "github.com/bugsnag/bugsnag-go" "github.com/bugsnag/bugsnag-go/gin" . "github.com/bugsnag/bugsnag-go/testutil" "github.com/gin-gonic/gin" ) func TestGin(t *testing.T) { ts, reports := Setup() defer ts.Close() g := gin.Default() userID := "<KEY>" g.Use(bugsnaggin.AutoNotify(bugsnag.Configuration{ APIKey: TestAPIKey, Endpoints: bugsnag.Endpoints{Notify: ts.URL, Sessions: ts.URL + "/sessions"}, }, bugsnag.User{Id: userID})) g.GET("/unhandled", performUnhandledCrash) g.GET("/handled", performHandledError) go g.Run(":9079") //This call blocks t.Run("AutoNotify", func(st *testing.T) { time.Sleep(1 * time.Second) _, err := http.Get("http://localhost:9079/unhandled") if err != nil { t.Error(err) } report := <-reports r, _ := simplejson.NewJson(report) hostname, _ := os.Hostname() AssertPayload(st, r, fmt.Sprintf(` { "apiKey":"166f5ad3590596f9aa8d601ea89af845", "events":[ { "app":{ "releaseStage":"" }, "context":"/unhandled", "device":{ "hostname": "%s" }, "exceptions":[ { "errorClass":"*errors.errorString", "message":"you shouldn't have done that", "stacktrace":[] } ], "payloadVersion":"4", "severity":"error", "severityReason":{ "type":"unhandledErrorMiddleware" }, "unhandled":true, "request": { "url": "http://localhost:9079/unhandled", "httpMethod": "GET", "referer": "", "headers": { "Accept-Encoding": "gzip" } }, "user":{ "id": "%s" } } ], "notifier":{ "name":"<NAME>", "url":"https://github.com/bugsnag/bugsnag-go", "version": "%s" } } `, hostname, userID, bugsnag.VERSION)) }) t.Run("Manual notify", func(st *testing.T) { _, err := http.Get("http://localhost:9079/handled") if err != nil { t.Error(err) } report := <-reports r, _ := simplejson.NewJson(report) hostname, _ := os.Hostname() AssertPayload(st, r, fmt.Sprintf(` { "apiKey":"166f5ad3590596f9aa8d601ea89af845", "events":[ { "app":{ "releaseStage":"" }, "context":"/handled", "device":{ "hostname": "%s" }, "exceptions":[ { "errorClass":"*errors.errorString", "message":"Ooopsie", "stacktrace":[] } ], "payloadVersion":"4", "severity":"warning", "severityReason":{ "type":"handledError" }, "unhandled":false, "request": { "url": "http://localhost:9079/handled", "httpMethod": "GET", "referer": "", "headers": { "Accept-Encoding": "gzip" } }, "user":{ "id": "%s" } } ], "notifier":{ "name":"Bugsnag Go", "url":"https://github.com/bugsnag/bugsnag-go", "version": "%s" } } `, hostname, "987zyx", bugsnag.VERSION)) }) } func performHandledError(c *gin.Context) { ctx := c.Request.Context() bugsnag.Notify(fmt.Errorf("Ooopsie"), ctx, bugsnag.User{Id: "987zyx"}) } func performUnhandledCrash(c *gin.Context) { panic("you shouldn't have done that") } func crash(a interface{}) string { return a.(string) }
byterom/android_external_chromium_org_v8
src/base/bits.cc
// Copyright 2014 the V8 project 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 "src/base/bits.h" #include "src/base/logging.h" namespace v8 { namespace base { namespace bits { uint32_t RoundUpToPowerOfTwo32(uint32_t value) { DCHECK_LE(value, 0x80000000u); value = value - 1; value = value | (value >> 1); value = value | (value >> 2); value = value | (value >> 4); value = value | (value >> 8); value = value | (value >> 16); return value + 1; } } // namespace bits } // namespace base } // namespace v8
dzaima/UI
src/dzaima/ui/node/prop/PropI.java
<filename>src/dzaima/ui/node/prop/PropI.java package dzaima.ui.node.prop; public abstract class PropI extends Prop { }
sciencelabshs/lara
db/migrate/20180605181922_add_student_report_enabled.rb
<reponame>sciencelabshs/lara<gh_stars>1-10 class AddStudentReportEnabled < ActiveRecord::Migration def change add_column :lightweight_activities, :student_report_enabled, :boolean, :default => true end end
sibasish-palo/emodb
common/astyanax/src/main/java/com/bazaarvoice/emodb/common/cassandra/metrics/MetricConnectionPoolMonitor.java
package com.bazaarvoice.emodb.common.cassandra.metrics; import com.codahale.metrics.Gauge; import com.codahale.metrics.MetricRegistry; import com.google.inject.Inject; import com.netflix.astyanax.connectionpool.impl.CountingConnectionPoolMonitor; /** * Implementation of {@link com.netflix.astyanax.connectionpool.ConnectionPoolMonitor} that takes advantage of the * existing counting logic in {@link CountingConnectionPoolMonitor} and exposes key metrics to the metric registry. */ public class MetricConnectionPoolMonitor extends CountingConnectionPoolMonitor { @Inject public MetricConnectionPoolMonitor(String poolName, MetricRegistry metricRegistry) { metricRegistry.register( MetricRegistry.name("bv.emodb.astyanax", poolName, "ConnectionPool", "open-connections"), new Gauge<Long>() { @Override public Long getValue() { return getNumOpenConnections(); } }); metricRegistry.register( MetricRegistry.name("bv.emodb.astyanax", poolName, "ConnectionPool", "busy-connections"), new Gauge<Long>() { @Override public Long getValue() { return getNumBusyConnections(); } }); metricRegistry.register( MetricRegistry.name("bv.emodb.astyanax", poolName, "ConnectionPool", "pool-exhausted-timeouts"), new Gauge<Long>() { @Override public Long getValue() { return getPoolExhaustedTimeoutCount(); } }); metricRegistry.register( MetricRegistry.name("bv.emodb.astyanax", poolName, "ConnectionPool", "operation-timeouts"), new Gauge<Long>() { @Override public Long getValue() { return getOperationTimeoutCount(); } }); metricRegistry.register( MetricRegistry.name("bv.emodb.astyanax", poolName, "ConnectionPool", "hosts"), new Gauge<Long>() { @Override public Long getValue() { return getHostCount(); } }); metricRegistry.register( MetricRegistry.name("bv.emodb.astyanax", poolName, "ConnectionPool", "active-hosts"), new Gauge<Long>() { @Override public Long getValue() { return getHostActiveCount(); } }); } }
PradeepSingh1988/validation-app-engine
axon/common/metric_cache.py
<gh_stars>0 import abc import logging from threading import Event, Lock, Thread import time class Counter(object): def __init__(self): self._lock = Lock() self._count = 0 def inc(self, val=1): """Increase the value of the counter.""" with self._lock: self._count += val def count(self): """Get the value of the counter.""" with self._lock: return self._count def clear(self): """Reset the counter.""" with self._lock: self._count = 0 def dec(self, val=1): self.inc(-val) class MetricsCache(object): def __init__(self): self._counters = {} def counter(self, key): if key not in self._counters: self._counters[key] = Counter() return self._counters[key] def clear(self): self._counters.clear() def dump_metrics(self): metrics = {} for key in self._counters.keys(): metrics[key] = self._counters[key] return metrics class Reporter(abc.ABC): def __init__(self, cache, reporting_interval=30): self._cache = cache self._reporting_interval = reporting_interval self._stopped_event = Event() self._reporting_thread = Thread(target=self._report_loop) self._reporting_thread.daemon = True self._reporting_thread.start() def stop(self): self._stopped_event.set() def _report_loop(self): next_run_time = time.time() try: while not self._stopped_event.is_set(): try: self.report(self._cache) except Exception as e: print("here", e) next_run_time += self._reporting_interval wait = max(0, next_run_time - time.time()) time.sleep(wait) except Exception as e: print(e) @abc.abstractmethod def report(self, cache): pass class ExchangeReporter(Reporter): log = logging.getLogger(__name__) def __init__(self, cache, exchange, reporting_interval=30): super().__init__(cache, reporting_interval) self._exchange = exchange def report(self, cache): metrics = cache.dump_metrics() count_dict = {} for key in metrics.keys(): counter = metrics[key] count = counter.count() if count == 0: continue count_dict.update({key: count}) counter.dec(count) if count_dict: self._exchange.send(count_dict)
BonexGu/Blik2D
Blik2D/addon/libssh2-1.6.0_for_blik/src/publickey.c
<reponame>BonexGu/Blik2D /* Copyright (c) 2004-2007, <NAME> <<EMAIL>> * Copyright (c) 2010-2014 by <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the copyright holder nor the names * of any other contributors may be used to endorse or * promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. */ #include "libssh2_priv.h" #include BLIK_LIBSSH2_U_libssh2_publickey_h //original-code:"libssh2_publickey.h" #include "channel.h" #include "session.h" #define LIBSSH2_PUBLICKEY_VERSION 2 /* Numericised response codes -- Not IETF, just local representation */ #define LIBSSH2_PUBLICKEY_RESPONSE_STATUS 0 #define LIBSSH2_PUBLICKEY_RESPONSE_VERSION 1 #define LIBSSH2_PUBLICKEY_RESPONSE_PUBLICKEY 2 typedef struct _LIBSSH2_PUBLICKEY_CODE_LIST { int code; const char *name; int name_len; } LIBSSH2_PUBLICKEY_CODE_LIST; static const LIBSSH2_PUBLICKEY_CODE_LIST publickey_response_codes[] = { {LIBSSH2_PUBLICKEY_RESPONSE_STATUS, "status", sizeof("status") - 1}, {LIBSSH2_PUBLICKEY_RESPONSE_VERSION, "version", sizeof("version") - 1}, {LIBSSH2_PUBLICKEY_RESPONSE_PUBLICKEY, "publickey", sizeof("publickey") - 1} , {0, NULL, 0} }; /* PUBLICKEY status codes -- IETF defined */ #define LIBSSH2_PUBLICKEY_SUCCESS 0 #define LIBSSH2_PUBLICKEY_ACCESS_DENIED 1 #define LIBSSH2_PUBLICKEY_STORAGE_EXCEEDED 2 #define LIBSSH2_PUBLICKEY_VERSION_NOT_SUPPORTED 3 #define LIBSSH2_PUBLICKEY_KEY_NOT_FOUND 4 #define LIBSSH2_PUBLICKEY_KEY_NOT_SUPPORTED 5 #define LIBSSH2_PUBLICKEY_KEY_ALREADY_PRESENT 6 #define LIBSSH2_PUBLICKEY_GENERAL_FAILURE 7 #define LIBSSH2_PUBLICKEY_REQUEST_NOT_SUPPORTED 8 #define LIBSSH2_PUBLICKEY_STATUS_CODE_MAX 8 static const LIBSSH2_PUBLICKEY_CODE_LIST publickey_status_codes[] = { {LIBSSH2_PUBLICKEY_SUCCESS, "success", sizeof("success") - 1} , {LIBSSH2_PUBLICKEY_ACCESS_DENIED, "access denied", sizeof("access denied") - 1}, {LIBSSH2_PUBLICKEY_STORAGE_EXCEEDED, "storage exceeded", sizeof("storage exceeded") - 1} , {LIBSSH2_PUBLICKEY_VERSION_NOT_SUPPORTED, "version not supported", sizeof("version not supported") - 1} , {LIBSSH2_PUBLICKEY_KEY_NOT_FOUND, "key not found", sizeof("key not found") - 1}, {LIBSSH2_PUBLICKEY_KEY_NOT_SUPPORTED, "key not supported", sizeof("key not supported") - 1}, {LIBSSH2_PUBLICKEY_KEY_ALREADY_PRESENT, "key already present", sizeof("key already present") - 1}, {LIBSSH2_PUBLICKEY_GENERAL_FAILURE, "general failure", sizeof("general failure") - 1}, {LIBSSH2_PUBLICKEY_REQUEST_NOT_SUPPORTED, "request not supported", sizeof("request not supported") - 1}, {0, NULL, 0} }; /* * publickey_status_error * * Format an error message from a status code */ static void publickey_status_error(const LIBSSH2_PUBLICKEY *pkey, LIBSSH2_SESSION *session, int status) { const char *msg; /* GENERAL_FAILURE got remapped between version 1 and 2 */ if (status == 6 && pkey && pkey->version == 1) { status = 7; } if (status < 0 || status > LIBSSH2_PUBLICKEY_STATUS_CODE_MAX) { msg = "unknown"; } else { msg = publickey_status_codes[status].name; } _libssh2_error(session, LIBSSH2_ERROR_PUBLICKEY_PROTOCOL, msg); } /* * publickey_packet_receive * * Read a packet from the subsystem */ static int publickey_packet_receive(LIBSSH2_PUBLICKEY * pkey, unsigned char **data, size_t *data_len) { LIBSSH2_CHANNEL *channel = pkey->channel; LIBSSH2_SESSION *session = channel->session; unsigned char buffer[4]; int rc; *data = NULL; /* default to nothing returned */ *data_len = 0; if (pkey->receive_state == libssh2_NB_state_idle) { rc = _libssh2_channel_read(channel, 0, (char *) buffer, 4); if (rc == LIBSSH2_ERROR_EAGAIN) { return rc; } else if (rc != 4) { return _libssh2_error(session, LIBSSH2_ERROR_PUBLICKEY_PROTOCOL, "Invalid response from publickey subsystem"); } pkey->receive_packet_len = _libssh2_ntohu32(buffer); pkey->receive_packet = LIBSSH2_ALLOC(session, pkey->receive_packet_len); if (!pkey->receive_packet) { return _libssh2_error(session, LIBSSH2_ERROR_ALLOC, "Unable to allocate publickey response " "buffer"); } pkey->receive_state = libssh2_NB_state_sent; } if (pkey->receive_state == libssh2_NB_state_sent) { rc = _libssh2_channel_read(channel, 0, (char *) pkey->receive_packet, pkey->receive_packet_len); if (rc == LIBSSH2_ERROR_EAGAIN) { return rc; } else if (rc != (int)pkey->receive_packet_len) { LIBSSH2_FREE(session, pkey->receive_packet); pkey->receive_packet = NULL; pkey->receive_state = libssh2_NB_state_idle; return _libssh2_error(session, LIBSSH2_ERROR_SOCKET_TIMEOUT, "Timeout waiting for publickey subsystem " "response packet"); } *data = pkey->receive_packet; *data_len = pkey->receive_packet_len; } pkey->receive_state = libssh2_NB_state_idle; return 0; } /* publickey_response_id * * Translate a string response name to a numeric code * Data will be incremented by 4 + response_len on success only */ static int publickey_response_id(unsigned char **pdata, size_t data_len) { size_t response_len; unsigned char *data = *pdata; const LIBSSH2_PUBLICKEY_CODE_LIST *codes = publickey_response_codes; if (data_len < 4) { /* Malformed response */ return -1; } response_len = _libssh2_ntohu32(data); data += 4; data_len -= 4; if (data_len < response_len) { /* Malformed response */ return -1; } while (codes->name) { if ((unsigned long)codes->name_len == response_len && strncmp(codes->name, (char *) data, response_len) == 0) { *pdata = data + response_len; return codes->code; } codes++; } return -1; } /* publickey_response_success * * Generic helper routine to wait for success response and nothing else */ static int publickey_response_success(LIBSSH2_PUBLICKEY * pkey) { LIBSSH2_SESSION *session = pkey->channel->session; unsigned char *data, *s; size_t data_len; int response; while (1) { int rc = publickey_packet_receive(pkey, &data, &data_len); if (rc == LIBSSH2_ERROR_EAGAIN) { return rc; } else if (rc) { return _libssh2_error(session, LIBSSH2_ERROR_SOCKET_TIMEOUT, "Timeout waiting for response from " "publickey subsystem"); } s = data; response = publickey_response_id(&s, data_len); switch (response) { case LIBSSH2_PUBLICKEY_RESPONSE_STATUS: /* Error, or processing complete */ { unsigned long status = _libssh2_ntohu32(s); LIBSSH2_FREE(session, data); if (status == LIBSSH2_PUBLICKEY_SUCCESS) return 0; publickey_status_error(pkey, session, status); return -1; } default: LIBSSH2_FREE(session, data); if (response < 0) { return _libssh2_error(session, LIBSSH2_ERROR_PUBLICKEY_PROTOCOL, "Invalid publickey subsystem response"); } /* Unknown/Unexpected */ _libssh2_error(session, LIBSSH2_ERROR_PUBLICKEY_PROTOCOL, "Unexpected publickey subsystem response"); data = NULL; } } /* never reached, but include `return` to silence compiler warnings */ return -1; } /* ***************** * Publickey API * ***************** */ /* * publickey_init * * Startup the publickey subsystem */ static LIBSSH2_PUBLICKEY *publickey_init(LIBSSH2_SESSION *session) { int response; int rc; if (session->pkeyInit_state == libssh2_NB_state_idle) { session->pkeyInit_data = NULL; session->pkeyInit_pkey = NULL; session->pkeyInit_channel = NULL; _libssh2_debug(session, LIBSSH2_TRACE_PUBLICKEY, "Initializing publickey subsystem"); session->pkeyInit_state = libssh2_NB_state_allocated; } if (session->pkeyInit_state == libssh2_NB_state_allocated) { session->pkeyInit_channel = _libssh2_channel_open(session, "session", sizeof("session") - 1, LIBSSH2_CHANNEL_WINDOW_DEFAULT, LIBSSH2_CHANNEL_PACKET_DEFAULT, NULL, 0); if (!session->pkeyInit_channel) { if (libssh2_session_last_errno(session) == LIBSSH2_ERROR_EAGAIN) /* The error state is already set, so leave it */ return NULL; _libssh2_error(session, LIBSSH2_ERROR_CHANNEL_FAILURE, "Unable to startup channel"); goto err_exit; } session->pkeyInit_state = libssh2_NB_state_sent; } if (session->pkeyInit_state == libssh2_NB_state_sent) { rc = _libssh2_channel_process_startup(session->pkeyInit_channel, "subsystem", sizeof("subsystem") - 1, "publickey", sizeof("publickey") - 1); if (rc == LIBSSH2_ERROR_EAGAIN) { _libssh2_error(session, LIBSSH2_ERROR_EAGAIN, "Would block starting publickey subsystem"); return NULL; } else if (rc) { _libssh2_error(session, LIBSSH2_ERROR_CHANNEL_FAILURE, "Unable to request publickey subsystem"); goto err_exit; } session->pkeyInit_state = libssh2_NB_state_sent1; } if (session->pkeyInit_state == libssh2_NB_state_sent1) { unsigned char *s; rc = _libssh2_channel_extended_data(session->pkeyInit_channel, LIBSSH2_CHANNEL_EXTENDED_DATA_IGNORE); if (rc == LIBSSH2_ERROR_EAGAIN) { _libssh2_error(session, LIBSSH2_ERROR_EAGAIN, "Would block starting publickey subsystem"); return NULL; } session->pkeyInit_pkey = LIBSSH2_CALLOC(session, sizeof(LIBSSH2_PUBLICKEY)); if (!session->pkeyInit_pkey) { _libssh2_error(session, LIBSSH2_ERROR_ALLOC, "Unable to allocate a new publickey structure"); goto err_exit; } session->pkeyInit_pkey->channel = session->pkeyInit_channel; session->pkeyInit_pkey->version = 0; s = session->pkeyInit_buffer; _libssh2_htonu32(s, 4 + (sizeof("version") - 1) + 4); s += 4; _libssh2_htonu32(s, sizeof("version") - 1); s += 4; memcpy(s, "version", sizeof("version") - 1); s += sizeof("version") - 1; _libssh2_htonu32(s, LIBSSH2_PUBLICKEY_VERSION); session->pkeyInit_buffer_sent = 0; _libssh2_debug(session, LIBSSH2_TRACE_PUBLICKEY, "Sending publickey advertising version %d support", (int) LIBSSH2_PUBLICKEY_VERSION); session->pkeyInit_state = libssh2_NB_state_sent2; } if (session->pkeyInit_state == libssh2_NB_state_sent2) { rc = _libssh2_channel_write(session->pkeyInit_channel, 0, session->pkeyInit_buffer, 19 - session->pkeyInit_buffer_sent); if (rc == LIBSSH2_ERROR_EAGAIN) { _libssh2_error(session, LIBSSH2_ERROR_EAGAIN, "Would block sending publickey version packet"); return NULL; } else if (rc < 0) { _libssh2_error(session, rc, "Unable to send publickey version packet"); goto err_exit; } session->pkeyInit_buffer_sent += rc; if(session->pkeyInit_buffer_sent < 19) { _libssh2_error(session, LIBSSH2_ERROR_EAGAIN, "Need to be called again to complete this"); return NULL; } session->pkeyInit_state = libssh2_NB_state_sent3; } if (session->pkeyInit_state == libssh2_NB_state_sent3) { while (1) { unsigned char *s; rc = publickey_packet_receive(session->pkeyInit_pkey, &session->pkeyInit_data, &session->pkeyInit_data_len); if (rc == LIBSSH2_ERROR_EAGAIN) { _libssh2_error(session, LIBSSH2_ERROR_EAGAIN, "Would block waiting for response from " "publickey subsystem"); return NULL; } else if (rc) { _libssh2_error(session, LIBSSH2_ERROR_SOCKET_TIMEOUT, "Timeout waiting for response from " "publickey subsystem"); goto err_exit; } s = session->pkeyInit_data; if ((response = publickey_response_id(&s, session->pkeyInit_data_len)) < 0) { _libssh2_error(session, LIBSSH2_ERROR_PUBLICKEY_PROTOCOL, "Invalid publickey subsystem response code"); goto err_exit; } switch (response) { case LIBSSH2_PUBLICKEY_RESPONSE_STATUS: /* Error */ { unsigned long status, descr_len, lang_len; status = _libssh2_ntohu32(s); s += 4; descr_len = _libssh2_ntohu32(s); s += 4; /* description starts here */ s += descr_len; lang_len = _libssh2_ntohu32(s); s += 4; /* lang starts here */ s += lang_len; if (s > session->pkeyInit_data + session->pkeyInit_data_len) { _libssh2_error(session, LIBSSH2_ERROR_PUBLICKEY_PROTOCOL, "Malformed publickey subsystem packet"); goto err_exit; } publickey_status_error(NULL, session, status); goto err_exit; } case LIBSSH2_PUBLICKEY_RESPONSE_VERSION: /* What we want */ session->pkeyInit_pkey->version = _libssh2_ntohu32(s); if (session->pkeyInit_pkey->version > LIBSSH2_PUBLICKEY_VERSION) { _libssh2_debug(session, LIBSSH2_TRACE_PUBLICKEY, "Truncate remote publickey version from %lu", session->pkeyInit_pkey->version); session->pkeyInit_pkey->version = LIBSSH2_PUBLICKEY_VERSION; } _libssh2_debug(session, LIBSSH2_TRACE_PUBLICKEY, "Enabling publickey subsystem version %lu", session->pkeyInit_pkey->version); LIBSSH2_FREE(session, session->pkeyInit_data); session->pkeyInit_data = NULL; session->pkeyInit_state = libssh2_NB_state_idle; return session->pkeyInit_pkey; default: /* Unknown/Unexpected */ _libssh2_error(session, LIBSSH2_ERROR_PUBLICKEY_PROTOCOL, "Unexpected publickey subsystem response, " "ignoring"); LIBSSH2_FREE(session, session->pkeyInit_data); session->pkeyInit_data = NULL; } } } /* Never reached except by direct goto */ err_exit: session->pkeyInit_state = libssh2_NB_state_sent4; if (session->pkeyInit_channel) { rc = _libssh2_channel_close(session->pkeyInit_channel); if (rc == LIBSSH2_ERROR_EAGAIN) { _libssh2_error(session, LIBSSH2_ERROR_EAGAIN, "Would block closing channel"); return NULL; } } if (session->pkeyInit_pkey) { LIBSSH2_FREE(session, session->pkeyInit_pkey); session->pkeyInit_pkey = NULL; } if (session->pkeyInit_data) { LIBSSH2_FREE(session, session->pkeyInit_data); session->pkeyInit_data = NULL; } session->pkeyInit_state = libssh2_NB_state_idle; return NULL; } /* * libssh2_publickey_init * * Startup the publickey subsystem */ LIBSSH2_API LIBSSH2_PUBLICKEY * libssh2_publickey_init(LIBSSH2_SESSION *session) { LIBSSH2_PUBLICKEY *ptr; BLOCK_ADJUST_ERRNO(ptr, session, publickey_init(session)); return ptr; } /* * libssh2_publickey_add_ex * * Add a new public key entry */ LIBSSH2_API int libssh2_publickey_add_ex(LIBSSH2_PUBLICKEY *pkey, const unsigned char *name, unsigned long name_len, const unsigned char *blob, unsigned long blob_len, char overwrite, unsigned long num_attrs, const libssh2_publickey_attribute attrs[]) { LIBSSH2_CHANNEL *channel; LIBSSH2_SESSION *session; /* 19 = packet_len(4) + add_len(4) + "add"(3) + name_len(4) + {name} blob_len(4) + {blob} */ unsigned long i, packet_len = 19 + name_len + blob_len; unsigned char *comment = NULL; unsigned long comment_len = 0; int rc; if(!pkey) return LIBSSH2_ERROR_BAD_USE; channel = pkey->channel; session = channel->session; if (pkey->add_state == libssh2_NB_state_idle) { pkey->add_packet = NULL; _libssh2_debug(session, LIBSSH2_TRACE_PUBLICKEY, "Adding %s publickey", name); if (pkey->version == 1) { for(i = 0; i < num_attrs; i++) { /* Search for a comment attribute */ if (attrs[i].name_len == (sizeof("comment") - 1) && strncmp(attrs[i].name, "comment", sizeof("comment") - 1) == 0) { comment = (unsigned char *) attrs[i].value; comment_len = attrs[i].value_len; break; } } packet_len += 4 + comment_len; } else { packet_len += 5; /* overwrite(1) + attribute_count(4) */ for(i = 0; i < num_attrs; i++) { packet_len += 9 + attrs[i].name_len + attrs[i].value_len; /* name_len(4) + value_len(4) + mandatory(1) */ } } pkey->add_packet = LIBSSH2_ALLOC(session, packet_len); if (!pkey->add_packet) { return _libssh2_error(session, LIBSSH2_ERROR_ALLOC, "Unable to allocate memory for " "publickey \"add\" packet"); } pkey->add_s = pkey->add_packet; _libssh2_htonu32(pkey->add_s, packet_len - 4); pkey->add_s += 4; _libssh2_htonu32(pkey->add_s, sizeof("add") - 1); pkey->add_s += 4; memcpy(pkey->add_s, "add", sizeof("add") - 1); pkey->add_s += sizeof("add") - 1; if (pkey->version == 1) { _libssh2_htonu32(pkey->add_s, comment_len); pkey->add_s += 4; if (comment) { memcpy(pkey->add_s, comment, comment_len); pkey->add_s += comment_len; } _libssh2_htonu32(pkey->add_s, name_len); pkey->add_s += 4; memcpy(pkey->add_s, name, name_len); pkey->add_s += name_len; _libssh2_htonu32(pkey->add_s, blob_len); pkey->add_s += 4; memcpy(pkey->add_s, blob, blob_len); pkey->add_s += blob_len; } else { /* Version == 2 */ _libssh2_htonu32(pkey->add_s, name_len); pkey->add_s += 4; memcpy(pkey->add_s, name, name_len); pkey->add_s += name_len; _libssh2_htonu32(pkey->add_s, blob_len); pkey->add_s += 4; memcpy(pkey->add_s, blob, blob_len); pkey->add_s += blob_len; *(pkey->add_s++) = overwrite ? 0x01 : 0; _libssh2_htonu32(pkey->add_s, num_attrs); pkey->add_s += 4; for(i = 0; i < num_attrs; i++) { _libssh2_htonu32(pkey->add_s, attrs[i].name_len); pkey->add_s += 4; memcpy(pkey->add_s, attrs[i].name, attrs[i].name_len); pkey->add_s += attrs[i].name_len; _libssh2_htonu32(pkey->add_s, attrs[i].value_len); pkey->add_s += 4; memcpy(pkey->add_s, attrs[i].value, attrs[i].value_len); pkey->add_s += attrs[i].value_len; *(pkey->add_s++) = attrs[i].mandatory ? 0x01 : 0; } } _libssh2_debug(session, LIBSSH2_TRACE_PUBLICKEY, "Sending publickey \"add\" packet: " "type=%s blob_len=%ld num_attrs=%ld", name, blob_len, num_attrs); pkey->add_state = libssh2_NB_state_created; } if (pkey->add_state == libssh2_NB_state_created) { rc = _libssh2_channel_write(channel, 0, pkey->add_packet, (pkey->add_s - pkey->add_packet)); if (rc == LIBSSH2_ERROR_EAGAIN) { return rc; } else if ((pkey->add_s - pkey->add_packet) != rc) { LIBSSH2_FREE(session, pkey->add_packet); pkey->add_packet = NULL; return _libssh2_error(session, LIBSSH2_ERROR_SOCKET_SEND, "Unable to send publickey add packet"); } LIBSSH2_FREE(session, pkey->add_packet); pkey->add_packet = NULL; pkey->add_state = libssh2_NB_state_sent; } rc = publickey_response_success(pkey); if (rc == LIBSSH2_ERROR_EAGAIN) { return rc; } pkey->add_state = libssh2_NB_state_idle; return rc; } /* libssh2_publickey_remove_ex * Remove an existing publickey so that authentication can no longer be * performed using it */ LIBSSH2_API int libssh2_publickey_remove_ex(LIBSSH2_PUBLICKEY * pkey, const unsigned char *name, unsigned long name_len, const unsigned char *blob, unsigned long blob_len) { LIBSSH2_CHANNEL *channel; LIBSSH2_SESSION *session; /* 22 = packet_len(4) + remove_len(4) + "remove"(6) + name_len(4) + {name} + blob_len(4) + {blob} */ unsigned long packet_len = 22 + name_len + blob_len; int rc; if(!pkey) return LIBSSH2_ERROR_BAD_USE; channel = pkey->channel; session = channel->session; if (pkey->remove_state == libssh2_NB_state_idle) { pkey->remove_packet = NULL; pkey->remove_packet = LIBSSH2_ALLOC(session, packet_len); if (!pkey->remove_packet) { return _libssh2_error(session, LIBSSH2_ERROR_ALLOC, "Unable to allocate memory for " "publickey \"remove\" packet"); } pkey->remove_s = pkey->remove_packet; _libssh2_htonu32(pkey->remove_s, packet_len - 4); pkey->remove_s += 4; _libssh2_htonu32(pkey->remove_s, sizeof("remove") - 1); pkey->remove_s += 4; memcpy(pkey->remove_s, "remove", sizeof("remove") - 1); pkey->remove_s += sizeof("remove") - 1; _libssh2_htonu32(pkey->remove_s, name_len); pkey->remove_s += 4; memcpy(pkey->remove_s, name, name_len); pkey->remove_s += name_len; _libssh2_htonu32(pkey->remove_s, blob_len); pkey->remove_s += 4; memcpy(pkey->remove_s, blob, blob_len); pkey->remove_s += blob_len; _libssh2_debug(session, LIBSSH2_TRACE_PUBLICKEY, "Sending publickey \"remove\" packet: " "type=%s blob_len=%ld", name, blob_len); pkey->remove_state = libssh2_NB_state_created; } if (pkey->remove_state == libssh2_NB_state_created) { rc = _libssh2_channel_write(channel, 0, pkey->remove_packet, (pkey->remove_s - pkey->remove_packet)); if (rc == LIBSSH2_ERROR_EAGAIN) { return rc; } else if ((pkey->remove_s - pkey->remove_packet) != rc) { LIBSSH2_FREE(session, pkey->remove_packet); pkey->remove_packet = NULL; pkey->remove_state = libssh2_NB_state_idle; return _libssh2_error(session, LIBSSH2_ERROR_SOCKET_SEND, "Unable to send publickey remove packet"); } LIBSSH2_FREE(session, pkey->remove_packet); pkey->remove_packet = NULL; pkey->remove_state = libssh2_NB_state_sent; } rc = publickey_response_success(pkey); if (rc == LIBSSH2_ERROR_EAGAIN) { return rc; } pkey->remove_state = libssh2_NB_state_idle; return rc; } /* libssh2_publickey_list_fetch * Fetch a list of supported public key from a server */ LIBSSH2_API int libssh2_publickey_list_fetch(LIBSSH2_PUBLICKEY * pkey, unsigned long *num_keys, libssh2_publickey_list ** pkey_list) { LIBSSH2_CHANNEL *channel; LIBSSH2_SESSION *session; libssh2_publickey_list *list = NULL; unsigned long buffer_len = 12, keys = 0, max_keys = 0, i; /* 12 = packet_len(4) + list_len(4) + "list"(4) */ int response; int rc; if(!pkey) return LIBSSH2_ERROR_BAD_USE; channel = pkey->channel; session = channel->session; if (pkey->listFetch_state == libssh2_NB_state_idle) { pkey->listFetch_data = NULL; pkey->listFetch_s = pkey->listFetch_buffer; _libssh2_htonu32(pkey->listFetch_s, buffer_len - 4); pkey->listFetch_s += 4; _libssh2_htonu32(pkey->listFetch_s, sizeof("list") - 1); pkey->listFetch_s += 4; memcpy(pkey->listFetch_s, "list", sizeof("list") - 1); pkey->listFetch_s += sizeof("list") - 1; _libssh2_debug(session, LIBSSH2_TRACE_PUBLICKEY, "Sending publickey \"list\" packet"); pkey->listFetch_state = libssh2_NB_state_created; } if (pkey->listFetch_state == libssh2_NB_state_created) { rc = _libssh2_channel_write(channel, 0, pkey->listFetch_buffer, (pkey->listFetch_s - pkey->listFetch_buffer)); if (rc == LIBSSH2_ERROR_EAGAIN) { return rc; } else if ((pkey->listFetch_s - pkey->listFetch_buffer) != rc) { pkey->listFetch_state = libssh2_NB_state_idle; return _libssh2_error(session, LIBSSH2_ERROR_SOCKET_SEND, "Unable to send publickey list packet"); } pkey->listFetch_state = libssh2_NB_state_sent; } while (1) { rc = publickey_packet_receive(pkey, &pkey->listFetch_data, &pkey->listFetch_data_len); if (rc == LIBSSH2_ERROR_EAGAIN) { return rc; } else if (rc) { _libssh2_error(session, LIBSSH2_ERROR_SOCKET_TIMEOUT, "Timeout waiting for response from " "publickey subsystem"); goto err_exit; } pkey->listFetch_s = pkey->listFetch_data; if ((response = publickey_response_id(&pkey->listFetch_s, pkey->listFetch_data_len)) < 0) { _libssh2_error(session, LIBSSH2_ERROR_PUBLICKEY_PROTOCOL, "Invalid publickey subsystem response code"); goto err_exit; } switch (response) { case LIBSSH2_PUBLICKEY_RESPONSE_STATUS: /* Error, or processing complete */ { unsigned long status, descr_len, lang_len; status = _libssh2_ntohu32(pkey->listFetch_s); pkey->listFetch_s += 4; descr_len = _libssh2_ntohu32(pkey->listFetch_s); pkey->listFetch_s += 4; /* description starts at pkey->listFetch_s */ pkey->listFetch_s += descr_len; lang_len = _libssh2_ntohu32(pkey->listFetch_s); pkey->listFetch_s += 4; /* lang starts at pkey->listFetch_s */ pkey->listFetch_s += lang_len; if (pkey->listFetch_s > pkey->listFetch_data + pkey->listFetch_data_len) { _libssh2_error(session, LIBSSH2_ERROR_PUBLICKEY_PROTOCOL, "Malformed publickey subsystem packet"); goto err_exit; } if (status == LIBSSH2_PUBLICKEY_SUCCESS) { LIBSSH2_FREE(session, pkey->listFetch_data); pkey->listFetch_data = NULL; *pkey_list = list; *num_keys = keys; pkey->listFetch_state = libssh2_NB_state_idle; return 0; } publickey_status_error(pkey, session, status); goto err_exit; } case LIBSSH2_PUBLICKEY_RESPONSE_PUBLICKEY: /* What we want */ if (keys >= max_keys) { libssh2_publickey_list *newlist; /* Grow the key list if necessary */ max_keys += 8; newlist = LIBSSH2_REALLOC(session, list, (max_keys + 1) * sizeof(libssh2_publickey_list)); if (!newlist) { _libssh2_error(session, LIBSSH2_ERROR_ALLOC, "Unable to allocate memory for " "publickey list"); goto err_exit; } list = newlist; } if (pkey->version == 1) { unsigned long comment_len; comment_len = _libssh2_ntohu32(pkey->listFetch_s); pkey->listFetch_s += 4; if (comment_len) { list[keys].num_attrs = 1; list[keys].attrs = LIBSSH2_ALLOC(session, sizeof(libssh2_publickey_attribute)); if (!list[keys].attrs) { _libssh2_error(session, LIBSSH2_ERROR_ALLOC, "Unable to allocate memory for " "publickey attributes"); goto err_exit; } list[keys].attrs[0].name = "comment"; list[keys].attrs[0].name_len = sizeof("comment") - 1; list[keys].attrs[0].value = (char *) pkey->listFetch_s; list[keys].attrs[0].value_len = comment_len; list[keys].attrs[0].mandatory = 0; pkey->listFetch_s += comment_len; } else { list[keys].num_attrs = 0; list[keys].attrs = NULL; } list[keys].name_len = _libssh2_ntohu32(pkey->listFetch_s); pkey->listFetch_s += 4; list[keys].name = pkey->listFetch_s; pkey->listFetch_s += list[keys].name_len; list[keys].blob_len = _libssh2_ntohu32(pkey->listFetch_s); pkey->listFetch_s += 4; list[keys].blob = pkey->listFetch_s; pkey->listFetch_s += list[keys].blob_len; } else { /* Version == 2 */ list[keys].name_len = _libssh2_ntohu32(pkey->listFetch_s); pkey->listFetch_s += 4; list[keys].name = pkey->listFetch_s; pkey->listFetch_s += list[keys].name_len; list[keys].blob_len = _libssh2_ntohu32(pkey->listFetch_s); pkey->listFetch_s += 4; list[keys].blob = pkey->listFetch_s; pkey->listFetch_s += list[keys].blob_len; list[keys].num_attrs = _libssh2_ntohu32(pkey->listFetch_s); pkey->listFetch_s += 4; if (list[keys].num_attrs) { list[keys].attrs = LIBSSH2_ALLOC(session, list[keys].num_attrs * sizeof(libssh2_publickey_attribute)); if (!list[keys].attrs) { _libssh2_error(session, LIBSSH2_ERROR_ALLOC, "Unable to allocate memory for " "publickey attributes"); goto err_exit; } for(i = 0; i < list[keys].num_attrs; i++) { list[keys].attrs[i].name_len = _libssh2_ntohu32(pkey->listFetch_s); pkey->listFetch_s += 4; list[keys].attrs[i].name = (char *) pkey->listFetch_s; pkey->listFetch_s += list[keys].attrs[i].name_len; list[keys].attrs[i].value_len = _libssh2_ntohu32(pkey->listFetch_s); pkey->listFetch_s += 4; list[keys].attrs[i].value = (char *) pkey->listFetch_s; pkey->listFetch_s += list[keys].attrs[i].value_len; /* actually an ignored value */ list[keys].attrs[i].mandatory = 0; } } else { list[keys].attrs = NULL; } } /* To be FREEd in libssh2_publickey_list_free() */ list[keys].packet = pkey->listFetch_data; keys++; list[keys].packet = NULL; /* Terminate the list */ pkey->listFetch_data = NULL; break; default: /* Unknown/Unexpected */ _libssh2_error(session, LIBSSH2_ERROR_PUBLICKEY_PROTOCOL, "Unexpected publickey subsystem response"); LIBSSH2_FREE(session, pkey->listFetch_data); pkey->listFetch_data = NULL; } } /* Only reached via explicit goto */ err_exit: if (pkey->listFetch_data) { LIBSSH2_FREE(session, pkey->listFetch_data); pkey->listFetch_data = NULL; } if (list) { libssh2_publickey_list_free(pkey, list); } pkey->listFetch_state = libssh2_NB_state_idle; return -1; } /* libssh2_publickey_list_free * Free a previously fetched list of public keys */ LIBSSH2_API void libssh2_publickey_list_free(LIBSSH2_PUBLICKEY * pkey, libssh2_publickey_list * pkey_list) { LIBSSH2_SESSION *session; libssh2_publickey_list *p = pkey_list; if(!pkey || !p) return; session = pkey->channel->session; while (p->packet) { if (p->attrs) { LIBSSH2_FREE(session, p->attrs); } LIBSSH2_FREE(session, p->packet); p++; } LIBSSH2_FREE(session, pkey_list); } /* libssh2_publickey_shutdown * Shutdown the publickey subsystem */ LIBSSH2_API int libssh2_publickey_shutdown(LIBSSH2_PUBLICKEY *pkey) { LIBSSH2_SESSION *session; int rc; if(!pkey) return LIBSSH2_ERROR_BAD_USE; session = pkey->channel->session; /* * Make sure all memory used in the state variables are free */ if (pkey->receive_packet) { LIBSSH2_FREE(session, pkey->receive_packet); pkey->receive_packet = NULL; } if (pkey->add_packet) { LIBSSH2_FREE(session, pkey->add_packet); pkey->add_packet = NULL; } if (pkey->remove_packet) { LIBSSH2_FREE(session, pkey->remove_packet); pkey->remove_packet = NULL; } if (pkey->listFetch_data) { LIBSSH2_FREE(session, pkey->listFetch_data); pkey->listFetch_data = NULL; } rc = _libssh2_channel_free(pkey->channel); if (rc == LIBSSH2_ERROR_EAGAIN) return rc; LIBSSH2_FREE(session, pkey); return 0; }
zhoxie-cisco/datahub
metadata-ingestion/src/datahub/metadata/com/linkedin/events/__init__.py
<reponame>zhoxie-cisco/datahub # flake8: noqa # This file is autogenerated by /metadata-ingestion/scripts/avro_codegen.py # Do not modify manually! # fmt: off from ....schema_classes import KafkaAuditHeaderClass KafkaAuditHeader = KafkaAuditHeaderClass # fmt: on
eshelmarc/noobaa-core
src/server/object_services/schemas/object_multipart_schema.js
/* Copyright (C) 2016 NooBaa */ 'use strict'; module.exports = { id: 'multipart_schema', type: 'object', required: [ '_id', 'system', 'bucket', 'obj', 'num', ], properties: { _id: { objectid: true }, deleted: { date: true }, system: { objectid: true }, bucket: { objectid: true }, obj: { objectid: true }, // the multipart number in range 1 - 10000 num: { type: 'integer' }, // size in bytes size: { type: 'integer' }, // hashes are saved when provided during upload // md5 is used for multipart etag md5_b64: { type: 'string' }, sha256_b64: { type: 'string' }, create_time: { date: true }, num_parts: { type: 'integer' }, // the uncommitted property is set on creation, // and unset only once the multipart is chosen to be part of the object. // see complete_object_upload() uncommitted: { type: 'boolean' }, } };
umjammer/tritonus
tritonus-saol/src/main/java/org/tritonus/saol/engine/RTSystem.java
<filename>tritonus-saol/src/main/java/org/tritonus/saol/engine/RTSystem.java /* * Copyright (c) 2002 by <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.tritonus.saol.engine; import java.io.IOException; import java.lang.reflect.Constructor; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.tritonus.share.TDebug; /** * RTSystem. * * This file is part of Tritonus: http://www.tritonus.org/ */ public class RTSystem extends Thread { private static final boolean DEBUG = false; private SystemOutput m_output; private Map<String, Class<AbstractInstrument>> m_instrumentMap; private boolean m_bRunning; private int m_nTime; private float m_fTimeStep; private int m_nARate; private int m_nKRate; private int m_nAToKRateFactor; private List<AbstractInstrument> m_activeInstruments; private List<AbstractInstrument> m_scheduledInstruments; private int m_nScheduledEndTime; private float m_fFloatToIntTimeFactor; private float m_fIntToFloatTimeFactor; public RTSystem(SystemOutput output, Map<String, Class<AbstractInstrument>> instrumentMap) { m_output = output; m_instrumentMap = instrumentMap; // TODO: setRates(44100, 100); m_activeInstruments = new LinkedList<>(); m_scheduledInstruments = new LinkedList<>(); m_nScheduledEndTime = Integer.MAX_VALUE; } private void setRates(int nARate, int nKRate) { m_nARate = nARate; m_nKRate = nKRate; m_nAToKRateFactor = nARate / nKRate; m_fTimeStep = 1.0F / nKRate; // following is only correct for 60 BPM m_fFloatToIntTimeFactor = nKRate; m_fIntToFloatTimeFactor = m_fTimeStep; } public void run() { try { runImpl(); } catch (IOException e) { e.printStackTrace(); } } private void runImpl() throws IOException { m_bRunning = true; m_nTime = 0; while (m_bRunning) { doI(); doK(); for (int i = 0; i < m_nAToKRateFactor; i++) { doA(); } advanceTime(); } m_output.close(); } private void doI() { if (DEBUG) { TDebug.out("doI()"); TDebug.out("time: " + getTime()); } synchronized (m_scheduledInstruments) { Iterator<AbstractInstrument> scheduledInstruments = m_scheduledInstruments.iterator(); while (scheduledInstruments.hasNext()) { if (DEBUG) { TDebug.out("scheduled instrument"); } AbstractInstrument instrument = scheduledInstruments.next(); if (DEBUG) { TDebug.out("instrument start time: " + instrument.getStartTime()); } if (getTime() >= instrument.getStartTime()) { if (DEBUG) { TDebug.out("...activating"); } scheduledInstruments.remove(); instrument.doIPass(this); m_activeInstruments.add(instrument); } } } Iterator<AbstractInstrument> activeInstruments = m_activeInstruments.iterator(); while (activeInstruments.hasNext()) { AbstractInstrument instrument = activeInstruments.next(); if (getTime() > instrument.getEndTime()) { if (DEBUG) { TDebug.out("...DEactivating"); } activeInstruments.remove(); } } if (getTime() >= getScheduledEndTime()) { stopEngine(); } } private void doK() { Iterator<AbstractInstrument> activeInstruments = m_activeInstruments.iterator(); while (activeInstruments.hasNext()) { AbstractInstrument instrument = activeInstruments.next(); instrument.doKPass(this); } } private void doA() throws IOException { // TDebug.out("doA()"); m_output.clear(); Iterator<AbstractInstrument> activeInstruments = m_activeInstruments.iterator(); while (activeInstruments.hasNext()) { // TDebug.out("doA(): has active Instrument"); AbstractInstrument instrument = activeInstruments.next(); instrument.doAPass(this); } m_output.emit(); } public void scheduleInstrument(String strInstrumentName, float fStartTime, float fDuration) { AbstractInstrument instrument = createInstrumentInstance(strInstrumentName); int nStartTime = Math.round(fStartTime * m_fFloatToIntTimeFactor); int nEndTime = Math.round((fStartTime + fDuration) * m_fFloatToIntTimeFactor); instrument.setStartAndEndTime(nStartTime, nEndTime); synchronized (m_scheduledInstruments) { m_scheduledInstruments.add(instrument); if (DEBUG) { TDebug.out("adding instrument"); TDebug.out("start: " + nStartTime); TDebug.out("end: " + nEndTime); } } } public void scheduleEnd(float fEndTime) { m_nScheduledEndTime = Math.round(fEndTime * m_fFloatToIntTimeFactor); // TODO: } public void stopEngine() { m_bRunning = false; } private void advanceTime() { m_nTime++; } public int getTime() { return m_nTime; } public void output(float fValue) { m_output.output(fValue); } private int getScheduledEndTime() { return m_nScheduledEndTime; } private AbstractInstrument createInstrumentInstance(String strInstrumentName) { AbstractInstrument instrument = null; Class<AbstractInstrument> instrumentClass = m_instrumentMap.get(strInstrumentName); try { Constructor<AbstractInstrument> constructor = instrumentClass.getConstructor(RTSystem.class); instrument = constructor.newInstance(this); } catch (Exception e) { e.printStackTrace(); } return instrument; } }
LightBitsLabs/mongo
src/third_party/mozjs-38/extract/js/src/proxy/Proxy.h
<gh_stars>10-100 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * vim: set ts=8 sts=4 et sw=4 tw=99: * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef proxy_Proxy_h #define proxy_Proxy_h #include "NamespaceImports.h" #include "js/Class.h" namespace js { class RegExpGuard; /* * Dispatch point for handlers that executes the appropriate C++ or scripted traps. * * Important: All proxy methods need either (a) an AutoEnterPolicy in their * Proxy::foo entry point below or (b) an override in SecurityWrapper. See bug * 945826 comment 0. */ class Proxy { public: /* Standard internal methods. */ static bool getOwnPropertyDescriptor(JSContext* cx, HandleObject proxy, HandleId id, MutableHandle<JSPropertyDescriptor> desc); static bool defineProperty(JSContext* cx, HandleObject proxy, HandleId id, MutableHandle<JSPropertyDescriptor> desc); static bool ownPropertyKeys(JSContext* cx, HandleObject proxy, AutoIdVector& props); static bool delete_(JSContext* cx, HandleObject proxy, HandleId id, bool* bp); static bool enumerate(JSContext* cx, HandleObject proxy, MutableHandleObject objp); static bool isExtensible(JSContext* cx, HandleObject proxy, bool* extensible); static bool preventExtensions(JSContext* cx, HandleObject proxy, bool* succeeded); static bool getPrototypeOf(JSContext* cx, HandleObject proxy, MutableHandleObject protop); static bool setPrototypeOf(JSContext* cx, HandleObject proxy, HandleObject proto, bool* bp); static bool setImmutablePrototype(JSContext* cx, HandleObject proxy, bool* succeeded); static bool has(JSContext* cx, HandleObject proxy, HandleId id, bool* bp); static bool get(JSContext* cx, HandleObject proxy, HandleObject receiver, HandleId id, MutableHandleValue vp); static bool set(JSContext* cx, HandleObject proxy, HandleObject receiver, HandleId id, bool strict, MutableHandleValue vp); static bool call(JSContext* cx, HandleObject proxy, const CallArgs& args); static bool construct(JSContext* cx, HandleObject proxy, const CallArgs& args); /* SpiderMonkey extensions. */ static bool getPropertyDescriptor(JSContext* cx, HandleObject proxy, HandleId id, MutableHandle<JSPropertyDescriptor> desc); static bool hasOwn(JSContext* cx, HandleObject proxy, HandleId id, bool* bp); static bool getOwnEnumerablePropertyKeys(JSContext* cx, HandleObject proxy, AutoIdVector& props); static bool nativeCall(JSContext* cx, IsAcceptableThis test, NativeImpl impl, CallArgs args); static bool hasInstance(JSContext* cx, HandleObject proxy, MutableHandleValue v, bool* bp); static bool objectClassIs(HandleObject obj, ESClassValue classValue, JSContext* cx); static const char* className(JSContext* cx, HandleObject proxy); static JSString* fun_toString(JSContext* cx, HandleObject proxy, unsigned indent); static bool regexp_toShared(JSContext* cx, HandleObject proxy, RegExpGuard* g); static bool boxedValue_unbox(JSContext* cx, HandleObject proxy, MutableHandleValue vp); static bool defaultValue(JSContext* cx, HandleObject obj, JSType hint, MutableHandleValue vp); static bool watch(JSContext* cx, HandleObject proxy, HandleId id, HandleObject callable); static bool unwatch(JSContext* cx, HandleObject proxy, HandleId id); static bool getElements(JSContext* cx, HandleObject obj, uint32_t begin, uint32_t end, ElementAdder* adder); static void trace(JSTracer* trc, JSObject* obj); /* IC entry path for handling __noSuchMethod__ on access. */ static bool callProp(JSContext* cx, HandleObject proxy, HandleObject reveiver, HandleId id, MutableHandleValue vp); }; } /* namespace js */ #endif /* proxy_Proxy_h */
ScalablyTyped/SlinkyTyped
r/react-native/src/main/scala/typingsSlinky/reactNative/mod/SectionListScrollParams.scala
<gh_stars>10-100 package typingsSlinky.reactNative.mod import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} @js.native trait SectionListScrollParams extends StObject { var animated: js.UndefOr[Boolean] = js.native var itemIndex: Double = js.native var sectionIndex: Double = js.native var viewOffset: js.UndefOr[Double] = js.native var viewPosition: js.UndefOr[Double] = js.native } object SectionListScrollParams { @scala.inline def apply(itemIndex: Double, sectionIndex: Double): SectionListScrollParams = { val __obj = js.Dynamic.literal(itemIndex = itemIndex.asInstanceOf[js.Any], sectionIndex = sectionIndex.asInstanceOf[js.Any]) __obj.asInstanceOf[SectionListScrollParams] } @scala.inline implicit class SectionListScrollParamsMutableBuilder[Self <: SectionListScrollParams] (val x: Self) extends AnyVal { @scala.inline def setAnimated(value: Boolean): Self = StObject.set(x, "animated", value.asInstanceOf[js.Any]) @scala.inline def setAnimatedUndefined: Self = StObject.set(x, "animated", js.undefined) @scala.inline def setItemIndex(value: Double): Self = StObject.set(x, "itemIndex", value.asInstanceOf[js.Any]) @scala.inline def setSectionIndex(value: Double): Self = StObject.set(x, "sectionIndex", value.asInstanceOf[js.Any]) @scala.inline def setViewOffset(value: Double): Self = StObject.set(x, "viewOffset", value.asInstanceOf[js.Any]) @scala.inline def setViewOffsetUndefined: Self = StObject.set(x, "viewOffset", js.undefined) @scala.inline def setViewPosition(value: Double): Self = StObject.set(x, "viewPosition", value.asInstanceOf[js.Any]) @scala.inline def setViewPositionUndefined: Self = StObject.set(x, "viewPosition", js.undefined) } }
ashutoshcipher/oozie
tools/src/test/java/org/apache/oozie/tools/OozieSharelibFileOperations.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.oozie.tools; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; public final class OozieSharelibFileOperations { /** * Suppress default constructor for noninstantiability */ private OozieSharelibFileOperations() { throw new UnsupportedOperationException(); } /** * generate a number of files equals with fileNr, and save the fileList parameter * @param fileNr number of files to be generated * @return a list of the generated files * @throws Exception */ public static List<File> generateAndWriteFiles(File libDirectory, int fileNr) throws IOException { List<File> fileList = new ArrayList<>(); for (int i=0; i<fileNr; i++) { String fileName = generateFileName(i); String fileContent = generateFileContent(i); fileList.add(writeFile(libDirectory, fileName, fileContent)); } return fileList; } /** * Create a file in a specified folder, with a specific name and content * @param folder source folder * @param filename name of the generated file * @param content content of the generated file * @return the created file * @throws Exception */ public static File writeFile(File folder, String filename, String content) throws IOException { File file = new File(folder.getAbsolutePath() + File.separator + filename); Writer writer = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8); writer.write(content); writer.flush(); writer.close(); return file; } public static String generateFileName(int i) { return "file_" + i; } public static String generateFileContent(int i) { return "test File " + i; } }
miaortizma/competitive-programming
online_judges/Vjudge/Training/d/d.cpp
#include<bits/stdc++.h> using namespace std; const int N = 1e6; int a, b, k; int lp[N + 1]; vector<int> pr; bool f(int m) { //cerr << "test: " << m << "\n"; int l = a, r = a + m - 1; int cnt = 0; for (int i = 0; i < m; ++i) { if (lp[a + i] == a + i) cnt++; //cerr << a + i << " "; } //cerr << "\n cnt:" << cnt << "\n"; if (cnt < k) return false; while (r < b) { if (lp[l] == l) cnt--; l++; ++r; if (lp[r] == r) cnt++; //cerr << "l: " << l << " r: " << r << " cnt: " << cnt << "\n"; if (cnt < k) return false; } //cerr << "true\n"; return true; } void sieve() { for (int i=2; i<=N; ++i) { if (lp[i] == 0) { lp[i] = i; pr.push_back(i); } for (int j=0; j<(int)pr.size() && pr[j]<=lp[i] && i*pr[j]<=N; ++j) lp[i * pr[j]] = pr[j]; } } int main() { ios_base::sync_with_stdio(0); cin.tie(NULL); cin >> a >> b >> k; int l = 1, h = b - a + 1; sieve(); while (l < h) { int m = l + (h - l) / 2; if (f(m)) h = m; else l = m + 1; } if (!f(l)) cout << -1; else cout << l; return 0; }
pepsi7959/OpenstudioThai
openstudiocore/src/energyplus/ForwardTranslator/ForwardTranslateEvaporativeCoolerIndirectResearchSpecial.cpp
<filename>openstudiocore/src/energyplus/ForwardTranslator/ForwardTranslateEvaporativeCoolerIndirectResearchSpecial.cpp /********************************************************************** * Copyright (c) 2008-2015, Alliance for Sustainable Energy. * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********************************************************************/ #include "../ForwardTranslator.hpp" #include "../../model/Model.hpp" #include "../../model/EvaporativeCoolerIndirectResearchSpecial.hpp" #include "../../model/EvaporativeCoolerIndirectResearchSpecial_Impl.hpp" #include "../../model/Node.hpp" #include "../../model/Node_Impl.hpp" #include "../../model/Schedule.hpp" #include "../../utilities/idf/Workspace.hpp" #include "../../utilities/core/Logger.hpp" #include <utilities/idd/EvaporativeCooler_Indirect_ResearchSpecial_FieldEnums.hxx> #include <utilities/idd/IddEnums.hxx> using namespace openstudio::model; namespace openstudio { namespace energyplus { boost::optional<IdfObject> ForwardTranslator::translateEvaporativeCoolerIndirectResearchSpecial( EvaporativeCoolerIndirectResearchSpecial & modelObject ) { OptionalString s; OptionalDouble d; OptionalModelObject temp; IdfObject idfObject(IddObjectType::EvaporativeCooler_Indirect_ResearchSpecial); m_idfObjects.push_back(idfObject); // Name s = modelObject.name(); if(s) { idfObject.setName(*s); } // AvailabilityScheduleName boost::optional<Schedule> sched = modelObject.availabilitySchedule(); if( sched ) { boost::optional<IdfObject> _sched = translateAndMapModelObject(sched.get()); OS_ASSERT(_sched); idfObject.setString(EvaporativeCooler_Indirect_ResearchSpecialFields::AvailabilityScheduleName,_sched->name().get()); } // CoolerMaximumEffectiveness d = modelObject.coolerMaximumEffectiveness(); if( d ) { idfObject.setDouble(EvaporativeCooler_Indirect_ResearchSpecialFields::CoolerMaximumEffectiveness,d.get()); } // RecirculatingWaterPumpPowerConsumption d = modelObject.recirculatingWaterPumpPowerConsumption(); if( d ) { idfObject.setDouble(EvaporativeCooler_Indirect_ResearchSpecialFields::RecirculatingWaterPumpPowerConsumption,d.get()); } // SecondaryFanFlowRate if( modelObject.isSecondaryFanFlowRateAutosized() ) { idfObject.setString(EvaporativeCooler_Indirect_ResearchSpecialFields::SecondaryFanFlowRate,"Autosize"); } else if( (d = modelObject.secondaryFanFlowRate()) ) { idfObject.setDouble(EvaporativeCooler_Indirect_ResearchSpecialFields::SecondaryFanFlowRate,d.get()); } // SecondaryFanTotalEfficiency d = modelObject.secondaryFanTotalEfficiency(); if( d ) { idfObject.setDouble(EvaporativeCooler_Indirect_ResearchSpecialFields::SecondaryFanTotalEfficiency,d.get()); } // SecondaryFanDeltaPressure d = modelObject.secondaryFanDeltaPressure(); if( d ) { idfObject.setDouble(EvaporativeCooler_Indirect_ResearchSpecialFields::SecondaryFanDeltaPressure,d.get()); } // PrimaryAirInletNodeName if( boost::optional<model::ModelObject> mo = modelObject.inletModelObject() ) { OS_ASSERT(mo->optionalCast<model::Node>()); idfObject.setString(EvaporativeCooler_Indirect_ResearchSpecialFields::PrimaryAirInletNodeName,mo->name().get()); } // PrimaryAirOutletNodeName if( boost::optional<model::ModelObject> mo = modelObject.outletModelObject() ) { OS_ASSERT(mo->optionalCast<model::Node>()); idfObject.setString(EvaporativeCooler_Indirect_ResearchSpecialFields::PrimaryAirOutletNodeName,mo->name().get()); idfObject.setString(EvaporativeCooler_Indirect_ResearchSpecialFields::SensorNodeName,mo->name().get()); } // DewpointEffectivenessFactor d = modelObject.dewpointEffectivenessFactor(); if( d ) { idfObject.setDouble(EvaporativeCooler_Indirect_ResearchSpecialFields::DewpointEffectivenessFactor,d.get()); } // DriftLossFraction d = modelObject.driftLossFraction(); if( d ) { idfObject.setDouble(EvaporativeCooler_Indirect_ResearchSpecialFields::DriftLossFraction,d.get()); } // BlowdownConcentrationRatio d = modelObject.blowdownConcentrationRatio(); if( d ) { idfObject.setDouble(EvaporativeCooler_Indirect_ResearchSpecialFields::BlowdownConcentrationRatio,d.get()); } // SecondaryAirInletNode if( boost::optional<model::Node> node = modelObject.getImpl<model::detail::EvaporativeCoolerIndirectResearchSpecial_Impl>()->reliefAirInletNode() ) { idfObject.setString(EvaporativeCooler_Indirect_ResearchSpecialFields::ReliefAirInletNodeName,node->name().get()); } return boost::optional<IdfObject>(idfObject); } } // energyplus } // openstudio
ouankou/rose
projects/MatlabTranslation/src/transformations/MatrixTypeTransformer.cc
#include <numeric> #include "MatrixTypeTransformer.h" #include "rose.h" #include "sageGeneric.h" #include "utility/utils.h" namespace sb = SageBuilder; namespace ru = RoseUtils; namespace MatlabToCpp { // \note see below for an alternative approach struct MatrixTypeSetter : AstSimpleProcessing { typedef std::map<SgType*, SgType*> instantiation_map; instantiation_map memory; MatrixTypeSetter() : memory() {} virtual void visit(SgNode* n); }; struct TemplateArgListBuilder { bool first; TemplateArgListBuilder() : first(true) {} std::string operator()(std::string s, SgType* t) { if (first) { first = false; s += ", "; } return s += t->unparseToString(); } }; struct MatrixVarTypeSetter { typedef MatrixTypeSetter::instantiation_map instantiation_map; instantiation_map& memory; explicit MatrixVarTypeSetter(instantiation_map& m) : memory(m) {} std::string genTemplateTypeName(SgTypeTuple& t) { return std::accumulate( t.get_types().begin(), t.get_types().end(), std::string("Tuple<"), TemplateArgListBuilder() ) + ">"; } std::string genTemplateTypeName(SgTypeMatrix& m) { std::string res = "Matrix<"; res += m.get_base_type()->unparseToString(); res += ">"; return res; } template <class T> void convert_type(SgInitializedName& n, T& t) { SgType*& prevconv = memory[&t]; if (!prevconv) { std::string tyname = genTemplateTypeName(t); SgScopeStatement* scope = sg::ancestor<SgScopeStatement>(&n); ROSE_ASSERT(scope); prevconv = sb::buildOpaqueType(tyname, scope); } n.set_type(prevconv); } void handle(SgNode& n) {} void handle(SgInitializedName& n) { if (isSgTypeMatrix(n.get_type())) convert_type(n, *isSgTypeMatrix(n.get_type())); else if (isSgTypeTuple(n.get_type())) convert_type(n, *isSgTypeTuple(n.get_type())); else { std::cerr << ":: " << n.get_name() << ": " << ru::str(n.get_type()) << std::flush << " " << typeid(*n.get_type()).name() << std::endl; // ROSE_ASSERT(false); } } }; void MatrixTypeSetter::visit(SgNode* n) { sg::dispatch(MatrixVarTypeSetter(memory), n); } void transformMatrixType(SgProject* project) { MatrixTypeSetter matrixTraversal; matrixTraversal.traverse(project, preorder); } } /* namespace MatlabTransformation */ /********* *******/ /********* end of file *******/ /********* *******/ /*****************************/ /********* *******/ /********* old stuff *******/ /********* below *******/ /********* *******/ /* struct PowerOpPattern : sg::DispatchHandler <std::vector<SgPowerOp*> > { void handle(SgNode& n) {} void handle(SgPowerOp& n) { res.push_back(&n); } }; struct PowerOpTransformer : AstSimpleProcessing { void visit(SgNode* ) override; }; PowerOpTransformer::visit(SgNode* n) { std::vector<SgPowerOp*> powerops = sg::dispatch(PowerOpPattern(), n); std::vector<SgPowerOp*>::iterator aa = powerops.begin(); std::vector<SgPowerOp*>::iterator zz = powerops.end(); while (aa != zz) { SgExpression* lhs = (**aa).get_lhs_operand(); SgExpression* rhs = (**aa).get_rhs_operand(); SgExpression* lcp = si::deepCopy(lhs); SgExpression* rcp = si::deepCopy(rhs); SgVarRefExpr* var = sb::buildOpaqueVarRefExp("pow"); SgFunctionCallExp* powcall = sb::buildFunctionCallExpr(var); } } */ #if 0 too complicated and does not work, as there is no Matrix template when we parse the Matlab code. ==> solution: opaque types! /// function family to find a template class declaration with a given name struct TemplateClassFinder : sg::DispatchHandler<SgTemplateClassDeclaration*> { SgName name; explicit TemplateClassFinder(SgName n) : name(n) {} void handle(SgNode&) { /* only looking for template class decls */ } void handle(SgTemplateClassDeclaration& n) { if ((n.get_name() == name) && true /* \todo \pp should be scope test */) { res = &n; } } }; /// \brief Traverses the AST and finds a matrix template. /// The found template can be instantiated with a float type. struct FindMatrixTemplate : AstSimpleProcessing { SgTemplateClassDeclaration* matrix; SgTemplateClassDeclaration* tuple; FindMatrixTemplate() : matrix(NULL), tuple(NULL) {} virtual void visit(SgNode* n); }; void FindMatrixTemplate::visit(SgNode* n) { static const std::string matrix_template_name("matrix"); static const std::string tuple_template_name("tuple"); if (!matrix) matrix = sg::dispatch(TemplateClassFinder(matrix_template_name), n); if (!tuple) tuple = sg::dispatch(TemplateClassFinder(tuple_template_name), n); } /// Traverses AST and replaces every SgMatrixType with a template /// instantiation of matrix<float>. struct MatrixTypeSetter : AstSimpleProcessing { typedef std::map<SgType*, SgType*> instantiation_map; instantiation_map memory; SgTemplateClassDeclaration* matrix_t; SgTemplateClassDeclaration* tuple_t; MatrixTypeSetter(SgTemplateClassDeclaration* m, SgTemplateClassDeclaration* t) : memory(), matrix_t(m), tuple_t(t) { ROSE_ASSERT(m && t); } virtual void visit(SgNode* n); }; struct MatrixVarTypeSetter { typedef MatrixTypeSetter::instantiation_map instantiation_map; instantiation_map& memory; SgTemplateClassDeclaration* matrix_t; SgTemplateClassDeclaration* tuple_t; MatrixVarTypeSetter( instantiation_map& mem, SgTemplateClassDeclaration* m, SgTemplateClassDeclaration* t ) : memory(mem), matrix_t(m), tuple_t(t) {} SgTemplateClassDeclaration* baseTemplate(const SgTypeTuple&) { return matrix_t; } SgTemplateClassDeclaration* baseTemplate(const SgTypeMatrix&) { return tuple_t; } SgNodePtrList genTemplateArgumentList(SgTypeTuple& t) { SgNodePtrList lst(t.get_types().begin(), t.get_types().end()); return lst; } SgNodePtrList genTemplateArgumentList(SgTypeMatrix& m) { SgNodePtrList res; res.push_back(m.get_base_type()); return res; } template <class T> void convert_type(SgInitializedName& n, T& t) { SgType*& prevconv = memory[&t]; if (!prevconv) { SgNodePtrList targs = genTemplateArgumentList(t); prevconv = sb::buildClassTemplateType(baseTemplate(t), targs); } n.set_type(prevconv); } void handle(SgNode& n) {} void handle(SgInitializedName& n) { if (isSgTypeMatrix(n.get_type())) convert_type(n, *isSgTypeMatrix(n.get_type())); else if (isSgTypeTuple(n.get_type())) convert_type(n, *isSgTypeTuple(n.get_type())); } }; #endif
zealoussnow/chromium
chrome/browser/extensions/installed_loader.h
<filename>chrome/browser/extensions/installed_loader.h // Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_EXTENSIONS_INSTALLED_LOADER_H_ #define CHROME_BROWSER_EXTENSIONS_INSTALLED_LOADER_H_ #include <set> #include "base/files/file_path.h" namespace extensions { class ExtensionPrefs; class ExtensionRegistry; class ExtensionService; struct ExtensionInfo; // Used in histogram Extensions.HostPermissions.GrantedAccess, // Extensions.HostPermissions.GrantedAccessForBroadRequests and // Extensions.HostPermissions.GrantedAccessForTargetedRequests. // Entries should not be renumbered and numeric values should never be reused. // If you are adding to this enum, update HostPermissionAccess enum in // tools/metrics/histograms/enums.xml. enum class HostPermissionsAccess { kCannotAffect = 0, kNotRequested = 1, kOnClick = 2, kOnSpecificSites = 3, kOnAllRequestedSites = 4, kOnActiveTabOnly = 5, kMaxValue = kOnActiveTabOnly, }; // Loads installed extensions from the prefs. class InstalledLoader { public: explicit InstalledLoader(ExtensionService* extension_service); virtual ~InstalledLoader(); // Loads extension from prefs. void Load(const ExtensionInfo& info, bool write_to_prefs); // Loads all installed extensions (used by startup and testing code). void LoadAllExtensions(); // Allows tests to verify metrics without needing to go through // LoadAllExtensions(). void RecordExtensionsMetricsForTesting(); private: // Returns the flags that should be used with Extension::Create() for an // extension that is already installed. int GetCreationFlags(const ExtensionInfo* info); // Record metrics related to the loaded extensions. void RecordExtensionsMetrics(); ExtensionService* extension_service_; ExtensionRegistry* extension_registry_; ExtensionPrefs* extension_prefs_; // Paths to invalid extension manifests, which should not be loaded. std::set<base::FilePath> invalid_extensions_; }; } // namespace extensions #endif // CHROME_BROWSER_EXTENSIONS_INSTALLED_LOADER_H_
RainbowKiwiFOX/AuthMeFixed
src/main/java/fr/xephi/authme/converter/SqlToFlat.java
package fr.xephi.authme.converter; import java.util.List; import org.bukkit.command.CommandSender; import fr.xephi.authme.AuthMe; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.cache.auth.PlayerAuth; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.FlatFileThread; import fr.xephi.authme.settings.Messages; public class SqlToFlat implements Converter { public AuthMe plugin; public DataSource database; public CommandSender sender; public SqlToFlat(AuthMe plugin, DataSource database, CommandSender sender) { this.plugin = plugin; this.database = database; this.sender = sender; } @Override public void run() { try { FlatFileThread flat = new FlatFileThread(); flat.start(); List<PlayerAuth> auths = database.getAllAuths(); int i = 0; final int size = auths.size(); for (PlayerAuth auth : auths) { flat.saveAuth(auth); i++; if ((i % 100) == 0) { sender.sendMessage("Conversion Status : " + i + " / " + size); } } if (flat != null && flat.isAlive()) flat.interrupt(); sender.sendMessage("Successfully convert from SQL table to file auths.db"); return; } catch (Exception ex) { ConsoleLogger.showError(ex.getMessage()); Messages.getInstance()._(sender, "error"); return; } } }
yyvess/spring-data-rest
spring-data-rest-tests/spring-data-rest-tests-jpa/src/test/java/org/springframework/data/rest/webmvc/RepositoryPropertyReferenceControllerIntegrationTests.java
<reponame>yyvess/spring-data-rest<gh_stars>100-1000 /* * Copyright 2015-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.data.rest.webmvc; import static org.assertj.core.api.Assertions.*; import static org.mockito.Mockito.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.rest.tests.AbstractControllerIntegrationTests; import org.springframework.data.rest.webmvc.jpa.Book; import org.springframework.data.rest.webmvc.jpa.BookRepository; import org.springframework.data.rest.webmvc.jpa.JpaRepositoryConfig; import org.springframework.data.rest.webmvc.jpa.TestDataPopulator; import org.springframework.http.HttpStatus; import org.springframework.test.context.ContextConfiguration; import org.springframework.transaction.annotation.Transactional; /** * @author <NAME> */ @ContextConfiguration(classes = JpaRepositoryConfig.class) @Transactional class RepositoryPropertyReferenceControllerIntegrationTests extends AbstractControllerIntegrationTests { @Autowired RepositoryPropertyReferenceController controller; @Autowired TestDataPopulator populator; @Autowired BookRepository books; PersistentEntityResourceAssembler assembler; RootResourceInformation information; @BeforeEach void setUp() { this.assembler = mock(PersistentEntityResourceAssembler.class); this.information = getResourceInformation(Book.class); this.populator.populateRepositories(); } @Test void exposesResourceForCustomizedPropertyResourcePath() throws Exception { Book book = books.findAll().iterator().next(); assertThat(controller.followPropertyReference(information, book.id, "creators", assembler).getStatusCode()) .isEqualTo(HttpStatus.OK); } @Test void doesNotExposeOriginalPathIfPropertyResourcePathIsCustomized() { Book book = books.findAll().iterator().next(); assertThatExceptionOfType(ResourceNotFoundException.class) // .isThrownBy(() -> controller.followPropertyReference(information, book.id, "authors", assembler)); } }
CommandPost/FinalCutProFrameworks
Headers/Frameworks/Ozone/OZCacheDisplayManager.h
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Mar 11 2021 20:53:35). // // Copyright (C) 1997-2019 <NAME>. // #import <objc/NSObject.h> @class NSMutableArray, NSTimer, OZCanvasModule; @interface OZCacheDisplayManager : NSObject { OZCanvasModule *_pCanvas; struct OZFrameSet *_pFrames; NSTimer *_pTimer; NSMutableArray *_pDisplays; CDStruct_1b6d18a9 _checkTime; BOOL _isObserver; BOOL _grabbingLocks; struct PCMutex _cacheLocksMutex; struct map<CMTime, std::__1::pair<PCHash128, PCNSRef<id>>, std::__1::less<CMTime>, std::__1::allocator<std::__1::pair<const CMTime, std::__1::pair<PCHash128, PCNSRef<id>>>>> _cacheLocks; } - (id).cxx_construct; - (void).cxx_destruct; - (void)clearBitmapLocks; - (void)addBitmapLock:(const CDStruct_1b6d18a9 *)arg1 hash:(const struct PCHash128 *)arg2 lock:(const PCNSRef_71174270 *)arg3; - (BOOL)isCached:(CDStruct_1b6d18a9)arg1; - (void)notify:(unsigned int)arg1; - (void)timerAction:(id)arg1; - (void)checkSomeFrames:(BOOL)arg1; - (void)reacquireCacheLocks; - (void)surrenderCacheLocks; - (void)stopTimer; - (void)resumeTimer; - (void)startTimer; - (void)removeFromOZObserver; - (void)addToOZObserver; - (void)updateSetup; - (const struct OZFrameSet *)getFrames; - (void)clearCached; - (void)addCachedStart:(const CDStruct_1b6d18a9 *)arg1 end:(const CDStruct_1b6d18a9 *)arg2; - (void)addCachedRange:(const struct PCTimeRange *)arg1; - (void)tellDisplaysToUpdate; - (void)removeDisplay:(id)arg1; - (void)addDisplay:(id)arg1; - (void)dealloc; - (id)initWithCanvas:(id)arg1; @end
didizlatkova/tvityr
bl/passport.js
<gh_stars>0 var FACEBOOK_APP_ID = process.env.FACEBOOK_APP_ID || "id", FACEBOOK_APP_SECRET = process.env.FACEBOOK_APP_SECRET || "secret", FacebookStrategy = require('passport-facebook').Strategy; module.exports = function(passport, database) { var usersDb = database.collection('users'), users = require('../db/users')(usersDb); var registerFacebookUser = function(profile, callback) { var user = { names: profile.name, userName: profile.id, birthdate: profile.birthday, email: profile.email }; if (profile.gender === 'male') { user.gender = 'мъж'; } else if (profile.gender === 'female') { user.gender = 'жена'; } if (profile.picture && profile.picture.data && profile.picture.data.url) { user.picture = profile.picture.data.url; } users.create(user, function(user, err) { callback(user); }); }; passport.serializeUser(function(user, done) { done(null, user); }); passport.deserializeUser(function(user, done) { done(null, user); }); passport.use(new FacebookStrategy({ clientID: FACEBOOK_APP_ID, clientSecret: FACEBOOK_APP_SECRET, callbackURL: "/auth/facebook/callback", profileFields: ['id', 'displayName', 'emails', 'gender', 'birthday', 'photos'] }, function(accessToken, refreshToken, profile, done) { profile = profile._json; users.getByUserName(profile.id, function(user) { if (user) { return done(null, user); } if (!profile.email) { registerFacebookUser(profile, function(user) { return done(null, user); }); } else { users.getByEmail(profile.email, function(user, err) { if (user) { return done(null, user); } registerFacebookUser(profile, function(user) { return done(null, user); }); }); } }); } )); };
1690296356/jdk
test/langtools/tools/javac/annotations/typeAnnotations/TypeAnnotationsPositionsOnRecords.java
/* * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * @test * @bug 8246774 * @summary Verify location of type annotations on records * @library /tools/lib * @modules * jdk.jdeps/com.sun.tools.classfile * jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main * jdk.compiler/com.sun.tools.javac.code * jdk.compiler/com.sun.tools.javac.util * @build toolbox.ToolBox toolbox.JavacTask * @run main TypeAnnotationsPositionsOnRecords */ import java.util.List; import java.util.ArrayList; import java.io.File; import java.nio.file.Paths; import java.lang.annotation.*; import java.util.Arrays; import com.sun.tools.classfile.*; import com.sun.tools.javac.util.Assert; import toolbox.JavacTask; import toolbox.ToolBox; public class TypeAnnotationsPositionsOnRecords { final String src = """ import java.lang.annotation.*; @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE_USE }) @interface Nullable {} record Record1(@Nullable String t) {} record Record2(@Nullable String t) { public Record2 {} } record Record3(@Nullable String t1, @Nullable String t2) {} record Record4(@Nullable String t1, @Nullable String t2) { public Record4 {} } record Record5(String t1, @Nullable String t2) {} record Record6(String t1, @Nullable String t2) { public Record6 {} } """; public static void main(String... args) throws Exception { new TypeAnnotationsPositionsOnRecords().run(); } ToolBox tb = new ToolBox(); void run() throws Exception { compileTestClass(); checkClassFile(new File(Paths.get(System.getProperty("user.dir"), "Record1.class").toUri()), 0); checkClassFile(new File(Paths.get(System.getProperty("user.dir"), "Record2.class").toUri()), 0); checkClassFile(new File(Paths.get(System.getProperty("user.dir"), "Record3.class").toUri()), 0, 1); checkClassFile(new File(Paths.get(System.getProperty("user.dir"), "Record4.class").toUri()), 0, 1); checkClassFile(new File(Paths.get(System.getProperty("user.dir"), "Record5.class").toUri()), 1); checkClassFile(new File(Paths.get(System.getProperty("user.dir"), "Record6.class").toUri()), 1); } void compileTestClass() throws Exception { new JavacTask(tb) .sources(src) .run(); } void checkClassFile(final File cfile, int... taPositions) throws Exception { ClassFile classFile = ClassFile.read(cfile); int accessorPos = 0; int checkedAccessors = 0; for (Method method : classFile.methods) { String methodName = method.getName(classFile.constant_pool); if (methodName.equals("toString") || methodName.equals("hashCode") || methodName.equals("equals")) { // ignore continue; } if (methodName.equals("<init>")) { checkConstructor(classFile, method, taPositions); } else { for (int taPos : taPositions) { if (taPos == accessorPos) { checkAccessor(classFile, method); checkedAccessors++; } } accessorPos++; } } checkFields(classFile, taPositions); Assert.check(checkedAccessors == taPositions.length); } /* * there can be several parameters annotated we have to check that the ones annotated are the * expected ones */ void checkConstructor(ClassFile classFile, Method method, int... positions) throws Exception { List<TypeAnnotation> annos = new ArrayList<>(); findAnnotations(classFile, method, annos); Assert.check(annos.size() == positions.length); int i = 0; for (int pos : positions) { TypeAnnotation ta = annos.get(i); Assert.check(ta.position.type.toString().equals("METHOD_FORMAL_PARAMETER")); Assert.check(ta.position.parameter_index == pos); i++; } } /* * this case is simpler as there can only be one annotation at the accessor and it has to be applied * at the return type */ void checkAccessor(ClassFile classFile, Method method) { List<TypeAnnotation> annos = new ArrayList<>(); findAnnotations(classFile, method, annos); Assert.check(annos.size() == 1); TypeAnnotation ta = annos.get(0); Assert.check(ta.position.type.toString().equals("METHOD_RETURN")); } /* * here we have to check that only the fields for which its position matches with the one of the * original annotated record component are annotated */ void checkFields(ClassFile classFile, int... positions) { if (positions != null && positions.length > 0) { int fieldPos = 0; int annotationPos = 0; int currentAnnoPosition = positions[annotationPos]; int annotatedFields = 0; for (Field field : classFile.fields) { List<TypeAnnotation> annos = new ArrayList<>(); findAnnotations(classFile, field, annos); if (fieldPos != currentAnnoPosition) { Assert.check(annos.size() == 0); } else { Assert.check(annos.size() == 1); TypeAnnotation ta = annos.get(0); Assert.check(ta.position.type.toString().equals("FIELD")); annotationPos++; currentAnnoPosition = annotationPos < positions.length ? positions[annotationPos] : -1; annotatedFields++; } fieldPos++; } Assert.check(annotatedFields == positions.length); } } // utility methods void findAnnotations(ClassFile cf, Method m, List<TypeAnnotation> annos) { findAnnotations(cf, m, Attribute.RuntimeVisibleTypeAnnotations, annos); findAnnotations(cf, m, Attribute.RuntimeInvisibleTypeAnnotations, annos); } void findAnnotations(ClassFile cf, Field m, List<TypeAnnotation> annos) { findAnnotations(cf, m, Attribute.RuntimeVisibleTypeAnnotations, annos); findAnnotations(cf, m, Attribute.RuntimeInvisibleTypeAnnotations, annos); } void findAnnotations(ClassFile cf, Method m, String name, List<TypeAnnotation> annos) { int index = m.attributes.getIndex(cf.constant_pool, name); if (index != -1) { Attribute attr = m.attributes.get(index); assert attr instanceof RuntimeTypeAnnotations_attribute; RuntimeTypeAnnotations_attribute tAttr = (RuntimeTypeAnnotations_attribute)attr; annos.addAll(Arrays.asList(tAttr.annotations)); } int cindex = m.attributes.getIndex(cf.constant_pool, Attribute.Code); if (cindex != -1) { Attribute cattr = m.attributes.get(cindex); assert cattr instanceof Code_attribute; Code_attribute cAttr = (Code_attribute)cattr; index = cAttr.attributes.getIndex(cf.constant_pool, name); if (index != -1) { Attribute attr = cAttr.attributes.get(index); assert attr instanceof RuntimeTypeAnnotations_attribute; RuntimeTypeAnnotations_attribute tAttr = (RuntimeTypeAnnotations_attribute)attr; annos.addAll(Arrays.asList(tAttr.annotations)); } } } void findAnnotations(ClassFile cf, Field m, String name, List<TypeAnnotation> annos) { int index = m.attributes.getIndex(cf.constant_pool, name); if (index != -1) { Attribute attr = m.attributes.get(index); assert attr instanceof RuntimeTypeAnnotations_attribute; RuntimeTypeAnnotations_attribute tAttr = (RuntimeTypeAnnotations_attribute)attr; annos.addAll(Arrays.asList(tAttr.annotations)); } } }
pop/wash
plugin/findEntry_test.go
package plugin import ( "context" "fmt" "testing" "github.com/puppetlabs/wash/datastore" "github.com/stretchr/testify/assert" ) type mockParent struct { EntryBase entries []Entry } func (g *mockParent) List(context.Context) ([]Entry, error) { return g.entries, nil } func (g *mockParent) ChildSchemas() []*EntrySchema { return nil } func (g *mockParent) Schema() *EntrySchema { return nil } type mockEntry struct { EntryBase } func newMockEntry(name string) *mockEntry { return &mockEntry{ EntryBase: NewEntry(name), } } func (e *mockEntry) Schema() *EntrySchema { return nil } func TestFindEntry(t *testing.T) { SetTestCache(datastore.NewMemCache()) defer UnsetTestCache() type testcase struct { segments []string expectedEntry string expectedErr error } runTestCase := func(parent Parent, c testcase) { got, err := FindEntry(context.Background(), parent, c.segments) if c.expectedEntry != "" && assert.NotNil(t, got) { assert.Equal(t, c.expectedEntry, CName(got)) } else { assert.Nil(t, got) } if c.expectedErr == nil { assert.Nil(t, err) } else { assert.Equal(t, c.expectedErr, err) } } foo := newMockEntry("foo/bar") parent := &mockParent{NewEntry("root"), []Entry{foo}} parent.SetTestID("/root") parent.DisableDefaultCaching() for _, c := range []testcase{ {[]string{"not found"}, "", fmt.Errorf("The not found entry does not exist")}, {[]string{"foo#bar"}, "foo#bar", nil}, {[]string{"foo#bar", "bar"}, "", fmt.Errorf("The entry foo#bar is not a parent")}, } { runTestCase(parent, c) } baz := newMockEntry("baz") nestedParent := &mockParent{NewEntry("bar"), []Entry{baz}} nestedParent.DisableDefaultCaching() parent.entries = append(parent.entries, nestedParent) for _, c := range []testcase{ {[]string{"bar"}, "bar", nil}, {[]string{"bar", "foo"}, "", fmt.Errorf("The foo entry does not exist in the bar parent")}, {[]string{"bar", "baz"}, "baz", nil}, } { runTestCase(parent, c) } // Finally, test the duplicate cname error response duplicateFoo := newMockEntry("foo#bar") parent.entries = append(parent.entries, duplicateFoo) expectedErr := DuplicateCNameErr{ ParentID: ID(parent), FirstChildName: foo.Name(), FirstChildSlashReplacer: '#', SecondChildName: duplicateFoo.Name(), SecondChildSlashReplacer: '#', CName: "foo#bar", } runTestCase( parent, testcase{[]string{"foo#bar"}, "", expectedErr}, ) }
lulululululu/cpp_client_telemetry
tests/common/MockIBandwidthController.hpp
// // Copyright (c) 2015-2020 Microsoft Corporation and Contributors. // SPDX-License-Identifier: Apache-2.0 // #pragma once #include "utils/Utils.hpp" #include "IBandwidthController.hpp" namespace testing { class MockIBandwidthController : public MAT::IBandwidthController { public: MOCK_METHOD0(GetProposedBandwidthBps, unsigned()); }; } // namespace testing
aliaksandr-klimovich/sandbox
language/patterns/observer.py
<filename>language/patterns/observer.py<gh_stars>1-10 # https://en.wikipedia.org/wiki/Observer_pattern class Observable: def __init__(self): self.__observers = [] def register_observer(self, observer): self.__observers.append(observer) def notify_observers(self, *args, **kwargs): for observer in self.__observers: observer.notify(self, *args, **kwargs) class Observer: def __init__(self, observable): observable.register_observer(self) def notify(self, observable, *args, **kwargs): print('Got', args, kwargs, 'from', observable, 'to', self) subject = Observable() observers = (Observer(subject), Observer(subject), Observer(subject)) subject.notify_observers('test')
JRF-tw/sunshine.jrf.org.tw
app/contexts/party/schedule_score_create_context.rb
<filename>app/contexts/party/schedule_score_create_context.rb class Party::ScheduleScoreCreateContext < BaseContext PERMITS = [:court_id, :year, :word_type, :number, :story_type, :start_on, :confirmed_realdate, :judge_name, :note, :appeal_judge].freeze + ScheduleScore.stored_attributes[:attitude_scores] # before_perform :can_not_score before_perform :check_story before_perform :check_schedule before_perform :check_judge before_perform :check_attitude_scores before_perform :build_schedule_score before_perform :assign_attribute before_perform :get_scorer_ids before_perform :get_scored_story_ids after_perform :auto_subscribe_story after_perform :alert_story_by_party_scored_count after_perform :alert_party_scored_story_count def initialize(party) @party = party end def perform(params) @params = permit_params(params[:schedule_score] || params, PERMITS) run_callbacks :perform do return add_error(:judge_already_scored) unless @schedule_score.save @schedule_score end end private def can_not_score # TODO : Block user end def check_story context = Party::CheckScheduleScoreInfoContext.new(@party) @story = context.perform(@params) return add_error(:story_not_found, context.error_messages.join(',')) unless @story end def check_schedule context = Party::CheckScheduleScoreDateContext.new(@party) @schedule = context.perform(@params) return add_error(:schedule_not_found, context.error_messages.join(',')) if context.has_error? end def check_judge context = Party::CheckScheduleScoreJudgeContext.new(@party) @judge = context.perform(@params) return add_error(:judge_not_found, context.error_messages.join(',')) unless @judge end def check_attitude_scores ScheduleScore.stored_attributes[:attitude_scores].each do |keys| return add_error(:attitude_scores_blank) unless @params[keys].present? end return false if has_error? end def build_schedule_score @schedule_score = @party.schedule_scores.new(@params) end def assign_attribute @schedule_score.assign_attributes(schedule: @schedule, judge: @judge, story: @story) end # TODO : alert need refactory, performance issue def get_scorer_ids schedule_scorer_ids = Story.find(@story.id).schedule_scores.where(schedule_rater_type: 'Party').map(&:schedule_rater_id) verdict_scorer_ids = Story.find(@story.id).verdict_scores.where(verdict_rater_type: 'Party').map(&:verdict_rater_id) @total_scorer_ids = (schedule_scorer_ids + verdict_scorer_ids).uniq end def get_scored_story_ids schedule_scored_story_ids = ScheduleScore.where(schedule_rater: @party).map(&:story_id) verdict_scored_story_ids = VerdictScore.where(verdict_rater: @party).map(&:story_id) @total_scored_story_ids = (schedule_scored_story_ids + verdict_scored_story_ids).uniq end def auto_subscribe_story Party::StorySubscriptionToggleContext.new(@story).perform(@party) unless PartyQueries.new(@party).already_subscribed_story?(@story) end def alert_story_by_party_scored_count SlackService.notify_scored_time_over_range_alert("案件編號 #{@story.id} 同一案件,參與評鑑的「當事人人數」超過 #{Story::MAX_PARTY_SCORED_COUNT} 人") if @total_scorer_ids.count >= Story::MAX_PARTY_SCORED_COUNT && !@total_scorer_ids.include?(@party.id) end def alert_party_scored_story_count SlackService.notify_scored_time_over_range_alert("當事人 #{@party.name} 已評鑑超過超過 #{Party::MAX_SCORED_COUNT}") if @total_scored_story_ids.count >= Party::MAX_SCORED_COUNT && !@total_scored_story_ids.include?(@story.id) end end
dkandalam/borrow-ui
packages/ui/src/components/grid/grid.test.js
import React from 'react'; import { render, screen } from '@testing-library/react'; import { Row, Col } from './Grid'; describe('Grid = Row and Col ', () => { test('renders Row', () => { render(<Row>Content</Row>); const content = screen.getByText('Content'); expect(content).toHaveClass(`row`); }); test('renders Col', () => { // with default classes render(<Col>Content</Col>); const content = screen.getByText('Content'); expect(content).toHaveClass(`col-xs-12 col-sm-6`); // with size render(<Col size={12}>Content Size</Col>); const contentSize = screen.getByText('Content Size'); expect(contentSize).toHaveClass(`col-xs-12`); expect(contentSize).toHaveClass(`col-sm-12`); // with overridden col modifiers and custom class render( <Col colClassName="col-xs-4 col-lg-1" className="test-class"> Content Custom </Col> ); const contentCustom = screen.getByText('Content Custom'); expect(contentCustom).toHaveClass(`col-xs-4`); expect(contentCustom).toHaveClass(`col-lg-1`); expect(contentCustom).toHaveClass(`test-class`); }); });
romanroson/pis_code
practicioner_bundle/ch06-ensembles/test_ensemble.py
<gh_stars>1-10 # -*- coding: utf-8 -*- """Evaluating an Ensemble First, the best possible model has to be found. Then, usually 5-10 CNN models ara used for an ensemble. Based on Jensen’s Inequality the performance of an ensemble cannot be worse than a single model Example: $ python test_ensemble.py --models models Attributes: models (str): ppath to where our serialized network weights are stored on disk """ import os import argparse import glob import numpy as np from sklearn.preprocessing import LabelBinarizer from sklearn.metrics import classification_report from keras.models import load_model from keras.datasets import cifar10 def main(): """Evaluate ensemble """ # construct the argument parse and parse the arguments args = argparse.ArgumentParser() args.add_argument("-m", "--models", required=True, help="path to models directory") args = vars(args.parse_args()) # load the testing data, then scale it into the range [0, 1] (test_x, test_y) = cifar10.load_data()[1] test_x = test_x.astype("float") / 255.0 # initialize the label names for the CIFAR-10 dataset label_names = ["airplane", "automobile", "bird", "cat", "deer", "dog", "frog", "horse", "ship", "truck"] # convert the labels from integers to vectors label_binarizer = LabelBinarizer() test_y = label_binarizer.fit_transform(test_y) # construct the path used to collect the models then initialize the models list model_paths = os.path.sep.join([args["models"], "*.model"]) model_paths = list(glob.glob(model_paths)) models = [] # loop over the model paths, loading the model, and adding it to the list of models for (i, model_path) in enumerate(model_paths): print("[INFO] loading model {}/{}".format(i + 1, len(model_paths))) models.append(load_model(model_path)) # initialize the list of predictions print("[INFO] evaluating ensemble...") predictions = [] # loop over the models for model in models: # use the current model to make predictions on the testing data, # then store these predictions in the aggregate predictions list predictions.append(model.predict(test_x, batch_size=64)) # average the probabilities across all model predictions, then show a classification report predictions = np.average(predictions, axis=0) print(classification_report(test_y.argmax(axis=1), predictions.argmax(axis=1), target_names=label_names)) if __name__ == "__main__": main()
lolcats111/JDBC-Project-Group-B
src/com/dao/LoginDao.java
package com.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import com.util.DBUtil; public class LoginDao { public LoginDao() { super(); } public byte[] getClarkHash(String username) { byte[] clarkHash = null; try { // Step 2: Create a Connection object Connection cn = DBUtil.createConnection(); // Step 3: Create a PreparedStatement object using the Connection PreparedStatement ps = cn.prepareStatement("SELECT password_hash FROM CLERKS WHERE username=?"); ps.setString(1, username); // Step 4: Execute the query and store the result. ResultSet rs = ps.executeQuery(); // Step 5: Iterate the resultset and extract the information. if (rs != null) { while (rs.next()) { clarkHash = rs.getBytes("password_hash"); } } // Step 6: Close all the objects in the reverse order of its // creation. DBUtil.closeAllConnection(cn, ps, rs); } catch (SQLException e) { System.out.println(e.getMessage()); } return clarkHash; } }
pioneerAlpha/CP_Beginner_B2_Amar_iSchool
class 04 - solve class 1/E.cpp
#include<bits/stdc++.h> #define N ((int)1e6 + 5) #define ll long long #define fastio ios_base::sync_with_stdio(false),cin.tie(NULL) #define MAX ((int)1e6 + 5) #define endl "\n" using namespace std; int arr[1005]; int main() { fastio; int n , m , k; cin>>n>>m>>k; for(int i = 0 ; i<=m ; i++) cin>>arr[i]; int ans = 0; for(int i = 0 ; i<m ; i++){ int a = arr[i]^arr[m] , cnt = 0; /// the number of 1's in a is the number of mismatch for(int j = 0 ; j<n ; j++){ if( ( a & (1<<j ) ) != 0) cnt++; } if(cnt <= k) ans++; } cout<<ans<<endl; return 0; }
ufopilot/QT-App-Builder
builder/widgets/label_horizontal/label_horizontal.py
from qt_core import * class LabelHorizontal(QLabel): def __init__(self, *args): QLabel.__init__(self, *args) def paintEvent(self, event): painter = QPainter(self) painter.translate(0, self.height()) #painter.rotate(-90) # calculate the size of the font fm = QFontMetrics(painter.font()) xoffset = int(fm.boundingRect(self.text()).width()/2) yoffset = int(fm.boundingRect(self.text()).height()/2) x = int(self.width()/2) + yoffset y = int(self.height()/2) - xoffset # because we rotated the label, x affects the vertical placement, and y affects the horizontal painter.drawText(self.y()+10, self.x()-8, self.text()) painter.end() def minimumSizeHint(self): size = QLabel.minimumSizeHint(self) return QSize(size.height(), size.width()) def sizeHint(self): size = QLabel.sizeHint(self) return QSize(size.height(), size.width())
steve-phan/suadienthoai
src/components/Cart/ReviewOder/index.js
import { Link, navigate } from "gatsby" import React, { useState, useEffect } from "react" import { useDispatch, useSelector } from "react-redux" import { clearCart, checkCheckoutSession, } from "../../../redux/Cart/cart.actions" // import SEO from "../SEO" // EmailJS import emailjs, { init } from "emailjs-com" import { updateShoppingItem } from "../../../redux/User/user.actions" init("user_pjN71AkA6f8IUCEG6ohxc") const mapState = ({ cartData, user }) => ({ cartItems: cartData.cartItems, currentUser: user.currentUser, }) const ReviewOder = ({ location }) => { const [session, setSession] = useState({}) const dispatch = useDispatch() const { cartItems, currentUser } = useSelector(mapState) const oderSuccessItems = [...cartItems] const sumPay = oderSuccessItems .reduce((a, b) => a + Number(b.price) * b.quantity, 0) .toFixed(2) const sessionId = location.search.replace("?session_id=", "") const sendEmail = getSession => { const templeHTML = () => `<div> <h2>Deine Bestellungen</h2> ${oderSuccessItems.map( item => `<h4 style='color : chocolate'> Artikel: ${item.fields.name} <h4 style='padding-left : 10px'>Qty:${item.quantity}x</h4> Price : EUR${item.price} </h4>` )} <h4> Summe: EUR${sumPay} </h4> </div>` const templateParams = { message_html: templeHTML().split(",").join(""), from_name: `PhoneABC GmbH`, to_bcc: getSession.customer_details.email, } emailjs .send( "service_l634urs", "template_ivzmfwk", templateParams, "user_pjN71AkA6f8IUCEG6ohxc" ) .then( result => { // TODO something ... dispatch(clearCart()) // AFTER 2mins ..!redirect user to Home ! setTimeout(() => { dispatch(checkCheckoutSession(sessionId)) }, 120000) }, error => { console.log(error.text) } ) } const fetchSession = async () => { const getSession = await fetch( "/.netlify/functions/checkout-session?sessionId=" + sessionId ) .then(res => res.json()) .catch(err => { // console.log("error") navigate("/") }) if (getSession) { setSession(getSession) sendEmail(getSession) } } useEffect(() => { fetchSession() dispatch(updateShoppingItem({ currentUser, cartItems })) }, []) return ( <div className="wrap-page success-page"> <div className="thanks"> Vielen <br /> Dank{" "} </div> <p className="cart-small-text"> An email to confirm your Oder sent your Email : </p> <p className="success-email">{session?.customer_details?.email}</p> <p className="success-back"> <Link to="/shop">Back to our Shop</Link> </p> </div> ) } export default ReviewOder
sjrd/closure-compiler
test/com/google/javascript/jscomp/CheckGlobalThisTest.java
/* * Copyright 2007 The Closure Compiler 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 com.google.javascript.jscomp; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests {@link CheckGlobalThis}. */ @RunWith(JUnit4.class) public final class CheckGlobalThisTest extends CompilerTestCase { @Override @Before public void setUp() throws Exception { super.setUp(); enableParseTypeInfo(); } @Override protected CompilerPass getProcessor(Compiler compiler) { return new CombinedCompilerPass( compiler, new CheckGlobalThis(compiler)); } private void testFailure(String js) { testWarning(js, CheckGlobalThis.GLOBAL_THIS); } @Test public void testGlobalThis1() { testSame("var a = this;"); } @Test public void testGlobalThis2() { testFailure("this.foo = 5;"); } @Test public void testGlobalThis3() { testFailure("this[foo] = 5;"); } @Test public void testGlobalThis4() { testFailure("this['foo'] = 5;"); } @Test public void testGlobalThis5() { testFailure("(a = this).foo = 4;"); } @Test public void testGlobalThis6() { testSame("a = this;"); } @Test public void testGlobalThis7() { testFailure("var a = this.foo;"); } @Test public void testStaticFunction1() { testSame("function a() { return this; }"); } @Test public void testStaticFunction2() { testFailure("function a() { this.complex = 5; }"); } @Test public void testStaticFunction3() { testSame("var a = function() { return this; }"); } @Test public void testStaticFunction4() { testFailure("var a = function() { this.foo.bar = 6; }"); } @Test public void testStaticFunction5() { testSame("function a() { return function() { return this; } }"); } @Test public void testStaticFunction6() { testSame("function a() { return function() { this.x = 8; } }"); } @Test public void testStaticFunction7() { testSame("var a = function() { return function() { this.x = 8; } }"); } @Test public void testStaticFunction8() { testFailure("var a = function() { return this.foo; };"); } @Test public void testConstructor1() { testSame("/** @constructor */function A() { this.m2 = 5; }"); } @Test public void testConstructor2() { testSame("/** @constructor */var A = function() { this.m2 = 5; }"); } @Test public void testConstructor3() { testSame("/** @constructor */a.A = function() { this.m2 = 5; }"); } @Test public void testInterface1() { testSame( "/** @interface */function A() { /** @type {string} */ this.m2; }"); } @Test public void testOverride1() { testSame("/** @constructor */function A() { } var a = new A();" + "/** @override */ a.foo = function() { this.bar = 5; };"); } @Test public void testThisJSDoc1() { testSame("/** @this {whatever} */function h() { this.foo = 56; }"); } @Test public void testThisJSDoc2() { testSame("/** @this {whatever} */var h = function() { this.foo = 56; }"); } @Test public void testThisJSDoc3() { testSame("/** @this {whatever} */foo.bar = function() { this.foo = 56; }"); } @Test public void testThisJSDoc4() { testSame("/** @this {whatever} */function f() { this.foo = 56; }"); } @Test public void testThisJSDoc5() { testSame("function a() { /** @this {x} */function f() { this.foo = 56; } }"); } @Test public void testMethod1() { testSame("A.prototype.m1 = function() { this.m2 = 5; }"); } @Test public void testMethod2() { testSame("a.B.prototype.m1 = function() { this.m2 = 5; }"); } @Test public void testMethod3() { testSame("a.b.c.D.prototype.m1 = function() { this.m2 = 5; }"); } @Test public void testMethod4() { testSame("a.prototype['x' + 'y'] = function() { this.foo = 3; };"); } @Test public void testPropertyOfMethod() { testFailure("a.protoype.b = {}; " + "a.prototype.b.c = function() { this.foo = 3; };"); } @Test public void testStaticMethod1() { testFailure("a.b = function() { this.m2 = 5; }"); } @Test public void testStaticMethod2() { testSame("a.b = function() { return function() { this.m2 = 5; } }"); } @Test public void testStaticMethod3() { testSame("a.b.c = function() { return function() { this.m2 = 5; } }"); } @Test public void testMethodInStaticFunction() { testSame("function f() { A.prototype.m1 = function() { this.m2 = 5; } }"); } @Test public void testStaticFunctionInMethod1() { testSame("A.prototype.m1 = function() { function me() { this.m2 = 5; } }"); } @Test public void testStaticFunctionInMethod2() { testSame("A.prototype.m1 = function() {" + " function me() {" + " function myself() {" + " function andI() { this.m2 = 5; } } } }"); } @Test public void testInnerFunction1() { testFailure("function f() { function g() { return this.x; } }"); } @Test public void testInnerFunction2() { testFailure("function f() { var g = function() { return this.x; } }"); } @Test public void testInnerFunction3() { testFailure( "function f() { var x = {}; x.y = function() { return this.x; } }"); } @Test public void testInnerFunction4() { testSame( "function f() { var x = {}; x.y(function() { return this.x; }); }"); } @Test public void testIssue182a() { testFailure("var NS = {read: function() { return this.foo; }};"); } @Test public void testIssue182b() { testFailure("var NS = {write: function() { this.foo = 3; }};"); } @Test public void testIssue182c() { testFailure("var NS = {}; NS.write2 = function() { this.foo = 3; };"); } @Test public void testIssue182d() { testSame("function Foo() {} " + "Foo.prototype = {write: function() { this.foo = 3; }};"); } @Test public void testLendsAnnotation1() { testFailure("/** @constructor */ function F() {}" + "dojo.declare(F, {foo: function() { return this.foo; }});"); } @Test public void testLendsAnnotation2() { testFailure("/** @constructor */ function F() {}" + "dojo.declare(F, /** @lends {F.bar} */ (" + " {foo: function() { return this.foo; }}));"); } @Test public void testLendsAnnotation3() { testSame("/** @constructor */ function F() {}" + "dojo.declare(F, /** @lends {F.prototype} */ (" + " {foo: function() { return this.foo; }}));"); } @Test public void testSuppressWarning() { testFailure("var x = function() { this.complex = 5; };"); } @Test public void testArrowFunction1() { testFailure("var a = () => this.foo;"); } @Test public void testArrowFunction2() { testFailure("(() => this.foo)();"); } @Test public void testArrowFunction3() { testFailure("function Foo() {} " + "Foo.prototype.getFoo = () => this.foo;"); } @Test public void testArrowFunction4() { testFailure("function Foo() {} " + "Foo.prototype.setFoo = (f) => { this.foo = f; };"); } @Test public void testInnerFunctionInClassMethod1() { // TODO(user): It would be nice to warn for using 'this' here testSame(lines( "function Foo() {}", "Foo.prototype.init = function() {", " button.addEventListener('click', function () {", " this.click();", " });", "}", "Foo.prototype.click = function() {}")); } @Test public void testInnerFunctionInClassMethod2() { // TODO(user): It would be nice to warn for using 'this' here testSame(lines( "function Foo() {", " var x = function() {", " button.addEventListener('click', function () {", " this.click();", " });", " }", "}")); } @Test public void testInnerFunctionInEs6ClassMethod() { // TODO(user): It would be nice to warn for using 'this' here testSame(lines( "class Foo {", " constructor() {", " button.addEventListener('click', function () {", " this.click();", " });", " }", " click() {}", "}")); } @Test public void testFunctionWithThisTypeAnnotated() throws Exception { testSame( lines( "/**", " * @type {function(this:{hello:string})}", " */", "function test() {", " console.log(this.hello)", "}")); } @Test public void testFunctionWithoutThisTypeAnnotated() throws Exception { testFailure( lines( "/**", " * @type {function()}", " */", "function test() {", " console.log(this.hello)", "}")); } }
jeffpanici75/programmers-calculator
shell/src/main/java/io/nybbles/progcalc/shell/Program.java
<filename>shell/src/main/java/io/nybbles/progcalc/shell/Program.java package io.nybbles.progcalc.shell; import io.nybbles.progcalc.common.Result; import io.nybbles.progcalc.shell.contracts.Configuration; import io.nybbles.progcalc.shell.gui.GuiShell; import io.nybbles.progcalc.shell.terminal.TerminalShell; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.swing.*; public class Program { private static final Logger s_logger = LoggerFactory.getLogger(Program.class); private Configuration _configuration; public Program(Configuration configuration) { _configuration = configuration; } private static void formatMessages(Result r) { for (var msg : r.getMessages()) { System.out.println(String.format( "[%s] %s", msg.getCode(), msg.getMessage())); } } private int runTerminal(String[] args) { var shell = new TerminalShell(_configuration); var r = new Result(); if (!shell.initialize(r)) { formatMessages(r); return 1; } var rc = shell.run(); return rc.isSuccess() ? 0 : 1; } private void runGui(String[] args) { try { System.setProperty( "apple.laf.useScreenMenuBar", "true"); System.setProperty( "com.apple.mrj.application.apple.menu.about.name", "Programmers' Calculator"); UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { s_logger.error("Unable to set macOS properties: {}", e.getMessage()); } var shell = new GuiShell(_configuration); var r = new Result(); if (!shell.initialize(r)) { formatMessages(r); return; } shell.run(); } public static void main(String[] args) { var options = new DefaultOptions(); options.parse(args); var configuration = new DefaultConfiguration(options); configuration.load(); Program main = new Program(configuration); main.runGui(args); } }
pranitpingale/gitJenkinsAllureCucumber16Feb19
node_modules/wdio-visual-regression-service/src/methods/SaveScreenshot.js
<gh_stars>0 import fs from 'fs-promise'; import BaseCompare from './BaseCompare'; import debug from 'debug'; const log = debug('wdio-visual-regression-service:SaveScreenshot'); export default class SaveScreenshot extends BaseCompare { constructor(options = {}) { super(); this.getScreenshotFile = options.screenshotName; } async afterScreenshot(context, base64Screenshot) { const screenshotPath = this.getScreenshotFile(context); log(`create screenshot file at ${screenshotPath}`); await fs.outputFile(screenshotPath, base64Screenshot, 'base64'); return this.createResultReport(0, true, true); } }
oyahiroki/nlp4j
nlp4j/nlp4j-wordnet/src/main/java/nlp4j/wordnetja/package-info.java
<reponame>oyahiroki/nlp4j<gh_stars>1-10 /** * @author <NAME> * */ package nlp4j.wordnetja;
rancherdev/ui
app/components/schema/input-masked/component.js
import Ember from 'ember'; export default Ember.TextField.extend({ classNames: ['form-control'], type: 'password' });
nokia/osgi-microfeatures
com.alcatel.as.service.api/src/com/alcatel/as/service/management/Shutdownable.java
<gh_stars>0 // Copyright 2000-2021 Nokia // // Licensed under the Apache License 2.0 // SPDX-License-Identifier: Apache-2.0 // package com.alcatel.as.service.management; /** * An interface to any contributor to the graceful shutdown mechanism * */ public interface Shutdownable { /** * invoked during shutdown procedure. implement condition checking. optionally * fork treatment in appropriate reactor. returning a non zero value trigger a * retry of the shutdown procedure maximum equal to the value of the return * * @return The retry delay in milliseconds, 0 if no retry needed */ int shutdown(); }
uluuka/3box-dapp
src/interface/store/departments/ipfs/selectors.js
export const initialState = {} export const getDeltaData = (state,delta) =>state[delta] && state[delta].data || null export const getDeltaStatus = (state,delta) =>state[delta] && state[delta].status || null export const getDeltaStarting = (state, starts) => Object.keys(state).filter(item => item.startsWith(starts)).map(filteredItem=> state[filteredItem])
dinorhythms/Teamwork-Backend
src/validation/JoiValidator.js
<filename>src/validation/JoiValidator.js<gh_stars>0 import Joi from '@hapi/joi'; /** * * Object that help to validate request details */ const JoiValidation = { validateString() { return Joi.string(); }, validateEmail() { return Joi.string().email(); }, validatePassword() { return Joi.string().min(8).strict() .required(); }, /** * number schema creator * @returns {Object} - number schema */ validateNumber() { return Joi.number(); }, }; export default JoiValidation;
git4wht/cloudbreak
core/src/main/java/com/sequenceiq/cloudbreak/reactor/api/event/recipe/UpscalePostRecipesRequest.java
<reponame>git4wht/cloudbreak package com.sequenceiq.cloudbreak.reactor.api.event.recipe; import java.util.Set; import com.sequenceiq.cloudbreak.reactor.api.event.resource.AbstractClusterScaleRequest; public class UpscalePostRecipesRequest extends AbstractClusterScaleRequest { public UpscalePostRecipesRequest(Long stackId, Set<String> hostGroups) { super(stackId, hostGroups); } }
jpmml/jpmml
pmml-evaluator/src/main/java/org/jpmml/evaluator/ArrayUtil.java
<filename>pmml-evaluator/src/main/java/org/jpmml/evaluator/ArrayUtil.java<gh_stars>10-100 /* * Copyright (c) 2012 University of Tartu */ package org.jpmml.evaluator; import java.util.*; import org.jpmml.manager.*; import org.dmg.pmml.*; import com.google.common.base.*; import com.google.common.cache.*; import com.google.common.collect.*; public class ArrayUtil { private ArrayUtil(){ } static public int getSize(Array array){ Integer n = array.getN(); if(n != null){ return n.intValue(); } List<String> context = getContent(array); return context.size(); } static public List<String> getContent(Array array){ return CacheUtil.getValue(array, ArrayUtil.cache); } static public double[] toArray(Array array){ int size = getSize(array); double[] result = new double[size]; List<? extends Number> content = getNumberContent(array); for(int i = 0; i < size; i++){ Number value = content.get(i); result[i] = value.doubleValue(); } return result; } static public List<? extends Number> getNumberContent(Array array){ Array.Type type = array.getType(); switch(type){ case INT: return getIntContent(array); case REAL: return getRealContent(array); default: break; } throw new TypeCheckException(Number.class, null); } static public List<Integer> getIntContent(Array array){ Function<String, Integer> transformer = new Function<String, Integer>(){ @Override public Integer apply(String string){ return Integer.valueOf(string); } }; return Lists.transform(getContent(array), transformer); } static public List<Double> getRealContent(Array array){ Function<String, Double> transformer = new Function<String, Double>(){ @Override public Double apply(String string){ return Double.valueOf(string); } }; return Lists.transform(getContent(array), transformer); } static public List<String> parse(Array array){ List<String> result; Array.Type type = array.getType(); switch(type){ case INT: case REAL: result = tokenize(array.getValue(), false); break; case STRING: result = tokenize(array.getValue(), true); break; default: throw new UnsupportedFeatureException(array, type); } Integer n = array.getN(); if(n != null && n.intValue() != result.size()){ throw new InvalidFeatureException(array); } return result; } static public List<String> tokenize(String string, boolean enableQuotes){ List<String> result = Lists.newArrayList(); StringBuilder sb = new StringBuilder(); boolean quoted = false; tokens: for(int i = 0; i < string.length(); i++){ char c = string.charAt(i); if(quoted){ if(c == '\\' && i < (string.length() - 1)){ c = string.charAt(i + 1); if(c == '\"'){ sb.append('\"'); i++; } else { sb.append('\\'); } continue tokens; } // End if sb.append(c); if(c == '\"'){ result.add(createToken(sb, enableQuotes)); quoted = false; } } else { if(c == '\"' && enableQuotes){ if(sb.length() > 0){ result.add(createToken(sb, enableQuotes)); } sb.append('\"'); quoted = true; } else if(Character.isWhitespace(c)){ if(sb.length() > 0){ result.add(createToken(sb, enableQuotes)); } } else { sb.append(c); } } } if(sb.length() > 0){ result.add(createToken(sb, enableQuotes)); } return Collections.unmodifiableList(result); } static private String createToken(StringBuilder sb, boolean enableQuotes){ String result; if(sb.length() > 1 && (sb.charAt(0) == '\"' && sb.charAt(sb.length() - 1) == '\"') && enableQuotes){ result = sb.substring(1, sb.length() - 1); } else { result = sb.substring(0, sb.length()); } sb.setLength(0); return result; } private static final LoadingCache<Array, List<String>> cache = CacheBuilder.newBuilder() .weakKeys() .build(new CacheLoader<Array, List<String>>(){ @Override public List<String> load(Array array){ return parse(array); } }); }
RUB-NDS/TLS-Attacker
TLS-Core/src/main/java/de/rub/nds/tlsattacker/core/constants/MaxFragmentLength.java
/** * TLS-Attacker - A Modular Penetration Testing Framework for TLS * * Copyright 2014-2022 Ruhr University Bochum, Paderborn University, Hackmanit GmbH * * Licensed under Apache License, Version 2.0 * http://www.apache.org/licenses/LICENSE-2.0.txt */ package de.rub.nds.tlsattacker.core.constants; import java.util.HashMap; import java.util.Map; import java.util.Random; public enum MaxFragmentLength { TWO_9((byte) 1), TWO_10((byte) 2), TWO_11((byte) 3), TWO_12((byte) 4); private byte value; private static final Map<Byte, MaxFragmentLength> MAP; private MaxFragmentLength(byte value) { this.value = value; } static { MAP = new HashMap<>(); for (MaxFragmentLength cm : MaxFragmentLength.values()) { MAP.put(cm.value, cm); } } public static MaxFragmentLength getMaxFragmentLength(byte value) { return MAP.get(value); } public static Integer getIntegerRepresentation(MaxFragmentLength maxFragmentLength) { switch (maxFragmentLength) { case TWO_9: return 512; case TWO_10: return 1024; case TWO_11: return 2048; case TWO_12: return 4096; // this SHOULD be unreachable default: return null; } } public byte getValue() { return value; } public byte[] getArrayValue() { return new byte[] { value }; } public static MaxFragmentLength getRandom(Random random) { MaxFragmentLength c = null; while (c == null) { Object[] o = MAP.values().toArray(); c = (MaxFragmentLength) o[random.nextInt(o.length)]; } return c; } }
Quicksilver-Project/quicksilveruml
src/uml/state_machine_diagram.h
#include "behavior_diagram.h" /**~UML Diagram Interchange~ * A_UMLStateMachine_modelElement_umlDiagramElement [Association] * * Owned Ends * *  umlDiagramElement : UMLStateMachineDiagram [0..*] * {redefines * A_UMLBehaviorDiagram_modelElement_umlDiagramElement * ::umlDiagramElement} (opposite * UMLStateMachineDiagram::modelElement) **/
denezt/software-design-patterns
solid/single_responsibility_principle/cohesion/refactoring/Main.java
class Main { public static void main(String[] args){ Square square = new Square(); square.calculateArea(); System.out.println("Value of square: " + String.valueOf(square.side)); SquareUI squareUI = new SquareUI(); for ( int i = 0; i < 100; i++) { if ((i * square.side) > 0){ squareUI.rotate(i * 5 * square.side); } } } }
markhorsfield/py4e101
other-proj/sandwich.func.py
<filename>other-proj/sandwich.func.py #!/usr/bin/python3 def sandwich(kind): print("-------") print(kind()) print("-------") def blt(): my_blt = " bacon\nlettuce\n tomato" return my_blt def bfast(): my_ec = " eggegg\ncheese" return my_ec sandwich(blt)
retrohead/openmenu
ui/ui_gdmenu.h
/* * File: ui_gdmenu.h * Project: ui * File Created: Sunday, 13th June 2021 12:33:33 pm * Author: <NAME> * ----- * Copyright (c) 2021 <NAME>, <NAME> * License: BSD 3-clause "New" or "Revised" License, http://www.opensource.org/licenses/BSD-3-Clause */ #pragma once #define UI_NAME GDMENU_EMU #define MAKE_FN(name, func) void name##_##func(void) #define FUNCTION(signal, func) MAKE_FN(signal, func) #define MAKE_FN_INPUT(name, func) void name##_##func(unsigned int button) #define FUNCTION_INPUT(signal, func) MAKE_FN_INPUT(signal, func) /* Called once on boot */ FUNCTION(UI_NAME, init); /* Similar to above for now but may change when swapping interfaces is added */ FUNCTION(UI_NAME, setup); /* Handles incoming input each frame, your job to manage */ FUNCTION_INPUT(UI_NAME, handle_input); /* Called per frame to draw your UI */ FUNCTION(UI_NAME, drawOP); FUNCTION(UI_NAME, drawTR);
clkbit123/TheOpenHarmony
Openharmony v1.0/foundation/graphic/lite/services/wms/include/server/lite_wms.h
<gh_stars>0 /* * Copyright (c) 2020 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef GRAPHIC_LITE_LITE_WMS_H #define GRAPHIC_LITE_LITE_WMS_H #include "common/lite_wm_type.h" #include "geometry2d.h" #include "liteipc_adapter.h" #include "serializer.h" namespace OHOS { class LiteWMS { public: static LiteWMS* GetInstance() { static LiteWMS wms; return &wms; } static void WMSRequestHandle(int funcId, void *origin, IpcIo *req, IpcIo *reply); private: LiteWMS() {}; ~LiteWMS() {} static int SurfaceRequestHandler(const IpcContext* context, void *ipcMsg, IpcIo *io, void *arg); void GetSurface(IpcIo *req, IpcIo *reply); void Show(IpcIo *req, IpcIo *reply); void Hide(IpcIo *req, IpcIo *reply); void RaiseToTop(IpcIo *req, IpcIo *reply); void LowerToBottom(IpcIo *req, IpcIo *reply); void MoveTo(IpcIo *req, IpcIo *reply); void Resize(IpcIo *req, IpcIo *reply); void Update(IpcIo *req, IpcIo *reply); void CreateWindow(IpcIo *req, IpcIo *reply); void RemoveWindow(IpcIo *req, IpcIo *reply); void GetEventData(IpcIo *req, IpcIo *reply); void Screenshot(IpcIo *req, IpcIo *reply); }; } #endif
kolinkrewinkel/Multiplex
Multiplex/IDEHeaders/IDEHeaders/IDEFoundation/IDEItemReferenceWrapper.h
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>. // #import "CDStructures.h" #import <IDEFoundation/IDEContainerItemWrapper.h> @interface IDEItemReferenceWrapper : IDEContainerItemWrapper { } - (void)setUsesTabs:(BOOL)arg1; - (BOOL)usesTabs; - (void)setTabWidth:(long long)arg1; - (long long)tabWidth; - (void)setRealPath:(id)arg1; - (id)realPath; - (void)setPath:(id)arg1; - (id)path; - (void)setLineEnding:(unsigned int)arg1; - (unsigned int)lineEnding; - (void)setIndentWidth:(long long)arg1; - (long long)indentWidth; - (void)setGroup:(id)arg1; - (id)group; - (void)setFullPath:(id)arg1; - (id)fullPath; - (void)setFileEncoding:(unsigned int)arg1; - (unsigned int)fileEncoding; - (void)setEntireContents:(id)arg1; - (id)entireContents; - (void)setContents:(id)arg1; - (id)contents; - (id)name; @end
mohnjahoney/website_source
plugins/similar_posts/similar_posts.py
""" Similar Posts plugin for Pelican. Adds a `similar_posts` list to every article's context. """ import logging import math import os from pelican import signals from gensim import corpora, models, similarities logger = logging.getLogger(__name__) def add_similar_posts(generator): max_count = generator.settings.get("SIMILAR_POSTS_MAX_COUNT", 5) min_score = generator.settings.get("SIMILAR_POSTS_MIN_SCORE", 0.0001) # Collect all documents. A document gets represented by a list of tags. docs = [ [tag.name for tag in article.tags] if hasattr(article, "tags") else [] for article in generator.articles ] if len(docs) == 0: return # No documents, nothing to do. # Build a dictionary of every unique tag. dictionary = corpora.Dictionary(docs) num_features = len(dictionary) if num_features == 0: return # No tags, nothing to do. # Vectorize each document as a bag-of-words. This creates a sparse matrix # where each line corresponds to a document, and each column a feature. corpus = [dictionary.doc2bow(doc) for doc in docs] del docs # Transform the vectors to tf*idf values. Here we use the same tf*idf # formula as Lucene's TFIDFSimilarity class, instead of Gensim's default # formula. Gensim's default idf = log2(D/df) does not handle some edge # cases very well, for example when all documents have the same terms # (because log2(D/df) == log2(1) == 0, which implies no similarity!) tfidf = models.TfidfModel( corpus, normalize=True, wlocal=lambda tf: tf ** 0.5, wglobal=lambda df, D: (1 + math.log((D + 1) / (df + 1))) ** 2, ) # Compute the cosine similarity of every document pair. sim = similarities.MatrixSimilarity(tfidf[corpus], num_features=num_features) for i, (article, scores) in enumerate(zip(generator.articles, sim)): # Obviously, article is similar to itself. Exclude it. scores[i] = min_score - 1 # Build (document index, score) tuples, sorted by score, then by date. selected = sorted( [(idx, score) for idx, score in enumerate(scores) if score >= min_score], key=lambda idx_score: (idx_score[1], generator.articles[idx_score[0]].date), reverse=True, )[:max_count] article.similar_posts = [generator.articles[idx] for idx, _ in selected] logger.debug( "{article}: similar_posts scores: {scores}".format( article=os.path.basename(article.source_path) if hasattr(article, "source_path") else i, scores=[score for _, score in selected], ) ) def register(): signals.article_generator_finalized.connect(add_similar_posts)
liaoheng/Common
common-ui/src/main/java/com/github/liaoheng/common/ui/widget/CURightClickVisibleContentEditText.java
package com.github.liaoheng.common.ui.widget; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import com.github.liaoheng.common.ui.R; import com.github.liaoheng.common.util.UIUtils; import androidx.core.content.ContextCompat; /** * 点击右侧图片显示密码 * * @author liaoheng * @version 2017-07-05 15:42 */ public class CURightClickVisibleContentEditText extends CURightClickEditText { private Drawable mShowImage; private Drawable mHideImage; public CURightClickVisibleContentEditText(Context context) { super(context); init(null); } public CURightClickVisibleContentEditText(Context context, AttributeSet attrs) { super(context, attrs); init(attrs); } public CURightClickVisibleContentEditText(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs); } public void init(AttributeSet attrs) { if (attrs != null) { TypedArray a = null; try { a = getContext().obtainStyledAttributes(attrs, R.styleable.CURightClickVisibleContentEditText); mShowImage = a.getDrawable(R.styleable.CURightClickVisibleContentEditText_showImage); mHideImage = a.getDrawable(R.styleable.CURightClickVisibleContentEditText_hideImage); } finally { if (mShowImage == null) { mShowImage = ContextCompat.getDrawable(getContext(), R.drawable.lcu_ic_remove_red_eye_black_24dp); } if (mHideImage == null) { mHideImage = ContextCompat.getDrawable(getContext(), R.drawable.lcu_ic_remove_red_eye_black_24dp); } if (a != null) { a.recycle(); } } } selectDrawable(false); setRightClickListener(new RightClickListener() { @Override public void onClick(Drawable right, boolean select) { selectDrawable(select); } }); } private void selectDrawable(boolean select) { Drawable left = getCompoundDrawables()[0]; if (select) { setCompoundDrawablesWithIntrinsicBounds( left, null, mShowImage, null); UIUtils.showOrHintEditTextContent(true, this); } else { setCompoundDrawablesWithIntrinsicBounds( left, null, mHideImage, null); UIUtils.showOrHintEditTextContent(false, this); } } }
contesini/redux-subspace
packages/react-redux-subspace/test/hooks/useParentSpace-spec.js
/** * Copyright 2017, IOOF Holdings Limited. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ import React from "react" import { Provider } from "react-redux" import configureStore from "redux-mock-store" import { renderHook } from "@testing-library/react-hooks" import useParentSpace from "../../src/hooks/useParentSpace" describe("useParentSpace Tests", () => { it("should return parent space", () => { let state = { subState: { value: "wrong" }, value: "expected" } let mockSubspace = configureStore()(state.subState) let mockStore = configureStore()(state) mockSubspace.parentStore = mockStore let wrapper = ({ children }) => ( <Provider store={mockSubspace}>{children}</Provider> ) let { result } = renderHook(() => useParentSpace(), { wrapper }) expect(result.current).to.equal(mockStore) }) it("should return new parent space if store change", () => { let state = { subState1: { value: "wrong" }, subState2: { value: "wrong" }, value: "expected" } let mockSubspace = configureStore()(state.subState1) let mockStore = configureStore()(state) mockSubspace.parentStore = mockStore let wrapper = ({ children }) => ( <Provider store={mockSubspace}>{children}</Provider> ) let { result, rerender } = renderHook(() => useParentSpace(), { wrapper }) mockSubspace = configureStore()(state.subState2) mockStore = configureStore()(state) mockSubspace.parentStore = mockStore rerender() expect(result.current).to.equal(mockStore) }) it("should return parent space from custom context", () => { it("should return parent space", () => { let state = { subState: { value: "wrong" }, value: "expected" } let mockSubspace = configureStore()(state.subState) let mockStore = configureStore()(state) mockSubspace.parentStore = mockStore let customContext = React.createContext(null) let wrapper = ({ children }) => ( <Provider store={mockSubspace} context={customContext}> {children} </Provider> ) let { result } = renderHook(() => useParentSpace(), { wrapper }) expect(result.current).to.equal(mockStore) }) }) })
KollegeX/DsaTabForMe
DsaTab/src/main/java/com/dsatab/data/Dice.java
<reponame>KollegeX/DsaTabForMe package com.dsatab.data; import android.text.TextUtils; import com.dsatab.util.Debug; import com.dsatab.util.Util; import java.security.SecureRandom; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Dice { public static class DiceRoll { public int dice; public int result; public DiceRoll(int dice, int result) { this.dice = dice; this.result = result; } } private static Random rnd = new SecureRandom(); public int diceCount = 1; public int diceType = 6; public int constant = 0; private static Pattern p = Pattern.compile("(\\d*)WA?(\\d*)([+-]?\\d*)", Pattern.CASE_INSENSITIVE); public static Dice parseDice(String tp) { Matcher m = p.matcher(tp); Dice dice = null; if (m.matches()) { dice = new Dice(); try { String s = m.group(1); if (!TextUtils.isEmpty(s)) { dice.diceCount = Integer.parseInt(s); } s = m.group(2); if (!TextUtils.isEmpty(s)) { dice.diceType = Integer.parseInt(s); } s = m.group(3); if (!TextUtils.isEmpty(s)) { dice.constant = Util.parseInteger(s); } } catch (IllegalStateException e) { Debug.e("unable to parse " + tp, e); return null; } catch (NumberFormatException e) { Debug.e("unable to parse " + tp, e); return null; } } return dice; } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(diceCount); sb.append("W"); if (diceType != 6) sb.append(diceType); if (constant != 0) sb.append(Util.toProbe(constant)); return sb.toString(); } public static DiceRoll diceRoll(int max) { return new DiceRoll(max, dice(max)); } /** * Returns a value between 1 and max (incl) * * @param max * @return */ public static int dice(int max) { return rnd.nextInt(max) + 1; } }
MythicalFish/mythical.fish
src/components/icons/solid/WindowRestore.js
import React from 'react' const WindowRestore = props => ( <svg fill='currentColor' viewBox='0 0 512 512' width='1em' height='1em' {...props} > <path d='M512 48v288c0 26.5-21.5 48-48 48h-48V176c0-44.1-35.9-80-80-80H128V48c0-26.5 21.5-48 48-48h288c26.5 0 48 21.5 48 48zM384 176v288c0 26.5-21.5 48-48 48H48c-26.5 0-48-21.5-48-48V176c0-26.5 21.5-48 48-48h288c26.5 0 48 21.5 48 48zm-68 28c0-6.6-5.4-12-12-12H76c-6.6 0-12 5.4-12 12v52h252v-52z' /> </svg> ) export default WindowRestore
SUNNYKIMM/tmax_front_sample
ReactProjectSample/ReactProjectSample/flone/src/layouts/LayoutThree.js
<reponame>SUNNYKIMM/tmax_front_sample import PropTypes from "prop-types"; import React, { Fragment } from "react"; import HeaderOne from "../wrappers/header/HeaderOne"; import FooterTwo from "../wrappers/footer/FooterTwo"; const LayoutThree = ({ children, headerContainerClass, headerTop, headerBorderStyle, headerPaddingClass }) => { return ( <Fragment> <HeaderOne layout={headerContainerClass} top={headerTop} borderStyle={headerBorderStyle} headerPaddingClass={headerPaddingClass} /> {children} <FooterTwo backgroundColorClass="footer-white" spaceLeftClass="ml-70" spaceRightClass="mr-70" footerTopBackgroundColorClass="bg-gray-2" footerTopSpaceTopClass="pt-80" footerTopSpaceBottomClass="pb-60" copyrightColorClass="copyright-gray" footerLogo="/assets/img/logo/logo.png" /> </Fragment> ); }; LayoutThree.propTypes = { children: PropTypes.any, headerBorderStyle: PropTypes.string, headerContainerClass: PropTypes.string, headerPaddingClass: PropTypes.string, headerTop: PropTypes.string }; export default LayoutThree;
Arihant25/beginner-python-projects
ISS_tracker.py
<reponame>Arihant25/beginner-python-projects import requests import smtplib from time import sleep from datetime import datetime, timezone MY_LAT = 20.368090 # Your latitude MY_LONG = 86.155860 # Your longitude MY_EMAIL = '<EMAIL>' # Your email MY_PASSWORD = '<PASSWORD>' # Your password SMTP_SERVER = 'smtp.office365.com' response = requests.get(url="http://api.open-notify.org/iss-now.json") response.raise_for_status() data = response.json() iss_latitude = float(data["iss_position"]["latitude"]) iss_longitude = float(data["iss_position"]["longitude"]) def is_close(): """Check if your position is within +5 or -5 degrees of the ISS position.""" if MY_LAT - 5 <= iss_latitude <= MY_LAT + 5 and MY_LONG - 5 <= iss_longitude <= MY_LONG + 5: return True else: return False def is_dark(): """Check if it's dark""" if sunset <= time_now <= sunrise: return True else: return False parameters = { "lat": MY_LAT, "lng": MY_LONG, "formatted": 0, } response = requests.get("https://api.sunrise-sunset.org/json", params=parameters) response.raise_for_status() data = response.json() # Get only the hours from the time sunrise = int(data["results"]["sunrise"].split("T")[1].split(":")[0]) sunset = int(data["results"]["sunset"].split("T")[1].split(":")[0]) time_now = datetime.now(timezone.utc).hour while True: # If the ISS is close to my current position and it is currently dark if is_close() and is_dark(): # Then send me an email to tell me to look up with smtplib.SMTP(SMTP_SERVER, port=587) as connection: connection.starttls() connection.login(user=MY_EMAIL, password=MY_PASSWORD) connection.sendmail(from_addr=MY_EMAIL, to_addrs=MY_EMAIL, msg="Subject: ISS OVERHEAD\n\n" "Look up, the International Space Station is passing over you!") # Run the code every 60 seconds sleep(60)