repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
saeedesm/UNMT_AH
model/mosesdecoder/moses/FF/RulePairUnlexicalizedSource.cpp
<reponame>saeedesm/UNMT_AH #include "RulePairUnlexicalizedSource.h" #include "moses/StaticData.h" #include "moses/InputFileStream.h" #include "moses/ScoreComponentCollection.h" #include "moses/FactorCollection.h" #include <sstream> #include "util/string_stream.hh" using namespace std; namespace Moses { RulePairUnlexicalizedSource::RulePairUnlexicalizedSource(const std::string &line) : StatelessFeatureFunction(1, line) , m_glueRules(false) , m_nonGlueRules(true) , m_glueTargetLHSStr("Q") { VERBOSE(1, "Initializing feature " << GetScoreProducerDescription() << " ..."); ReadParameters(); FactorCollection &factorCollection = FactorCollection::Instance(); m_glueTargetLHS = factorCollection.AddFactor(m_glueTargetLHSStr, true); VERBOSE(1, " Done."); } void RulePairUnlexicalizedSource::SetParameter(const std::string& key, const std::string& value) { if (key == "glueRules") { m_glueRules = Scan<bool>(value); } else if (key == "nonGlueRules") { m_nonGlueRules = Scan<bool>(value); } else if (key == "glueTargetLHS") { m_glueTargetLHSStr = value; } else { StatelessFeatureFunction::SetParameter(key, value); } } void RulePairUnlexicalizedSource::EvaluateInIsolation(const Phrase &source , const TargetPhrase &targetPhrase , ScoreComponentCollection &scoreBreakdown , ScoreComponentCollection &estimatedScores) const { const Factor* targetPhraseLHS = targetPhrase.GetTargetLHS()[0]; if ( !m_glueRules && (targetPhraseLHS == m_glueTargetLHS) ) { return; } if ( !m_nonGlueRules && (targetPhraseLHS != m_glueTargetLHS) ) { return; } for (size_t posS=0; posS<source.GetSize(); ++posS) { const Word &wordS = source.GetWord(posS); if ( !wordS.IsNonTerminal() ) { return; } } util::StringStream namestr; for (size_t posT=0; posT<targetPhrase.GetSize(); ++posT) { const Word &wordT = targetPhrase.GetWord(posT); const Factor* factorT = wordT[0]; if ( wordT.IsNonTerminal() ) { namestr << "["; } namestr << factorT->GetString(); if ( wordT.IsNonTerminal() ) { namestr << "]"; } namestr << "|"; } namestr << targetPhraseLHS->GetString() << "|"; for (AlignmentInfo::const_iterator it=targetPhrase.GetAlignNonTerm().begin(); it!=targetPhrase.GetAlignNonTerm().end(); ++it) { namestr << "|" << it->first << "-" << it->second; } scoreBreakdown.PlusEquals(this, namestr.str(), 1); if ( targetPhraseLHS != m_glueTargetLHS ) { scoreBreakdown.PlusEquals(this, 1); } } }
wsaada19/CommunityQuests
src/main/java/me/wonka01/ServerQuests/questcomponents/players/PlayerData.java
package me.wonka01.ServerQuests.questcomponents.players; // Stores data for each player who has contributed to a quest. public class PlayerData { private int amountContributed; private String playerName; public PlayerData(String name) { amountContributed = 0; playerName = name; } public PlayerData(String name, int amountContributed) { this.amountContributed = amountContributed; playerName = name; } public String getDisplayName() { return playerName; } public int getAmountContributed() { return amountContributed; } public void increaseContribution(int count) { amountContributed += count; } }
chyrony/WebProject10001
src/chapter03/LongEx1.java
<gh_stars>0 package chapter03; /* LongEx1.java */ /* Using long type Variable */ public class LongEx1{ public static void main(String args[]) { long Year = 10; long LightSpeed = 186000; long Distance; Distance = Year*365*24*60*60*LightSpeed; System.out.print("In " +Year + " years " ); System.out.print("light will travel about "); System.out.println(Distance + " miles"); } }
ZYJJerry/ReadAndLife
ReadAndLife/ReadAndLife/View/CollectionTableViewCell.h
// // CollectionTableViewCell.h // ReadAndLife // // Created by Jerry on 16/3/4. // Copyright © 2016年 周玉举. All rights reserved. // #import <UIKit/UIKit.h> #import "ArticleDetailModel.h" @interface CollectionTableViewCell : UITableViewCell @property (weak, nonatomic) IBOutlet UIImageView *collectionImage; @property (weak, nonatomic) IBOutlet UILabel *name; @property (weak, nonatomic) IBOutlet UILabel *desc; - (void)setCellContent:(ArticleDetailModel *)model; @end
kevin-411/SIUE-Projects
CS 425 & 499 Senior Project - Software Design & Implementation/LearnOBA/src/com/learnoba/classes/select/SelectClassView.java
<filename>CS 425 & 499 Senior Project - Software Design & Implementation/LearnOBA/src/com/learnoba/classes/select/SelectClassView.java package com.learnoba.classes.select; import javafx.scene.layout.AnchorPane; import com.learnoba.AbstractView; public class SelectClassView extends AbstractView<AnchorPane> { public SelectClassView(String resource, String title) { super(resource, title); } }
lowerrandom/DaBomb_dc27_badge
software/firmware/ChibiOS/os/hal/ports/STM32/LLD/QUADSPIv1/hal_qspi_lld.h
/* ChibiOS - Copyright (C) 2006..2018 <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. */ /** * @file QUADSPIv1/hal_qspi_lld.h * @brief STM32 QSPI subsystem low level driver header. * * @addtogroup QSPI * @{ */ #ifndef HAL_QSPI_LLD_H #define HAL_QSPI_LLD_H #if (HAL_USE_QSPI == TRUE) || defined(__DOXYGEN__) /*===========================================================================*/ /* Driver constants. */ /*===========================================================================*/ /** * @name QSPI capabilities * @{ */ #define QSPI_SUPPORTS_MEMMAP TRUE /** @} */ /** * @name DCR register options * @{ */ #define STM32_DCR_CK_MODE (1U << 0U) #define STM32_DCR_CSHT_MASK (7U << 8U) #define STM32_DCR_CSHT(n) ((n) << 8U) #define STM32_DCR_FSIZE_MASK (31U << 16U) #define STM32_DCR_FSIZE(n) ((n) << 16U) /** @} */ /*===========================================================================*/ /* Driver pre-compile time settings. */ /*===========================================================================*/ /** * @name Configuration options * @{ */ /** * @brief QUADSPI1 driver enable switch. * @details If set to @p TRUE the support for QUADSPI1 is included. * @note The default is @p FALSE. */ #if !defined(STM32_QSPI_USE_QUADSPI1) || defined(__DOXYGEN__) #define STM32_QSPI_USE_QUADSPI1 FALSE #endif /** * @brief QUADSPI1 prescaler setting. * @note This is the prescaler divider value 1..256. The maximum frequency * varies depending on the STM32 model and operating conditions, * find the details in the data sheet. */ #if !defined(STM32_QSPI_QUADSPI1_PRESCALER_VALUE) || defined(__DOXYGEN__) #define STM32_QSPI_QUADSPI1_PRESCALER_VALUE 1 #endif /** * @brief QUADSPI1 interrupt priority level setting. */ #if !defined(STM32_QSPI_QUADSPI1_IRQ_PRIORITY) || defined(__DOXYGEN__) #define STM32_QSPI_QUADSPI1_IRQ_PRIORITY 10 #endif /** * @brief QUADSPI1 DMA priority (0..3|lowest..highest). */ #if !defined(STM32_QSPI_QUADSPI1_DMA_PRIORITY) || defined(__DOXYGEN__) #define STM32_QSPI_QUADSPI1_DMA_PRIORITY 1 #endif /** * @brief QUADSPI1 DMA interrupt priority level setting. */ #if !defined(STM32_QSPI_QUADSPI1_DMA_IRQ_PRIORITY) || defined(__DOXYGEN__) #define STM32_QSPI_QUADSPI1_DMA_IRQ_PRIORITY 10 #endif /** * @brief QUADSPI DMA error hook. */ #if !defined(STM32_QSPI_DMA_ERROR_HOOK) || defined(__DOXYGEN__) #define STM32_QSPI_DMA_ERROR_HOOK(qspip) osalSysHalt("DMA failure") #endif /** * @brief Enables a workaround for a STM32L476 QUADSPI errata. * @details The document DM00111498 states: "QUADSPI_BK1_IO1 is always an * input when the command is sent in dual or quad SPI mode". * This workaround makes commands without address or data phases * to be sent as alternate bytes. */ #if !defined(STM32_USE_STM32_D1_WORKAROUND) || defined(__DOXYGEN__) #define STM32_USE_STM32_D1_WORKAROUND TRUE #endif /** @} */ /*===========================================================================*/ /* Derived constants and error checks. */ /*===========================================================================*/ #if STM32_QSPI_USE_QUADSPI1 && !STM32_HAS_QUADSPI1 #error "QUADSPI1 not present in the selected device" #endif #if !STM32_QSPI_USE_QUADSPI1 #error "QSPI driver activated but no QUADSPI peripheral assigned" #endif #if STM32_QSPI_USE_QUADSPI1 && \ !OSAL_IRQ_IS_VALID_PRIORITY(STM32_QSPI_QUADSPI1_IRQ_PRIORITY) #error "Invalid IRQ priority assigned to QUADSPI1" #endif #if STM32_QSPI_USE_QUADSPI1 && \ !OSAL_IRQ_IS_VALID_PRIORITY(STM32_QSPI_QUADSPI1_DMA_IRQ_PRIORITY) #error "Invalid IRQ priority assigned to QUADSPI1 DMA" #endif #if STM32_QSPI_USE_QUADSPI1 && \ !STM32_DMA_IS_VALID_PRIORITY(STM32_QSPI_QUADSPI1_DMA_PRIORITY) #error "Invalid DMA priority assigned to QUADSPI1" #endif #if (STM32_QSPI_QUADSPI1_PRESCALER_VALUE < 1) || \ (STM32_QSPI_QUADSPI1_PRESCALER_VALUE > 256) #error "STM32_QSPI_QUADSPI1_PRESCALER_VALUE not within 1..256" #endif /* The following checks are only required when there is a DMA able to reassign streams to different channels.*/ #if STM32_ADVANCED_DMA /* Check on the presence of the DMA streams settings in mcuconf.h.*/ #if STM32_QSPI_USE_QUADSPI1 && !defined(STM32_QSPI_QUADSPI1_DMA_STREAM) #error "QUADSPI1 DMA stream not defined" #endif /* Check on the validity of the assigned DMA channels.*/ #if STM32_QSPI_USE_QUADSPI1 && \ !STM32_DMA_IS_VALID_ID(STM32_QSPI_QUADSPI1_DMA_STREAM, STM32_QUADSPI1_DMA_MSK) #error "invalid DMA stream associated to QUADSPI1" #endif #endif /* STM32_ADVANCED_DMA */ #if !defined(STM32_DMA_REQUIRED) #define STM32_DMA_REQUIRED #endif /*===========================================================================*/ /* Driver data structures and types. */ /*===========================================================================*/ /** * @brief Type of a structure representing an QSPI driver. */ typedef struct QSPIDriver QSPIDriver; /** * @brief Type of a QSPI notification callback. * * @param[in] qspip pointer to the @p QSPIDriver object triggering the * callback */ typedef void (*qspicallback_t)(QSPIDriver *qspip); /** * @brief Driver configuration structure. */ typedef struct { /** * @brief Operation complete callback or @p NULL. */ qspicallback_t end_cb; /* End of the mandatory fields.*/ /** * @brief DCR register initialization data. */ uint32_t dcr; } QSPIConfig; /** * @brief Structure representing an QSPI driver. */ struct QSPIDriver { /** * @brief Driver state. */ qspistate_t state; /** * @brief Current configuration data. */ const QSPIConfig *config; #if (QSPI_USE_WAIT == TRUE) || defined(__DOXYGEN__) /** * @brief Waiting thread. */ thread_reference_t thread; #endif /* QSPI_USE_WAIT */ #if (QSPI_USE_MUTUAL_EXCLUSION == TRUE) || defined(__DOXYGEN__) /** * @brief Mutex protecting the peripheral. */ mutex_t mutex; #endif /* QSPI_USE_MUTUAL_EXCLUSION */ #if defined(QSPI_DRIVER_EXT_FIELDS) QSPI_DRIVER_EXT_FIELDS #endif /* End of the mandatory fields.*/ /** * @brief Pointer to the QUADSPIx registers block. */ QUADSPI_TypeDef *qspi; /** * @brief QUADSPI DMA stream. */ const stm32_dma_stream_t *dma; /** * @brief QUADSPI DMA mode bit mask. */ uint32_t dmamode; }; /*===========================================================================*/ /* Driver macros. */ /*===========================================================================*/ /*===========================================================================*/ /* External declarations. */ /*===========================================================================*/ #if (STM32_QSPI_USE_QUADSPI1 == TRUE) && !defined(__DOXYGEN__) extern QSPIDriver QSPID1; #endif #ifdef __cplusplus extern "C" { #endif void qspi_lld_init(void); void qspi_lld_start(QSPIDriver *qspip); void qspi_lld_stop(QSPIDriver *qspip); void qspi_lld_command(QSPIDriver *qspip, const qspi_command_t *cmdp); void qspi_lld_send(QSPIDriver *qspip, const qspi_command_t *cmdp, size_t n, const uint8_t *txbuf); void qspi_lld_receive(QSPIDriver *qspip, const qspi_command_t *cmdp, size_t n, uint8_t *rxbuf); #if QSPI_SUPPORTS_MEMMAP == TRUE void qspi_lld_map_flash(QSPIDriver *qspip, const qspi_command_t *cmdp, uint8_t **addrp); void qspi_lld_unmap_flash(QSPIDriver *qspip); #endif #ifdef __cplusplus } #endif #endif /* HAL_USE_QSPI */ #endif /* HAL_QSPI_LLD_H */ /** @} */
mosceo/sarama
delete_offsets_request.go
<reponame>mosceo/sarama package sarama type DeleteOffsetsRequest struct { Group string partitions map[string][]int32 } func (r *DeleteOffsetsRequest) encode(pe packetEncoder) (err error) { err = pe.putString(r.Group) if err != nil { return err } if r.partitions == nil { pe.putInt32(0) } else { if err = pe.putArrayLength(len(r.partitions)); err != nil { return err } } for topic, partitions := range r.partitions { err = pe.putString(topic) if err != nil { return err } err = pe.putInt32Array(partitions) if err != nil { return err } } return } func (r *DeleteOffsetsRequest) decode(pd packetDecoder, version int16) (err error) { r.Group, err = pd.getString() if err != nil { return err } var partitionCount int partitionCount, err = pd.getArrayLength() if err != nil { return err } if (partitionCount == 0 && version < 2) || partitionCount < 0 { return nil } r.partitions = make(map[string][]int32, partitionCount) for i := 0; i < partitionCount; i++ { var topic string topic, err = pd.getString() if err != nil { return err } var partitions []int32 partitions, err = pd.getInt32Array() if err != nil { return err } r.partitions[topic] = partitions } return nil } func (r *DeleteOffsetsRequest) key() int16 { return 47 } func (r *DeleteOffsetsRequest) version() int16 { return 0 } func (r *DeleteOffsetsRequest) headerVersion() int16 { return 1 } func (r *DeleteOffsetsRequest) requiredVersion() KafkaVersion { return V2_4_0_0 } func (r *DeleteOffsetsRequest) AddPartition(topic string, partitionID int32) { if r.partitions == nil { r.partitions = make(map[string][]int32) } r.partitions[topic] = append(r.partitions[topic], partitionID) }
Yurzs/boto
boto/ec2/virtualswitch.py
<gh_stars>1-10 """Croc Cloud EC2 Virtual Switch.""" from boto.ec2.ec2object import TaggedEC2Object class VirtualSwitch(TaggedEC2Object): def __init__(self, connection=None, id=None, name=None): super(VirtualSwitch, self).__init__(connection) self.id = id self.name = name self.availability_zone = None def __repr__(self): return 'VirtualSwitch:%s' % self.name def startElement(self, name, attrs, connection): retval = super(VirtualSwitch, self).startElement(name, attrs, connection) if retval is not None: return retval else: return def endElement(self, name, value, connection): if name == 'switchId': self.id = value elif name == 'switchName': self.name = value elif name == 'availabilityZone': self.availability_zone = value elif name == 'return': if value == 'false': self.status = False elif value == 'true': self.status = True else: raise Exception( 'Unexpected value of status ' '%s for group %s' % (value, self.name)) else: setattr(self, name, value) def delete(self, dry_run=False): """ Delete virtual switch. :type dry_run: bool :param dry_run: dry run """ kwargs = {'switch_id': self.id} if self.id else {'name': self.name} kwargs['dry_run'] = dry_run return self.connection.delete_virtual_switch(**kwargs) def create(self, availability_zone=None, dry_run=False): """ Create virtual switch. :type dry_run: bool :param dry_run: dry run :rtype: :class:`boto.ec2.virtualswitch.VirtualSwitch` :return: created virtual switch """ kwargs = { 'name': self.name, 'availability_zone': availability_zone, 'dry_run': dry_run, } return self.connection.create_virtual_switch(**kwargs)
jamesjcai/scGEAtoolbox
+run/thirdparty/umapFileExchange/nndescent/C++/distances.h
// // Created by <NAME> on 7/17/20. // /* AUTHORS <NAME> <<EMAIL>> <NAME> <<EMAIL>> <NAME> <<EMAIL>> Provided by suh ( Stanford University's Herzenberg Lab) License: BSD 3 clause */ // Expect to evolve this file when we start adding other distance metrics // Also plan to deprecate preprocessor macros (e.g. euclideanMacro) #ifndef SUH_DISTANCES_H #define SUH_DISTANCES_H #include "suh_math.h" namespace suh { inline double euclidean( const double * x, const double * y, const size_t size){ double result = 0.0; // accelerate slightly with pointer arithmetic + indirection // instead of integer arithmetic + indexing+indirection for (const double * const end=x+size;x<end;x++, y++) result +=((*x - *y)*(*x - *y)); return sqrt(result); } // DistanceMetric is an abstract class for computing one of the following types of distances /* * 'euclidean' Euclidean distance (default). * 'cityblock' City block distance. * 'cosine' One minus the cosine of the included angle between points (treated as vectors). * 'mahalanobis' Mahalanobis distance using the sample covariance of X, C = cov(X,'omitrows'). * Use sub class data to specify another value for C, where the matrix C is * symmetric and positive definite. * 'squaredeuclidean' Squared Euclidean distance. (This option is provided for efficiency only. * It does not satisfy the triangle inequality.) * 'seuclidean' Standardized Euclidean distance. Each coordinate difference between observations * is scaled by dividing by the corresponding element of the standard deviation, * S = std(X,'omitnan'). Use sub class data to specify another value for S. * 'minkowski' Minkowski distance. The default exponent is 2. Use sub class data to specify a * different exponent P, where P is a positive scalar value of the exponent. * 'chebychev' Chebychev distance (maximum coordinate difference). * 'correlation' One minus the sample correlation between points (treated as sequences of values). * 'hamming' Hamming distance, which is the percentage of coordinates that differ. * 'jaccard' One minus the Jaccard coefficient, which is the percentage of nonzero coordinates that differ. * 'spearman' One minus the sample Spearman's rank correlation between observations * (treated as sequences of values). */ class DistanceMetric { std::string name; public: virtual double compute(const double * x, const double * y, const size_t size)=0; virtual double compute_sortable(const double * x, const double * y, const int size) { // if no sortable version exists then just use full computation return compute(x,y,size); } // for efficiency this computes an intermediate form of the distance for sorting purposes with KnnGraph virtual double finalize_sortable(const double sortable_distance) { // if no sortable version exists then just use full computation return sortable_distance; } inline static std::shared_ptr<DistanceMetric> find(std::string name, const void * dist_args, const suh::MatrixPtr self) { return find(name.c_str(), dist_args, (const double **) self->matrix_, self->rows_, self->columns_); } inline static std::shared_ptr<DistanceMetric> find(std::string name, const void *dist_args, const suh::MatrixPtr self, const suh::MatrixPtr other){ return find(name.c_str(), dist_args, (const double **)self->matrix_, self->rows_, self->columns_, (const double **)other->matrix_, other->rows_, other->columns_); } static std::shared_ptr<DistanceMetric>find(const std::string &name, const void *dist_args, const double** self, const size_t self_rows, const size_t self_columns, const double ** other=nullptr, const size_t other_rows=0, const size_t other_columns=0); virtual ~DistanceMetric(); static std::shared_ptr<DistanceMetric> euclidean(); protected: // set by sub class if sortable distance is worth computing separately bool needs_finalizing_=false; public: bool needs_finalizing(){ return needs_finalizing_; } void set_finalizing_complete(){ needs_finalizing_=false; } static bool IsSupported(const char *name); }; using DistancePtr = std::shared_ptr<DistanceMetric>; } #endif //SUH_DISTANCES_H
m7onov/pgjdbc-ng
documentation/src/docs/examples/copy/to_system_out.java
<filename>documentation/src/docs/examples/copy/to_system_out.java System.setOut(new FileOutputStream("table.txt")); // <1> try (Statement statement = connection.createStatement()) { statement.execute("COPY a_table TO STDOUT"); // <2> }
ThomasBDZ/JAVAFX-Application
src/test/java/eu/telecomnancy/model/ProfRDVTests.java
<reponame>ThomasBDZ/JAVAFX-Application package eu.telecomnancy.model; import eu.telecomnancy.javafx.model.Creneau; import eu.telecomnancy.javafx.model.Enseignant; import eu.telecomnancy.javafx.model.Etudiant; import eu.telecomnancy.javafx.model.GestionnaireDB.*; import eu.telecomnancy.javafx.model.RDV; import org.junit.jupiter.api.Test; import java.sql.SQLException; import java.util.ArrayList; import static org.junit.jupiter.api.Assertions.assertEquals; public class ProfRDVTests { // @BeforeAll @Test void addition() { assertEquals(2, 2); } @Test void testPickuser() { PickUser picker = new PickUser(); int a = picker.Pick("eleve"); assertEquals(1, a); } @Test void testGetterRdv_getInfoRdv() { GetterRdv getterRdv = new GetterRdv(); RDV rdv = new RDV(); rdv = getterRdv.getInfoRdv(10); assertEquals("prof", rdv.enseignant.mail); } // @Test // void testGetterRdv_getAllRdvValide() throws SQLException { // GetterRdv getterRdv = new GetterRdv(); // RDV rdv = new RDV(); // rdv = getterRdv.getInfoRdv(10); // ArrayList<RDV> rdvValide = new ArrayList<>(); // rdvValide = getterRdv.getAllRdvValide(rdv.enseignant); // assertEquals(4, rdvValide.size()); // } @Test void testGetterRdv_getAllRdvNonValide() throws SQLException { GetterRdv getterRdv = new GetterRdv(); RDV rdv = new RDV(); rdv = getterRdv.getInfoRdv(7); ArrayList<RDV> rdvNonValide = new ArrayList<>(); rdvNonValide = getterRdv.getAllRdvNonValide(rdv.enseignant); assertEquals(1, rdvNonValide.size()); } @Test void testGetterRdv_getAllRdv() throws SQLException { GetterRdv getterRdv = new GetterRdv(); RDV rdv = new RDV(); rdv = getterRdv.getInfoRdv(5); ArrayList<RDV> rdvAll = new ArrayList<>(); rdvAll = getterRdv.getAllRDV(rdv.enseignant); assertEquals(8, rdvAll.size()); assertEquals("<EMAIL>", rdvAll.get(4).etudiant.mail); } @Test void testGetterRdv_getRdvWeek() throws SQLException { GetterRdv getterRdv = new GetterRdv(); RDV rdv = new RDV(); rdv = getterRdv.getInfoRdv(5); ArrayList<RDV> rdvWeek = new ArrayList<>(); rdvWeek = getterRdv.getRDVWeek(rdv.enseignant, "2022-01-25"); assertEquals(40, rdvWeek.size()); assertEquals("Rencontre parent", rdvWeek.get(10).libelle); } // @Test // void testGetterUser_getInfo() throws SQLException { // GetterUser getterUser = new GetterUser(); // Enseignant enseignant = new Enseignant(); // Etudiant etudiant = new Etudiant(); // enseignant = getterUser.getInfoProf(4); // etudiant = getterUser.getInfoEleve(1); // assertEquals("<EMAIL>", enseignant.mail); // assertEquals("<EMAIL>",etudiant.mail); // } @Test void testGetterUser_getMdp() throws SQLException { GetterUser getterUser = new GetterUser(); Enseignant enseignant = new Enseignant(); Etudiant etudiant = new Etudiant(); enseignant = getterUser.getInfoProf(1); etudiant = getterUser.getInfoEleve(1); String mdpConnexionEtudiant = getterUser.getMdp(etudiant); String mdpConnexionEnseignant = getterUser.getMdp(enseignant); assertEquals("eleve", mdpConnexionEtudiant); assertEquals("prof",mdpConnexionEnseignant); } // @Test // void testGetterUser_getThemAll() throws SQLException { // GetterUser getterUser = new GetterUser(); // ArrayList<Etudiant> listeEtudiant = new ArrayList<>(); // ArrayList<Enseignant> listeEnseignant = new ArrayList<>(); // listeEtudiant = getterUser.getAllEleves(); // listeEnseignant = getterUser.getAllProfs(); // assertEquals(10, getterUser.getAllEleves().size()); // assertEquals(11,getterUser.getAllProfs().size()); // } @Test void testDisponibilityProf_getCreneau() throws SQLException { GestionRDV gestionRDV = new GestionRDV(); DisponibilityProf disponibilityProf = new DisponibilityProf(); Creneau creneau = new Creneau(); creneau = disponibilityProf.getCreneau(86); assertEquals(5, creneau.indice); } // @Test // void testGestionRDV_AddCreneau() throws Exception { // GetterUser getterUser = new GetterUser(); // ArrayList<Enseignant> listeEnseignant; // listeEnseignant = getterUser.getAllProfs(); // DisponibilityProf disponibilityProf = new DisponibilityProf(); // ArrayList<Creneau> avantPush; // ArrayList<Creneau> apresPushpush; // avantPush = disponibilityProf.getProfCreneau(listeEnseignant.get(0).mail, "2022-02-17"); // assertEquals(0, avantPush.size()); // disponibilityProf.insertCreneauProf(listeEnseignant.get(0),10,11,"2022-02-17"); // apresPushpush = disponibilityProf.getProfCreneau(listeEnseignant.get(0).mail, "2022-02-17"); // assertEquals(1, apresPushpush.size()); // } @Test void testGestionRDV_AddRdv() throws Exception { GestionRDV gestionRDV = new GestionRDV(); GetterUser getterUser = new GetterUser(); ArrayList<Enseignant> listeEnseignant; ArrayList<Etudiant> listeEtudiant; listeEnseignant = getterUser.getAllProfs(); listeEtudiant = getterUser.getAllEleves(); DisponibilityProf disponibilityProf = new DisponibilityProf(); disponibilityProf.insertCreneauProf(listeEnseignant.get(0),10,8,"2022-01-30"); Creneau creneau = disponibilityProf.getProfCreneau(listeEnseignant.get(0).mail, "2022-01-30").get(0); RDV rdv = new RDV(Boolean.TRUE,Boolean.FALSE,"Paris","Oral concours",listeEnseignant.get(0),listeEtudiant.get(2),creneau,"Le rendez-vous de la Coding Week"); gestionRDV.AddRdv(rdv); assertEquals("Le rendez-vous de la Coding Week", rdv.description); } }
webb04/frontend
sport/app/football/controllers/MatchListController.scala
<filename>sport/app/football/controllers/MatchListController.scala package football.controllers import common.{Edition, JsonComponent} import feed.Competitions import football.model.MatchesList import implicits.Requests import model.Cached.RevalidatableResult import model.{ApplicationContext, Cached, Competition, TeamMap} import org.joda.time.LocalDate import org.joda.time.format.DateTimeFormat import pa.FootballTeam import play.api.mvc.{BaseController, RequestHeader} import play.twirl.api.Html trait MatchListController extends BaseController with Requests { def competitionsService: Competitions protected val datePattern = DateTimeFormat.forPattern("yyyyMMMdd").withZone(Edition.defaultEdition.timezone) protected def createDate(year: String, month: String, day: String): LocalDate = datePattern.parseDateTime(s"$year$month$day").toLocalDate protected def renderMatchList( page: FootballPage, matchesList: MatchesList, filters: Map[String, Seq[CompetitionFilter]] )(implicit request: RequestHeader, context: ApplicationContext) = { Cached(10) { if (request.isJson) JsonComponent( "html" -> football.views.html.matchList.matchesComponent(matchesList), "next" -> Html(matchesList.nextPage.getOrElse("")), "previous" -> Html(matchesList.previousPage.getOrElse("")) ) else RevalidatableResult.Ok(football.views.html.matchList.matchesPage(page, matchesList, filters)) } } protected def renderMoreMatches( page: FootballPage, matchesList: MatchesList, filters: Map[String, Seq[CompetitionFilter]] )(implicit request: RequestHeader, context: ApplicationContext) = { Cached(10) { if(request.isJson) JsonComponent( "html" -> football.views.html.matchList.moreMatchesComponent(matchesList), "next" -> Html(matchesList.nextPage.getOrElse("")), "previous" -> Html(matchesList.previousPage.getOrElse("")) ) else RevalidatableResult.Ok(football.views.html.matchList.matchesPage(page, matchesList, filters)) } } protected def lookupCompetition(tag: String): Option[Competition] = { competitionsService.competitionsWithTag(tag).orElse(competitionsService.competitionsWithId(tag)) } protected def lookupTeam(tag: String): Option[FootballTeam] = { for { teamId <- TeamMap.findTeamIdByUrlName(tag) team <- competitionsService.findTeam(teamId) } yield team } }
jkuczynski1/os_jk
OpenScienceJournal/whistlepunk_library/src/main/java/com/google/android/apps/forscience/whistlepunk/ExternalSensorAppearance.java
<reponame>jkuczynski1/os_jk<filename>OpenScienceJournal/whistlepunk_library/src/main/java/com/google/android/apps/forscience/whistlepunk/ExternalSensorAppearance.java /* * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.forscience.whistlepunk; import android.content.Context; /** * Subclass of {@link BuiltInSensorAppearance} which includes the external device name. */ public class ExternalSensorAppearance extends BuiltInSensorAppearance { private String mDeviceName; public ExternalSensorAppearance(int nameStringId, int drawableId, int unitsStringId, int shortDescriptionId, int firstParagraphStringId, int secondParagraphStringId, int infoDrawableId, SensorAnimationBehavior sensorAnimationBehavior, String deviceName) { super(nameStringId, drawableId, unitsStringId, shortDescriptionId, firstParagraphStringId, secondParagraphStringId, infoDrawableId, sensorAnimationBehavior, BuiltInSensorAppearance.DEFAULT_POINTS_AFTER_DECIMAL); mDeviceName = deviceName; } @Override public String getName(Context context) { return context.getResources().getString(R.string.external_sensor_appearance_name, super.getName(context), mDeviceName); } }
tsegall/fta
src/test/java/com/cobber/fta/TestTokens.java
<gh_stars>1-10 package com.cobber.fta; import java.io.IOException; import java.util.Map; import java.util.Random; import org.testng.Assert; import org.testng.annotations.Test; import com.cobber.fta.core.FTAException; import com.cobber.fta.token.CharClassToken; import com.cobber.fta.token.Token; import com.cobber.fta.token.TokenStream; import com.cobber.fta.token.TokenStreams; public class TestTokens { @Test(groups = { TestGroups.ALL, TestGroups.TOKENS }) public void tooLong() throws IOException, FTAException { final String input = "0123456789012345678901234567890"; TokenStream ts = new TokenStream(input, 1); Assert.assertEquals(ts.getKey(), "ANY"); Assert.assertEquals(ts.getOccurrences(), 1); Assert.assertEquals(ts.getRegExp(false), ".+"); } @Test(groups = { TestGroups.ALL, TestGroups.TOKENS }) public void oneDigit() throws IOException, FTAException { final String input = "0"; TokenStream ts = new TokenStream(input, 1); Assert.assertEquals(ts.getKey(), "9"); Assert.assertEquals(ts.getCompressedKey(), "9"); Assert.assertEquals(ts.getRegExp(false), "\\d"); Assert.assertEquals(ts.getRegExp(true), "0"); Assert.assertEquals(ts.getOccurrences(), 1); } @Test(groups = { TestGroups.ALL, TestGroups.TOKENS }) public void twoDigits() throws IOException, FTAException { final String input = "01"; TokenStream ts = new TokenStream(input, 1); Assert.assertEquals(ts.getKey(), "99"); Assert.assertEquals(ts.getCompressedKey(), "9"); Assert.assertEquals(ts.getRegExp(false), "\\d{2}"); Assert.assertEquals(ts.getRegExp(true), "01"); Assert.assertEquals(ts.getOccurrences(), 1); } @Test(groups = { TestGroups.ALL, TestGroups.TOKENS }) public void justDigits() throws IOException, FTAException { final String input = "0123456789"; TokenStream ts = new TokenStream(input, 1); Assert.assertEquals(ts.getKey(), "9999999999"); Assert.assertEquals(ts.getCompressedKey(), "9"); Assert.assertEquals(ts.getRegExp(false), "\\d{10}"); Assert.assertEquals(ts.getRegExp(true), "0123456789"); Assert.assertEquals(ts.getOccurrences(), 1); } @Test(groups = { TestGroups.ALL, TestGroups.TOKENS }) public void simpleUpper() throws IOException, FTAException { final String input = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; TokenStream ts = new TokenStream(input, 1); Assert.assertEquals(ts.getKey(), "XXXXXXXXXXXXXXXXXXXXXXXXXX"); Assert.assertEquals(ts.getCompressedKey(), "X"); Assert.assertEquals(ts.getRegExp(false), "\\p{IsAlphabetic}{26}"); Assert.assertEquals(ts.getRegExp(true), "ABCDEFGHIJKLMNOPQRSTUVWXYZ"); } @Test(groups = { TestGroups.ALL, TestGroups.TOKENS }) public void simpleLower() throws IOException, FTAException { final String input = "abcdefghijklmnopqrstuvwxyz"; TokenStream ts = new TokenStream(input, 1); Assert.assertEquals(ts.getKey(), "XXXXXXXXXXXXXXXXXXXXXXXXXX"); Assert.assertEquals(ts.getRegExp(false), "\\p{IsAlphabetic}{26}"); Assert.assertEquals(ts.getRegExp(true), "abcdefghijklmnopqrstuvwxyz"); } @Test(groups = { TestGroups.ALL, TestGroups.TOKENS }) public void nonASCII() throws IOException, FTAException { final String input = "München"; TokenStream ts = new TokenStream(input, 1); Assert.assertEquals(ts.getKey(), "XXXXXXX"); Assert.assertEquals(ts.getCompressedKey(), "X"); Assert.assertEquals(ts.getRegExp(false), "\\p{IsAlphabetic}{7}"); Assert.assertEquals(ts.getRegExp(true), "München"); for (Token token : ts.getTokens()) { if (token instanceof CharClassToken) { CharClassToken ccToken = (CharClassToken)token; Assert.assertEquals(ccToken.getRanges().size(), 1); } } } @Test(groups = { TestGroups.ALL, TestGroups.TOKENS }) public void randomStuff() throws IOException, FTAException { final String input = "+-=?#$"; TokenStream ts = new TokenStream(input, 1); Assert.assertEquals(ts.getKey(), "+-=?#$"); Assert.assertEquals(ts.getCompressedKey(), "+-=?#$"); Assert.assertEquals(ts.getRegExp(false), "\\+-=?#\\$"); Assert.assertEquals(ts.getRegExp(true), "\\+-=?#\\$"); } @Test(groups = { TestGroups.ALL, TestGroups.TOKENS }) public void testMerge() throws IOException, FTAException { TokenStreams ts = new TokenStreams(10); ts.track("16789", 1); ts.track("01338", 2); ts.track("22457", 3); Assert.assertEquals(ts.getSamples(), 6); Assert.assertEquals(ts.getRegExp(false), "\\d{5}"); String fittedAnswer = "[0-2][1-26][3-47][358][7-9]"; Assert.assertEquals(ts.getRegExp(true), fittedAnswer); Assert.assertTrue("16789".matches(fittedAnswer)); Assert.assertTrue("01338".matches(fittedAnswer)); Assert.assertTrue("22457".matches(fittedAnswer)); Token[] tokens = ts.getBest().getTokens(); for (int i = 0; i < tokens.length; i++) { CharClassToken ccToken = (CharClassToken)tokens[i]; for (CharClassToken.Range range : ccToken.getRanges()) { if (i == 0) { Assert.assertEquals(ccToken.getRanges().size(), 1); Assert.assertEquals(range.getMin(), '0'); Assert.assertEquals(range.getMax(), '2'); } else if (i == 1) Assert.assertEquals(ccToken.getRanges().size(), 2); else if (i == 2) Assert.assertEquals(ccToken.getRanges().size(), 2); else if (i == 3) Assert.assertEquals(ccToken.getRanges().size(), 3); else if (i == 4) { Assert.assertEquals(ccToken.getRanges().size(), 1); Assert.assertEquals(range.getMin(), '7'); Assert.assertEquals(range.getMax(), '9'); } } } } @Test(groups = { TestGroups.ALL, TestGroups.TOKENS }) public void testWords() throws IOException, FTAException { TokenStreams ts = new TokenStreams(10); ts.track("uvuck qdtxnz pkaow nu q fdvhuykn okb ar kjdw upfl cxchmna nilb fvtuoqhy", 1); ts.track("rtifwhajt ozcjr qmje x mrtklqjhn pfqzdcosa xbhqerf odl xwcxsqua scyptz qv otvif v h hlqfbjl", 2); ts.track("mxewys ramyc mhfxuwnt i ypesjme zoxayy", 3); ts.track("Hello", 3); Assert.assertEquals(ts.getRegExp(false), ".+"); Assert.assertEquals(ts.getRegExp(true), ".+"); } @Test(groups = { TestGroups.ALL, TestGroups.TOKENS }) public void testNumeric() throws IOException, FTAException { TokenStreams ts = new TokenStreams(10); ts.track("09:09:08:07:04:05", 1); ts.track("09:09:08:07:04:60", 1); ts.track("89:39:33:17:04:44", 1); ts.track("09:19:88:07:04:00", 1); ts.track("09:04:08:11:01:22", 1); Assert.assertEquals(ts.size(), 1); TokenStream tokenStream = ts.getStreams().values().iterator().next(); Assert.assertTrue(tokenStream.matches("[0-9][0-9]:[0-9][0-9]:[0-9][0-9]:[0-9][0-9]:[0-9][0-9]:[0-9][0-9]")); } @Test(groups = { TestGroups.ALL, TestGroups.TOKENS }) public void testNotAllNumeric() throws IOException, FTAException { TokenStreams ts = new TokenStreams(10); ts.track("09:09:08:07:04:05", 1); ts.track("09:09:08:07:04:60", 1); ts.track("89:39:3A:17:04:44", 1); ts.track("09:19:88:07:04:00", 1); ts.track("09:04:08:11:01:22", 1); Assert.assertEquals(ts.size(), 2); int matches = 0; for (Map.Entry<String, TokenStream> entry : ts.getStreams().entrySet()) { if (entry.getValue().matches("[0-9][0-9]:[0-9][0-9]:[0-9][0-9]:[0-9][0-9]:[0-9][0-9]:[0-9][0-9]")) matches++; } Assert.assertEquals(matches, 1); } @Test(groups = { TestGroups.ALL, TestGroups.TOKENS }) public void testHex() throws IOException, FTAException { TokenStreams ts = new TokenStreams(10); ts.track("09:09:08:07:04:05", 1); ts.track("00:a9:b8:07:04:60", 1); ts.track("00:39:33:17:04:44", 1); ts.track("00:19:8c:0F:04:00", 1); ts.track("00:04:08:1E:01:DD", 1); for (Map.Entry<String, TokenStream> entry : ts.getStreams().entrySet()) Assert.assertTrue(entry.getValue().matches("[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}")); Assert.assertTrue(ts.matches("[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}")); } @Test(groups = { TestGroups.ALL, TestGroups.TOKENS }) public void testNonHex() throws IOException, FTAException { TokenStreams ts = new TokenStreams(10); ts.track("09:09:08:07:04:05", 1); ts.track("00:a9:b8:07:04:60", 1); ts.track("00:39:33:17:04:44", 1); ts.track("00:19:8c:0F:04:00", 1); ts.track("00:04:08:1E:01:GG", 1); Assert.assertFalse(ts.matches("[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}")); } @Test(groups = { TestGroups.ALL, TestGroups.TOKENS }) public void testShapes() throws IOException, FTAException { final String alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; String[] prefixes = new String[] { "INCA-", "ICD9-", "ICD10-" }; Random r = new Random(); TokenStreams tokenStreams = new TokenStreams(10); for (String prefix : prefixes) { for (int i = 1000; i < 2000; i++) { String sample = i%2 == 0 ? prefix + String.valueOf(i) : String.valueOf(alpha.charAt(r.nextInt(alpha.length()))); tokenStreams.track(sample, 1); } } Assert.assertEquals(tokenStreams.size(), 4); for (Map.Entry<String, TokenStream> entry : tokenStreams.getStreams().entrySet()) { if ("XXX9-9999".equals(entry.getKey())) { Assert.assertEquals(entry.getValue().getRegExp(false), "\\p{IsAlphabetic}{3}\\d-\\d{4}"); Assert.assertEquals(entry.getValue().getRegExp(true), "ICD9-1[0-9]{2}[02468]"); Assert.assertEquals(entry.getValue().getOccurrences(), 500); } else if ("XXX99-9999".equals(entry.getKey())) { Assert.assertEquals(entry.getValue().getRegExp(false), "\\p{IsAlphabetic}{3}\\d{2}-\\d{4}"); Assert.assertEquals(entry.getValue().getRegExp(true), "ICD10-1[0-9]{2}[02468]"); Assert.assertEquals(entry.getValue().getOccurrences(), 500); } else if ("XXXX-9999".equals(entry.getKey())) { Assert.assertEquals(entry.getValue().getRegExp(false), "\\p{IsAlphabetic}{4}-\\d{4}"); Assert.assertEquals(entry.getValue().getRegExp(true), "INCA-1[0-9]{2}[02468]"); Assert.assertEquals(entry.getValue().getOccurrences(), 500); } else if ("X".equals(entry.getKey())) { Assert.assertEquals(entry.getValue().getRegExp(false), "\\p{IsAlphabetic}"); Assert.assertEquals(entry.getValue().getRegExp(true), "\\p{IsAlphabetic}"); Assert.assertEquals(entry.getValue().getOccurrences(), 1500); } } } }
intrepidcs/OBD2PRO_WIFI_CC32XX
ti_simplelink_sdk/source/ti/net/mqtt/interface/mqtt_client.c
<reponame>intrepidcs/OBD2PRO_WIFI_CC32XX /* * Copyright (C) 2016 Texas Instruments Incorporated * * All rights reserved. Property of Texas Instruments Incorporated. * Restricted rights to use, duplicate or disclose this code are * granted through contract. * * The program may not be used without the written permission of * Texas Instruments Incorporated or against the terms and conditions * stipulated in the agreement under which this program has been supplied, * and under no circumstances can it be used with non-TI connectivity device. * */ //***************************************************************************** // includes //***************************************************************************** #include <ti/net/mqtt/mqtt_client.h> #include <ti/net/mqtt/platform/cc32xx_sl_net.h> /* POSIX Header files */ #include <pthread.h> #include <semaphore.h> //***************************************************************************** // defines //***************************************************************************** #ifndef CFG_SL_CL_BUF_LEN #define MQTTCLIENT_BUF_LEN 1024 /*Buffer length*/ #else #define MQTTCLIENT_BUF_LEN CFG_SL_CL_BUF_LEN #endif #ifndef CFG_SL_CL_MAX_MQP #define MQTTCLIENT_MAX_MQP 2 /* # of buffers */ #else #define MQTTCLIENT_MAX_MQP CFG_SL_CL_MAX_MQP #endif #define UART_PRINT Report /*Defining QOS value. Getting QOS value from fixed header*/ #define MQTTClient_mqpPubQos(mqp) ((mqp->fhByte1 >>1) & 0x03) #define MQTTClient_ackRxSignalWait(ackSyncObj) sem_wait(ackSyncObj) #define MQTTClient_ackRxSignalPost(ackSyncObj) sem_post(ackSyncObj) #define MQTTClient_str2UTFConv(utf_s, str) {utf_s.buffer = (char *)str; utf_s.length = strlen(str);} /*Defining Event Messages*/ #define MQTTCLIENT_ACK "Ack Received from server" #define MQTTCLIENT_ERROR "Connection Lost with broker" #define MQTTCLIENT_DISCONNECT_CB 0xCB /* Custom define for implementation ease */ #define MQTTCLIENT_MAX_SIMULTANEOUS_SUB_TOPICS 4 #define MQTTCLIENT_MAX_SIMULTANEOUS_UNSUB_TOPICS 4 #ifndef CFG_CL_MQTT_CTXS #define MQTTCLIENT_MAX_SIMULTANEOUS_SERVER_CONN 4 #else #define MQTTCLIENT_MAX_SIMULTANEOUS_SERVER_CONN CFG_MQTT_CL_CTXS #endif #define MQTTClient_rxTxSemWait() sem_wait(&MQTTClient_Lib_CB.MQTTClient_syncRxTx) #define MQTTClient_rxTxSemPost() sem_post(&MQTTClient_Lib_CB.MQTTClient_syncRxTx) #define MQTTClient_mutexLock() pthread_mutex_lock(&MQTTClient_Lib_CB.MQTTClient_mutex); // forever #define MQTTClient_mutexUnlock() pthread_mutex_unlock(&MQTTClient_Lib_CB.MQTTClient_mutex); //***************************************************************************** // typedefs //***************************************************************************** /* MQTT Lib structure which holds Initialization Data */ typedef struct _SlMQTTClient_LibCfg_t_ { /**< Loopback port is used to manage lib internal functioning in case of connections to multiple servers simultaneously is desired. */ uint16_t loopbackPort; /**< Loopback port = 0, implies connection to only single server */ /**< Loopback port != 0, implies connection to multiple servers */ uint32_t respTime; /**< Reasonable response time (seconds) from server */ int32_t (*dbgPrint)(const char *pcFormat, ...); /**< Print debug information */ } SlMQTTClient_LibCfg_t; typedef struct _MQTTClient_ConnectCfg_t_ { bool clean; uint16_t keepAliveTimeout; } MQTTClient_ConnectCfg_t; typedef struct _SlMQTTClient_Ctx_t_ { /* Client information details */ char *clientID; char *usrName; char *usrPwd; MQTTClient_Will_t mqttWill; /* Client management variables */ bool inUse; char awaitedAck; uint16_t connAck; /*Sync Object used to ensure single in-flight message - used in blocking mode to wait on ack*/ sem_t ackSyncObj; /* Suback QoS pointer to store passed by application */ char *subackQos; /* Application information */ void* appHndl; NetAppCallBack_t appCBs; /* Library information */ void *cliHndl; bool blockingSend; bool connectedState; }SlMQTTClient_Ctx_t; //***************************************************************************** //globals //***************************************************************************** extern int32_t Report(const char *pcFormat, ...); SlMQTTClient_LibCfg_t SlMQTTClient_clientCfg = { 0, 30, (int32_t (*)(const char *, ...)) UART_PRINT }; int32_t MQTTClient_closeContext = 0; SlMQTTClient_Ctx_t *MQTTClient_clientContext = NULL; static SlMQTTClient_Ctx_t SlMQTTClient_ctx[MQTTCLIENT_MAX_SIMULTANEOUS_SERVER_CONN]; /* Creating a pool of MQTT constructs that can be used by the MQTT Lib MQTTClient_packet => pointer to a pool of the mqtt packet constructs MQTTClient_buffer => the buffer area which is attached with each of MQTTClient_packet*/ static MQTT_Packet_t MQTTClient_packet[MQTTCLIENT_MAX_MQP]; static uint8_t MQTTClient_buffer[MQTTCLIENT_MAX_MQP][MQTTCLIENT_BUF_LEN]; /*Task Priority and Response Time*/ uint16_t MQTTClient_waitSecs; bool MQTTClient_multiSrvConn = false; MQTTClient_ConnectCfg_t MQTTClient_connectCfg = { true, 25 }; /* MQTT Quality of Service */ static _const MQTT_QOS MQTTClient_qos[] = { MQTT_QOS0, MQTT_QOS1, MQTT_QOS2 }; /* Network Services specific to cc32xx*/ MQTT_DeviceNetServices_t MQTTClient_net = { commOpen, tcpSend, tcpRecv, sendTo, recvFrom, commClose, tcpListen, tcpAccept, tcpSelect, rtcSecs }; typedef struct _MQTTClient_LibControlBlock_t_ { /* Variable That is true when waitForMqttClose semaphore created, and false when the semaphore doesn't exists.*/ bool MQTTClient_sem_waitForMqttClose_Created; sem_t MQTTClient_waitForMqttClose; /* Lock Object to be passed to the MQTT lib */ pthread_mutex_t MQTTClient_libLock; /* Synchronization object used between the Rx and App task */ sem_t MQTTClient_syncRxTx; pthread_mutex_t MQTTClient_mutex; /* Multi-task Lock */ }MQTTClient_LibControlBlock_t; MQTTClient_LibControlBlock_t MQTTClient_Lib_CB; //***************************************************************************** // MQTT Client Internal Routines //***************************************************************************** //***************************************************************************** // //! \brief // //***************************************************************************** static inline void SetCondAwaitedAckLocked(SlMQTTClient_Ctx_t *clientCtx, char cond, char val) { MQTTClient_mutexLock(); if(cond == clientCtx->awaitedAck) { clientCtx->awaitedAck = val; } MQTTClient_mutexUnlock(); } //***************************************************************************** // //! \brief // //***************************************************************************** void mutexLockup(void *mqttLibLock) { pthread_mutex_lock((pthread_mutex_t)mqttLibLock); //forever } //***************************************************************************** // //! \brief // //***************************************************************************** void mutexUnlock(void *mqttLibLock) { pthread_mutex_unlock((pthread_mutex_t)mqttLibLock); } //***************************************************************************** // //! \brief Wait for the response (callback) from the server (network) // //***************************************************************************** int32_t _sl_ExtLib_ServerAckLockedWait(SlMQTTClient_Ctx_t *clientCtx) { int32_t rc = 0; MQTTClient_mutexLock(); if (true == clientCtx->blockingSend) { MQTTClient_mutexUnlock(); MQTTClient_ackRxSignalWait(&(clientCtx->ackSyncObj)); MQTTClient_mutexLock(); rc = (MQTT_DISCONNECT == clientCtx->awaitedAck) ? MQTT_PACKET_ERR_NOTCONN : 0; } MQTTClient_mutexUnlock(); return rc; } //***************************************************************************** // //! \brief Set (unprotected) in the implementation the value of the ACK from the server // //***************************************************************************** bool _sl_ExtLib_AwaitedAckSet(SlMQTTClient_Ctx_t *clientCtx, uint8_t newAwaited) { bool rc = false; if (MQTT_DISCONNECT != clientCtx->awaitedAck) { clientCtx->awaitedAck = newAwaited; rc = true; } return rc; } //***************************************************************************** // //! \brief Set (protected) in the implementation the value of the ACK from the server // //***************************************************************************** bool _sl_ExtLib_AwaitedAckLockedSet(SlMQTTClient_Ctx_t *clientCtx, uint8_t newAwaited) { bool rc; MQTTClient_mutexLock(); rc = _sl_ExtLib_AwaitedAckSet(clientCtx, newAwaited); MQTTClient_mutexUnlock(); return rc; } //***************************************************************************** // //! \brief // //***************************************************************************** static void processNotifyAckCB(void *app, uint8_t msgType, uint16_t msgID, uint8_t *buf, uint32_t len) { SlMQTTClient_Ctx_t *clientCtx = (SlMQTTClient_Ctx_t *) app; int32_t loopcnt; MQTTClient_OperationMetaDataCB_t eventCB; MQTTClient_mutexLock(); switch (msgType) { case MQTT_CONNACK: clientCtx->connAck = ((buf[0] << 8) | buf[1]); clientCtx->awaitedAck = 0; eventCB.messageType = MQTT_CONNACK; /* Notify the application which ConnAck return code received from the server */ clientCtx->appCBs( MQTT_CLIENT_OPERATION_CB_EVENT, (void*)&eventCB, sizeof(eventCB), (void*)&(clientCtx->connAck), sizeof(clientCtx->connAck)); MQTTClient_ackRxSignalPost(&(clientCtx->ackSyncObj)); break; case MQTT_SUBACK: if (true == clientCtx->blockingSend) { for (loopcnt = 0; loopcnt < len; loopcnt++) { clientCtx->subackQos[loopcnt] = buf[loopcnt]; } if (clientCtx->awaitedAck == msgType) { clientCtx->awaitedAck = 0; MQTTClient_ackRxSignalPost(&(clientCtx->ackSyncObj)); } } else { eventCB.messageType = MQTT_SUBACK; clientCtx->appCBs( MQTT_CLIENT_OPERATION_CB_EVENT, (void*)&eventCB, sizeof(eventCB), (void*)buf, len); } break; default: if (true == clientCtx->blockingSend) { if (clientCtx->awaitedAck == msgType) { clientCtx->awaitedAck = 0; MQTTClient_ackRxSignalPost(&(clientCtx->ackSyncObj)); } } else { eventCB.messageType = msgType; clientCtx->appCBs( MQTT_CLIENT_OPERATION_CB_EVENT, (void*)&eventCB, sizeof(eventCB), (void*)MQTTCLIENT_ACK, strlen(MQTTCLIENT_ACK)); } break; } MQTTClient_mutexUnlock(); return; } //***************************************************************************** // //! \brief // //***************************************************************************** static bool processPublishRxCB(void *app, bool dup, MQTT_QOS qos, bool retain, MQTT_Packet_t *mqp) { SlMQTTClient_Ctx_t *clientCtx = (SlMQTTClient_Ctx_t *) app; MQTTClient_RecvMetaDataCB_t metaData; MQTTClient_mutexLock(); /*If incoming message is a publish message from broker */ /* Invokes the event handler with topic,topic length,payload and payload length values*/ if (MQTT_DISCONNECT != clientCtx->awaitedAck) { metaData.topic = (char _const*) MQTT_PACKET_PUB_TOP_BUF(mqp); metaData.topLen = MQTT_PACKET_PUB_TOP_LEN(mqp); metaData.dup = dup; metaData.qos = MQTTClient_mqpPubQos(mqp); metaData.retain = retain; clientCtx->appCBs(MQTT_CLIENT_RECV_CB_EVENT, &metaData, sizeof(metaData), MQTT_PACKET_PUB_PAY_BUF(mqp), MQTT_PACKET_PUB_PAY_LEN(mqp)); } MQTTClient_mutexUnlock(); return true; } //***************************************************************************** // //! \brief // //***************************************************************************** static void processDisconnCB(void *app, int32_t cause) { SlMQTTClient_Ctx_t *clientCtx = (SlMQTTClient_Ctx_t *) app; MQTTClient_mutexLock(); if (MQTT_DISCONNECT != clientCtx->awaitedAck) { clientCtx->awaitedAck = MQTT_DISCONNECT; MQTTClient_ackRxSignalPost(&(clientCtx->ackSyncObj)); } clientCtx->appCBs(MQTT_CLIENT_DISCONNECT_CB_EVENT, NULL,0,NULL,0); MQTTClient_mutexUnlock(); return; } //***************************************************************************** // //! \brief // //***************************************************************************** static SlMQTTClient_Ctx_t *getAvailableClictxMem(void) { int32_t loopcnt; int32_t maxStore; if (false == MQTTClient_multiSrvConn) { maxStore = 1; } else { maxStore = MQTTCLIENT_MAX_SIMULTANEOUS_SERVER_CONN; } for (loopcnt = 0; loopcnt < maxStore; loopcnt++) { if (false == SlMQTTClient_ctx[loopcnt].inUse) { SlMQTTClient_ctx[loopcnt].inUse = true; return (&(SlMQTTClient_ctx[loopcnt])); } } return NULL; } //***************************************************************************** // //! \brief // //***************************************************************************** int32_t MqttClientCtxCreate(_const MQTTClient_Attrib_t *ctxCfg) { SlMQTTClient_Ctx_t *clientCtxPtr; MQTTClientCore_CtxCfg_t libCtxCfg; MQTTClientCore_CtxCBs_t libCliCBs; MQTT_SecureConn_t libNwSecurity; int32_t retval; /* Get a client context storage area */ clientCtxPtr = getAvailableClictxMem(); if (clientCtxPtr == NULL) { return -1; } /* Create the sync object to signal on arrival of ACK packet */ retval = sem_init(&(clientCtxPtr->ackSyncObj), 0, 0); if (retval < 0) { clientCtxPtr->inUse = false; return -1; } sem_trywait(&(clientCtxPtr->ackSyncObj)); /* Initialize the ACK awaited */ clientCtxPtr->awaitedAck = MQTT_DISCONNECT; /* Initialize the client lib */ libCtxCfg.configOpts = ctxCfg->mqttMode31; if (true == MQTTClient_multiSrvConn) { libCtxCfg.configOpts |= (MQTTCLIENTCORE_CFG_APP_HAS_RTSK | MQTTCLIENTCORE_CFG_MK_GROUP_CTX); } else { libCtxCfg.configOpts |= MQTTCLIENTCORE_CFG_APP_HAS_RTSK; } /* get the network connection options */ clientCtxPtr->blockingSend = ctxCfg->blockingSend; libCtxCfg.nwconnOpts = ctxCfg->connParams->netconnFlags; libCtxCfg.serverAddr = (char*) ctxCfg->connParams->serverAddr; libCtxCfg.portNumber = ctxCfg->connParams->port; /* Initialize secure socket parameters */ /* Check if the secure connection flag in on */ if ((libCtxCfg.nwconnOpts & MQTT_DEV_NETCONN_OPT_SEC) != 0) { /* Check if the UDP socket flag in off */ if ((libCtxCfg.nwconnOpts & MQTT_DEV_NETCONN_OPT_UDP) == 0) { /* Check if the secure connection parameters are set */ if (ctxCfg->connParams->cipher && ctxCfg->connParams->method && ctxCfg->connParams->nFiles) { libCtxCfg.nwconnOpts |= MQTT_DEV_NETCONN_OPT_TCP; libCtxCfg.nwSecurity = &libNwSecurity; /* initialize secure socket parameters */ libCtxCfg.nwSecurity->cipher = (void*) &(ctxCfg->connParams->cipher); libCtxCfg.nwSecurity->method = (void*) &(ctxCfg->connParams->method); libCtxCfg.nwSecurity->nFile = ctxCfg->connParams->nFiles; libCtxCfg.nwSecurity->files = (char**) ctxCfg->connParams->secureFiles; } else { /* Not all the secure connection parameters are set */ UART_PRINT("\n\rSecure connection flag is on, missing security parameters\n\r\n\r"); return -1; } } else { /* Check if the UDP socket and the secure connection flags are on. This state isn't allowed */ UART_PRINT("\n\rSecure connection is on, UDP Socket is not allowed\n\r\n\r"); return -1; } } else { /* Secure connection flag in off */ /* Check if the secure connection parameters are set when Secure connection flag in off */ if (ctxCfg->connParams->cipher || ctxCfg->connParams->method || ctxCfg->connParams->nFiles) { UART_PRINT("\n\rSecure connection flag is off, security parameters will be discard\n\r\n\r"); } /* Check if UDP socket flag is off */ if ((libCtxCfg.nwconnOpts & MQTT_DEV_NETCONN_OPT_UDP) == 0) { libCtxCfg.nwconnOpts |= MQTT_DEV_NETCONN_OPT_TCP; } libCtxCfg.nwSecurity = NULL; } libCliCBs.publishRx = processPublishRxCB; libCliCBs.ackNotify = processNotifyAckCB; libCliCBs.disconnCB = processDisconnCB; retval = MQTTClientCore_createCtx(&libCtxCfg, &libCliCBs, clientCtxPtr, &clientCtxPtr->cliHndl); if (retval < 0) { clientCtxPtr->inUse = false; return -1; } MQTTClient_clientContext = clientCtxPtr; return 0; } //***************************************************************************** // //! \brief Deletes the specified client context. //! //! \param[in] cli_ctx refers to client context to be deleted //! \return Success (0) or Failure (< 0) // //***************************************************************************** int32_t MqttClientCtxDelete(void) { SlMQTTClient_Ctx_t *clientCtx = (SlMQTTClient_Ctx_t *) MQTTClient_clientContext; int32_t retval; retval = MQTTClientCore_deleteCtx(clientCtx->cliHndl); if ((retval >= 0) || (1 == MQTTClient_closeContext)) { /* Delete the semaphore */ sem_destroy(&(clientCtx->ackSyncObj)); /* Free up the context */ memset(clientCtx, 0, sizeof(SlMQTTClient_Ctx_t)); } return ((retval < 0) ? -1 : 0); } //***************************************************************************** // //! \brief SUBSCRIBE a set of topics. //! To receive data about a set of topics from the server, the app through //! this routine must subscribe to those topic names with the server. The //! caller can indicate whether the routine should block until a time, the //! message has been acknowledged by the server. //! //! In case, the app has chosen not to await for the ACK from the server, //! the SL MQTT implementation will notify the app about the subscription //! through the callback routine. //! //! \param[in] cli_ctx refers to the handle to the client context //! \param[in] topics set of topic names to subscribe. It is an array of //! pointers to NUL terminated strings. //! \param[in,out] qos array of qos values for each topic in the same order //! of the topic array. If configured to await for SUB-ACK from server, the //! array will contain qos responses for topics from the server. //! \param[in] count number of such topics //! //! \return Success(transaction Message ID) or Failure(< 0) // //***************************************************************************** int32_t MqttClientSub(MQTTClient_SubscribeParams_t* pValue, int32_t count) { int32_t ret = MQTT_PACKET_ERR_FNPARAM, i; char qosLevel[MQTTCLIENT_MAX_SIMULTANEOUS_SUB_TOPICS]; MQTT_UTF8StrQOS_t qosTopics[MQTTCLIENT_MAX_SIMULTANEOUS_SUB_TOPICS]; SlMQTTClient_Ctx_t *clientCtx = (SlMQTTClient_Ctx_t *)MQTTClient_clientContext; if(count > MQTTCLIENT_MAX_SIMULTANEOUS_SUB_TOPICS) { return ret; /* client not connected*/ } for(i = 0; i < count; i++) { qosTopics[i].buffer = ( const char *)((pValue[i]).topic); qosTopics[i].qosreq = MQTTClient_qos[(pValue[i]).qos]; qosLevel[i] = qosTopics[i].qosreq; qosTopics[i].length = strlen(qosTopics[i].buffer); } ret = MQTT_PACKET_ERR_NOTCONN; MQTTClient_mutexLock(); if(_sl_ExtLib_AwaitedAckSet(clientCtx, MQTT_SUBACK) == false) { MQTTClient_mutexUnlock(); return ret; } clientCtx->subackQos = qosLevel; MQTTClient_mutexUnlock(); /* Send the subscription MQTT message */ ret = MQTTClientCore_sendSubMsg(clientCtx->cliHndl, qosTopics, count); if(ret < 0) { SetCondAwaitedAckLocked(clientCtx, MQTT_SUBACK, 0); return ret; } ret = _sl_ExtLib_ServerAckLockedWait(clientCtx); return ((ret >= 0)? 0: ret); } //***************************************************************************** // //! \brief UNSUBSCRIBE a set of topics. //! The app should use this service to stop receiving data for the named //! topics from the server. The caller can indicate whether the routine //! should block until a time, the message has been acknowledged by the //! server. //! //! In case, the app has chosen not to await for the ACK from the server, //! the SL MQTT implementation will notify the app about the subscription //! through the callback routine. //! //! \param[in] cli_ctx refers to the handle to the client context //! \param[in] topics set of topics to be unsubscribed. It is an array of //! pointers to NUL terminated strings. //! \param[in] count number of topics to be unsubscribed //! //! \return Success(transaction Message ID) or Failure(< 0) // //***************************************************************************** int32_t MqttClientUnsub(MQTTClient_UnsubscribeParams_t* pValue, int32_t count) { int32_t ret = MQTT_PACKET_ERR_FNPARAM, i; MQTT_UTF8String_t unsubTopics[MQTTCLIENT_MAX_SIMULTANEOUS_UNSUB_TOPICS]; SlMQTTClient_Ctx_t *clientCtx = (SlMQTTClient_Ctx_t *) MQTTClient_clientContext; if (count > MQTTCLIENT_MAX_SIMULTANEOUS_UNSUB_TOPICS) { return ret; } for (i = 0; i < count; i++) { MQTTClient_str2UTFConv(unsubTopics[i], (pValue[i]).topic); } ret = MQTT_PACKET_ERR_NOTCONN; if (_sl_ExtLib_AwaitedAckLockedSet(clientCtx, MQTT_UNSUBACK) == false) { return ret; } /* Send the unsubscription MQTT message */ ret = MQTTClientCore_sendUnsubMsg(clientCtx->cliHndl, unsubTopics, count); if (ret < 0) { SetCondAwaitedAckLocked(clientCtx, MQTT_UNSUBACK, 0); return ret; } ret = _sl_ExtLib_ServerAckLockedWait(clientCtx); return ((ret >= 0) ? 0 : ret); } //***************************************************************************** // //! \brief // //***************************************************************************** int32_t MqttClientConfig(_const SlMQTTClient_LibCfg_t *cfg) { MQTTClientCore_LibCfg_t libCfg; int32_t retval; /* Setup the MQTT client lib configurations */ libCfg.loopbackPort = cfg->loopbackPort; if (cfg->loopbackPort) { MQTTClient_multiSrvConn = true; libCfg.grpUsesCbfn = true; /* Does use the group callback func */ } else { MQTTClient_multiSrvConn = false; libCfg.grpUsesCbfn = false; /* Doesn't use the group callback func */ /* Create the sync object between Rx and App tasks */ retval = sem_init(&MQTTClient_Lib_CB.MQTTClient_syncRxTx, 0, 0); /* If semaphore couldn't be created return error */ if (retval < 0) { UART_PRINT("could not create SyncRxTx semaphore\n\r"); return -1; } sem_trywait(&MQTTClient_Lib_CB.MQTTClient_syncRxTx); } MQTTClient_waitSecs = cfg->respTime; /* Setup the mutex operations */ retval = pthread_mutex_init(&MQTTClient_Lib_CB.MQTTClient_libLock, (const pthread_mutexattr_t *)NULL); if (retval < 0) { UART_PRINT("could not create Lib Lock mutex\n\r"); return -1; } /* setup the mutex operations */ retval = pthread_mutex_init(&MQTTClient_Lib_CB.MQTTClient_mutex, (const pthread_mutexattr_t *)NULL); if (retval < 0) { UART_PRINT("could not create Multi-task Lock mutex\n\r"); return -1; } libCfg.mutex = (void *) &MQTTClient_Lib_CB.MQTTClient_libLock; libCfg.mutexLockin = mutexLockup; libCfg.mutexUnlock = mutexUnlock; /* hooking DBG print function */ libCfg.debugPrintf = cfg->dbgPrint; /* Initialize client library */ if (MQTTClientCore_initLib(&libCfg) < 0) { return -1; } return 0; } //***************************************************************************** // MQTT Client External Routines //***************************************************************************** //***************************************************************************** // //! \brief // //***************************************************************************** NetAppHandle_t MQTTClient_create(NetAppCallBack_t defaultCallback , MQTTClient_Attrib_t *attrib) { NetAppHandle_t handle = (NetAppHandle_t)1; int32_t retval; MQTTClient_closeContext = 0; MqttClientConfig(&SlMQTTClient_clientCfg); /* Initialize the control variables */ memset(SlMQTTClient_ctx, 0, sizeof(SlMQTTClient_ctx)); /* provide MQTT Lib information to create a pool of MQTT constructs. */ MQTTClientCore_registerBuffers(MQTTCLIENT_MAX_MQP, MQTTClient_packet, MQTTCLIENT_BUF_LEN, &MQTTClient_buffer[0][0]); /* Register network services specific to CC32xx */ MQTTClientCore_registerNetSvc(&MQTTClient_net); MQTTClient_mutexLock(); if (true == MQTTClient_Lib_CB.MQTTClient_sem_waitForMqttClose_Created) { sem_destroy(&MQTTClient_Lib_CB.MQTTClient_waitForMqttClose); MQTTClient_Lib_CB.MQTTClient_sem_waitForMqttClose_Created = false; } MQTTClient_mutexUnlock(); /* sync object for inter thread communication */ retval = sem_init(&MQTTClient_Lib_CB.MQTTClient_waitForMqttClose, 0, 1); if (retval < 0) { UART_PRINT("could not create semaphore\n\r"); return NULL; } // // Set Client ID // MQTTClient_Lib_CB.MQTTClient_sem_waitForMqttClose_Created = true; if(MqttClientCtxCreate(attrib) ) { UART_PRINT("could not init connection\n\r"); return NULL; } MQTTClient_clientContext->clientID = attrib->clientId; MQTTClient_clientContext->appCBs = defaultCallback; return (NetAppHandle_t)(handle); } //***************************************************************************** // //! \brief // //***************************************************************************** int16_t MQTTClient_delete(NetAppHandle_t handle) { int32_t retval; SlMQTTClient_Ctx_t *clientCtx = (SlMQTTClient_Ctx_t *) MQTTClient_clientContext; MQTTClient_closeContext = 1; // Disconnect from Broker if (false != clientCtx->connectedState) { MQTTClient_disconnect(handle); } // // deleting the context for the connection // MqttClientCtxDelete(); MQTTClient_mutexLock(); if (true == MQTTClient_Lib_CB.MQTTClient_sem_waitForMqttClose_Created) { MQTTClient_closeContext = 1; MQTTClient_rxTxSemPost(); sem_wait(&MQTTClient_Lib_CB.MQTTClient_waitForMqttClose); sem_destroy(&MQTTClient_Lib_CB.MQTTClient_waitForMqttClose); MQTTClient_Lib_CB.MQTTClient_sem_waitForMqttClose_Created = false; } MQTTClient_mutexUnlock(); /* Deinitialize the MQTT client lib */ retval = MQTTClientCore_exitLib(); if ((retval >= 0) || (1 == MQTTClient_closeContext)) { if (&MQTTClient_Lib_CB.MQTTClient_libLock != NULL) { /* Delete the MQTT lib lock object */ pthread_mutex_destroy(&MQTTClient_Lib_CB.MQTTClient_libLock); } if (&MQTTClient_Lib_CB.MQTTClient_mutex != NULL) { /* Delete the MT lock object */ pthread_mutex_destroy(&MQTTClient_Lib_CB.MQTTClient_mutex); } /* Delete the Rx-Tx task sync object */ sem_destroy(&MQTTClient_Lib_CB.MQTTClient_syncRxTx); MQTTClient_Lib_CB.MQTTClient_libLock = NULL; } return ((retval < 0) ? -1 : 0); } //***************************************************************************** // //! \brief Receive Task. Invokes in the context of a task // //***************************************************************************** int16_t MQTTClient_run(NetAppHandle_t handle) { int32_t retval; /* The semaphore created with value 1, the following line will clear it */ sem_wait(&MQTTClient_Lib_CB.MQTTClient_waitForMqttClose); do { if (false == MQTTClient_multiSrvConn) { /* wait on broker connection */ MQTTClient_rxTxSemWait(); while (1) { /* Forcing to use the index 0 always - caution */ retval = MQTTClientCore_ctxRun(SlMQTTClient_ctx[0].cliHndl, MQTTClient_waitSecs); if (((retval < 0) && (retval != MQTT_PACKET_ERR_TIMEOUT)) || (1 == MQTTClient_closeContext)) { sem_post(&MQTTClient_Lib_CB.MQTTClient_waitForMqttClose); return 0; } } } else { retval = MQTTClientCore_run(MQTTClient_waitSecs); if (((retval < 0) && (retval != MQTT_PACKET_ERR_TIMEOUT)) || (1 == MQTTClient_closeContext)) { sem_post(&MQTTClient_Lib_CB.MQTTClient_waitForMqttClose); MQTTClient_closeContext = 0; break; } } } while (1); return 0; } //***************************************************************************** // //! \brief // //***************************************************************************** int16_t MQTTClient_connect(NetAppHandle_t handle) { int32_t ret = MQTT_PACKET_ERR_NOTCONN; SlMQTTClient_Ctx_t *clientCtx = (SlMQTTClient_Ctx_t *) MQTTClient_clientContext; /*utf8 strings into which client info will be stored*/ MQTT_UTF8String_t clientID, username, usrPwd, will_topic, willMsg; MQTT_UTF8String_t *usrname = NULL, *usrpasswd = NULL, *clientid = NULL; MQTTClient_mutexLock(); clientCtx->connectedState = false; if (MQTT_DISCONNECT != clientCtx->awaitedAck) { clientCtx->connAck = 0; MQTTClient_mutexUnlock(); return ret; } /* Provide Client ID,user name and password into MQTT Library */ if (clientCtx->clientID != NULL) { MQTTClient_str2UTFConv(clientID, clientCtx->clientID); clientid = &clientID; } if (clientCtx->usrName != NULL) { MQTTClient_str2UTFConv(username, clientCtx->usrName); usrname = &username; } if (clientCtx->usrPwd != NULL) { MQTTClient_str2UTFConv(usrPwd, clientCtx->usrPwd); usrpasswd = &<PASSWORD>; } ret = MQTTClientCore_registerCtxInfo(clientCtx->cliHndl, clientid, usrname, usrpasswd); if (ret < 0) { clientCtx->connAck = 0; MQTTClient_mutexUnlock(); return ret; } /* Register a will message, if specified, into MQTT Library */ if (NULL != clientCtx->mqttWill.willTopic) { MQTTClient_str2UTFConv(will_topic, clientCtx->mqttWill.willTopic); MQTTClient_str2UTFConv(willMsg, clientCtx->mqttWill.willMsg); ret = MQTTClientCore_registerWillInfo(clientCtx->cliHndl, &will_topic, &willMsg, MQTTClient_qos[clientCtx->mqttWill.willQos], clientCtx->mqttWill.retain); if (ret < 0) { clientCtx->connAck = 0; MQTTClient_mutexUnlock(); return ret; } } clientCtx->connAck = 0; clientCtx->awaitedAck = MQTT_CONNACK; MQTTClient_mutexUnlock(); /* Connect to the server */ ret = MQTTClientCore_sendConnectMsg(clientCtx->cliHndl, MQTTClient_connectCfg.clean, MQTTClient_connectCfg.keepAliveTimeout); MQTTClient_mutexLock(); if (false == MQTTClient_multiSrvConn) { /* Unblock the receive task here */ MQTTClient_rxTxSemPost(); } MQTTClient_mutexUnlock(); /*Network or Socket Error happens*/ if (ret < 0) { SetCondAwaitedAckLocked(clientCtx, MQTT_CONNACK, MQTT_DISCONNECT); return ret; } /* Wait for a CONNACK here */ MQTTClient_ackRxSignalWait(&(clientCtx->ackSyncObj)); MQTTClient_mutexLock(); if (MQTT_DISCONNECT != clientCtx->awaitedAck) { /* Check the return code of connAck (LSB) */ if( 0 == (clientCtx->connAck & 0xff) ) { ret = clientCtx->connAck; clientCtx->connectedState = true; } else { /* Error received, Connection failed */ ret = 0 - clientCtx->connAck; clientCtx->connectedState = false; } } MQTTClient_mutexUnlock(); return ret; } //***************************************************************************** // //! \brief // //***************************************************************************** int16_t MQTTClient_disconnect(NetAppHandle_t handle) { SlMQTTClient_Ctx_t *clientCtx = (SlMQTTClient_Ctx_t *) MQTTClient_clientContext; int32_t retval = MQTT_PACKET_ERR_NOTCONN; clientCtx->connectedState = false; if (_sl_ExtLib_AwaitedAckLockedSet(clientCtx,MQTTCLIENT_DISCONNECT_CB) == true) { /* Already disconnected - quit */ /* send the disconnect command. */ retval = MQTTClientCore_sendDisconn(clientCtx->cliHndl); if (retval >= 0) { MQTTClient_ackRxSignalWait(&(clientCtx->ackSyncObj)); } } return ((retval >= 0) ? 0 : retval); } //***************************************************************************** // //! \brief // //***************************************************************************** uint16_t MqttClient_send(NetAppHandle_t hdl , void* pMeta , uint16_t MetaLen , void* pData , uint16_t DataLen , uint32_t flags) { int32_t ret = MQTT_PACKET_ERR_FNPARAM; MQTT_UTF8String_t topicUTF8; SlMQTTClient_Ctx_t *clientCtx = (SlMQTTClient_Ctx_t *) MQTTClient_clientContext; uint8_t qosLevel = (flags & (MQTT_QOS_0 | MQTT_QOS_1 | MQTT_QOS_2)); bool retain = (flags & MQTT_PUBLISH_RETAIN); uint8_t awaitedAcks[] = { 0 /* connected */, MQTT_PUBACK, MQTT_PUBCOMP }; uint8_t awaitedAck; MQTTClient_str2UTFConv(topicUTF8, pMeta); awaitedAck = awaitedAcks[qosLevel]; ret = MQTT_PACKET_ERR_NOTCONN; if (_sl_ExtLib_AwaitedAckLockedSet(clientCtx, awaitedAck) == false) { return ret; } /*publish the message*/ ret = MQTTClientCore_sendPubMsg(clientCtx->cliHndl, &topicUTF8, pData , DataLen , MQTTClient_qos[qosLevel], retain); if (ret < 0) { SetCondAwaitedAckLocked(clientCtx, awaitedAck, 0); return ret; } if (qosLevel) { ret = _sl_ExtLib_ServerAckLockedWait(clientCtx); } return ((ret >= 0) ? 0 : ret); } //***************************************************************************** // //! \brief // //***************************************************************************** int16_t MQTTClient_publish(NetAppHandle_t handle, char *topic, uint16_t topicLen, char *msg, uint16_t msgLen, uint32_t flags) { return (MqttClient_send(handle, (void*)topic,topicLen , (void*) msg , msgLen , flags)); } //***************************************************************************** // //! \brief // //***************************************************************************** int16_t MQTTClient_subscribe(NetAppHandle_t handle , MQTTClient_SubscribeParams_t *value, uint8_t numberOfTopics) { return (MqttClientSub((MQTTClient_SubscribeParams_t *)value, (int32_t)numberOfTopics)); } //***************************************************************************** // //! \brief // //***************************************************************************** int16_t MQTTClient_unsubscribe(NetAppHandle_t handle , MQTTClient_UnsubscribeParams_t *value, uint8_t numberOfTopics) { return (MqttClientUnsub((MQTTClient_UnsubscribeParams_t*)value, numberOfTopics)); } //***************************************************************************** // //! \brief // //***************************************************************************** int16_t MQTTClient_get(NetAppHandle_t handle, uint16_t option , void *value, uint16_t valueLength) { return 0; } //***************************************************************************** // //! \brief // //***************************************************************************** int16_t MQTTClient_set(NetAppHandle_t handle , uint16_t option , void *value , uint16_t valueLength) { int32_t retVal = 0; switch (option) { case MQTT_CLIENT_USER_NAME: /* Save the reference to the Username */ MQTTClient_clientContext->usrName = (char*) value; break; case MQTT_CLIENT_PASSWORD: /* Save the reference to the password */ MQTTClient_clientContext->usrPwd = (char*) value; break; case MQTT_CLIENT_WILL_PARAM: /* Save the reference to will parameters*/ MQTTClient_clientContext->mqttWill = *((MQTTClient_Will_t*) value); break; case MQTT_CLIENT_KEEPALIVE_TIME: { uint16_t *keep_alive = (uint16_t*) value; MQTTClient_connectCfg.keepAliveTimeout = *keep_alive; } break; case MQTT_CLIENT_CLEAN_CONNECT: { bool *clean = (bool *) value; MQTTClient_connectCfg.clean = *clean; } break; default: break; } return retVal; }
FTC-9974-THOR/SkyStone
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/beuler/BeulerTeleOp.java
<reponame>FTC-9974-THOR/SkyStone package org.firstinspires.ftc.teamcode.beuler; import android.os.SystemClock; import com.qualcomm.hardware.lynx.LynxModule; import com.qualcomm.hardware.rev.RevBlinkinLedDriver; import com.qualcomm.robotcore.eventloop.opmode.OpMode; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import com.qualcomm.robotcore.util.ElapsedTime; import org.ftc9974.thorcore.control.PIDF; import org.ftc9974.thorcore.control.navigation.IMUNavSource; import org.ftc9974.thorcore.control.navigation.NavSource; import org.ftc9974.thorcore.robot.drivetrains.MecanumDrive; import java.util.List; @TeleOp(name = "Beuler Tele Op") public class BeulerTeleOp extends OpMode { private MecanumDrive rb; private Arm arm; private Intake intake; private FoundationClaw foundationClaw; private Blinkin blinkin; private StoneArm stoneArm; private ParkingTape parkingTape; private Odometer odometer; private NavSource navSource; private PIDF headingPid; private boolean lastTurnInput; private boolean turnMaxDetectionActive; private double lastTurnError; private long lastTimeStamp; private long blinkinTimeStamp; private boolean homingSequenceComplete; private boolean armRTP, lastReady, lastPlace, lastRetract, lastLowPlace; private boolean liftRTP; private boolean lastLiftInput; private boolean liftMaxDetectionActive; private double lastLiftError; private enum RetractState { RELEASE, LIFT_A_BIT, REVOLVE_ARM, LOWER_LIFT_UNTIL_ARM_READY, LOWER_LIFT_WITH_ARM } private RetractState retractState; private ElapsedTime retractTimer; private boolean retractSequenceEngaged; private List<LynxModule> revHubs; @Override public void init() { rb = new MecanumDrive(hardwareMap); rb.setAxisInversion(true, true, false); arm = new Arm(hardwareMap); intake = new Intake(hardwareMap); foundationClaw = new FoundationClaw(hardwareMap); blinkin = new Blinkin(hardwareMap); stoneArm = new StoneArm(hardwareMap); stoneArm.retract(); stoneArm.release(); parkingTape = new ParkingTape(hardwareMap); odometer = new Odometer(hardwareMap, intake.intake0); odometer.retract(); arm.setArmTargetPosition(arm.getArmPosition()); arm.holdCapstone(); navSource = new IMUNavSource(hardwareMap); headingPid = new PIDF(0.7, 0, 0, 0); headingPid.setInputFunction(navSource::getHeading); headingPid.setAtTargetThreshold(Math.toRadians(1)); headingPid.setContinuityRange(-Math.PI, Math.PI); headingPid.setContinuous(true); Thread.currentThread().setPriority(7); retractTimer = new ElapsedTime(); revHubs = hardwareMap.getAll(LynxModule.class); for (LynxModule revHub : revHubs) { revHub.setBulkCachingMode(LynxModule.BulkCachingMode.MANUAL); } } @Override public void loop() { long startTime = System.nanoTime(); lastTimeStamp = startTime; for (LynxModule revHub : revHubs) { revHub.clearBulkCache(); } //telemetry.addData("Odometer Position", odometer.getOdometerPosition()); //Vector2 driveInput = new Vector2(gamepad1.right_stick_x, -gamepad1.right_stick_y); //driveInput = driveInput.rotate(navSource.getHeading()); boolean currentTurnInput = Math.abs(gamepad1.left_stick_x) > 0.1; double currentTurnError = Math.abs(headingPid.getLastError()); double x = gamepad1.right_stick_x * Math.abs(gamepad1.right_stick_x); double y = -gamepad1.right_stick_y * Math.abs(gamepad1.right_stick_y); double r = -gamepad1.left_stick_x * Math.abs(gamepad1.left_stick_x); telemetry.addData("X", x); telemetry.addData("Y", y); telemetry.addData("R", r); telemetry.addData("X raw", gamepad1.right_stick_x); telemetry.addData("Y raw", -gamepad1.right_stick_y); telemetry.addData("R raw", -gamepad1.left_stick_x); if (currentTurnInput && !lastTurnInput) { // begin turning rb.drive(x, y, r); } else if (currentTurnInput && lastTurnInput) { // turning rb.drive(x, y, r); } else if (lastTurnInput) { // end turning turnMaxDetectionActive = true; headingPid.setSetpoint(navSource.getHeading()); rb.drive(x, y, r); } else { // idle if (turnMaxDetectionActive) { if (currentTurnError < lastTurnError) { headingPid.setSetpoint(navSource.getHeading()); turnMaxDetectionActive = false; } } rb.drive(x, y, headingPid.update()); } lastTurnInput = currentTurnInput; lastTurnError = currentTurnError; if (gamepad1.a) { headingPid.setSetpoint(navSource.getHeading()); } //telemetry.addData("Drive System Time", (System.nanoTime() - lastTimeStamp) / 1000000.0); //lastTimeStamp = System.nanoTime(); if (gamepad2.y) { arm.releaseCapstone(); blinkin.setPattern(RevBlinkinLedDriver.BlinkinPattern.BLUE); blinkinTimeStamp = SystemClock.uptimeMillis(); } else if (gamepad2.x) { arm.holdCapstone(); } else if (gamepad2.a) { arm.grab(); } else if (gamepad2.b) { arm.release(); blinkin.setPattern(RevBlinkinLedDriver.BlinkinPattern.GOLD); blinkinTimeStamp = SystemClock.uptimeMillis(); } //telemetry.addData("Manipulator Time", (System.nanoTime() - lastTimeStamp) / 1000000.0); //lastTimeStamp = System.nanoTime(); if (gamepad1.x) { foundationClaw.extend(); } else if (gamepad1.y) { foundationClaw.retract(); } //telemetry.addData("Claw Time", (System.nanoTime() - lastTimeStamp) / 1000000.0); //lastTimeStamp = System.nanoTime(); if (!homingSequenceComplete && arm.liftAtBottom()) { blinkin.setPattern(RevBlinkinLedDriver.BlinkinPattern.HOT_PINK); blinkinTimeStamp = SystemClock.uptimeMillis(); homingSequenceComplete = true; } if (gamepad1.left_trigger > 0.8 || gamepad2.left_trigger > 0.8) { intake.intake(1); blinkin.setPattern(RevBlinkinLedDriver.BlinkinPattern.GREEN); } else if (gamepad1.right_trigger > 0.8 || gamepad2.right_trigger > 0.8) { intake.outtake(1); blinkin.setPattern(RevBlinkinLedDriver.BlinkinPattern.RED); } else { intake.stop(); if (SystemClock.uptimeMillis() - blinkinTimeStamp > 1000) { blinkin.defaultPattern(); } } //telemetry.addData("Intake Time", (System.nanoTime() - lastTimeStamp) / 1000000.0); //lastTimeStamp = System.nanoTime(); if (gamepad2.back && !lastRetract) { retractState = RetractState.RELEASE; retractTimer.reset(); arm.release(); retractSequenceEngaged = true; } lastRetract = gamepad2.back; if (retractSequenceEngaged) { switch (retractState) { case RELEASE: if (retractTimer.seconds() > 0.3) { retractState = RetractState.LIFT_A_BIT; liftRTP = true; arm.setLiftTargetPosition(Math.min(arm.getLiftPosition() + 900, arm.getLiftMaxPosition())); } break; case LIFT_A_BIT: if (Math.abs(arm.lastLiftPIDError()) < 75) { armRTP = true; arm.startControlledArmMotion(1.7); retractTimer.reset(); retractState = RetractState.REVOLVE_ARM; } break; case REVOLVE_ARM: if (arm.getArmPosition() > 1.5) { liftRTP = true; arm.setLiftTargetPosition(143); retractState = RetractState.LOWER_LIFT_UNTIL_ARM_READY; } break; case LOWER_LIFT_UNTIL_ARM_READY: if (retractTimer.seconds() > 1.5) { armRTP = true; arm.startControlledArmMotion(3); retractState = RetractState.LOWER_LIFT_WITH_ARM; arm.setLiftClosedLoopEnabled(false); arm.setLiftPower(-1); } break; case LOWER_LIFT_WITH_ARM: if (arm.getLiftPosition() < 0 || arm.liftAtBottom()) { arm.setLiftPower(0); } if (arm.getLiftPosition() < 230 && arm.getArmPosition() > 2.8) { retractSequenceEngaged = false; liftRTP = false; armRTP = false; } break; } } telemetry.addData("Retract Sequence Engaged", retractSequenceEngaged); telemetry.addData("Retract State", retractState); boolean currentInput = Math.abs(gamepad2.left_stick_y) > 0.05; if (gamepad2.left_bumper) { if (!lastReady) { arm.startControlledArmMotion(1.45); } armRTP = true; } else if (gamepad2.right_bumper) { if (!lastPlace) { arm.startControlledArmMotion(0.953); } armRTP = true; } else if (gamepad2.dpad_down) { if (!lastLowPlace) { arm.startControlledArmMotion(0.4); } armRTP = true; } lastReady = gamepad2.left_bumper; lastPlace = gamepad2.right_bumper; lastLowPlace = gamepad2.dpad_down; if (armRTP) { if (currentInput) { retractSequenceEngaged = false; arm.stopControlledArmMotion(); armRTP = false; } } else { arm.setArmClosedLoopEnabled(false); if (Math.abs(gamepad2.left_stick_y) > 0.05) { arm.setShoulderPower(-gamepad2.left_stick_y); } else { arm.setShoulderPower(0); } } /*telemetry.addData("Stick", gamepad2.left_stick_y); telemetry.addData("Speed Limit", arm.speedLimit); telemetry.addData("Arm RTP", armRTP); telemetry.addData("Start Point", arm.shoulderStartPoint); telemetry.addData("Target Point", arm.getArmTargetPosition()); telemetry.addData("To Target", arm.toTarget); telemetry.addData("From Start", arm.fromStart); telemetry.addData("Arm Position", arm.getArmPosition()); telemetry.addData("Last Arm Error", arm.lastArmPIDError()); telemetry.addData("Pid Output", arm.pidOutput);*/ //telemetry.addData("Shoulder Time", (System.nanoTime() - lastTimeStamp) / 1000000.0); //telemetry.addData("Arm Position", arm.getArmPosition()); //telemetry.addData("RTP Active", armRTP); //lastTimeStamp = System.nanoTime(); boolean liftInput = Math.abs(gamepad2.right_stick_y) > 0.05 || gamepad2.right_stick_button; if (gamepad2.left_bumper) { liftRTP = true; arm.setLiftTargetPosition(arm.getLiftMaxPosition()); } else if (gamepad2.dpad_down) { liftRTP = true; arm.setLiftTargetPosition(4218); } if (liftRTP) { arm.setLiftClosedLoopEnabled(true); if (liftInput) { retractSequenceEngaged = false; liftRTP = false; } } else { if (liftInput || !arm.isLiftHomed()) { arm.setLiftClosedLoopEnabled(false); arm.setLiftPower(-gamepad2.right_stick_y); } else if (lastLiftInput) { arm.setLiftClosedLoopEnabled(true); arm.setLiftTargetPosition(arm.getLiftPosition()); liftMaxDetectionActive = true; lastLiftError = -1; } if (liftMaxDetectionActive) { double currentError = Math.abs(arm.lastLiftPIDError()); if (currentError < lastLiftError) { liftMaxDetectionActive = false; arm.setLiftTargetPosition(arm.getLiftPosition()); } lastLiftError = currentError; } } lastLiftInput = liftInput; //telemetry.addData("Lift RTP", liftRTP); //telemetry.addData("Lift Target", arm.getLiftTargetPosition()); telemetry.addData("Lift Homed", arm.isLiftHomed()); telemetry.addData("Lift Position", arm.getLiftPosition()); //telemetry.addData("Arm Angle", arm.getArmAngle()); //telemetry.addData("Lift Height", arm.getLiftHeight()); //telemetry.addData("Manipulator Height", arm.getManipulatorHeight()); //telemetry.addData("Manipulator Offset", arm.getManipulatorOffset()); arm.update(); foundationClaw.update(); //telemetry.addData("Update Time", (System.nanoTime() - lastTimeStamp) / 1000000.0); //lastTimeStamp = System.nanoTime(); if (gamepad1.left_bumper) { parkingTape.setPower(1); } else if (gamepad1.right_bumper) { parkingTape.setPower(-1); } else { parkingTape.setPower(0); } if (gamepad1.dpad_down) { odometer.extend(); } else if (gamepad1.dpad_up) { odometer.retract(); } if (gamepad1.b) { odometer.resetOdometer(); } telemetry.addData("Loop Time", (System.nanoTime() - startTime) / 1000000.0); } }
coderanant/Competitive-Programming
CodeForces/Codeforces Round 640/F.cpp
/*coderanant*/ #include <bits/stdc++.h> using namespace std; #define int long long #define ll long long #define f1(i,a,b) for(int i=a;i<b;i++) #define f2(i,a,b) for(int i=a;i>=b;i--) #define endl '\n' #define pb push_back #define gp " " #define ff first #define ss second #define mp make_pair const int mod=1000000007; ll temp; int32_t main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int t; cin>>t; while(t--) { int n0, n1, n2; cin>>n0>>n1>>n2; vector<int> ans; if(n1 % 2 == 1) { f1(i,0,n0 + 1) ans.pb(0); while(n1 > 0) { if(ans[ans.size() - 1] == 0) ans.pb(1); else ans.pb(0); n1--; } f1(i,0,n2) ans.pb(1); } else { if(n1 == 0 && n2 == 0) { f1(i,0,n0 + 1) ans.pb(0); goto A; } ans.pb(1); if(n0 > 0 || n1 > 0) { ans.pb(0); n1--; } f1(i,0,n0) ans.pb(0); while(n1 > 0) { if(ans[ans.size() - 1] == 0) ans.pb(1); else ans.pb(0); n1--; } f1(i,0,n2) ans.pb(1); } A: f1(i,0,ans.size()) cout<<ans[i]; cout<<endl; } return 0; }
u2ware/u2ware-data-rest
src/test/java/io/github/u2ware/data/test/example09/source2/Bar.java
<filename>src/test/java/io/github/u2ware/data/test/example09/source2/Bar.java package io.github.u2ware.data.test.example09.source2; import java.util.UUID; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import lombok.Data; @Table(name="example09_bar") @Entity public @Data class Bar { @Id @Column(name = "id") private UUID id; private String name; private Integer age; public Bar() { } public Bar(String name) { } public Bar(UUID id, String name, Integer age) { this.id = id; this.name = name; this.age = age; } }
vadimdemedes/treport
tap-snapshots/lib-reports-specy-log.test.jsx-TAP.test.js
<gh_stars>0 /* IMPORTANT * This snapshot file is auto-generated, but designed for humans. * It should be checked into source control and tracked carefully. * Re-generate by setting TAP_SNAPSHOT=1 and running tests. * Make sure to inspect the output below. Do not ignore changes! */ 'use strict' exports[`lib/reports/specy/log.test.jsx TAP > must match snapshot 1`] = ` hello ✓ this is fine ✖ not fine `
Aleshkev/algoritmika
codeforces-519/c--smallest-word.cpp
#include <bits/stdc++.h> using namespace std; typedef intmax_t I; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); string s; cin >> s; I n = s.size(); vector<bool> v(n); for (I i = 1; i < n; ++i) { if (s[i] == 'a') { v[i] = true; v[i - 1] = !v[i - 1]; } } for (bool i : v) cout << i << ' '; cout << '\n'; return 0; }
tmertens/globalhack
db/migrate/20161022164156_add_owner_to_organization.rb
<reponame>tmertens/globalhack<gh_stars>0 class AddOwnerToOrganization < ActiveRecord::Migration[5.0] def change add_reference(:organizations, :owner, foreign_key: {to_table: :users}) end end
sumelms/microservice-classes
internal/subscription/domain/service.go
package domain import ( "context" "fmt" "github.com/go-kit/kit/log" ) type ServiceInterface interface { ListSubscription(context.Context, map[string]interface{}) ([]Subscription, error) CreateSubscription(context.Context, *Subscription) (Subscription, error) FindSubscription(context.Context, string) (Subscription, error) UpdateSubscription(context.Context, *Subscription) (Subscription, error) DeleteSubscription(context.Context, string) error } type Service struct { repo Repository logger log.Logger } func NewService(repo Repository, logger log.Logger) *Service { return &Service{ repo: repo, logger: logger, } } func (s *Service) ListSubscription(ctx context.Context, filters map[string]interface{}) ([]Subscription, error) { list, err := s.repo.List(filters) if err != nil { return []Subscription{}, fmt.Errorf("Service didn't found any subscription: %w", err) } return list, nil } func (s *Service) CreateSubscription(ctx context.Context, subscription *Subscription) (Subscription, error) { sub, err := s.repo.Create(subscription) if err != nil { return Subscription{}, fmt.Errorf("Service can't create subscription: %w", err) } return sub, nil } func (s *Service) FindSubscription(ctx context.Context, id string) (Subscription, error) { sub, err := s.repo.Find(id) if err != nil { return Subscription{}, fmt.Errorf("Service can't find subscription: %w", err) } return sub, nil } func (s *Service) UpdateSubscription(ctx context.Context, subscription *Subscription) (Subscription, error) { sub, err := s.repo.Update(subscription) if err != nil { return Subscription{}, fmt.Errorf("Service can't update subscription: %w", err) } return sub, nil } func (s *Service) DeleteSubscription(ctx context.Context, id string) error { err := s.repo.Delete(id) if err != nil { return fmt.Errorf("Service can't delete subscription: %w", err) } return nil }
uk-gov-mirror/DFE-Digital.register-trainee-teachers
spec/features/trainees/degrees/editing_degree_spec.rb
<filename>spec/features/trainees/degrees/editing_degree_spec.rb # frozen_string_literal: true require "rails_helper" feature "editing a degree" do background { given_i_am_authenticated } context "UK degree" do scenario "the user enters valid details" do given_a_trainee_with_a_uk_degree when_i_visit_the_edit_degree_details_page and_i_enter_valid_uk_degree_details and_i_click_the_continue_button then_i_am_redirected_to_confirm_page end scenario "the user enters invalid details" do given_a_trainee_with_a_uk_degree when_i_visit_the_edit_degree_details_page and_i_click_the_continue_button then_i_see_the_error_summary end end context "Non UK degree" do scenario "the user enters valid details" do given_a_trainee_with_a_non_uk_degree when_i_visit_the_edit_degree_details_page and_i_enter_valid_non_uk_degree_details and_i_click_the_continue_button then_i_am_redirected_to_confirm_page end scenario "the user enters invalid details" do given_a_trainee_with_a_non_uk_degree when_i_visit_the_edit_degree_details_page and_i_click_the_continue_button then_i_see_the_error_summary end end private def given_a_trainee_with_a_uk_degree uk_trainee end def given_a_trainee_with_a_non_uk_degree non_uk_trainee end def and_i_click_the_continue_button edit_degree_details_page.continue.click end def and_i_enter_valid_non_uk_degree_details template = build(:degree, :non_uk_degree_with_details) edit_degree_details_page.subject.select(template.subject) edit_degree_details_page.country.select(template.country) edit_degree_details_page.graduation_year.fill_in(with: template.graduation_year) end def and_i_enter_valid_uk_degree_details template = build(:degree, :uk_degree_with_details) edit_degree_details_page.subject.select(template.subject) edit_degree_details_page.institution.select(template.institution) edit_degree_details_page.grade.choose(template.grade) edit_degree_details_page.graduation_year.fill_in(with: template.graduation_year) end def when_i_visit_the_edit_degree_details_page edit_degree_details_page.load(trainee_id: trainee.slug, id: trainee.degrees.first.slug) end def then_i_am_redirected_to_confirm_page degrees_confirm_page.load(trainee_id: trainee.slug) expect(degrees_confirm_page).to be_displayed(trainee_id: trainee.slug) end def then_i_see_the_error_summary expect(edit_degree_details_page.error_summary).to be_visible end def trainee (@uk_trainee || @non_uk_trainee) end def uk_trainee @uk_trainee ||= create(:trainee, provider: current_user.provider).tap do |t| t.degrees << build(:degree, :uk_degree_type) end end def non_uk_trainee @non_uk_trainee ||= create(:trainee, provider: current_user.provider).tap do |t| t.degrees << build(:degree, :non_uk_degree_type) end end end
solosTec/cyng
lib/sql/src/constant.cpp
/* * The MIT License (MIT) * * Copyright (c) 2017 <NAME> * */ #include <cyng/sql/dsl/constant.hpp> #include <cyng/io/io_chrono.hpp> namespace cyng { namespace sql { /** * std::string */ constant < std::string >::constant (std::string const& c) : c_(c) {} void constant < std::string >::serialize(std::ostream& os, meta_table_ptr, dialect dia, bool lhe) const { os << '\'' << c_ << '\''; } /** * boolean */ constant < bool >::constant (bool b) : b_(b) {} void constant < bool >::serialize(std::ostream& os, meta_table_ptr, dialect dia, bool lhe) const { if (dia == SQLITE) { os << (b_ ? "1" : "0"); } else { // However, the values TRUE and FALSE are merely aliases for 1 and 0. os << (b_ ? "TRUE" : "FALSE"); } } /** * timepoint */ constant < std::chrono::system_clock::time_point >::constant (std::chrono::system_clock::time_point tp) : tp_(tp) {} void constant < std::chrono::system_clock::time_point >::serialize(std::ostream& os, meta_table_ptr, dialect dia, bool lhe) const { if (!has_feature(dia, DATE_TIME_SUPPORT)) { os << "julianday('" << to_str(tp_) << "')" ; } else { os << to_str(tp_); } } } }
liumapp/compiling-jvm
openjdk/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/GTKLookAndFeel.java
<gh_stars>0 /* * Copyright (c) 2002, 2009, 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. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. */ package com.sun.java.swing.plaf.gtk; import java.awt.*; import java.awt.event.*; import java.beans.*; import java.io.File; import java.lang.ref.*; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Locale; import javax.swing.*; import javax.swing.colorchooser.*; import javax.swing.plaf.*; import javax.swing.plaf.synth.*; import javax.swing.text.DefaultEditorKit; import com.sun.java.swing.plaf.gtk.GTKConstants.PositionType; import com.sun.java.swing.plaf.gtk.GTKConstants.StateType; import sun.awt.SunToolkit; import sun.awt.UNIXToolkit; import sun.awt.OSInfo; import sun.security.action.GetPropertyAction; import sun.swing.DefaultLayoutStyle; import sun.swing.SwingUtilities2; /** * @author <NAME> */ public class GTKLookAndFeel extends SynthLookAndFeel { private static final boolean IS_22; /** * Whether or not text is drawn antialiased. This keys off the * desktop property 'gnome.Xft/Antialias' and 'gnome.Xft/RGBA' * We should assume ON - or some variation of ON as no GTK desktop * ships with it OFF. */ static Object aaTextInfo; /** * Solaris, or Linux with Sun JDS in a CJK Locale. * Used to determine if Sun's high quality CJK fonts are present. */ private static boolean isSunCJK; /* * Used to override if system (desktop) text anti-aliasing settings should * be used. The reasons for this are are is that currently its "off" * for CJK locales which is not likely to be a good universal answer, and * also its off for remote display. So this provides an unsupported * way to explicitly request that it be "on". */ private static boolean gtkAAFontSettingsCond; /** * Font to use in places where there is no widget. */ private Font fallbackFont; /** * If true, GTKLookAndFeel is inside the <code>initialize</code> * method. */ private boolean inInitialize; /** * If true, PropertyChangeListeners have been installed for the * Toolkit. */ private boolean pclInstalled; /** * StyleFactory needs to be created only the first time. */ private GTKStyleFactory styleFactory; /** * Cached theme name. Used by GTKGraphicsUtils */ private static String gtkThemeName = "Default"; static { // Backup for specifying the version, this isn't currently documented. // If you pass in anything but 2.2 you got the 2.0 colors/look. String version = AccessController.doPrivileged( new GetPropertyAction("swing.gtk.version")); if (version != null) { IS_22 = version.equals("2.2"); } else { IS_22 = true; } String language = Locale.getDefault().getLanguage(); boolean cjkLocale = (Locale.CHINESE.getLanguage().equals(language) || Locale.JAPANESE.getLanguage().equals(language) || Locale.KOREAN.getLanguage().equals(language)); if (cjkLocale) { boolean isSunDesktop = false; switch (OSInfo.getOSType()) { case SOLARIS: isSunDesktop = true; break; case LINUX: Boolean val = AccessController.doPrivileged( new PrivilegedAction<Boolean>() { public Boolean run() { File f = new File("/etc/sun-release"); return Boolean.valueOf(f.exists()); } }); isSunDesktop = val.booleanValue(); } if (isSunDesktop && !sun.java2d.SunGraphicsEnvironment.isOpenSolaris) { isSunCJK = true; } } } /** * Returns true if running on system containing at least 2.2. */ static boolean is2_2() { // NOTE: We're currently hard coding to use 2.2. // If we want to support both GTK 2.0 and 2.2, we'll // need to get the major/minor/micro version from the .so. // Refer to bug 4912613 for details. return IS_22; } /** * Maps a swing constant to a GTK constant. */ static PositionType SwingOrientationConstantToGTK(int side) { switch (side) { case SwingConstants.LEFT: return PositionType.LEFT; case SwingConstants.RIGHT: return PositionType.RIGHT; case SwingConstants.TOP: return PositionType.TOP; case SwingConstants.BOTTOM: return PositionType.BOTTOM; } assert false : "Unknown orientation: " + side; return PositionType.TOP; } /** * Maps from Synth state to native GTK state using typesafe enumeration * StateType. This is only used by GTKEngine. */ static StateType synthStateToGTKStateType(int state) { StateType result; switch (state) { case SynthConstants.PRESSED: result = StateType.ACTIVE; break; case SynthConstants.MOUSE_OVER: result = StateType.PRELIGHT; break; case SynthConstants.SELECTED: result = StateType.SELECTED; break; case SynthConstants.DISABLED: result = StateType.INSENSITIVE; break; case SynthConstants.ENABLED: default: result = StateType.NORMAL; break; } return result; } /** * Maps from a Synth state to the corresponding GTK state. * The GTK states are named differently than Synth's states, the * following gives the mapping: * <table><tr><td>Synth<td>GTK * <tr><td>SynthConstants.PRESSED<td>ACTIVE * <tr><td>SynthConstants.SELECTED<td>SELECTED * <tr><td>SynthConstants.MOUSE_OVER<td>PRELIGHT * <tr><td>SynthConstants.DISABLED<td>INSENSITIVE * <tr><td>SynthConstants.ENABLED<td>NORMAL * </table> * Additionally some widgets are special cased. */ static int synthStateToGTKState(Region region, int state) { if ((state & SynthConstants.PRESSED) != 0) { if (region == Region.RADIO_BUTTON || region == Region.CHECK_BOX || region == Region.MENU || region == Region.MENU_ITEM || region == Region.RADIO_BUTTON_MENU_ITEM || region == Region.CHECK_BOX_MENU_ITEM || region == Region.SPLIT_PANE) { state = SynthConstants.MOUSE_OVER; } else { state = SynthConstants.PRESSED; } } else if (region == Region.TABBED_PANE_TAB) { if ((state & SynthConstants.DISABLED) != 0) { state = SynthConstants.DISABLED; } else if ((state & SynthConstants.SELECTED) != 0) { state = SynthConstants.ENABLED; } else { state = SynthConstants.PRESSED; } } else if ((state & SynthConstants.SELECTED) != 0) { if (region == Region.MENU) { state = SynthConstants.MOUSE_OVER; } else if (region == Region.RADIO_BUTTON || region == Region.TOGGLE_BUTTON || region == Region.RADIO_BUTTON_MENU_ITEM || region == Region.CHECK_BOX_MENU_ITEM || region == Region.CHECK_BOX || region == Region.BUTTON) { if ((state & SynthConstants.DISABLED) != 0) { state = SynthConstants.DISABLED; } // If the button is SELECTED and is PRELIGHT we need to // make the state MOUSE_OVER otherwise we don't paint the // PRELIGHT. else if ((state & SynthConstants.MOUSE_OVER) != 0) { state = SynthConstants.MOUSE_OVER; } else { state = SynthConstants.PRESSED; } } else { state = SynthConstants.SELECTED; } } else if ((state & SynthConstants.MOUSE_OVER) != 0) { state = SynthConstants.MOUSE_OVER; } else if ((state & SynthConstants.DISABLED) != 0) { state = SynthConstants.DISABLED; } else { if (region == Region.SLIDER_TRACK) { state = SynthConstants.PRESSED; } else { state = SynthConstants.ENABLED; } } return state; } static boolean isText(Region region) { // These Regions treat FOREGROUND as TEXT. return (region == Region.TEXT_FIELD || region == Region.FORMATTED_TEXT_FIELD || region == Region.LIST || region == Region.PASSWORD_FIELD || region == Region.SPINNER || region == Region.TABLE || region == Region.TEXT_AREA || region == Region.TEXT_FIELD || region == Region.TEXT_PANE || region == Region.TREE); } public UIDefaults getDefaults() { // We need to call super for basic's properties file. UIDefaults table = super.getDefaults(); // SynthTabbedPaneUI supports rollover on tabs, GTK does not table.put("TabbedPane.isTabRollover", Boolean.FALSE); // Prevents Synth from setting text AA by itself table.put("Synth.doNotSetTextAA", true); initResourceBundle(table); // For compatability with apps expecting certain defaults we'll // populate the table with the values from basic. initSystemColorDefaults(table); initComponentDefaults(table); installPropertyChangeListeners(); return table; } private void installPropertyChangeListeners() { if(!pclInstalled) { Toolkit kit = Toolkit.getDefaultToolkit(); WeakPCL pcl = new WeakPCL(this, kit, "gnome.Net/ThemeName"); kit.addPropertyChangeListener(pcl.getKey(), pcl); pcl = new WeakPCL(this, kit, "gnome.Gtk/FontName"); kit.addPropertyChangeListener(pcl.getKey(), pcl); pcl = new WeakPCL(this, kit, "gnome.Xft/DPI"); kit.addPropertyChangeListener(pcl.getKey(), pcl); flushUnreferenced(); pclInstalled = true; } } private void initResourceBundle(UIDefaults table) { table.addResourceBundle("com.sun.java.swing.plaf.gtk.resources.gtk"); } protected void initComponentDefaults(UIDefaults table) { // For compatability with apps expecting certain defaults we'll // populate the table with the values from basic. super.initComponentDefaults(table); Integer zero = Integer.valueOf(0); Object zeroBorder = new sun.swing.SwingLazyValue( "javax.swing.plaf.BorderUIResource$EmptyBorderUIResource", new Object[] {zero, zero, zero, zero}); Object focusBorder = new GTKStyle.GTKLazyValue( "com.sun.java.swing.plaf.gtk.GTKPainter$ListTableFocusBorder", "getUnselectedCellBorder"); Object focusSelectedBorder = new GTKStyle.GTKLazyValue( "com.sun.java.swing.plaf.gtk.GTKPainter$ListTableFocusBorder", "getSelectedCellBorder"); Object noFocusBorder = new GTKStyle.GTKLazyValue( "com.sun.java.swing.plaf.gtk.GTKPainter$ListTableFocusBorder", "getNoFocusCellBorder"); GTKStyleFactory factory = (GTKStyleFactory)getStyleFactory(); GTKStyle tableStyle = (GTKStyle)factory.getStyle(null, Region.TREE); Color tableBg = tableStyle.getGTKColor(SynthConstants.ENABLED, GTKColorType.TEXT_BACKGROUND); Color tableFocusCellBg = tableStyle.getGTKColor(SynthConstants.ENABLED, GTKColorType.BACKGROUND); Color tableFocusCellFg = tableStyle.getGTKColor(SynthConstants.ENABLED, GTKColorType.FOREGROUND); // The following progress bar size calculations come from // gtkprogressbar.c (version 2.8.20), see MIN_* constants and // the gtk_progress_bar_size_request() method. GTKStyle progStyle = (GTKStyle) factory.getStyle(null, Region.PROGRESS_BAR); int progXThickness = progStyle.getXThickness(); int progYThickness = progStyle.getYThickness(); int hProgWidth = 150 - (progXThickness * 2); int hProgHeight = 20 - (progYThickness * 2); int vProgWidth = 22 - (progXThickness * 2); int vProgHeight = 80 - (progYThickness * 2); Integer caretBlinkRate = Integer.valueOf(500); Insets zeroInsets = new InsetsUIResource(0, 0, 0, 0); Double defaultCaretAspectRatio = new Double(0.025); Color caretColor = table.getColor("caretColor"); Color controlText = table.getColor("controlText"); Object fieldInputMap = new UIDefaults.LazyInputMap(new Object[] { "ctrl C", DefaultEditorKit.copyAction, "ctrl V", DefaultEditorKit.pasteAction, "ctrl X", DefaultEditorKit.cutAction, "COPY", DefaultEditorKit.copyAction, "PASTE", DefaultEditorKit.pasteAction, "CUT", DefaultEditorKit.cutAction, "control INSERT", DefaultEditorKit.copyAction, "shift INSERT", DefaultEditorKit.pasteAction, "shift DELETE", DefaultEditorKit.cutAction, "shift LEFT", DefaultEditorKit.selectionBackwardAction, "shift KP_LEFT", DefaultEditorKit.selectionBackwardAction, "shift RIGHT", DefaultEditorKit.selectionForwardAction, "shift KP_RIGHT", DefaultEditorKit.selectionForwardAction, "ctrl LEFT", DefaultEditorKit.previousWordAction, "ctrl KP_LEFT", DefaultEditorKit.previousWordAction, "ctrl RIGHT", DefaultEditorKit.nextWordAction, "ctrl KP_RIGHT", DefaultEditorKit.nextWordAction, "ctrl shift LEFT", DefaultEditorKit.selectionPreviousWordAction, "ctrl shift KP_LEFT", DefaultEditorKit.selectionPreviousWordAction, "ctrl shift RIGHT", DefaultEditorKit.selectionNextWordAction, "ctrl shift KP_RIGHT", DefaultEditorKit.selectionNextWordAction, "ctrl A", DefaultEditorKit.selectAllAction, "HOME", DefaultEditorKit.beginLineAction, "END", DefaultEditorKit.endLineAction, "shift HOME", DefaultEditorKit.selectionBeginLineAction, "shift END", DefaultEditorKit.selectionEndLineAction, "BACK_SPACE", DefaultEditorKit.deletePrevCharAction, "shift BACK_SPACE", DefaultEditorKit.deletePrevCharAction, "ctrl H", DefaultEditorKit.deletePrevCharAction, "DELETE", DefaultEditorKit.deleteNextCharAction, "ctrl DELETE", DefaultEditorKit.deleteNextWordAction, "ctrl BACK_SPACE", DefaultEditorKit.deletePrevWordAction, "RIGHT", DefaultEditorKit.forwardAction, "LEFT", DefaultEditorKit.backwardAction, "KP_RIGHT", DefaultEditorKit.forwardAction, "KP_LEFT", DefaultEditorKit.backwardAction, "ENTER", JTextField.notifyAction, "ctrl BACK_SLASH", "unselect"/*DefaultEditorKit.unselectAction*/, "control shift O", "toggle-componentOrientation"/*DefaultEditorKit.toggleComponentOrientation*/ }); Object passwordInputMap = new UIDefaults.LazyInputMap(new Object[] { "ctrl C", DefaultEditorKit.copyAction, "ctrl V", DefaultEditorKit.pasteAction, "ctrl X", DefaultEditorKit.cutAction, "COPY", DefaultEditorKit.copyAction, "PASTE", DefaultEditorKit.pasteAction, "CUT", DefaultEditorKit.cutAction, "control INSERT", DefaultEditorKit.copyAction, "shift INSERT", DefaultEditorKit.pasteAction, "shift DELETE", DefaultEditorKit.cutAction, "shift LEFT", DefaultEditorKit.selectionBackwardAction, "shift KP_LEFT", DefaultEditorKit.selectionBackwardAction, "shift RIGHT", DefaultEditorKit.selectionForwardAction, "shift KP_RIGHT", DefaultEditorKit.selectionForwardAction, "ctrl LEFT", DefaultEditorKit.beginLineAction, "ctrl KP_LEFT", DefaultEditorKit.beginLineAction, "ctrl RIGHT", DefaultEditorKit.endLineAction, "ctrl KP_RIGHT", DefaultEditorKit.endLineAction, "ctrl shift LEFT", DefaultEditorKit.selectionBeginLineAction, "ctrl shift KP_LEFT", DefaultEditorKit.selectionBeginLineAction, "ctrl shift RIGHT", DefaultEditorKit.selectionEndLineAction, "ctrl shift KP_RIGHT", DefaultEditorKit.selectionEndLineAction, "ctrl A", DefaultEditorKit.selectAllAction, "HOME", DefaultEditorKit.beginLineAction, "END", DefaultEditorKit.endLineAction, "shift HOME", DefaultEditorKit.selectionBeginLineAction, "shift END", DefaultEditorKit.selectionEndLineAction, "BACK_SPACE", DefaultEditorKit.deletePrevCharAction, "shift BACK_SPACE", DefaultEditorKit.deletePrevCharAction, "ctrl H", DefaultEditorKit.deletePrevCharAction, "DELETE", DefaultEditorKit.deleteNextCharAction, "RIGHT", DefaultEditorKit.forwardAction, "LEFT", DefaultEditorKit.backwardAction, "KP_RIGHT", DefaultEditorKit.forwardAction, "KP_LEFT", DefaultEditorKit.backwardAction, "ENTER", JTextField.notifyAction, "ctrl BACK_SLASH", "unselect"/*DefaultEditorKit.unselectAction*/, "control shift O", "toggle-componentOrientation"/*DefaultEditorKit.toggleComponentOrientation*/ }); Object editorMargin = new InsetsUIResource(3,3,3,3); Object multilineInputMap = new UIDefaults.LazyInputMap(new Object[] { "ctrl C", DefaultEditorKit.copyAction, "ctrl V", DefaultEditorKit.pasteAction, "ctrl X", DefaultEditorKit.cutAction, "COPY", DefaultEditorKit.copyAction, "PASTE", DefaultEditorKit.pasteAction, "CUT", DefaultEditorKit.cutAction, "control INSERT", DefaultEditorKit.copyAction, "shift INSERT", DefaultEditorKit.pasteAction, "shift DELETE", DefaultEditorKit.cutAction, "shift LEFT", DefaultEditorKit.selectionBackwardAction, "shift KP_LEFT", DefaultEditorKit.selectionBackwardAction, "shift RIGHT", DefaultEditorKit.selectionForwardAction, "shift KP_RIGHT", DefaultEditorKit.selectionForwardAction, "ctrl LEFT", DefaultEditorKit.previousWordAction, "ctrl KP_LEFT", DefaultEditorKit.previousWordAction, "ctrl RIGHT", DefaultEditorKit.nextWordAction, "ctrl KP_RIGHT", DefaultEditorKit.nextWordAction, "ctrl shift LEFT", DefaultEditorKit.selectionPreviousWordAction, "ctrl shift KP_LEFT", DefaultEditorKit.selectionPreviousWordAction, "ctrl shift RIGHT", DefaultEditorKit.selectionNextWordAction, "ctrl shift KP_RIGHT", DefaultEditorKit.selectionNextWordAction, "ctrl A", DefaultEditorKit.selectAllAction, "HOME", DefaultEditorKit.beginLineAction, "END", DefaultEditorKit.endLineAction, "shift HOME", DefaultEditorKit.selectionBeginLineAction, "shift END", DefaultEditorKit.selectionEndLineAction, "UP", DefaultEditorKit.upAction, "KP_UP", DefaultEditorKit.upAction, "DOWN", DefaultEditorKit.downAction, "KP_DOWN", DefaultEditorKit.downAction, "PAGE_UP", DefaultEditorKit.pageUpAction, "PAGE_DOWN", DefaultEditorKit.pageDownAction, "shift PAGE_UP", "selection-page-up", "shift PAGE_DOWN", "selection-page-down", "ctrl shift PAGE_UP", "selection-page-left", "ctrl shift PAGE_DOWN", "selection-page-right", "shift UP", DefaultEditorKit.selectionUpAction, "shift KP_UP", DefaultEditorKit.selectionUpAction, "shift DOWN", DefaultEditorKit.selectionDownAction, "shift KP_DOWN", DefaultEditorKit.selectionDownAction, "ENTER", DefaultEditorKit.insertBreakAction, "BACK_SPACE", DefaultEditorKit.deletePrevCharAction, "shift BACK_SPACE", DefaultEditorKit.deletePrevCharAction, "ctrl H", DefaultEditorKit.deletePrevCharAction, "DELETE", DefaultEditorKit.deleteNextCharAction, "ctrl DELETE", DefaultEditorKit.deleteNextWordAction, "ctrl BACK_SPACE", DefaultEditorKit.deletePrevWordAction, "RIGHT", DefaultEditorKit.forwardAction, "LEFT", DefaultEditorKit.backwardAction, "KP_RIGHT", DefaultEditorKit.forwardAction, "KP_LEFT", DefaultEditorKit.backwardAction, "TAB", DefaultEditorKit.insertTabAction, "ctrl BACK_SLASH", "unselect"/*DefaultEditorKit.unselectAction*/, "ctrl HOME", DefaultEditorKit.beginAction, "ctrl END", DefaultEditorKit.endAction, "ctrl shift HOME", DefaultEditorKit.selectionBeginAction, "ctrl shift END", DefaultEditorKit.selectionEndAction, "ctrl T", "next-link-action", "ctrl shift T", "previous-link-action", "ctrl SPACE", "activate-link-action", "control shift O", "toggle-componentOrientation"/*DefaultEditorKit.toggleComponentOrientation*/ }); class FontLazyValue implements UIDefaults.LazyValue { private Region region; FontLazyValue(Region region) { this.region = region; } public Object createValue(UIDefaults table) { GTKStyleFactory factory = (GTKStyleFactory)getStyleFactory(); GTKStyle style = (GTKStyle)factory.getStyle(null, region); return style.getFontForState(null); } } Object[] defaults = new Object[] { "ArrowButton.size", Integer.valueOf(13), "Button.defaultButtonFollowsFocus", Boolean.FALSE, "Button.focusInputMap", new UIDefaults.LazyInputMap(new Object[] { "SPACE", "pressed", "released SPACE", "released", "ENTER", "pressed", "released ENTER", "released" }), "Button.font", new FontLazyValue(Region.BUTTON), "Button.margin", zeroInsets, "CheckBox.focusInputMap", new UIDefaults.LazyInputMap(new Object[]{ "SPACE", "pressed", "released SPACE", "released" }), "CheckBox.icon", new GTKStyle.GTKLazyValue( "com.sun.java.swing.plaf.gtk.GTKIconFactory", "getCheckBoxIcon"), "CheckBox.font", new FontLazyValue(Region.CHECK_BOX), "CheckBox.margin", zeroInsets, "CheckBoxMenuItem.arrowIcon", null, "CheckBoxMenuItem.checkIcon", new GTKStyle.GTKLazyValue( "com.sun.java.swing.plaf.gtk.GTKIconFactory", "getCheckBoxMenuItemCheckIcon"), "CheckBoxMenuItem.font", new FontLazyValue(Region.CHECK_BOX_MENU_ITEM), "CheckBoxMenuItem.margin", zeroInsets, "CheckBoxMenuItem.alignAcceleratorText", Boolean.FALSE, "ColorChooser.showPreviewPanelText", Boolean.FALSE, "ColorChooser.panels", new UIDefaults.ActiveValue() { public Object createValue(UIDefaults table) { return new AbstractColorChooserPanel[] { new GTKColorChooserPanel() }; } }, "ColorChooser.font", new FontLazyValue(Region.COLOR_CHOOSER), "ComboBox.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { "ESCAPE", "hidePopup", "PAGE_UP", "pageUpPassThrough", "PAGE_DOWN", "pageDownPassThrough", "HOME", "homePassThrough", "END", "endPassThrough", "DOWN", "selectNext", "KP_DOWN", "selectNext", "alt DOWN", "togglePopup", "alt KP_DOWN", "togglePopup", "alt UP", "togglePopup", "alt KP_UP", "togglePopup", "SPACE", "spacePopup", "ENTER", "enterPressed", "UP", "selectPrevious", "KP_UP", "selectPrevious" }), "ComboBox.font", new FontLazyValue(Region.COMBO_BOX), "ComboBox.isEnterSelectablePopup", Boolean.TRUE, "EditorPane.caretForeground", caretColor, "EditorPane.caretAspectRatio", defaultCaretAspectRatio, "EditorPane.caretBlinkRate", caretBlinkRate, "EditorPane.margin", editorMargin, "EditorPane.focusInputMap", multilineInputMap, "EditorPane.font", new FontLazyValue(Region.EDITOR_PANE), "FileChooser.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { "ESCAPE", "cancelSelection", "ctrl ENTER", "approveSelection" }), "FileChooserUI", "com.sun.java.swing.plaf.gtk.GTKLookAndFeel", "FormattedTextField.caretForeground", caretColor, "FormattedTextField.caretAspectRatio", defaultCaretAspectRatio, "FormattedTextField.caretBlinkRate", caretBlinkRate, "FormattedTextField.focusInputMap", new UIDefaults.LazyInputMap(new Object[] { "ctrl C", DefaultEditorKit.copyAction, "ctrl V", DefaultEditorKit.pasteAction, "ctrl X", DefaultEditorKit.cutAction, "COPY", DefaultEditorKit.copyAction, "PASTE", DefaultEditorKit.pasteAction, "CUT", DefaultEditorKit.cutAction, "control INSERT", DefaultEditorKit.copyAction, "shift INSERT", DefaultEditorKit.pasteAction, "shift DELETE", DefaultEditorKit.cutAction, "shift LEFT", DefaultEditorKit.selectionBackwardAction, "shift KP_LEFT", DefaultEditorKit.selectionBackwardAction, "shift RIGHT", DefaultEditorKit.selectionForwardAction, "shift KP_RIGHT", DefaultEditorKit.selectionForwardAction, "ctrl LEFT", DefaultEditorKit.previousWordAction, "ctrl KP_LEFT", DefaultEditorKit.previousWordAction, "ctrl RIGHT", DefaultEditorKit.nextWordAction, "ctrl KP_RIGHT", DefaultEditorKit.nextWordAction, "ctrl shift LEFT", DefaultEditorKit.selectionPreviousWordAction, "ctrl shift KP_LEFT", DefaultEditorKit.selectionPreviousWordAction, "ctrl shift RIGHT", DefaultEditorKit.selectionNextWordAction, "ctrl shift KP_RIGHT", DefaultEditorKit.selectionNextWordAction, "ctrl A", DefaultEditorKit.selectAllAction, "HOME", DefaultEditorKit.beginLineAction, "END", DefaultEditorKit.endLineAction, "shift HOME", DefaultEditorKit.selectionBeginLineAction, "shift END", DefaultEditorKit.selectionEndLineAction, "BACK_SPACE", DefaultEditorKit.deletePrevCharAction, "shift BACK_SPACE", DefaultEditorKit.deletePrevCharAction, "ctrl H", DefaultEditorKit.deletePrevCharAction, "DELETE", DefaultEditorKit.deleteNextCharAction, "ctrl DELETE", DefaultEditorKit.deleteNextWordAction, "ctrl BACK_SPACE", DefaultEditorKit.deletePrevWordAction, "RIGHT", DefaultEditorKit.forwardAction, "LEFT", DefaultEditorKit.backwardAction, "KP_RIGHT", DefaultEditorKit.forwardAction, "KP_LEFT", DefaultEditorKit.backwardAction, "ENTER", JTextField.notifyAction, "ctrl BACK_SLASH", "unselect", "control shift O", "toggle-componentOrientation", "ESCAPE", "reset-field-edit", "UP", "increment", "KP_UP", "increment", "DOWN", "decrement", "KP_DOWN", "decrement", }), "FormattedTextField.font", new FontLazyValue(Region.FORMATTED_TEXT_FIELD), "InternalFrameTitlePane.titlePaneLayout", new GTKStyle.GTKLazyValue("com.sun.java.swing.plaf.gtk.Metacity", "getTitlePaneLayout"), "InternalFrame.windowBindings", new Object[] { "shift ESCAPE", "showSystemMenu", "ctrl SPACE", "showSystemMenu", "ESCAPE", "hideSystemMenu" }, "InternalFrame.layoutTitlePaneAtOrigin", Boolean.TRUE, "InternalFrame.useTaskBar", Boolean.TRUE, "InternalFrameTitlePane.iconifyButtonOpacity", null, "InternalFrameTitlePane.maximizeButtonOpacity", null, "InternalFrameTitlePane.closeButtonOpacity", null, "Label.font", new FontLazyValue(Region.LABEL), "List.background", tableBg, "List.focusCellHighlightBorder", focusBorder, "List.focusSelectedCellHighlightBorder", focusSelectedBorder, "List.noFocusBorder", noFocusBorder, "List.focusInputMap", new UIDefaults.LazyInputMap(new Object[] { "ctrl C", "copy", "ctrl V", "paste", "ctrl X", "cut", "COPY", "copy", "PASTE", "paste", "CUT", "cut", "control INSERT", "copy", "shift INSERT", "paste", "shift DELETE", "cut", "UP", "selectPreviousRow", "KP_UP", "selectPreviousRow", "shift UP", "selectPreviousRowExtendSelection", "shift KP_UP", "selectPreviousRowExtendSelection", "ctrl shift UP", "selectPreviousRowExtendSelection", "ctrl shift KP_UP", "selectPreviousRowExtendSelection", "ctrl UP", "selectPreviousRowChangeLead", "ctrl KP_UP", "selectPreviousRowChangeLead", "DOWN", "selectNextRow", "KP_DOWN", "selectNextRow", "shift DOWN", "selectNextRowExtendSelection", "shift KP_DOWN", "selectNextRowExtendSelection", "ctrl shift DOWN", "selectNextRowExtendSelection", "ctrl shift KP_DOWN", "selectNextRowExtendSelection", "ctrl DOWN", "selectNextRowChangeLead", "ctrl KP_DOWN", "selectNextRowChangeLead", "LEFT", "selectPreviousColumn", "KP_LEFT", "selectPreviousColumn", "shift LEFT", "selectPreviousColumnExtendSelection", "shift KP_LEFT", "selectPreviousColumnExtendSelection", "ctrl shift LEFT", "selectPreviousColumnExtendSelection", "ctrl shift KP_LEFT", "selectPreviousColumnExtendSelection", "ctrl LEFT", "selectPreviousColumnChangeLead", "ctrl KP_LEFT", "selectPreviousColumnChangeLead", "RIGHT", "selectNextColumn", "KP_RIGHT", "selectNextColumn", "shift RIGHT", "selectNextColumnExtendSelection", "shift KP_RIGHT", "selectNextColumnExtendSelection", "ctrl shift RIGHT", "selectNextColumnExtendSelection", "ctrl shift KP_RIGHT", "selectNextColumnExtendSelection", "ctrl RIGHT", "selectNextColumnChangeLead", "ctrl KP_RIGHT", "selectNextColumnChangeLead", "HOME", "selectFirstRow", "shift HOME", "selectFirstRowExtendSelection", "ctrl shift HOME", "selectFirstRowExtendSelection", "ctrl HOME", "selectFirstRowChangeLead", "END", "selectLastRow", "shift END", "selectLastRowExtendSelection", "ctrl shift END", "selectLastRowExtendSelection", "ctrl END", "selectLastRowChangeLead", "PAGE_UP", "scrollUp", "shift PAGE_UP", "scrollUpExtendSelection", "ctrl shift PAGE_UP", "scrollUpExtendSelection", "ctrl PAGE_UP", "scrollUpChangeLead", "PAGE_DOWN", "scrollDown", "shift PAGE_DOWN", "scrollDownExtendSelection", "ctrl shift PAGE_DOWN", "scrollDownExtendSelection", "ctrl PAGE_DOWN", "scrollDownChangeLead", "ctrl A", "selectAll", "ctrl SLASH", "selectAll", "ctrl BACK_SLASH", "clearSelection", "SPACE", "addToSelection", "ctrl SPACE", "toggleAndAnchor", "shift SPACE", "extendTo", "ctrl shift SPACE", "moveSelectionTo" }), "List.focusInputMap.RightToLeft", new UIDefaults.LazyInputMap(new Object[] { "LEFT", "selectNextColumn", "KP_LEFT", "selectNextColumn", "shift LEFT", "selectNextColumnExtendSelection", "shift KP_LEFT", "selectNextColumnExtendSelection", "ctrl shift LEFT", "selectNextColumnExtendSelection", "ctrl shift KP_LEFT", "selectNextColumnExtendSelection", "ctrl LEFT", "selectNextColumnChangeLead", "ctrl KP_LEFT", "selectNextColumnChangeLead", "RIGHT", "selectPreviousColumn", "KP_RIGHT", "selectPreviousColumn", "shift RIGHT", "selectPreviousColumnExtendSelection", "shift KP_RIGHT", "selectPreviousColumnExtendSelection", "ctrl shift RIGHT", "selectPreviousColumnExtendSelection", "ctrl shift KP_RIGHT", "selectPreviousColumnExtendSelection", "ctrl RIGHT", "selectPreviousColumnChangeLead", "ctrl KP_RIGHT", "selectPreviousColumnChangeLead", }), "List.font", new FontLazyValue(Region.LIST), "List.rendererUseUIBorder", Boolean.FALSE, "Menu.shortcutKeys", new int[] {KeyEvent.ALT_MASK}, "Menu.arrowIcon", new GTKStyle.GTKLazyValue( "com.sun.java.swing.plaf.gtk.GTKIconFactory", "getMenuArrowIcon"), "Menu.checkIcon", null, "Menu.font", new FontLazyValue(Region.MENU), "Menu.margin", zeroInsets, "Menu.cancelMode", "hideMenuTree", "Menu.alignAcceleratorText", Boolean.FALSE, "MenuBar.windowBindings", new Object[] { "F10", "takeFocus" }, "MenuBar.font", new FontLazyValue(Region.MENU_BAR), "MenuItem.arrowIcon", null, "MenuItem.checkIcon", null, "MenuItem.font", new FontLazyValue(Region.MENU_ITEM), "MenuItem.margin", zeroInsets, "MenuItem.alignAcceleratorText", Boolean.FALSE, "OptionPane.setButtonMargin", Boolean.FALSE, "OptionPane.sameSizeButtons", Boolean.TRUE, "OptionPane.buttonOrientation", new Integer(SwingConstants.RIGHT), "OptionPane.minimumSize", new DimensionUIResource(262, 90), "OptionPane.buttonPadding", new Integer(10), "OptionPane.windowBindings", new Object[] { "ESCAPE", "close" }, "OptionPane.buttonClickThreshhold", new Integer(500), "OptionPane.isYesLast", Boolean.TRUE, "OptionPane.font", new FontLazyValue(Region.OPTION_PANE), "Panel.font", new FontLazyValue(Region.PANEL), "PasswordField.caretForeground", caretColor, "PasswordField.caretAspectRatio", defaultCaretAspectRatio, "PasswordField.caretBlinkRate", caretBlinkRate, "PasswordField.margin", zeroInsets, "PasswordField.focusInputMap", passwordInputMap, "PasswordField.font", new FontLazyValue(Region.PASSWORD_FIELD), "PopupMenu.consumeEventOnClose", Boolean.TRUE, "PopupMenu.selectedWindowInputMapBindings", new Object[] { "ESCAPE", "cancel", "DOWN", "selectNext", "KP_DOWN", "selectNext", "UP", "selectPrevious", "KP_UP", "selectPrevious", "LEFT", "selectParent", "KP_LEFT", "selectParent", "RIGHT", "selectChild", "KP_RIGHT", "selectChild", "ENTER", "return", "SPACE", "return" }, "PopupMenu.selectedWindowInputMapBindings.RightToLeft", new Object[] { "LEFT", "selectChild", "KP_LEFT", "selectChild", "RIGHT", "selectParent", "KP_RIGHT", "selectParent", }, "PopupMenu.font", new FontLazyValue(Region.POPUP_MENU), "ProgressBar.horizontalSize", new DimensionUIResource(hProgWidth, hProgHeight), "ProgressBar.verticalSize", new DimensionUIResource(vProgWidth, vProgHeight), "ProgressBar.font", new FontLazyValue(Region.PROGRESS_BAR), "RadioButton.focusInputMap", new UIDefaults.LazyInputMap(new Object[] { "SPACE", "pressed", "released SPACE", "released", "RETURN", "pressed" }), "RadioButton.icon", new GTKStyle.GTKLazyValue( "com.sun.java.swing.plaf.gtk.GTKIconFactory", "getRadioButtonIcon"), "RadioButton.font", new FontLazyValue(Region.RADIO_BUTTON), "RadioButton.margin", zeroInsets, "RadioButtonMenuItem.arrowIcon", null, "RadioButtonMenuItem.checkIcon", new GTKStyle.GTKLazyValue( "com.sun.java.swing.plaf.gtk.GTKIconFactory", "getRadioButtonMenuItemCheckIcon"), "RadioButtonMenuItem.font", new FontLazyValue(Region.RADIO_BUTTON_MENU_ITEM), "RadioButtonMenuItem.margin", zeroInsets, "RadioButtonMenuItem.alignAcceleratorText", Boolean.FALSE, // These bindings are only enabled when there is a default // button set on the rootpane. "RootPane.defaultButtonWindowKeyBindings", new Object[] { "ENTER", "press", "released ENTER", "release", "ctrl ENTER", "press", "ctrl released ENTER", "release" }, "ScrollBar.squareButtons", Boolean.FALSE, "ScrollBar.thumbHeight", Integer.valueOf(14), "ScrollBar.width", Integer.valueOf(16), "ScrollBar.minimumThumbSize", new Dimension(8, 8), "ScrollBar.maximumThumbSize", new Dimension(4096, 4096), "ScrollBar.allowsAbsolutePositioning", Boolean.TRUE, "ScrollBar.alwaysShowThumb", Boolean.TRUE, "ScrollBar.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { "RIGHT", "positiveUnitIncrement", "KP_RIGHT", "positiveUnitIncrement", "DOWN", "positiveUnitIncrement", "KP_DOWN", "positiveUnitIncrement", "PAGE_DOWN", "positiveBlockIncrement", "LEFT", "negativeUnitIncrement", "KP_LEFT", "negativeUnitIncrement", "UP", "negativeUnitIncrement", "KP_UP", "negativeUnitIncrement", "PAGE_UP", "negativeBlockIncrement", "HOME", "minScroll", "END", "maxScroll" }), "ScrollBar.ancestorInputMap.RightToLeft", new UIDefaults.LazyInputMap(new Object[] { "RIGHT", "negativeUnitIncrement", "KP_RIGHT", "negativeUnitIncrement", "LEFT", "positiveUnitIncrement", "KP_LEFT", "positiveUnitIncrement", }), "Spinner.disableOnBoundaryValues", Boolean.TRUE, "ScrollPane.fillUpperCorner", Boolean.TRUE, "ScrollPane.fillLowerCorner", Boolean.TRUE, "ScrollPane.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { "RIGHT", "unitScrollRight", "KP_RIGHT", "unitScrollRight", "DOWN", "unitScrollDown", "KP_DOWN", "unitScrollDown", "LEFT", "unitScrollLeft", "KP_LEFT", "unitScrollLeft", "UP", "unitScrollUp", "KP_UP", "unitScrollUp", "PAGE_UP", "scrollUp", "PAGE_DOWN", "scrollDown", "ctrl PAGE_UP", "scrollLeft", "ctrl PAGE_DOWN", "scrollRight", "ctrl HOME", "scrollHome", "ctrl END", "scrollEnd" }), "ScrollPane.ancestorInputMap.RightToLeft", new UIDefaults.LazyInputMap(new Object[] { "ctrl PAGE_UP", "scrollRight", "ctrl PAGE_DOWN", "scrollLeft", }), "ScrollPane.font", new FontLazyValue(Region.SCROLL_PANE), "Separator.insets", zeroInsets, "Separator.thickness", Integer.valueOf(2), "Slider.paintValue", Boolean.TRUE, "Slider.thumbWidth", Integer.valueOf(30), "Slider.thumbHeight", Integer.valueOf(14), "Slider.focusInputMap", new UIDefaults.LazyInputMap(new Object[] { "RIGHT", "positiveUnitIncrement", "KP_RIGHT", "positiveUnitIncrement", "DOWN", "negativeUnitIncrement", "KP_DOWN", "negativeUnitIncrement", "PAGE_DOWN", "negativeBlockIncrement", "LEFT", "negativeUnitIncrement", "KP_LEFT", "negativeUnitIncrement", "UP", "positiveUnitIncrement", "KP_UP", "positiveUnitIncrement", "PAGE_UP", "positiveBlockIncrement", "HOME", "minScroll", "END", "maxScroll" }), "Slider.focusInputMap.RightToLeft", new UIDefaults.LazyInputMap(new Object[] { "RIGHT", "negativeUnitIncrement", "KP_RIGHT", "negativeUnitIncrement", "LEFT", "positiveUnitIncrement", "KP_LEFT", "positiveUnitIncrement", }), "Slider.onlyLeftMouseButtonDrag", Boolean.FALSE, "Spinner.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { "UP", "increment", "KP_UP", "increment", "DOWN", "decrement", "KP_DOWN", "decrement", }), "Spinner.font", new FontLazyValue(Region.SPINNER), "Spinner.editorAlignment", JTextField.LEADING, "SplitPane.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { "UP", "negativeIncrement", "DOWN", "positiveIncrement", "LEFT", "negativeIncrement", "RIGHT", "positiveIncrement", "KP_UP", "negativeIncrement", "KP_DOWN", "positiveIncrement", "KP_LEFT", "negativeIncrement", "KP_RIGHT", "positiveIncrement", "HOME", "selectMin", "END", "selectMax", "F8", "startResize", "F6", "toggleFocus", "ctrl TAB", "focusOutForward", "ctrl shift TAB", "focusOutBackward" }), "SplitPane.size", Integer.valueOf(7), "SplitPane.oneTouchOffset", Integer.valueOf(2), "SplitPane.oneTouchButtonSize", Integer.valueOf(5), "SplitPane.supportsOneTouchButtons", Boolean.FALSE, "TabbedPane.focusInputMap", new UIDefaults.LazyInputMap(new Object[] { "RIGHT", "navigateRight", "KP_RIGHT", "navigateRight", "LEFT", "navigateLeft", "KP_LEFT", "navigateLeft", "UP", "navigateUp", "KP_UP", "navigateUp", "DOWN", "navigateDown", "KP_DOWN", "navigateDown", "ctrl DOWN", "requestFocusForVisibleComponent", "ctrl KP_DOWN", "requestFocusForVisibleComponent", "SPACE", "selectTabWithFocus" }), "TabbedPane.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { "ctrl TAB", "navigateNext", "ctrl shift TAB", "navigatePrevious", "ctrl PAGE_DOWN", "navigatePageDown", "ctrl PAGE_UP", "navigatePageUp", "ctrl UP", "requestFocus", "ctrl KP_UP", "requestFocus", }), "TabbedPane.labelShift", 3, "TabbedPane.selectedLabelShift", 3, "TabbedPane.font", new FontLazyValue(Region.TABBED_PANE), "TabbedPane.selectedTabPadInsets", new InsetsUIResource(2, 2, 0, 1), "Table.scrollPaneBorder", zeroBorder, "Table.background", tableBg, "Table.focusCellBackground", tableFocusCellBg, "Table.focusCellForeground", tableFocusCellFg, "Table.focusCellHighlightBorder", focusBorder, "Table.focusSelectedCellHighlightBorder", focusSelectedBorder, "Table.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { "ctrl C", "copy", "ctrl V", "paste", "ctrl X", "cut", "COPY", "copy", "PASTE", "paste", "CUT", "cut", "control INSERT", "copy", "shift INSERT", "paste", "shift DELETE", "cut", "RIGHT", "selectNextColumn", "KP_RIGHT", "selectNextColumn", "shift RIGHT", "selectNextColumnExtendSelection", "shift KP_RIGHT", "selectNextColumnExtendSelection", "ctrl shift RIGHT", "selectNextColumnExtendSelection", "ctrl shift KP_RIGHT", "selectNextColumnExtendSelection", "ctrl RIGHT", "selectNextColumnChangeLead", "ctrl KP_RIGHT", "selectNextColumnChangeLead", "LEFT", "selectPreviousColumn", "KP_LEFT", "selectPreviousColumn", "shift LEFT", "selectPreviousColumnExtendSelection", "shift KP_LEFT", "selectPreviousColumnExtendSelection", "ctrl shift LEFT", "selectPreviousColumnExtendSelection", "ctrl shift KP_LEFT", "selectPreviousColumnExtendSelection", "ctrl LEFT", "selectPreviousColumnChangeLead", "ctrl KP_LEFT", "selectPreviousColumnChangeLead", "DOWN", "selectNextRow", "KP_DOWN", "selectNextRow", "shift DOWN", "selectNextRowExtendSelection", "shift KP_DOWN", "selectNextRowExtendSelection", "ctrl shift DOWN", "selectNextRowExtendSelection", "ctrl shift KP_DOWN", "selectNextRowExtendSelection", "ctrl DOWN", "selectNextRowChangeLead", "ctrl KP_DOWN", "selectNextRowChangeLead", "UP", "selectPreviousRow", "KP_UP", "selectPreviousRow", "shift UP", "selectPreviousRowExtendSelection", "shift KP_UP", "selectPreviousRowExtendSelection", "ctrl shift UP", "selectPreviousRowExtendSelection", "ctrl shift KP_UP", "selectPreviousRowExtendSelection", "ctrl UP", "selectPreviousRowChangeLead", "ctrl KP_UP", "selectPreviousRowChangeLead", "HOME", "selectFirstColumn", "shift HOME", "selectFirstColumnExtendSelection", "ctrl shift HOME", "selectFirstRowExtendSelection", "ctrl HOME", "selectFirstRow", "END", "selectLastColumn", "shift END", "selectLastColumnExtendSelection", "ctrl shift END", "selectLastRowExtendSelection", "ctrl END", "selectLastRow", "PAGE_UP", "scrollUpChangeSelection", "shift PAGE_UP", "scrollUpExtendSelection", "ctrl shift PAGE_UP", "scrollLeftExtendSelection", "ctrl PAGE_UP", "scrollLeftChangeSelection", "PAGE_DOWN", "scrollDownChangeSelection", "shift PAGE_DOWN", "scrollDownExtendSelection", "ctrl shift PAGE_DOWN", "scrollRightExtendSelection", "ctrl PAGE_DOWN", "scrollRightChangeSelection", "TAB", "selectNextColumnCell", "shift TAB", "selectPreviousColumnCell", "ENTER", "selectNextRowCell", "shift ENTER", "selectPreviousRowCell", "ctrl A", "selectAll", "ctrl SLASH", "selectAll", "ctrl BACK_SLASH", "clearSelection", "ESCAPE", "cancel", "F2", "startEditing", "SPACE", "addToSelection", "ctrl SPACE", "toggleAndAnchor", "shift SPACE", "extendTo", "ctrl shift SPACE", "moveSelectionTo", "F8", "focusHeader" }), "Table.ancestorInputMap.RightToLeft", new UIDefaults.LazyInputMap(new Object[] { "RIGHT", "selectPreviousColumn", "KP_RIGHT", "selectPreviousColumn", "shift RIGHT", "selectPreviousColumnExtendSelection", "shift KP_RIGHT", "selectPreviousColumnExtendSelection", "ctrl shift RIGHT", "selectPreviousColumnExtendSelection", "ctrl shift KP_RIGHT", "selectPreviousColumnExtendSelection", "shift RIGHT", "selectPreviousColumnChangeLead", "shift KP_RIGHT", "selectPreviousColumnChangeLead", "LEFT", "selectNextColumn", "KP_LEFT", "selectNextColumn", "shift LEFT", "selectNextColumnExtendSelection", "shift KP_LEFT", "selectNextColumnExtendSelection", "ctrl shift LEFT", "selectNextColumnExtendSelection", "ctrl shift KP_LEFT", "selectNextColumnExtendSelection", "ctrl LEFT", "selectNextColumnChangeLead", "ctrl KP_LEFT", "selectNextColumnChangeLead", "ctrl PAGE_UP", "scrollRightChangeSelection", "ctrl PAGE_DOWN", "scrollLeftChangeSelection", "ctrl shift PAGE_UP", "scrollRightExtendSelection", "ctrl shift PAGE_DOWN", "scrollLeftExtendSelection", }), "Table.font", new FontLazyValue(Region.TABLE), "Table.ascendingSortIcon", new GTKStyle.GTKLazyValue( "com.sun.java.swing.plaf.gtk.GTKIconFactory", "getAscendingSortIcon"), "Table.descendingSortIcon", new GTKStyle.GTKLazyValue( "com.sun.java.swing.plaf.gtk.GTKIconFactory", "getDescendingSortIcon"), "TableHeader.font", new FontLazyValue(Region.TABLE_HEADER), "TableHeader.alignSorterArrow", Boolean.TRUE, "TextArea.caretForeground", caretColor, "TextArea.caretAspectRatio", defaultCaretAspectRatio, "TextArea.caretBlinkRate", caretBlinkRate, "TextArea.margin", zeroInsets, "TextArea.focusInputMap", multilineInputMap, "TextArea.font", new FontLazyValue(Region.TEXT_AREA), "TextField.caretForeground", caretColor, "TextField.caretAspectRatio", defaultCaretAspectRatio, "TextField.caretBlinkRate", caretBlinkRate, "TextField.margin", zeroInsets, "TextField.focusInputMap", fieldInputMap, "TextField.font", new FontLazyValue(Region.TEXT_FIELD), "TextPane.caretForeground", caretColor, "TextPane.caretAspectRatio", defaultCaretAspectRatio, "TextPane.caretBlinkRate", caretBlinkRate, "TextPane.margin", editorMargin, "TextPane.focusInputMap", multilineInputMap, "TextPane.font", new FontLazyValue(Region.TEXT_PANE), "TitledBorder.titleColor", controlText, "TitledBorder.border", new UIDefaults.LazyValue() { public Object createValue(UIDefaults table) { return new GTKPainter.TitledBorder(); } }, "ToggleButton.focusInputMap", new UIDefaults.LazyInputMap(new Object[] { "SPACE", "pressed", "released SPACE", "released" }), "ToggleButton.font", new FontLazyValue(Region.TOGGLE_BUTTON), "ToggleButton.margin", zeroInsets, "ToolBar.separatorSize", new DimensionUIResource(10, 10), "ToolBar.handleIcon", new UIDefaults.ActiveValue() { public Object createValue(UIDefaults table) { return GTKIconFactory.getToolBarHandleIcon(); } }, "ToolBar.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { "UP", "navigateUp", "KP_UP", "navigateUp", "DOWN", "navigateDown", "KP_DOWN", "navigateDown", "LEFT", "navigateLeft", "KP_LEFT", "navigateLeft", "RIGHT", "navigateRight", "KP_RIGHT", "navigateRight" }), "ToolBar.font", new FontLazyValue(Region.TOOL_BAR), "ToolTip.font", new FontLazyValue(Region.TOOL_TIP), "Tree.padding", Integer.valueOf(4), "Tree.background", tableBg, "Tree.drawHorizontalLines", Boolean.FALSE, "Tree.drawVerticalLines", Boolean.FALSE, "Tree.rowHeight", Integer.valueOf(-1), "Tree.scrollsOnExpand", Boolean.FALSE, "Tree.expanderSize", Integer.valueOf(10), "Tree.repaintWholeRow", Boolean.TRUE, "Tree.closedIcon", null, "Tree.leafIcon", null, "Tree.openIcon", null, "Tree.expandedIcon", new GTKStyle.GTKLazyValue( "com.sun.java.swing.plaf.gtk.GTKIconFactory", "getTreeExpandedIcon"), "Tree.collapsedIcon", new GTKStyle.GTKLazyValue( "com.sun.java.swing.plaf.gtk.GTKIconFactory", "getTreeCollapsedIcon"), "Tree.leftChildIndent", Integer.valueOf(2), "Tree.rightChildIndent", Integer.valueOf(12), "Tree.scrollsHorizontallyAndVertically", Boolean.FALSE, "Tree.drawsFocusBorder", Boolean.TRUE, "Tree.focusInputMap", new UIDefaults.LazyInputMap(new Object[] { "ctrl C", "copy", "ctrl V", "paste", "ctrl X", "cut", "COPY", "copy", "PASTE", "paste", "CUT", "cut", "control INSERT", "copy", "shift INSERT", "paste", "shift DELETE", "cut", "UP", "selectPrevious", "KP_UP", "selectPrevious", "shift UP", "selectPreviousExtendSelection", "shift KP_UP", "selectPreviousExtendSelection", "ctrl shift UP", "selectPreviousExtendSelection", "ctrl shift KP_UP", "selectPreviousExtendSelection", "ctrl UP", "selectPreviousChangeLead", "ctrl KP_UP", "selectPreviousChangeLead", "DOWN", "selectNext", "KP_DOWN", "selectNext", "shift DOWN", "selectNextExtendSelection", "shift KP_DOWN", "selectNextExtendSelection", "ctrl shift DOWN", "selectNextExtendSelection", "ctrl shift KP_DOWN", "selectNextExtendSelection", "ctrl DOWN", "selectNextChangeLead", "ctrl KP_DOWN", "selectNextChangeLead", "RIGHT", "selectChild", "KP_RIGHT", "selectChild", "LEFT", "selectParent", "KP_LEFT", "selectParent", "typed +", "expand", "typed -", "collapse", "BACK_SPACE", "moveSelectionToParent", "PAGE_UP", "scrollUpChangeSelection", "shift PAGE_UP", "scrollUpExtendSelection", "ctrl shift PAGE_UP", "scrollUpExtendSelection", "ctrl PAGE_UP", "scrollUpChangeLead", "PAGE_DOWN", "scrollDownChangeSelection", "shift PAGE_DOWN", "scrollDownExtendSelection", "ctrl shift PAGE_DOWN", "scrollDownExtendSelection", "ctrl PAGE_DOWN", "scrollDownChangeLead", "HOME", "selectFirst", "shift HOME", "selectFirstExtendSelection", "ctrl shift HOME", "selectFirstExtendSelection", "ctrl HOME", "selectFirstChangeLead", "END", "selectLast", "shift END", "selectLastExtendSelection", "ctrl shift END", "selectLastExtendSelection", "ctrl END", "selectLastChangeLead", "F2", "startEditing", "ctrl A", "selectAll", "ctrl SLASH", "selectAll", "ctrl BACK_SLASH", "clearSelection", "ctrl LEFT", "scrollLeft", "ctrl KP_LEFT", "scrollLeft", "ctrl RIGHT", "scrollRight", "ctrl KP_RIGHT", "scrollRight", "SPACE", "addToSelection", "ctrl SPACE", "toggleAndAnchor", "shift SPACE", "extendTo", "ctrl shift SPACE", "moveSelectionTo" }), "Tree.focusInputMap.RightToLeft", new UIDefaults.LazyInputMap(new Object[] { "RIGHT", "selectParent", "KP_RIGHT", "selectParent", "LEFT", "selectChild", "KP_LEFT", "selectChild", }), "Tree.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { "ESCAPE", "cancel" }), "Tree.font", new FontLazyValue(Region.TREE), "Viewport.font", new FontLazyValue(Region.VIEWPORT) }; table.putDefaults(defaults); if (fallbackFont != null) { table.put("TitledBorder.font", fallbackFont); } table.put(SwingUtilities2.AA_TEXT_PROPERTY_KEY, aaTextInfo); } protected void initSystemColorDefaults(UIDefaults table) { GTKStyleFactory factory = (GTKStyleFactory)getStyleFactory(); GTKStyle windowStyle = (GTKStyle)factory.getStyle(null, Region.INTERNAL_FRAME); table.put("window", windowStyle.getGTKColor(SynthConstants.ENABLED, GTKColorType.BACKGROUND)); table.put("windowText", windowStyle.getGTKColor(SynthConstants.ENABLED, GTKColorType.TEXT_FOREGROUND)); GTKStyle entryStyle = (GTKStyle)factory.getStyle(null, Region.TEXT_FIELD); table.put("text", entryStyle.getGTKColor(SynthConstants.ENABLED, GTKColorType.TEXT_BACKGROUND)); table.put("textText", entryStyle.getGTKColor(SynthConstants.ENABLED, GTKColorType.TEXT_FOREGROUND)); table.put("textHighlight", entryStyle.getGTKColor(SynthConstants.SELECTED, GTKColorType.TEXT_BACKGROUND)); table.put("textHighlightText", entryStyle.getGTKColor(SynthConstants.SELECTED, GTKColorType.TEXT_FOREGROUND)); table.put("textInactiveText", entryStyle.getGTKColor(SynthConstants.DISABLED, GTKColorType.TEXT_FOREGROUND)); Object caretColor = entryStyle.getClassSpecificValue("cursor-color"); if (caretColor == null) { caretColor = GTKStyle.BLACK_COLOR; } table.put("caretColor", caretColor); GTKStyle menuStyle = (GTKStyle)factory.getStyle(null, Region.MENU_ITEM); table.put("menu", menuStyle.getGTKColor(SynthConstants.ENABLED, GTKColorType.BACKGROUND)); table.put("menuText", menuStyle.getGTKColor(SynthConstants.ENABLED, GTKColorType.TEXT_FOREGROUND)); GTKStyle scrollbarStyle = (GTKStyle)factory.getStyle(null, Region.SCROLL_BAR); table.put("scrollbar", scrollbarStyle.getGTKColor(SynthConstants.ENABLED, GTKColorType.BACKGROUND)); GTKStyle infoStyle = (GTKStyle)factory.getStyle(null, Region.OPTION_PANE); table.put("info", infoStyle.getGTKColor(SynthConstants.ENABLED, GTKColorType.BACKGROUND)); table.put("infoText", infoStyle.getGTKColor(SynthConstants.ENABLED, GTKColorType.TEXT_FOREGROUND)); GTKStyle desktopStyle = (GTKStyle)factory.getStyle(null, Region.DESKTOP_PANE); table.put("desktop", desktopStyle.getGTKColor(SynthConstants.ENABLED, GTKColorType.BACKGROUND)); // colors specific only for GTK // It is impossible to create a simple GtkWidget without specifying the // type. So for GtkWidget we can use any appropriate concrete type of // wigdet. LABEL in this case. GTKStyle widgetStyle = (GTKStyle)factory.getStyle(null, Region.LABEL); Color bg = widgetStyle.getGTKColor(SynthConstants.ENABLED, GTKColorType.BACKGROUND); table.put("control", bg); table.put("controlHighlight", bg); table.put("controlText", widgetStyle.getGTKColor(SynthConstants.ENABLED, GTKColorType.TEXT_FOREGROUND)); table.put("controlLtHighlight", widgetStyle.getGTKColor( SynthConstants.ENABLED, GTKColorType.LIGHT)); table.put("controlShadow", widgetStyle.getGTKColor( SynthConstants.ENABLED, GTKColorType.DARK)); table.put("controlDkShadow", widgetStyle.getGTKColor( SynthConstants.ENABLED, GTKColorType.BLACK)); table.put("light", widgetStyle.getGTKColor( SynthConstants.ENABLED, GTKColorType.LIGHT)); table.put("mid", widgetStyle.getGTKColor( SynthConstants.ENABLED, GTKColorType.MID)); table.put("dark", widgetStyle.getGTKColor( SynthConstants.ENABLED, GTKColorType.DARK)); table.put("black", widgetStyle.getGTKColor( SynthConstants.ENABLED, GTKColorType.BLACK)); table.put("white", widgetStyle.getGTKColor( SynthConstants.ENABLED, GTKColorType.WHITE)); } /** * Creates the GTK look and feel class for the passed in Component. */ public static ComponentUI createUI(JComponent c) { String key = c.getUIClassID().intern(); if (key == "FileChooserUI") { return GTKFileChooserUI.createUI(c); } return SynthLookAndFeel.createUI(c); } /** * Returns the cached gtkThemeName */ static String getGtkThemeName() { return gtkThemeName; } static boolean isLeftToRight(Component c) { return c.getComponentOrientation().isLeftToRight(); } public void initialize() { /* * We need to call loadGTK() to ensure that the native GTK * libraries are loaded. It is very unlikely that this call will * fail (since we've already verified native GTK support in * isSupportedLookAndFeel()), but we can throw an error in the * failure situation just in case. */ Toolkit toolkit = Toolkit.getDefaultToolkit(); if (toolkit instanceof UNIXToolkit && !((UNIXToolkit)toolkit).loadGTK()) { throw new InternalError("Unable to load native GTK libraries"); } super.initialize(); inInitialize = true; loadStyles(); inInitialize = false; /* * Check if system AA font settings should be used. * Sun's JDS (for Linux and Solaris) ships with high quality CJK * fonts and specifies via fontconfig that these be rendered in * B&W to take advantage of the embedded bitmaps. * If is a Sun CJK locale or remote display, indicate by the condition * variable that in this case the L&F recommends ignoring desktop * settings. On other Unixes (eg Linux) this doesn't apply. * REMIND 1: The isSunCJK test is really just a place holder * until we can properly query fontconfig and use the properties * set for specific fonts. * REMIND 2: See comment on isLocalDisplay() definition regarding * XRender. */ gtkAAFontSettingsCond = !isSunCJK && SwingUtilities2.isLocalDisplay(); aaTextInfo = SwingUtilities2.AATextInfo.getAATextInfo(gtkAAFontSettingsCond); } static ReferenceQueue<GTKLookAndFeel> queue = new ReferenceQueue<GTKLookAndFeel>(); private static void flushUnreferenced() { WeakPCL pcl; while ((pcl = (WeakPCL)queue.poll()) != null) { pcl.dispose(); } } static class WeakPCL extends WeakReference<GTKLookAndFeel> implements PropertyChangeListener { private Toolkit kit; private String key; WeakPCL(GTKLookAndFeel target, Toolkit kit, String key) { super(target, queue); this.kit = kit; this.key = key; } public String getKey() { return key; } public void propertyChange(final PropertyChangeEvent pce) { final GTKLookAndFeel lnf = get(); if (lnf == null || UIManager.getLookAndFeel() != lnf) { // The property was GC'ed, we're no longer interested in // PropertyChanges, remove the listener. dispose(); } else { // We are using invokeLater here because we are getting called // on the AWT-Motif thread which can cause a deadlock. SwingUtilities.invokeLater(new Runnable() { public void run() { String name = pce.getPropertyName(); /* We are listening for GTK desktop text AA settings: * "gnome.Xft/Antialias" and "gnome.Xft/RGBA". * However we don't need to read these here as * the UIDefaults reads them and this event causes * those to be reinitialised. */ if ("gnome.Net/ThemeName".equals(name)) { GTKEngine.INSTANCE.themeChanged(); GTKIconFactory.resetIcons(); } lnf.loadStyles(); Window appWindows[] = Window.getWindows(); for (int i = 0; i < appWindows.length; i++) { SynthLookAndFeel.updateStyles(appWindows[i]); } } }); } } void dispose() { kit.removePropertyChangeListener(key, this); } } public boolean isSupportedLookAndFeel() { Toolkit toolkit = Toolkit.getDefaultToolkit(); return (toolkit instanceof SunToolkit && ((SunToolkit)toolkit).isNativeGTKAvailable()); } public boolean isNativeLookAndFeel() { return true; } public String getDescription() { return "GTK look and feel"; } public String getName() { return "GTK look and feel"; } public String getID() { return "GTK"; } // Subclassed to pass in false to the superclass, we don't want to try // and load the system colors. protected void loadSystemColors(UIDefaults table, String[] systemColors, boolean useNative) { super.loadSystemColors(table, systemColors, false); } private void loadStyles() { gtkThemeName = (String)Toolkit.getDefaultToolkit(). getDesktopProperty("gnome.Net/ThemeName"); setStyleFactory(getGTKStyleFactory()); // If we are in initialize initializations will be // called later, don't do it now. if (!inInitialize) { UIDefaults table = UIManager.getLookAndFeelDefaults(); initSystemColorDefaults(table); initComponentDefaults(table); } } private GTKStyleFactory getGTKStyleFactory() { GTKEngine engine = GTKEngine.INSTANCE; Object iconSizes = engine.getSetting(GTKEngine.Settings.GTK_ICON_SIZES); if (iconSizes instanceof String) { if (!configIconSizes((String)iconSizes)) { System.err.println("Error parsing gtk-icon-sizes string: '" + iconSizes + "'"); } } // Desktop property appears to have preference over rc font. Object fontName = Toolkit.getDefaultToolkit().getDesktopProperty( "gnome.Gtk/FontName"); if (!(fontName instanceof String)) { fontName = engine.getSetting(GTKEngine.Settings.GTK_FONT_NAME); if (!(fontName instanceof String)) { fontName = "sans 10"; } } if (styleFactory == null) { styleFactory = new GTKStyleFactory(); } Font defaultFont = PangoFonts.lookupFont((String)fontName); fallbackFont = defaultFont; styleFactory.initStyles(defaultFont); return styleFactory; } private boolean configIconSizes(String sizeString) { String[] sizes = sizeString.split(":"); for (int i = 0; i < sizes.length; i++) { String[] splits = sizes[i].split("="); if (splits.length != 2) { return false; } String size = splits[0].trim().intern(); if (size.length() < 1) { return false; } splits = splits[1].split(","); if (splits.length != 2) { return false; } String width = splits[0].trim(); String height = splits[1].trim(); if (width.length() < 1 || height.length() < 1) { return false; } int w; int h; try { w = Integer.parseInt(width); h = Integer.parseInt(height); } catch (NumberFormatException nfe) { return false; } if (w > 0 && h > 0) { int type = GTKStyle.GTKStockIconInfo.getIconType(size); GTKStyle.GTKStockIconInfo.setIconSize(type, w, h); } else { System.err.println("Invalid size in gtk-icon-sizes: " + w + "," + h); } } return true; } /** * Returns whether or not the UIs should update their * <code>SynthStyles</code> from the <code>SynthStyleFactory</code> * when the ancestor of the Component changes. * * @return whether or not the UIs should update their * <code>SynthStyles</code> from the <code>SynthStyleFactory</code> * when the ancestor changed. */ public boolean shouldUpdateStyleOnAncestorChanged() { return true; } /** * {@inheritDoc} */ public LayoutStyle getLayoutStyle() { return GnomeLayoutStyle.INSTANCE; } /** * Gnome layout style. From: * http://developer.gnome.org/projects/gup/hig/2.0/design-window.html#window-layout-spacing * You'll notice this doesn't do the radiobutton/checkbox border * adjustments that windows/metal do. This is because gtk doesn't * provide margins/insets for checkbox/radiobuttons. */ private static class GnomeLayoutStyle extends DefaultLayoutStyle { private static GnomeLayoutStyle INSTANCE = new GnomeLayoutStyle(); @Override public int getPreferredGap(JComponent component1, JComponent component2, ComponentPlacement type, int position, Container parent) { // Checks args super.getPreferredGap(component1, component2, type, position, parent); switch(type) { case INDENT: if (position == SwingConstants.EAST || position == SwingConstants.WEST) { // Indent group members 12 pixels to denote hierarchy and // association. return 12; } // Fall through to related // As a basic rule of thumb, leave space between user // interface components in increments of 6 pixels, going up as // the relationship between related elements becomes more // distant. For example, between icon labels and associated // graphics within an icon, 6 pixels are adequate. Between // labels and associated components, leave 12 horizontal // pixels. For vertical spacing between groups of components, // 18 pixels is adequate. // // The first part of this is handled automatically by Icon (which // won't give you 6 pixels). case RELATED: if (isLabelAndNonlabel(component1, component2, position)) { return 12; } return 6; case UNRELATED: return 12; } return 0; } @Override public int getContainerGap(JComponent component, int position, Container parent) { // Checks args super.getContainerGap(component, position, parent); // A general padding of 12 pixels is // recommended between the contents of a dialog window and the // window borders. return 12; } } }
lacau/onebr-service
src/main/java/br/com/onebr/controller/response/ResistomeRes.java
<filename>src/main/java/br/com/onebr/controller/response/ResistomeRes.java<gh_stars>0 package br.com.onebr.controller.response; import br.com.onebr.model.resistome.Aminoglycoside; import br.com.onebr.model.resistome.BLactam; import br.com.onebr.model.resistome.Colistin; import br.com.onebr.model.resistome.Fosfomycin; import br.com.onebr.model.resistome.FusidicAcid; import br.com.onebr.model.resistome.Glycopeptide; import br.com.onebr.model.resistome.Macrolide; import br.com.onebr.model.resistome.Nitroimidazole; import br.com.onebr.model.resistome.Oxazolidinone; import br.com.onebr.model.resistome.Phenicol; import br.com.onebr.model.resistome.Quinolone; import br.com.onebr.model.resistome.Rifampicin; import br.com.onebr.model.resistome.Sulphonamide; import br.com.onebr.model.resistome.Tetracycline; import br.com.onebr.model.resistome.Trimethoprim; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import java.util.List; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; @Data @Builder @NoArgsConstructor @AllArgsConstructor @JsonPropertyOrder({"b_lactam", "phenicol", "colistin", "tetracycline", "glycopeptide", "aminoglycoside", "fosfomycin", "trimethoprim", "nitroimidazole", "macrolide", "quinolone", "sulphonamide", "rifampicin", "fusidic_acid", "oxazolidinone"}) public class ResistomeRes { @JsonProperty("b_lactam") private List<BLactam> bLactamList; @JsonProperty("phenicol") private List<Phenicol> phenicolList; @JsonProperty("colistin") private List<Colistin> colistinList; @JsonProperty("tetracycline") private List<Tetracycline> tetracyclineList; @JsonProperty("glycopeptide") private List<Glycopeptide> glycopeptideList; @JsonProperty("aminoglycoside") private List<Aminoglycoside> aminoglycosideList; @JsonProperty("fosfomycin") private List<Fosfomycin> fosfomycinList; @JsonProperty("trimethoprim") private List<Trimethoprim> trimethoprimList; @JsonProperty("nitroimidazole") private List<Nitroimidazole> nitroimidazoleList; @JsonProperty("macrolide") private List<Macrolide> macrolideList; @JsonProperty("quinolone") private List<Quinolone> quinoloneList; @JsonProperty("sulphonamide") private List<Sulphonamide> sulphonamideList; @JsonProperty("rifampicin") private List<Rifampicin> rifampicinList; @JsonProperty("fusidic_acid") private List<FusidicAcid> fusidicAcidList; @JsonProperty("oxazolidinone") private List<Oxazolidinone> oxazolidinoneList; }
asad-awadia/yugabyte-db
src/yb/tserver/heartbeater.h
<reponame>asad-awadia/yugabyte-db // 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. // // The following only applies to changes made to this file as part of YugaByte development. // // Portions Copyright (c) YugaByte, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express // or implied. See the License for the specific language governing permissions and limitations // under the License. // #ifndef YB_TSERVER_HEARTBEATER_H #define YB_TSERVER_HEARTBEATER_H #include <memory> #include "yb/server/server_base_options.h" #include "yb/gutil/macros.h" #include "yb/master/master_fwd.h" #include "yb/master/master_heartbeat.fwd.h" #include "yb/tserver/tserver_fwd.h" #include "yb/util/status_fwd.h" #include "yb/util/net/net_util.h" namespace yb { namespace tserver { // Interface data providers to be used for filling data into heartbeat request. // Data provider could fill in data into TSHeartbeatRequestPB that will be send by Heartbeater // after that. class HeartbeatDataProvider { public: explicit HeartbeatDataProvider(TabletServer* server) : server_(*CHECK_NOTNULL(server)) {} virtual ~HeartbeatDataProvider() {} // Add data to heartbeat, provider could skip and do nothing if is it too early for example for // periodical provider. // Called on every heartbeat from Heartbeater::Thread::TryHeartbeat. virtual void AddData( const master::TSHeartbeatResponsePB& last_resp, master::TSHeartbeatRequestPB* req) = 0; const std::string& LogPrefix() const; TabletServer& server() { return server_; } private: TabletServer& server_; }; // Component of the Tablet Server which is responsible for heartbeating to the // leader master. // // TODO: send heartbeats to non-leader masters. class Heartbeater { public: Heartbeater( const TabletServerOptions& options, TabletServer* server, std::vector<std::unique_ptr<HeartbeatDataProvider>>&& data_providers); Heartbeater(const Heartbeater& other) = delete; void operator=(const Heartbeater& other) = delete; Status Start(); Status Stop(); // Trigger a heartbeat as soon as possible, even if the normal // heartbeat interval has not expired. void TriggerASAP(); void set_master_addresses(server::MasterAddressesPtr master_addresses); ~Heartbeater(); private: class Thread; std::unique_ptr<Thread> thread_; }; class PeriodicalHeartbeatDataProvider : public HeartbeatDataProvider { public: PeriodicalHeartbeatDataProvider(TabletServer* server, const MonoDelta& period) : HeartbeatDataProvider(server), period_(period) {} void AddData( const master::TSHeartbeatResponsePB& last_resp, master::TSHeartbeatRequestPB* req) override; CoarseTimePoint prev_run_time() const { return prev_run_time_; } private: virtual void DoAddData( const master::TSHeartbeatResponsePB& last_resp, master::TSHeartbeatRequestPB* req) = 0; MonoDelta period_; CoarseTimePoint prev_run_time_; }; } // namespace tserver } // namespace yb #endif /* YB_TSERVER_HEARTBEATER_H */
digital-ECMT/acuity-vahub
vahub-model/src/test/java/com/acuity/visualisations/rawdatamodel/service/filters/CerebrovascularFilterServiceTest.java
/* * Copyright 2021 The University of Manchester * * 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.acuity.visualisations.rawdatamodel.service.filters; import com.acuity.visualisations.rawdatamodel.dataproviders.CerebrovascularDatasetsDataProvider; import com.acuity.visualisations.rawdatamodel.filters.CerebrovascularFilters; import com.acuity.visualisations.rawdatamodel.filters.PopulationFilters; import com.acuity.visualisations.rawdatamodel.filters.SetFilter; import com.acuity.visualisations.rawdatamodel.vo.CerebrovascularRaw; import com.acuity.visualisations.rawdatamodel.vo.FilterQuery; import com.acuity.visualisations.rawdatamodel.vo.FilterResult; import com.acuity.visualisations.rawdatamodel.vo.Subject; import com.acuity.visualisations.rawdatamodel.vo.wrappers.Cerebrovascular; import org.assertj.core.api.JUnitSoftAssertions; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.util.List; import java.util.stream.Collectors; import static com.google.common.collect.Lists.newArrayList; import static com.google.common.collect.Sets.newHashSet; import static org.mockito.Matchers.any; import static org.mockito.Mockito.when; public class CerebrovascularFilterServiceTest { @InjectMocks private CerebrovascularFilterService cerebrovascularFilterService; @Mock private CerebrovascularDatasetsDataProvider cerebrovascularDatasetsDataProvider; @Mock private PopulationRawDataFilterService subjectService; @Before public void setUp() { MockitoAnnotations.initMocks(this); } @Rule public final JUnitSoftAssertions softly = new JUnitSoftAssertions(); @Test public void shouldGetAvailableFiltersWithEmptyFilters() throws Exception { //Given List<Cerebrovascular> events = createListOfFour(); final List<Subject> subjects = events.stream().map(e -> e.getSubject()).collect(Collectors.toList()); FilterQuery<Subject> populationFilteredQuery = new FilterQuery<>(subjects, PopulationFilters.empty()); FilterResult<Subject> filteredPopulation = new FilterResult<>(populationFilteredQuery); filteredPopulation.withResults(subjects, subjects); when(subjectService.getPopulationFilterResult(any(FilterQuery.class))).thenReturn(filteredPopulation); //When CerebrovascularFilters result = (CerebrovascularFilters) cerebrovascularFilterService.getAvailableFilters(events, CerebrovascularFilters.empty(), subjects, PopulationFilters.empty()); //Then softly.assertThat(result.getAeNumber().getValues()).containsExactlyInAnyOrder("E01-213", "E02-213", "E03-21", "E04-21"); softly.assertThat(result.getComment().getValues()).containsExactlyInAnyOrder("Comment", "Comment2", "Comment3", "Comment4"); softly.assertThat(result.getEventType().getValues().size()).isEqualTo(1); softly.assertThat(result.getEventType().getValues().contains(null)).isTrue(); softly.assertThat(result.getEventTerm().getValues().size()).isEqualTo(1); softly.assertThat(result.getEventTerm().getValues().contains(null)).isTrue(); softly.assertThat(result.getMatchedItemsCount()).isEqualTo(4); } @Test public void shouldGetAvailableFilters() throws Exception { //Given List<Cerebrovascular> events = createListOfFour(); final List<Subject> subjects = events.stream().map(e -> e.getSubject()).collect(Collectors.toList()); CerebrovascularFilters filters = new CerebrovascularFilters(); filters.setAeNumber(new SetFilter<>(newHashSet("E03-21"))); FilterQuery<Subject> populationFilteredQuery = new FilterQuery<>(subjects, PopulationFilters.empty()); FilterResult<Subject> filteredPopulation = new FilterResult<>(populationFilteredQuery); filteredPopulation.withResults(subjects, subjects); when(subjectService.getPopulationFilterResult(any(FilterQuery.class))).thenReturn(filteredPopulation); //When CerebrovascularFilters result = (CerebrovascularFilters) cerebrovascularFilterService.getAvailableFilters(events, filters, subjects, PopulationFilters.empty()); //Then softly.assertThat(result.getAeNumber().getValues()).containsExactlyInAnyOrder("E03-21"); softly.assertThat(result.getComment().getValues()).containsExactlyInAnyOrder("Comment3"); softly.assertThat(result.getEventType().getValues().size()).isEqualTo(1); softly.assertThat(result.getEventType().getValues().contains(null)).isTrue(); softly.assertThat(result.getEventTerm().getValues().size()).isEqualTo(1); softly.assertThat(result.getEventTerm().getValues().contains(null)).isTrue(); softly.assertThat(result.getMatchedItemsCount()).isEqualTo(1); } @Test public void shouldGetAvailableFiltersImplWithEmptyFilters() { //Given List<Cerebrovascular> cerebrovasculars = createListOfFour(); FilterQuery<Cerebrovascular> query = new FilterQuery<>(cerebrovasculars, new CerebrovascularFilters(), newArrayList(), new PopulationFilters()); FilterResult<Cerebrovascular> filterResult = new FilterResult<>(query); filterResult.withResults(cerebrovasculars, cerebrovasculars); //When CerebrovascularFilters result = cerebrovascularFilterService.getAvailableFiltersImpl(filterResult); //Then softly.assertThat(result.getAeNumber().getValues()).containsExactlyInAnyOrder("E01-213", "E02-213", "E03-21", "E04-21"); softly.assertThat(result.getComment().getValues()).containsExactlyInAnyOrder("Comment", "Comment2", "Comment3", "Comment4"); softly.assertThat(result.getEventType().getValues().size()).isEqualTo(1); softly.assertThat(result.getEventType().getValues().contains(null)).isTrue(); softly.assertThat(result.getEventTerm().getValues().size()).isEqualTo(1); softly.assertThat(result.getEventTerm().getValues().contains(null)).isTrue(); softly.assertThat(result.getMatchedItemsCount()).isEqualTo(4); } @Test public void shouldGetAvailableFiltersImpl() { //Given List<Cerebrovascular> events = createListOfFour(); CerebrovascularFilters filters = new CerebrovascularFilters(); filters.setAeNumber(new SetFilter<>(newHashSet("E01-213"))); FilterQuery<Cerebrovascular> query = new FilterQuery<>(events, filters, newArrayList(), new PopulationFilters()); FilterResult<Cerebrovascular> filterResult = new FilterResult<>(query); filterResult.withResults(events, events); final List<Subject> subjects = events.stream().map(e -> e.getSubject()).collect(Collectors.toList()); FilterQuery<Subject> populationFilteredQuery = new FilterQuery<>(subjects, PopulationFilters.empty()); FilterResult<Subject> filteredPopulation = new FilterResult<>(populationFilteredQuery); filteredPopulation.withResults(subjects, subjects); when(subjectService.getPopulationFilterResult(any(FilterQuery.class))).thenReturn(filteredPopulation); //When final FilterResult<Cerebrovascular> res = cerebrovascularFilterService.query(query); CerebrovascularFilters result = cerebrovascularFilterService.getAvailableFiltersImpl(res); //Then softly.assertThat(result.getAeNumber().getValues()).containsExactlyInAnyOrder("E01-213"); softly.assertThat(result.getComment().getValues()).containsExactlyInAnyOrder("Comment"); softly.assertThat(result.getEventType().getValues().size()).isEqualTo(1); softly.assertThat(result.getEventType().getValues().contains(null)).isTrue(); softly.assertThat(result.getEventTerm().getValues().size()).isEqualTo(1); softly.assertThat(result.getEventTerm().getValues().contains(null)).isTrue(); softly.assertThat(result.getMatchedItemsCount()).isEqualTo(1); } private List<Cerebrovascular> createListOfFour() { Cerebrovascular cerebrovascular1 = new Cerebrovascular(CerebrovascularRaw.builder().aeNumber(213).comment("Comment").build(), Subject.builder().subjectId("1").subjectCode("E01").build()); Cerebrovascular cerebrovascular2 = new Cerebrovascular(CerebrovascularRaw.builder().aeNumber(213).comment("Comment2").build(), Subject.builder().subjectId("2").subjectCode("E02").build()); Cerebrovascular cerebrovascular3 = new Cerebrovascular(CerebrovascularRaw.builder().aeNumber(21).comment("Comment3").build(), Subject.builder().subjectId("3").subjectCode("E03").build()); Cerebrovascular cerebrovascular4 = new Cerebrovascular(CerebrovascularRaw.builder().aeNumber(21).comment("Comment4").build(), Subject.builder().subjectId("4").subjectCode("E04").build()); return newArrayList(cerebrovascular1, cerebrovascular2, cerebrovascular3, cerebrovascular4); } }
ProjectAsura/D3D11Samples
D3D11_USM/USM/asdx/include/asdxTextRenderer.h
//--------------------------------------------------------------------------------------------- // File : asdxTextRenderer.h // Desc : Text Renderer Module. // Copyright(c) Project Asura. All right reserved. //--------------------------------------------------------------------------------------------- #ifndef __ASDX_TEXT_RENDERER_H__ #define __ASDX_TEXT_RENDERER_H__ //--------------------------------------------------------------------------------------------- // Includes //--------------------------------------------------------------------------------------------- #include <d3d11.h> #include <asdxMath.h> #include <vector> namespace asdx { /////////////////////////////////////////////////////////////////////////////////////////////// // TextRenderer class /////////////////////////////////////////////////////////////////////////////////////////////// class TextRenderer { //======================================================================================== // list of friend classes and methods. //======================================================================================== /* NOTHING */ public: ////////////////////////////////////////////////////////////////////////////////////////// // Glyph structure ////////////////////////////////////////////////////////////////////////////////////////// struct Glyph { uint32_t Character; //!< 文字コードです. RECT SubRect; //!< 矩形です. float OffsetX; //!< X方向のオフセットです. float OffsetY; //!< Y方向のオフセットです. float AdvanceX; //!< 文字スペースです. }; //======================================================================================== // public variables. //======================================================================================== /* NOTHING */ //======================================================================================== // public methods. //======================================================================================== //---------------------------------------------------------------------------------------- //! @brief コンストラクタです. //---------------------------------------------------------------------------------------- TextRenderer(); //---------------------------------------------------------------------------------------- //! @brief デストラクタです. //---------------------------------------------------------------------------------------- virtual ~TextRenderer(); //---------------------------------------------------------------------------------------- //! @brief 初期化処理です. //! //! @param [in] pDevice デバイスです. //! @param [in] filename フォントファイル名です. //! @retval true 初期化に成功. //! @retval false 初期化に失敗. //---------------------------------------------------------------------------------------- bool Init( ID3D11Device* pDevice, const wchar_t* filename ); //---------------------------------------------------------------------------------------- //! @brief 終了処理です. //---------------------------------------------------------------------------------------- void Term(); //---------------------------------------------------------------------------------------- //! @brief 描画開始処理です. //---------------------------------------------------------------------------------------- void Begin(); //---------------------------------------------------------------------------------------- //! @brief 文字列を描画します. //! //! @param [in] text 描画する文字列です. //! @param [in] position 描画開始位置です. //! @param [in] color 文字カラーです. //! @param [in] layDepth レイヤーの深さです. //---------------------------------------------------------------------------------------- void DrawString( wchar_t* text, FLOAT2 position, FLOAT4 color = FLOAT4( 1.0f, 1.0f, 1.0f, 1.0f ), float layerDepth = 0.0f ); //---------------------------------------------------------------------------------------- //! @brief 描画終了処理です. //---------------------------------------------------------------------------------------- void End( ID3D11DeviceContext* pDeviceContext ); //---------------------------------------------------------------------------------------- //! @brief 行間サイズを取得します. //! //! @return 行間サイズを返却します. //---------------------------------------------------------------------------------------- float GetLineSpace() const; //---------------------------------------------------------------------------------------- //! @brief 行間サイズを設定します. //! //! @param [in] lineSpace 設定する行間サイズです. //---------------------------------------------------------------------------------------- void SetLineSpace( float lineSpace ); //---------------------------------------------------------------------------------------- //! @brief デフォルト文字を取得します. //! //! @return デフォルト文字を返却します. //---------------------------------------------------------------------------------------- wchar_t GetDefaultCharacter() const; //---------------------------------------------------------------------------------------- //! @brief デフォルト文字を設定します. //! //! @param [in] character 設定するデフォルト文字です. //---------------------------------------------------------------------------------------- void SetDefaultCharacter( wchar_t character ); //---------------------------------------------------------------------------------------- //! @brief 指定された文字が含まれているかチェックします. //! //! @retval true 含まれています. //! @retval false 含まれていません. //---------------------------------------------------------------------------------------- bool ContainsCharacter( wchar_t character ) const; protected: ////////////////////////////////////////////////////////////////////////////////////////// // Vertex structure ////////////////////////////////////////////////////////////////////////////////////////// struct Vertex { FLOAT3 Position; //!< 位置座標です. FLOAT4 Color; //!< 頂点カラーです. FLOAT2 TexCoord; //!< テクスチャ座標です. static const size_t InputElementCount = 3; //!< 入力要素数です. static const D3D11_INPUT_ELEMENT_DESC InputElements[ InputElementCount ]; //!< 入力要素です. }; //======================================================================================== // protected variables. //======================================================================================== static const size_t NUM_MAX_SPRITE = 2048; //!< 最大スプライト数です. static const size_t NUM_VERTEX_PER_SPRITE = 4; //!< 1スプライト当たりの頂点数です. static const size_t NUM_INDEX_PER_SRPITE = 6; //!< 1スプライト当たりのインデックス数です. ID3D11VertexShader* m_pVS; //!< 頂点シェーダです. ID3D11PixelShader* m_pPS; //!< ピクセルシェーダです. ID3D11InputLayout* m_pIL; //!< 入力レイアウトです. ID3D11Buffer* m_pVB; //!< 頂点バッファです. ID3D11Buffer* m_pIB; //!< インデックスバッファです. ID3D11Buffer* m_pCB; //!< 定数バッファです. ID3D11Texture2D* m_pTexture; //!< テクスチャです. ID3D11ShaderResourceView* m_pSRV; //!< シェーダリソースビューです. ID3D11SamplerState* m_pSmp; //!< サンプラーステートです. std::vector<Glyph> m_Glyphs; //!< グリフです. Glyph const* m_pDefaultGlyph; //!< デフォルトグリフです. float m_LineSpace; //!< 行間サイズです. size_t m_SpriteCount; //!< 描画するスプライト数です. bool m_IsBeginDraw; FLOAT2 MeasureString( wchar_t const* text ) const; Glyph const* FindGlyph ( wchar_t character ) const; void DrawSprite( ID3D11ShaderResourceView* pSRV, FLOAT2 position, RECT const* pSrcRect, FLOAT4 color, FLOAT2 origin, float layerDepth ); private: //======================================================================================== // private variables. //======================================================================================== /* NOTHING */ //======================================================================================== // private methods. //======================================================================================== TextRenderer ( const TextRenderer& value ); // アクセス禁止. void operator = ( const TextRenderer& value ); // アクセス禁止. }; } // namespace asdx #endif//__ASDX_TEXT_RENDERER_H__
pany-young/walle-rpc
walle-remoting/src/main/java/cn/pany/walle/remoting/api/Invoker.java
<filename>walle-remoting/src/main/java/cn/pany/walle/remoting/api/Invoker.java<gh_stars>1-10 package cn.pany.walle.remoting.api; /** * Created by pany on 17/12/11. */ public interface Invoker<T> { }
ScalablyTyped/SlinkyTyped
r/react-better-password/src/main/scala/typingsSlinky/reactBetterPassword/reactBetterPasswordStrings.scala
package typingsSlinky.reactBetterPassword import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} object reactBetterPasswordStrings { @js.native sealed trait Bullet extends StObject @scala.inline def Bullet: Bullet = "\u2022".asInstanceOf[Bullet] }
momotofu/lms_graphql_api
lib/lms_graphql/types/canvas/grader_input.rb
require_relative "../canvas_base_input_type" module LMSGraphQL module Types module Canvas class CanvasGraderInput < BaseInputObject description "Gradebook History. API Docs: https://canvas.instructure.com/doc/api/gradebook_history.html" argument :id, ID, "the user_id of the user who graded the contained submissions.Example: 27", required: false argument :name, String, "the name of the user who graded the contained submissions.Example: Some User", required: false argument :assignments, Int, "the assignment groups for all submissions in this response that were graded by this user. The details are not nested inside here, but the fact that an assignment is present here means that the grader did grade submissions for this assignment on the contextual date. You can use the id of a grader and of an assignment to make another API call to find all submissions for a grader/assignment combination on a given date..Example: 1, 2, 3", required: false end end end end
trekmedics/beacon
db/migrate/20150129190208_create_incident.rb
class CreateIncident < ActiveRecord::Migration def change create_table :incidents do |t| t.integer :state t.references :reporting_party, index: true t.references :incident_commander, index: true t.string :location t.integer :completion_status t.timestamps end add_foreign_key :incidents, :reporting_parties add_foreign_key :incidents, :incident_commanders end end
Skemba/alt-integration-cpp
test/entities/vbkpoptx_test.cpp
// Copyright (c) 2019-2020 <NAME> // https://www.veriblock.org // Distributed under the MIT software license, see the accompanying // file LICENSE or http://www.opensource.org/licenses/mit-license.php. #include "veriblock/entities/vbkpoptx.hpp" #include <gtest/gtest.h> #include "veriblock/literals.hpp" using namespace altintegration; static const NetworkBytePair networkByte{false, 0, (uint8_t)TxType::VBK_POP_TX}; static const VbkBlock defaultVbkBlock{4917, 2, "a793c872d6f6460e90bed623"_unhex, "42bb968195f8c515d3"_unhex, "eed7277a09efac4be9"_unhex, "9f95f0a15628b06ba3b44c0190b5c049"_unhex, 1553697485, 117556515, 1589362332}; static const auto btcTxBytes = "01000000010ce74f1fb694a001eebb1d7d08ce6208033f5bf7263ebad2de07bbf518672732" "00000" "0006a47304402200cf4998aba1682abeb777e762807a9dd2635a0b77773f66491b83ee3c87" "099ba" "022033b7ca24dc520915b8b0200cbdcf95ba6ae866354585af9c53ee86f27362ebec012103" "e5baf" "0709c395a82ef0bd63bc8847564ac201d69a8e6bf448d87aa53a1c431aaffffffff02b7270" "d0000" "0000001976a9148b9ea8545059f3a922457afd14ddf3855d8b109988ac0000000000000000" "536a4" "c50000013350002a793c872d6f6460e90bed62342bb968195f8c515d3eed7277a09efac4be" "99f95" "f0a15628b06ba3b44c0190b5c0495c9b8acd0701c5235ebbbe9cd4e943efe1864df0421661" "5cf92" "083f400000000"_unhex; static const MerklePath defaultPath{ 1659, uint256( "94E097B110BA3ADBB7B6C4C599D31D675DE7BE6E722407410C08EF352BE585F1"_unhex), std::vector<uint256>{ uint256( "4D66077FDF24246FFD6B6979DFEDEF5D46588654ADDEB35EDB11E993C131F612"_unhex), uint256( "023D1ABE8758C6F917EC0C65674BBD43D66EE14DC667B3117DFC44690C6F5AF1"_unhex), uint256( "096DDBA03CA952AF133FB06307C24171E53BF50AB76F1EDEABDE5E99F78D4EAD"_unhex), uint256( "2F32CF1BEE50349D56FC1943AF84F2D2ABDA520F64DC4DB37B2F3DB20B0ECB57"_unhex), uint256( "93E70120F1B539D0C1495B368061129F30D35F9E436F32D69967AE86031A2756"_unhex), uint256( "F554378A116E2142F9F6315A38B19BD8A1B2E6DC31201F2D37A058F03C39C06C"_unhex), uint256( "0824705685CECA003C95140434EE9D8BBBF4474B83FD4ECC2766137DB9A44D74"_unhex), uint256( "B7B9E52F3EE8CE4FBB8BE7D6CF66D33A20293F806C69385136662A74453FB162"_unhex), uint256( "1732C9A35E80D4796BABEA76AACE50B49F6079EA3E349F026B4491CFE720AD17"_unhex), uint256( "2D9B57E92AB51FE28A587050FD82ABB30ABD699A5CE8B54E7CD49B2A827BCB99"_unhex), uint256( "DCBA229ACDC6B7F028BA756FD5ABBFEBD31B4227CD4137D728EC5EA56C457618"_unhex), uint256( "2CF1439A6DBCC1A35E96574BDDBF2C5DB9174AF5AD0D278FE92E06E4AC349A42"_unhex)}}; static const BtcBlock defaultBtcBlock{ 549453824, uint256( "134f09d43659eb53982d9afb444b96fa4bb58c037d2914000000000000000000"_unhex), uint256( "ce0b1a9a77dd0db127b5df4bc368cd6ac299a9747d991ec2dacbc0b699a2e4a5"_unhex), 1553699251, 388767596, (uint32_t)-1069846413}; static const BtcBlock btcBlock1{ 545259520, uint256( "fc61cc9d4eac4b2d14761a4d06af8a9ef073dcd7fb5e0d000000000000000000"_unhex), uint256( "a31508d4b101d0ad11e43ef9419c23fc277f67edae83c598ee70866dbcef5e25"_unhex), 1553697574, 388767596, (uint32_t)-1351345951}; static const BtcBlock btcBlock2{ 541065216, uint256( "3f8e3980304439d853c302f6e496285e110e2512515313000000000000000000"_unhex), uint256( "39a72c22268381bd8d9dcfe002f472634a24cf0454de8b50f89e10891e5ffb1d"_unhex), 1553698272, 388767596, (uint32_t)-1844827836}; static const BtcBlock btcBlock3{ 536870912, uint256( "baa42e40345a7f826a31d37db1a5d64b67b72732477422000000000000000000"_unhex), uint256( "a33ad6be0634647b26633ab85fa8de258480bbb25e59c68e48bb0b608b12362b"_unhex), 1553699088, 388767596, (uint32_t)-254688183}; static const auto defaultSignature = "3045022100f4dce45edcc6bfc4a1f44ef04e47e90a348efd471f742f18b882ac77a8d0e89e" "022061" "7cf7c4a22211991687b17126c1bb007a3b2a25c550f75d66b857a8fd9d75e7"_unhex; static const auto defaultPublicKey = "3056301006072a8648ce3d020106052b8104000a03420004b3c10470c8e8e426f1937758d9" "fb5e97" "<KEY>" "313363" "26f7962750c8df99"_unhex; static const VbkPopTx defaultTx{ networkByte, Address::assertFromString("VE6MJFzmGdYdrxC8o6UCovVv7BdhdX"), defaultVbkBlock, BtcTx(btcTxBytes), defaultPath, defaultBtcBlock, std::vector<BtcBlock>{btcBlock1, btcBlock2, btcBlock3}, defaultSignature, defaultPublicKey}; static const std::string defaultTxEncoded = "02046102011667ff0a897e5d512a0b6da2f41c479867fe6b3a4cae2641000013350002a793" "c872d6f6460e90bed62342bb968195f8c515d3eed7277a09efac4be99f95f0a15628b06ba3" "b44c0190b5c0495c9b8acd0701c523005ebbbe9c02011b01000000010ce74f1fb694a001ee" "bb1d7d08ce6208033f5bf7263ebad2de07bbf518672732000000006a47304402200cf4998a" "ba1682abeb777e762807a9dd2635a0b77773f66491b83ee3c87099ba022033b7ca24dc5209" "<KEY>" "0bd63bc8847564ac201d69a8e6bf448d87aa53a1c431aaffffffff02b7270d000000000019" "76a9148b9ea8545059f3a922457afd14ddf3855d8b109988ac0000000000000000536a4c50" "000013350002a793c872d6f6460e90bed62342bb968195f8c515d3eed7277a09efac4be99f" "<KEY>" "615cf92083f40000000002019f040000067b040000000c040000000400000020204d66077f" "df24246ffd6b6979dfedef5d46588654addeb35edb11e993c131f61220023d1abe8758c6f9" "<KEY>" "07c24171e53bf50ab76f1edeabde5e99f78d4ead202f32cf1bee50349d56fc1943af84f2d2" "<KEY>" "436f32d69967ae86031a275620f554378a116e2142f9f6315a38b19bd8a1b2e6dc31201f2d" "37a058f03c39c06c200824705685ceca003c95140434ee9d8bbbf4474b83fd4ecc2766137d" "b9a44d7420b7b9e52f3ee8ce4fbb8be7d6cf66d33a20293f806c69385136662a74453fb162" "201732c9a35e80d4796babea76aace50b49f6079ea3e349f026b4491cfe720ad17202d9b57" "<KEY>" "f028ba756fd5abbfebd31b4227cd4137d728ec5ea56c457618202cf1439a6dbcc1a35e9657" "4bddbf2c5db9174af5ad0d278fe92e06e4ac349a42500000c0200000000000000000001429" "7d038cb54bfa964b44fb9a2d9853eb5936d4094f13a5e4a299b6c0cbdac21e997d74a999c2" "6acd68c34bdfb527b10ddd779a1a0bceb3919b5c6c1f2c1773703bc0010350000080200000" "000000000000000d5efbd7dc73f09e8aaf064d1a76142d4bac4e9dcc61fc255eefbc6d8670" "ee98c583aeed677f27fc239c41f93ee411add001b1d40815a3268b9b5c6c1f2c17e11874af" "500000402000000000000000000013535112250e115e2896e4f602c353d839443080398e3f" "1dfb5f1e89109ef8508bde5404cf244a6372f402e0cf9d8dbd818326222ca739e08d9b5c6c" "1f2c1744290a9250000000200000000000000000002274473227b7674bd6a5b17dd3316a82" "7f5a34402ea4ba2b36128b600bbb488ec6595eb2bb808425dea85fb83a63267b643406bed6" "3aa310919b5c6c1f2c1749c4d1f0473045022100f4dce45edcc6bfc4a1f44ef04e47e90a34" "8efd471f742f18b882ac77a8d0e89e0220617cf7c4a22211991687b17126c1bb007a3b2a25" "c550f75d66b857a8fd9d75e7583056301006072a8648ce3d020106052b8104000a03420004" "b3c10470c8e8e426f1937758d9fb5e97a1891176cb37d4c12d4af4107b1aa3e8a8a754c06a" "22760e44c60642fba883967c19740d5231336326f7962750c8df99"; TEST(VbkPopTx, DeserializeFromVbkEncoding) { auto decoded = AssertDeserializeFromHex<VbkPopTx>(defaultTxEncoded); EXPECT_EQ(decoded.networkOrType.typeId, defaultTx.networkOrType.typeId); EXPECT_EQ(decoded.address, defaultTx.address); EXPECT_EQ(decoded.publishedBlock.getHeight(), defaultTx.publishedBlock.getHeight()); EXPECT_EQ(decoded.bitcoinTransaction.tx, defaultTx.bitcoinTransaction.tx); EXPECT_EQ(decoded.blockOfProof.getVersion(), defaultTx.blockOfProof.getVersion()); EXPECT_EQ(decoded.blockOfProofContext.size(), defaultTx.blockOfProofContext.size()); EXPECT_EQ(decoded.blockOfProofContext[0].getVersion(), defaultTx.blockOfProofContext[0].getVersion()); EXPECT_EQ(decoded.merklePath.index, defaultTx.merklePath.index); EXPECT_EQ(decoded.signature, defaultTx.signature); EXPECT_EQ(decoded.publicKey, defaultTx.publicKey); } TEST(VbkPopTx, Serialize) { WriteStream stream; defaultTx.toVbkEncoding(stream); auto txBytes = stream.data(); auto txEncoded = HexStr(txBytes); EXPECT_EQ(txEncoded, defaultTxEncoded); } TEST(VbkPopTx, RoundTrip) { auto decoded = AssertDeserializeFromHex<VbkPopTx>(defaultTxEncoded); EXPECT_EQ(decoded.address, Address::assertFromString("VE6MJFzmGdYdrxC8o6UCovVv7BdhdX")); WriteStream outputStream; decoded.toVbkEncoding(outputStream); auto txBytes = outputStream.data(); auto txReEncoded = HexStr(txBytes); EXPECT_EQ(txReEncoded, defaultTxEncoded); } TEST(VbkPopTx, RoundTripNew) { auto txEncoded = ParseHex(defaultTxEncoded); VbkPopTx decoded; ValidationState state; bool ret = DeserializeFromVbkEncoding(txEncoded, decoded, state); ASSERT_TRUE(ret); EXPECT_TRUE(state.IsValid()); EXPECT_EQ(decoded.address, Address::assertFromString("VE6MJFzmGdYdrxC8o6UCovVv7BdhdX")); WriteStream outputStream; decoded.toVbkEncoding(outputStream); auto txBytes = outputStream.data(); auto txReEncoded = HexStr(txBytes); EXPECT_EQ(txReEncoded, defaultTxEncoded); }
kamleshbhalui/chapel
third-party/libfabric/libfabric-src/prov/rxm/src/rxm_atomic.c
<gh_stars>1-10 /* * Copyright (c) 2018 Cray Inc. All rights reserved. * Copyright (c) 2018 System Fabric Works, Inc. All rights reserved. * (C) Copyright 2020 Hewlett Packard Enterprise Development LP * * This software is available to you under a choice of one of two * licenses. You may choose to be licensed under the terms of the GNU * General Public License (GPL) Version 2, available from the file * COPYING in the main directory of this source tree, or the * BSD license below: * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. * * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <ofi_atomic.h> #include "rxm.h" static void rxm_ep_format_atomic_pkt_hdr(struct rxm_conn *rxm_conn, struct rxm_tx_buf *tx_buf, size_t data_len, uint32_t pkt_op, enum fi_datatype datatype, uint8_t atomic_op, uint64_t flags, uint64_t data, const struct fi_rma_ioc *rma_ioc, size_t rma_ioc_count) { struct rxm_atomic_hdr *atomic_hdr; atomic_hdr = (struct rxm_atomic_hdr *) tx_buf->pkt.data; rxm_ep_format_tx_buf_pkt(rxm_conn, data_len, pkt_op, data, 0, flags, &tx_buf->pkt); tx_buf->pkt.ctrl_hdr.type = rxm_ctrl_atomic; tx_buf->pkt.hdr.op = pkt_op; tx_buf->pkt.hdr.atomic.datatype = datatype; tx_buf->pkt.hdr.atomic.op = atomic_op; tx_buf->pkt.hdr.atomic.ioc_count = rma_ioc_count; if (rma_ioc_count) memcpy(atomic_hdr->rma_ioc, rma_ioc, rma_ioc_count * sizeof(struct fi_rma_ioc)); tx_buf->flags = flags; } static inline int rxm_ep_send_atomic_req(struct rxm_ep *rxm_ep, struct rxm_conn *rxm_conn, struct rxm_tx_buf *tx_buf, uint64_t len) { int ret; /* Atomic request TX completion processing is performed when the * software generated atomic response message is received. */ tx_buf->hdr.state = RXM_ATOMIC_RESP_WAIT; if (len <= rxm_ep->inject_limit) ret = fi_inject(rxm_conn->msg_ep, &tx_buf->pkt, len, 0); else ret = fi_send(rxm_conn->msg_ep, &tx_buf->pkt, len, tx_buf->hdr.desc, 0, tx_buf); if (ret == -FI_EAGAIN) rxm_ep_do_progress(&rxm_ep->util_ep); if (OFI_LIKELY(!ret)) FI_DBG(&rxm_prov, FI_LOG_EP_DATA, "sent atomic request: op: %" PRIu8 " msg_id: 0x%" PRIx64 "\n", tx_buf->pkt.hdr.op, tx_buf->pkt.ctrl_hdr.msg_id); else if (OFI_UNLIKELY(ret != -FI_EAGAIN)) FI_WARN(&rxm_prov, FI_LOG_EP_DATA, "unable to send atomic " "request: op: %" PRIu8 " msg_id: 0x%" PRIx64 "\n", tx_buf->pkt.hdr.op, tx_buf->pkt.ctrl_hdr.msg_id); return ret; } static ssize_t rxm_ep_atomic_common(struct rxm_ep *rxm_ep, struct rxm_conn *rxm_conn, const struct fi_msg_atomic *msg, const struct fi_ioc *comparev, void **compare_desc, size_t compare_iov_count, struct fi_ioc *resultv, void **result_desc, size_t result_iov_count, uint32_t op, uint64_t flags) { struct rxm_tx_buf *tx_buf; struct rxm_atomic_hdr *atomic_hdr; struct iovec buf_iov[RXM_IOV_LIMIT]; struct iovec cmp_iov[RXM_IOV_LIMIT]; enum fi_hmem_iface buf_iface = FI_HMEM_SYSTEM; enum fi_hmem_iface cmp_iface; uint64_t buf_device = 0; uint64_t cmp_device; size_t datatype_sz = ofi_datatype_size(msg->datatype); size_t buf_len = 0; size_t cmp_len = 0; size_t data_len, tot_len; ssize_t ret; int i; assert(msg->iov_count <= RXM_IOV_LIMIT && msg->rma_iov_count <= RXM_IOV_LIMIT); if (flags & FI_REMOTE_CQ_DATA) { FI_WARN(&rxm_prov, FI_LOG_EP_DATA, "atomic with remote CQ data not supported\n"); return -FI_EINVAL; } if (msg->op != FI_ATOMIC_READ) { assert(msg->msg_iov); ofi_ioc_to_iov(msg->msg_iov, buf_iov, msg->iov_count, datatype_sz); buf_len = ofi_total_iov_len(buf_iov, msg->iov_count); buf_iface = rxm_mr_desc_to_hmem_iface_dev(msg->desc, msg->iov_count, &buf_device); } if (op == ofi_op_atomic_compare) { assert(comparev); ofi_ioc_to_iov(comparev, cmp_iov, compare_iov_count, datatype_sz); cmp_len = ofi_total_iov_len(cmp_iov, compare_iov_count); assert(buf_len == cmp_len); cmp_iface = rxm_mr_desc_to_hmem_iface_dev(compare_desc, compare_iov_count, &cmp_device); } data_len = buf_len + cmp_len + sizeof(struct rxm_atomic_hdr); tot_len = data_len + sizeof(struct rxm_pkt); if (tot_len > rxm_packet_size) { FI_WARN(&rxm_prov, FI_LOG_EP_DATA, "atomic data too large %zu\n", tot_len); return -FI_EINVAL; } tx_buf = rxm_get_tx_buf(rxm_ep); if (!tx_buf) return -FI_EAGAIN; rxm_ep_format_atomic_pkt_hdr(rxm_conn, tx_buf, data_len, op, msg->datatype, msg->op, flags, msg->data, msg->rma_iov, msg->rma_iov_count); tx_buf->pkt.ctrl_hdr.msg_id = ofi_buf_index(tx_buf); tx_buf->app_context = msg->context; atomic_hdr = (struct rxm_atomic_hdr *) tx_buf->pkt.data; ret = ofi_copy_from_hmem_iov(atomic_hdr->data, buf_len, buf_iface, buf_device, buf_iov, msg->iov_count, 0); assert(ret == buf_len); if (cmp_len) { ret = ofi_copy_from_hmem_iov(atomic_hdr->data + buf_len, cmp_len, cmp_iface, cmp_device, cmp_iov, compare_iov_count, 0); assert(ret == cmp_len); } tx_buf->atomic_result.count = result_iov_count; if (resultv) { ofi_ioc_to_iov(resultv, tx_buf->atomic_result.iov, result_iov_count, datatype_sz); if (result_desc) { for (i = 0; i < result_iov_count; i++) tx_buf->atomic_result.desc[i] = result_desc[i]; } } ret = rxm_ep_send_atomic_req(rxm_ep, rxm_conn, tx_buf, tot_len); if (ret) rxm_free_rx_buf(rxm_ep, tx_buf); return ret; } static ssize_t rxm_ep_generic_atomic_writemsg(struct rxm_ep *rxm_ep, const struct fi_msg_atomic *msg, uint64_t flags) { struct rxm_conn *rxm_conn; ssize_t ret; ofi_ep_lock_acquire(&rxm_ep->util_ep); ret = rxm_get_conn(rxm_ep, msg->addr, &rxm_conn); if (ret) goto unlock; ret = rxm_ep_atomic_common(rxm_ep, rxm_conn, msg, NULL, NULL, 0, NULL, NULL, 0, ofi_op_atomic, flags); unlock: ofi_ep_lock_release(&rxm_ep->util_ep); return ret; } static ssize_t rxm_ep_atomic_writemsg(struct fid_ep *ep_fid, const struct fi_msg_atomic *msg, uint64_t flags) { struct rxm_ep *rxm_ep = container_of(ep_fid, struct rxm_ep, util_ep.ep_fid.fid); return rxm_ep_generic_atomic_writemsg(rxm_ep, msg, flags | rxm_ep->util_ep.tx_msg_flags); } static ssize_t rxm_ep_atomic_writev(struct fid_ep *ep_fid, const struct fi_ioc *iov, void **desc, size_t count, fi_addr_t dest_addr, uint64_t addr, uint64_t key, enum fi_datatype datatype, enum fi_op op, void *context) { struct rxm_ep *rxm_ep = container_of(ep_fid, struct rxm_ep, util_ep.ep_fid.fid); struct fi_rma_ioc rma_iov = { .addr = addr, .count = ofi_total_ioc_cnt(iov, count), .key = key, }; struct fi_msg_atomic msg = { .msg_iov = iov, .desc = desc, .iov_count = count, .addr = dest_addr, .rma_iov = &rma_iov, .rma_iov_count = 1, .datatype = datatype, .op = op, .context = context, .data = 0, }; return rxm_ep_generic_atomic_writemsg(rxm_ep, &msg, rxm_ep->util_ep.tx_op_flags); } static ssize_t rxm_ep_atomic_write(struct fid_ep *ep_fid, const void *buf, size_t count, void *desc, fi_addr_t dest_addr, uint64_t addr, uint64_t key, enum fi_datatype datatype, enum fi_op op, void *context) { const struct fi_ioc iov = { .addr = (void *) buf, .count = count, }; return rxm_ep_atomic_writev(ep_fid, &iov, &desc, 1, dest_addr, addr, key, datatype, op, context); } static ssize_t rxm_ep_atomic_inject(struct fid_ep *ep_fid, const void *buf, size_t count, fi_addr_t dest_addr, uint64_t addr, uint64_t key, enum fi_datatype datatype, enum fi_op op) { struct rxm_ep *rxm_ep = container_of(ep_fid, struct rxm_ep, util_ep.ep_fid.fid); struct fi_ioc msg_iov = { .addr = (void *) buf, .count = count, }; struct fi_rma_ioc rma_iov = { .addr = addr, .count = count, .key = key, }; struct fi_msg_atomic msg = { .msg_iov = &msg_iov, .desc = NULL, .iov_count = 1, .addr = dest_addr, .rma_iov = &rma_iov, .rma_iov_count = 1, .datatype = datatype, .op = op, .context = NULL, .data = 0, }; return rxm_ep_generic_atomic_writemsg(rxm_ep, &msg, FI_INJECT); } static ssize_t rxm_ep_generic_atomic_readwritemsg(struct rxm_ep *rxm_ep, const struct fi_msg_atomic *msg, struct fi_ioc *resultv, void **result_desc, size_t result_count, uint64_t flags) { struct rxm_conn *rxm_conn; ssize_t ret; ofi_ep_lock_acquire(&rxm_ep->util_ep); ret = rxm_get_conn(rxm_ep, msg->addr, &rxm_conn); if (ret) goto unlock; ret = rxm_ep_atomic_common(rxm_ep, rxm_conn, msg, NULL, NULL, 0, resultv, result_desc, result_count, ofi_op_atomic_fetch, flags); unlock: ofi_ep_lock_release(&rxm_ep->util_ep); return ret; } static ssize_t rxm_ep_atomic_readwritemsg(struct fid_ep *ep_fid, const struct fi_msg_atomic *msg, struct fi_ioc *resultv, void **result_desc, size_t result_count, uint64_t flags) { struct rxm_ep *rxm_ep = container_of(ep_fid, struct rxm_ep, util_ep.ep_fid.fid); return rxm_ep_generic_atomic_readwritemsg(rxm_ep, msg, resultv, result_desc, result_count, flags | rxm_ep->util_ep.tx_msg_flags); } static ssize_t rxm_ep_atomic_readwritev(struct fid_ep *ep_fid, const struct fi_ioc *iov, void **desc, size_t count, struct fi_ioc *resultv, void **result_desc, size_t result_count, fi_addr_t dest_addr, uint64_t addr, uint64_t key, enum fi_datatype datatype, enum fi_op op, void *context) { struct rxm_ep *rxm_ep = container_of(ep_fid, struct rxm_ep, util_ep.ep_fid.fid); struct fi_rma_ioc rma_iov = { .addr = addr, .count = ofi_total_ioc_cnt(iov, count), .key = key, }; struct fi_msg_atomic msg = { .msg_iov = iov, .desc = desc, .iov_count = count, .addr = dest_addr, .rma_iov = &rma_iov, .rma_iov_count = 1, .datatype = datatype, .op = op, .context = context, .data = 0, }; return rxm_ep_generic_atomic_readwritemsg(rxm_ep, &msg, resultv, result_desc, result_count, rxm_ep->util_ep.tx_op_flags); } static ssize_t rxm_ep_atomic_readwrite(struct fid_ep *ep_fid, const void *buf, size_t count, void *desc, void *result, void *result_desc, fi_addr_t dest_addr, uint64_t addr, uint64_t key, enum fi_datatype datatype, enum fi_op op, void *context) { struct fi_ioc iov = { .addr = (op == FI_ATOMIC_READ) ? NULL : (void *) buf, .count = count, }; struct fi_ioc result_iov = { .addr = result, .count = count, }; if (!buf && op != FI_ATOMIC_READ) return -FI_EINVAL; return rxm_ep_atomic_readwritev(ep_fid, &iov, &desc, 1, &result_iov, &result_desc, 1, dest_addr, addr, key, datatype, op, context); } static ssize_t rxm_ep_generic_atomic_compwritemsg(struct rxm_ep *rxm_ep, const struct fi_msg_atomic *msg, const struct fi_ioc *comparev, void **compare_desc, size_t compare_count, struct fi_ioc *resultv, void **result_desc, size_t result_count, uint64_t flags) { struct rxm_conn *rxm_conn; ssize_t ret; ofi_ep_lock_acquire(&rxm_ep->util_ep); ret = rxm_get_conn(rxm_ep, msg->addr, &rxm_conn); if (ret) goto unlock; ret = rxm_ep_atomic_common(rxm_ep, rxm_conn, msg, comparev, compare_desc, compare_count, resultv, result_desc, result_count, ofi_op_atomic_compare, flags); unlock: ofi_ep_lock_release(&rxm_ep->util_ep); return ret; } static ssize_t rxm_ep_atomic_compwritemsg(struct fid_ep *ep_fid, const struct fi_msg_atomic *msg, const struct fi_ioc *comparev, void **compare_desc, size_t compare_count, struct fi_ioc *resultv, void **result_desc, size_t result_count, uint64_t flags) { struct rxm_ep *rxm_ep = container_of(ep_fid, struct rxm_ep, util_ep.ep_fid.fid); return rxm_ep_generic_atomic_compwritemsg(rxm_ep, msg, comparev, compare_desc, compare_count, resultv, result_desc, result_count, flags | rxm_ep->util_ep.tx_msg_flags); } static ssize_t rxm_ep_atomic_compwritev(struct fid_ep *ep_fid, const struct fi_ioc *iov, void **desc, size_t count, const struct fi_ioc *comparev, void **compare_desc, size_t compare_count, struct fi_ioc *resultv, void **result_desc, size_t result_count, fi_addr_t dest_addr, uint64_t addr, uint64_t key, enum fi_datatype datatype, enum fi_op op, void *context) { struct rxm_ep *rxm_ep = container_of(ep_fid, struct rxm_ep, util_ep.ep_fid.fid); struct fi_rma_ioc rma_iov = { .addr = addr, .count = ofi_total_ioc_cnt(iov, count), .key = key, }; struct fi_msg_atomic msg = { .msg_iov = iov, .desc = desc, .iov_count = count, .addr = dest_addr, .rma_iov = &rma_iov, .rma_iov_count = 1, .datatype = datatype, .op = op, .context = context, .data = 0, }; return rxm_ep_generic_atomic_compwritemsg(rxm_ep, &msg, comparev, compare_desc, compare_count, resultv, result_desc, result_count, rxm_ep->util_ep.tx_op_flags); } static ssize_t rxm_ep_atomic_compwrite(struct fid_ep *ep_fid, const void *buf, size_t count, void *desc, const void *compare, void *compare_desc, void *result, void *result_desc, fi_addr_t dest_addr, uint64_t addr, uint64_t key, enum fi_datatype datatype, enum fi_op op, void *context) { struct fi_ioc iov = { .addr = (void *) buf, .count = count, }; struct fi_ioc resultv = { .addr = result, .count = count, }; struct fi_ioc comparev = { .addr = (void *) compare, .count = count, }; return rxm_ep_atomic_compwritev(ep_fid, &iov, &desc, 1, &comparev, &compare_desc, 1, &resultv, &result_desc, 1, dest_addr, addr, key, datatype, op, context); } int rxm_ep_query_atomic(struct fid_domain *domain, enum fi_datatype datatype, enum fi_op op, struct fi_atomic_attr *attr, uint64_t flags) { struct rxm_domain *rxm_domain = container_of(domain, struct rxm_domain, util_domain.domain_fid); size_t tot_size; int ret; if (flags & FI_TAGGED) { FI_WARN(&rxm_prov, FI_LOG_EP_DATA, "tagged atomic op not supported\n"); return -FI_EINVAL; } ret = ofi_atomic_valid(&rxm_prov, datatype, op, flags); if (ret || !attr) return ret; tot_size = flags & FI_COMPARE_ATOMIC ? rxm_domain->max_atomic_size / 2 : rxm_domain->max_atomic_size; attr->size = ofi_datatype_size(datatype); attr->count = tot_size / attr->size; if (attr->count == 0) return -FI_EOPNOTSUPP; return FI_SUCCESS; } static int rxm_ep_atomic_valid(struct fid_ep *ep_fid, enum fi_datatype datatype, enum fi_op op, size_t *count) { struct rxm_ep *rxm_ep = container_of(ep_fid, struct rxm_ep, util_ep.ep_fid); struct fi_atomic_attr attr; int ret; ret = rxm_ep_query_atomic(&rxm_ep->util_ep.domain->domain_fid, datatype, op, &attr, 0); if (!ret) *count = attr.count; return ret; } static int rxm_ep_atomic_fetch_valid(struct fid_ep *ep_fid, enum fi_datatype datatype, enum fi_op op, size_t *count) { struct rxm_ep *rxm_ep = container_of(ep_fid, struct rxm_ep, util_ep.ep_fid); struct fi_atomic_attr attr; int ret; ret = rxm_ep_query_atomic(&rxm_ep->util_ep.domain->domain_fid, datatype, op, &attr, FI_FETCH_ATOMIC); if (!ret) *count = attr.count; return ret; } static int rxm_ep_atomic_cswap_valid(struct fid_ep *ep_fid, enum fi_datatype datatype, enum fi_op op, size_t *count) { struct rxm_ep *rxm_ep = container_of(ep_fid, struct rxm_ep, util_ep.ep_fid); struct fi_atomic_attr attr; int ret; ret = rxm_ep_query_atomic(&rxm_ep->util_ep.domain->domain_fid, datatype, op, &attr, FI_COMPARE_ATOMIC); if (!ret) *count = attr.count; return ret; } struct fi_ops_atomic rxm_ops_atomic = { .size = sizeof(struct fi_ops_atomic), .write = rxm_ep_atomic_write, .writev = rxm_ep_atomic_writev, .writemsg = rxm_ep_atomic_writemsg, .inject = rxm_ep_atomic_inject, .readwrite = rxm_ep_atomic_readwrite, .readwritev = rxm_ep_atomic_readwritev, .readwritemsg = rxm_ep_atomic_readwritemsg, .compwrite = rxm_ep_atomic_compwrite, .compwritev = rxm_ep_atomic_compwritev, .compwritemsg = rxm_ep_atomic_compwritemsg, .writevalid = rxm_ep_atomic_valid, .readwritevalid = rxm_ep_atomic_fetch_valid, .compwritevalid = rxm_ep_atomic_cswap_valid, };
zjjzmw1/ZMWCustomView
ZMWCustomView/Utils/CustomLabel.h
<filename>ZMWCustomView/Utils/CustomLabel.h // // DJLabel.h // zhangmingwei // // Created by 张 on 14-3-18. // Copyright (c) 2014年 zhangmingwei. All rights reserved. // #import <UIKit/UIKit.h> @interface CustomLabel : UILabel @property (nonatomic, assign) UIEdgeInsets insets; - (id)initWithFrame:(CGRect)frame fontSize:(float)fontSize alignment:(NSTextAlignment)alignment textColor:(UIColor *)textColor; -(UILabel *)updateWithText:(NSString *)text specialTextColor:(UIColor *)specialColor range:(NSRange)range ; @end
BeamMW/plugin-red-envelope
wallet/rpc-post.go
<reponame>BeamMW/plugin-red-envelope<filename>wallet/rpc-post.go<gh_stars>1-10 package wallet import ( "bytes" "encoding/json" "fmt" "github.com/BeamMW/plugin-red-envelope/jsonrpc" "io/ioutil" "net/http" ) type JsonParams map[string]interface{} func (api *API) rpcPost(method string, params interface{}) (res *json.RawMessage, err error) { var pbytes []byte if pbytes, err = json.Marshal(params); err != nil { return } rawId := json.RawMessage(`"http-dummy"`) rawParams := json.RawMessage(pbytes) request := jsonrpc.RequestHeader { Jsonrpc: "2.0", Id: &rawId, Method: method, Params: &rawParams, } var rbytes []byte if rbytes, err = json.Marshal(request); err != nil { return } var rbuffer = bytes.NewBuffer(rbytes) var resp *http.Response if resp, err = http.Post(api.Address, "application/json", rbuffer); err != nil { return } defer resp.Body.Close() var body []byte if body, err = ioutil.ReadAll(resp.Body); err != nil { return } var rpcr jsonrpc.ResponseHeader if err = json.Unmarshal(body, &rpcr); err != nil { return } if rpcr.Error != nil { err = fmt.Errorf("jsonrpc error: %s", string(*rpcr.Error)) return } res = rpcr.Result return }
ioannis-mylonas/orange-talents-03-template-ecommerce
src/main/java/bootcamp/mercado/produto/compra/gateway/GatewayList.java
package bootcamp.mercado.produto.compra.gateway; import org.springframework.stereotype.Component; import java.util.Collection; import java.util.Optional; @Component public class GatewayList { private Collection<Gateway> gateways; public GatewayList(Collection<Gateway> gateways) { this.gateways = gateways; } public Optional<Gateway> getGateway(String nome) { return gateways.stream() .filter(i -> i.isGateway(nome)) .findFirst(); } public Boolean exists(String nome) { return gateways.stream() .anyMatch(i -> i.isGateway(nome)); } }
w181496/OJ
TIOJ/1023.cpp
#include <iostream> #include <algorithm> #include <vector> using namespace std; int main() { int t; while(cin>>t) { vector<int> n1; vector<int> n2; long long int sum=0,e; for(int i=0;i<t;i++) { cin>>e; n1.push_back(e); } for(int i=0;i<t;i++) { cin>>e; n2.push_back(e); } sort(n1.begin(),n1.end()); sort(n2.begin(),n2.end()); for(int i=t-1;i>=0;i--) { sum+=n1[i]*n2[i]; } cout<<sum<<endl; } return 0; }
sourcery-ai-bot/factom-core
p2p/parcel.py
<reponame>sourcery-ai-bot/factom-core from enum import IntEnum, unique @unique class ParcelType(IntEnum): HEART_BEAT = 0 # Deprecated PING = 1 # Sent if no other parcels have been sent in a while PONG = 2 # Response to a ping PEER_REQUEST = 3 # Indicates a peer wants to be updated of endpoints PEER_RESPONSE = 4 # Carries a payload with protocol specific endpoints ALERT = 5 # Deprecated MESSAGE = 6 # Carries an application message in the payload MESSAGE_PART = 7 # Deprecated HANDSHAKE = 8 # The first parcel sent after making a connection @classmethod def is_valid(cls, value: int) -> bool: """ Test if a given integer is a valid ParcelType :param value: the integer to test validity :return: `True` if specified `value` is a valid ParcelType """ return any(value == item.value for item in cls) class Parcel: BROADCAST_ADDRESS = "<BROADCAST>" FULL_BROADCAST_ADDRESS = "<FULLBORADCAST>" RANDOM_PEER_ADDRESS = "<RANDOMPEER>" def __init__(self, parcel_type: ParcelType, address: str, payload: bytes): """ The raw data interface between the network, the p2p package, and the application. """ if not ParcelType.is_valid(parcel_type): raise ValueError("Invalid parcel_type provided") elif type(address) is str and address is not None: raise ValueError("address must be a string or None") elif type(payload) is not bytes or len(payload) == 0: raise ValueError("payload must be a bytes object of non-zero length") self.parcel_type = parcel_type # 2 bytes - network level commands self.address = address # ? bytes - "" or None for broadcast, otherwise the destination peer's hash self.payload = payload def is_application_message(self) -> bool: return self.parcel_type in {ParcelType.MESSAGE, ParcelType.MESSAGE_PART} def __str__(self): return '{}(payload_size={})'.format(self.__class__.__name__, self.parcel_type, len(self.payload))
RoubyTerenui/Casse-Brique
html/search/files_a.js
var searchData= [ ['ui_5fmainwindow_2eh',['ui_mainwindow.h',['../ui__mainwindow_8h.html',1,'']]] ];
ninaandrup/flix
main/src/ca/uwaterloo/flix/language/phase/unification/BoolTable.scala
<filename>main/src/ca/uwaterloo/flix/language/phase/unification/BoolTable.scala /* * Copyright 2022 <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 ca.uwaterloo.flix.language.phase.unification import ca.uwaterloo.flix.api.Flix import ca.uwaterloo.flix.language.ast.{Kind, Symbol, Type} import ca.uwaterloo.flix.language.phase.unification.BoolFormula._ import ca.uwaterloo.flix.util.{InternalCompilerException, LocalResource, StreamOps} import ca.uwaterloo.flix.util.collection.Bimap import java.io.IOException import java.util.zip.ZipInputStream import scala.annotation.tailrec import scala.collection.immutable.SortedSet /** * A Boolean minimization technique that uses on pre-computed tables of minimal formulas. * * We pre-compute (offline) a table of all formulas of up to `MaxVars` variables and * enumerate their minimal formula. * * We use this table to lookup the minimal formula of a given formula. */ object BoolTable { /** * A flag used to control whether to print debug information. */ private val Debug: Boolean = false /** * The path to the table. */ private val Path: String = "/src/ca/uwaterloo/flix/language/phase/unification/Table4.pn.zip" /** * The number of variables that the minimization table uses. * * Warning: If the number is set incorrectly minimization will be wrong! */ private val MaxVars: Int = 4 /** * The size a formula (but represented as a type) must have before we try to minimize it. */ private val Threshold: Int = 10 /** * A Boolean variable is represented by a unique number. */ private type Variable = Int /** * A table that maps Boolean semantic functions to their minimal formulas. * * The table is pre-computed and initialized when this class is loaded. */ private lazy val Table: Array[BoolFormula] = initTable() /** * Attempts to minimize the given Boolean formula `tpe`. * * Returns the same formula or a smaller formula that is equivalent. */ def minimizeType(tpe: Type)(implicit flix: Flix): Type = { // Check whether minimization via tabling is disabled. if (flix.options.xnobooltable) { return tpe } // Check that the `tpe` argument is a Boolean formula. if (tpe.kind != Kind.Bool) { throw InternalCompilerException(s"Unexpected non-Bool kind: '${tpe.kind}'.") } // Compute the size of `tpe`. val currentSize = tpe.size // Return `tpe` immediately if it is "small". if (currentSize < Threshold) { return tpe } // Compute the variables in `tpe`. val tvars = tpe.typeVars.map(_.sym).toList // Construct a bi-directional map from type variables to indices. // The idea is that the first variable becomes x0, the next x1, and so forth. val m = tvars.zipWithIndex.foldLeft(Bimap.empty[Symbol.KindedTypeVarSym, Variable]) { case (macc, (sym, x)) => macc + (sym -> x) } // Convert the type `tpe` to a Boolean formula. val input = fromType(tpe, m) // Minimize the Boolean formula. val minimized = minimizeFormula(input) // Convert the formula back to a type. toType(minimized, m, tpe.loc) } /** * Attempts to minimize the given formula `f`. * * Returns the same formula or a smaller formula. */ def minimizeFormula(f: BoolFormula): BoolFormula = { // Compute the number of free variables. val numVars = f.freeVars.size // Determine whether to minimize once or recursively. val result = if (numVars <= MaxVars) { // Case 1: The number of variables in the formula is less than those of the table. // We can immediately lookup the minimal formula in the table. if (Debug) println(s"Minimize by lookup ($numVars variables)") lookup(f) } else { // Case 2: The formula has more variables than the table. // We try to recursively minimize each sub-formula. // This does not guarantee that we arrive at a minimal formula, but it is better than nothing. if (Debug) println(s"Minimize by recursion ($numVars variables)") minimizeFormulaRecursively(f)._1 } // Debugging. if (Debug) { println(s" Replace: $f") println(s" By: $result") println(s" Change: ${f.size} -> ${result.size}") println() } // Return the result. result } /** * Tries to recursively minimize the formula `f`. * * Each call returns a pair of a formula and its free variables. * * Bottom-up reconstructs a formula. Whenever we construct a conjunction or disjunction we * check whether we the number of free variables exceed those of the table. If so, we * minimize the two sub-formulas before constructing the conjunction / disjunction. * * This is not guaranteed to give a minimal representation. However, it does allow us to * use the tabling approach even when a formula overall has more variables than the table. */ private def minimizeFormulaRecursively(f: BoolFormula): (BoolFormula, SortedSet[Variable]) = f match { case True => (True, SortedSet.empty) case False => (False, SortedSet.empty) case Var(x) => (Var(x), SortedSet(x)) case Neg(formula) => val (f, fvs) = minimizeFormulaRecursively(formula) (Neg(f), fvs) case Conj(formula1, formula2) => // Recursive minimize each sub-formula. val (f1, fvs1) = minimizeFormulaRecursively(formula1) val (f2, fvs2) = minimizeFormulaRecursively(formula2) // Compute all the variables that occur in the left and right sub-formulas. val fvs = fvs1 ++ fvs2 // Determine if we must minimize. if (fvs.size <= MaxVars) { // The number of free variables does not (yet) exceed the number of variables in the table. // Consequence we do not yet minimize. We do not yet minimize in attempt to avoid a // potential quadratic blow-up where we would minimize at every level. (Conj(f1, f2), fvs) } else { // The number of variables exceeds the number of variables in the table. // We minimize both the left and right sub-formulas and then construct the conjunction. // Note: We have to recompute the variables (since a variable could get eliminated). val minf1 = alphaRenameAndLookup(f1) val minf2 = alphaRenameAndLookup(f2) (Conj(minf1, minf2), minf1.freeVars ++ minf2.freeVars) } case Disj(formula1, formula2) => // This case is similar to the above case. val (f1, fvs1) = minimizeFormulaRecursively(formula1) val (f2, fvs2) = minimizeFormulaRecursively(formula2) val fvs = fvs1 ++ fvs2 if (fvs.size <= MaxVars) { (Disj(f1, f2), fvs) } else { val minf1 = alphaRenameAndLookup(f1) val minf2 = alphaRenameAndLookup(f2) (Disj(minf1, minf2), minf1.freeVars ++ minf2.freeVars) } } /** * Renames every variable in the given formula `f` and looks it up in the minimal table. */ private def alphaRenameAndLookup(f: BoolFormula): BoolFormula = { // Compute a renaming. The first variable is x0, the next is x1, and so forth. val m = f.freeVars.toList.zipWithIndex.foldLeft(Bimap.empty[Variable, Variable]) { case (macc, (k, v)) => macc + (k -> v) } // Rename all variables, lookup the minimal formula, and then rename everything back. substitute(lookup(substitute(f, m)), m.swap) } /** * Attempts to minimize the given Boolean formula `f` using the table. */ private def lookup(f: BoolFormula): BoolFormula = { // If the formula `f` has more variables than `f` then we cannot use the table. if (f.freeVars.size > MaxVars) { // Return the same formula. return f } // Computes the semantic function of `f`. val semantic = computeSemanticFunction(f, (0 until MaxVars).toList, 0, new Array[Boolean](MaxVars)) // Lookup the semantic function in the table. Table(semantic) } /** * Computes the semantic function of the given formula `f` under the given environment `m`. * * @param f the Boolean formula. * @param fvs the list of free variables. * @param position the position in the bitvector where to store the result (true/false). * @param env the environment which binds each variable to true or false. */ private def computeSemanticFunction(f: BoolFormula, fvs: List[Variable], position: Int, env: Array[Boolean]): Int = fvs match { case Nil => if (eval(f, env)) 1 << position else 0 case x :: xs => // The environment is modified in both recursive calls, hence we copy it. // We could probably safely re-use the original array, but we choose not to. val ml = env.clone() val mr = env.clone() ml(x) = true // Bind x to true. mr(x) = false // Bind x to false. // Recurse on both environments. val l = computeSemanticFunction(f, xs, position, ml) val r = computeSemanticFunction(f, xs, position + (1 << (fvs.length - 1)), mr) // The result is the bitwise union. l | r } /** * Evaluates the given formula `f` to a Boolean value under the given environment `env`. * * The environment must bind *all* variables in `f`. * * The environment maps the variable with index i to true or false. */ private def eval(f: BoolFormula, env: Array[Boolean]): Boolean = f match { case True => true case False => false case Var(x) => env(x) case Neg(f) => !eval(f, env) case Conj(f1, f2) => eval(f1, env) && eval(f2, env) case Disj(f1, f2) => eval(f1, env) || eval(f2, env) } /** * Parses the built-in table into an S-expression and then into an in-memory table. */ private def initTable(): Array[BoolFormula] = { val table = loadTable() if (Debug) { println("== Minimization Array ==") println() for (i <- table.indices) { println(s" ${toBinaryString(i, 1 << MaxVars)}: ${table(i)}") } println(s"Total Array Size = ${table.length}") println() } table } /** * Loads the table of minimal Boolean formulas from the disk. */ private def loadTable(): Array[BoolFormula] = try { val allLines = readTableFromZip(Path) // Split the string into lines. val lines = allLines.split("\n") // Parse each line into a formula. val formulas = lines.map(parseLine) // Allocate the result table. The table has size 2^(2^MaxVars). val table = new Array[BoolFormula](1 << (1 << MaxVars)) // Fill the table. for ((f, i) <- formulas.zipWithIndex) { table(i) = f } // Return the table. table } catch { case ex: IOException => throw InternalCompilerException(s"Unable to load Boolean minimization table: '$Path'.") } /** * Attempts to read the given `path` as a local resource which is a zip-file. * * Returns the first zip-entry as a string. */ private def readTableFromZip(path: String): String = { val inputStream = LocalResource.getInputStream(path) val zipIn = new ZipInputStream(inputStream) val entry = zipIn.getNextEntry StreamOps.readAll(zipIn) } /** * Parses the given line `l` into a Boolean formula. * * The format is in reverse polish notation: * * 301a2oa should be interpreted as: * * x3 x0 x1 and x2 or and, that is: * and(x3,or(and(x0,x1),x2)) * */ private def parseLine(l: String): BoolFormula = { @tailrec def parse(input: List[Char], stack: List[BoolFormula]): BoolFormula = (input, stack) match { case (Nil, formula :: Nil) => formula case ('T' :: rest, stack) => parse(rest, True :: stack) case ('F' :: rest, stack) => parse(rest, False :: stack) case ('0' :: rest, stack) => parse(rest, Var(0) :: stack) case ('1' :: rest, stack) => parse(rest, Var(1) :: stack) case ('2' :: rest, stack) => parse(rest, Var(2) :: stack) case ('3' :: rest, stack) => parse(rest, Var(3) :: stack) case ('n' :: rest, f :: stack) => parse(rest, Neg(f) :: stack) case ('a' :: rest, f2 :: f1 :: stack) => parse(rest, Conj(f1, f2) :: stack) case ('o' :: rest, f2 :: f1 :: stack) => parse(rest, Disj(f1, f2) :: stack) case _ => throw InternalCompilerException(s"Parse Error. input = ${input.mkString(" :: ")}, stack = $stack.") } parse(l.trim().toList, Nil) } /** * Formats the given int `i` as a bit string with `n` bits. */ private def toBinaryString(i: Int, n: Int): String = leftPad(i.toBinaryString, n) /** * Left pads `s` with `c` to reach length `len`. */ private def leftPad(s: String, len: Int): String = ' '.toString * (len - s.length()) + s }
BrendanLeber/adventofcode
2015/10-look_and_say/solver.py
<gh_stars>0 #!/usr/bin/env python # -*- coding: utf-8 -*- import pdb import sys import traceback from typing import Tuple def look_and_say(sequence: str) -> str: # create a run-length list of (char, count) from the input rle = [] old_ch = sequence[0] counter = 1 for ch in sequence[1:]: if old_ch != ch: rle.append((old_ch, counter)) old_ch = ch counter = 1 else: counter += 1 rle.append((old_ch, counter)) # build the new say sequence from the character counts result = [] for ch, count in rle: result.append(str(count)) result.append(ch) # reassemble into a string as required by the specification result = "".join(result) return result def solve(number: str) -> Tuple[int, int]: part_1 = number for _ in range(40): part_1 = look_and_say(part_1) part_2 = part_1 for _ in range(10): part_2 = look_and_say(part_2) return (len(part_1), len(part_2)) if __name__ == "__main__": try: print(solve(sys.argv[1])) except Exception: traceback.print_exc() pdb.post_mortem()
alwell-kevin/gitlab
ee/spec/lib/ee/gitlab/usage_data_spec.rb
# frozen_string_literal: true require 'spec_helper' describe Gitlab::UsageData do before do allow(ActiveRecord::Base.connection).to receive(:transaction_open?).and_return(false) end describe '#data' do # using Array.new to create a different creator User for each of the projects let_it_be(:projects) { Array.new(3) { create(:project, :repository, creator: create(:user, group_view: :security_dashboard)) } } let(:count_data) { subject[:counts] } let_it_be(:board) { create(:board, project: projects[0]) } before_all do projects.last.creator.block # to get at least one non-active User pipeline = create(:ci_pipeline, project: projects[0]) create(:ci_build, name: 'container_scanning', pipeline: pipeline) create(:ci_build, name: 'dast', pipeline: pipeline) create(:ci_build, name: 'dependency_scanning', pipeline: pipeline) create(:ci_build, name: 'license_management', pipeline: pipeline) create(:ee_ci_build, name: 'license_scanning', pipeline: pipeline) create(:ci_build, name: 'sast', pipeline: pipeline) create(:prometheus_alert, project: projects[0]) create(:prometheus_alert, project: projects[0]) create(:prometheus_alert, project: projects[1]) create(:service, project: projects[1], type: 'JenkinsService', active: true) create(:package, project: projects[0]) create(:package, project: projects[0]) create(:package, project: projects[1]) create(:project_tracing_setting, project: projects[0]) create(:operations_feature_flag, project: projects[0]) create(:issue, project: projects[1]) create(:issue, health_status: :on_track, project: projects[1]) create(:issue, health_status: :at_risk, project: projects[1]) # for group_view testing create(:user) # user with group_view = NULL (should be counted as having default value 'details') create(:user, group_view: :details) # Status Page create(:status_page_setting, project: projects[0], enabled: true) create(:status_page_setting, project: projects[1], enabled: false) # 1 public issue on 1 projects with status page enabled create(:issue, project: projects[0]) create(:issue, :confidential, project: projects[0]) end subject { described_class.data } it 'gathers usage data' do expect(subject.keys).to include(*%i( historical_max_users license_add_ons license_plan license_expires_at license_starts_at license_user_count license_trial licensee license_md5 license_id elasticsearch_enabled geo_enabled license_trial_ends_on )) end it 'gathers usage counts', :aggregate_failures do expect(count_data[:boards]).to eq(1) expect(count_data[:projects]).to eq(3) expect(count_data.keys).to include(*%i( container_scanning_jobs dast_jobs dependency_list_usages_total dependency_scanning_jobs epics epics_deepest_relationship_level feature_flags geo_nodes issues_with_health_status ldap_group_links ldap_keys ldap_users license_management_jobs licenses_list_views operations_dashboard_default_dashboard operations_dashboard_users_with_projects_added pod_logs_usages_total projects_jenkins_active projects_jira_dvcs_cloud_active projects_jira_dvcs_server_active projects_mirrored_with_pipelines_enabled projects_reporting_ci_cd_back_to_github projects_with_packages projects_with_prometheus_alerts projects_with_tracing_enabled sast_jobs status_page_projects status_page_issues design_management_designs_create design_management_designs_update design_management_designs_delete user_preferences_group_overview_details user_preferences_group_overview_security_dashboard template_repositories )) expect(count_data[:projects_jenkins_active]).to eq(1) expect(count_data[:projects_with_prometheus_alerts]).to eq(2) expect(count_data[:projects_with_packages]).to eq(2) expect(count_data[:feature_flags]).to eq(1) expect(count_data[:status_page_projects]).to eq(1) expect(count_data[:status_page_issues]).to eq(1) expect(count_data[:issues_with_health_status]).to eq(2) end it 'has integer value for epic relationship level' do expect(count_data[:epics_deepest_relationship_level]).to be_a_kind_of(Integer) end it 'has integer values for all counts' do expect(count_data.values).to all(be_a_kind_of(Integer)) end it 'gathers security products usage data' do expect(count_data[:container_scanning_jobs]).to eq(1) expect(count_data[:dast_jobs]).to eq(1) expect(count_data[:dependency_scanning_jobs]).to eq(1) expect(count_data[:license_management_jobs]).to eq(2) expect(count_data[:sast_jobs]).to eq(1) end it 'correctly shows failure for combined license management' do allow(Gitlab::Database::BatchCount).to receive(:batch_count).and_raise(ActiveRecord::StatementInvalid) expect(count_data[:license_management_jobs]).to eq(-1) end it 'gathers group overview preferences usage data', :aggregate_failures do expect(subject[:counts][:user_preferences_group_overview_details]).to eq(User.active.count - 2) # we have exactly 2 active users with security dashboard set expect(subject[:counts][:user_preferences_group_overview_security_dashboard]).to eq 2 end end describe '#features_usage_data_ee' do subject { described_class.features_usage_data_ee } it 'gathers feature usage data of EE' do expect(subject[:elasticsearch_enabled]).to eq(Gitlab::CurrentSettings.elasticsearch_search?) expect(subject[:geo_enabled]).to eq(Gitlab::Geo.enabled?) expect(subject[:license_trial_ends_on]).to eq(License.trial_ends_on) end end describe '#license_usage_data' do subject { described_class.license_usage_data } it 'gathers license data' do license = ::License.current expect(subject[:license_md5]).to eq(Digest::MD5.hexdigest(license.data)) expect(subject[:license_id]).to eq(license.license_id) expect(subject[:historical_max_users]).to eq(::HistoricalData.max_historical_user_count) expect(subject[:licensee]).to eq(license.licensee) expect(subject[:license_user_count]).to eq(license.restricted_user_count) expect(subject[:license_starts_at]).to eq(license.starts_at) expect(subject[:license_expires_at]).to eq(license.expires_at) expect(subject[:license_add_ons]).to eq(license.add_ons) expect(subject[:license_trial]).to eq(license.trial?) end end describe '.service_desk_counts' do subject { described_class.service_desk_counts } context 'when Service Desk is disabled' do it 'returns an empty hash' do stub_licensed_features(service_desk: false) expect(subject).to eq({}) end end context 'when there is no license' do it 'returns an empty hash' do allow(License).to receive(:current).and_return(nil) expect(subject).to eq({}) end end context 'when Service Desk is enabled' do let(:project) { create(:project, :service_desk_enabled) } it 'gathers Service Desk data' do create_list(:issue, 2, confidential: true, author: User.support_bot, project: project) stub_licensed_features(service_desk: true) allow(::EE::Gitlab::ServiceDesk).to receive(:enabled?).with(anything).and_return(true) expect(subject).to eq(service_desk_enabled_projects: 1, service_desk_issues: 2) end end end describe 'code owner approval required' do before do create(:protected_branch, code_owner_approval_required: true) create(:protected_branch, code_owner_approval_required: true, project: create(:project, :archived)) create(:protected_branch, code_owner_approval_required: true, project: create(:project, pending_delete: true)) end it 'counts the projects actively requiring code owner approval' do expect(described_class.system_usage_data[:counts][:projects_enforcing_code_owner_approval]).to eq(1) end end describe '#operations_dashboard_usage' do subject { described_class.operations_dashboard_usage } before_all do blocked_user = create(:user, :blocked, dashboard: 'operations') user_with_ops_dashboard = create(:user, dashboard: 'operations') create(:users_ops_dashboard_project, user: blocked_user) create(:users_ops_dashboard_project, user: user_with_ops_dashboard) create(:users_ops_dashboard_project, user: user_with_ops_dashboard) create(:users_ops_dashboard_project) end it 'gathers data on operations dashboard' do expect(subject.keys).to include(*%i( operations_dashboard_default_dashboard operations_dashboard_users_with_projects_added )) end it 'bases counts on active users', :aggregate_failures do expect(subject[:operations_dashboard_default_dashboard]).to eq(1) expect(subject[:operations_dashboard_users_with_projects_added]).to eq(2) end end [true, false].each do |usage_ping_batch_counter_on| describe "when the feature flag usage_ping_batch_counter is set to #{usage_ping_batch_counter_on}" do before do stub_feature_flags(usage_ping_batch_counter: usage_ping_batch_counter_on) end describe '.uncached_data' do context 'when the :usage_activity_by_stage feature is not enabled' do before do stub_feature_flags(usage_activity_by_stage: false) end it "does not include usage_activity_by_stage data" do expect(described_class.uncached_data).not_to include(:usage_activity_by_stage) expect(described_class.uncached_data).not_to include(:usage_activity_by_stage_monthly) end end context 'when the :usage_activity_by_stage feature is enabled' do it 'includes usage_activity_by_stage data' do expect(described_class.uncached_data).to include(:usage_activity_by_stage) expect(described_class.uncached_data).to include(:usage_activity_by_stage_monthly) end context 'for configure' do it 'includes accurate usage_activity_by_stage data' do for_defined_days_back do user = create(:user) cluster = create(:cluster, user: user) project = create(:project, creator: user) create(:clusters_applications_cert_manager, :installed, cluster: cluster) create(:clusters_applications_helm, :installed, cluster: cluster) create(:clusters_applications_ingress, :installed, cluster: cluster) create(:clusters_applications_knative, :installed, cluster: cluster) create(:cluster, :disabled, user: user) create(:cluster_provider_gcp, :created) create(:cluster_provider_aws, :created) create(:cluster_platform_kubernetes) create(:cluster, :group, :disabled, user: user) create(:cluster, :group, user: user) create(:cluster, :instance, :disabled, :production_environment) create(:cluster, :instance, :production_environment) create(:cluster, :management_project) create(:slack_service, project: project) create(:slack_slash_commands_service, project: project) create(:prometheus_service, project: project) end expect(described_class.uncached_data[:usage_activity_by_stage][:configure]).to eq( clusters_applications_cert_managers: 2, clusters_applications_helm: 2, clusters_applications_ingress: 2, clusters_applications_knative: 2, clusters_management_project: 2, clusters_disabled: 4, clusters_enabled: 12, clusters_platforms_gke: 2, clusters_platforms_eks: 2, clusters_platforms_user: 2, instance_clusters_disabled: 2, instance_clusters_enabled: 2, group_clusters_disabled: 2, group_clusters_enabled: 2, project_clusters_disabled: 2, project_clusters_enabled: 10, projects_slack_notifications_active: 2, projects_slack_slash_active: 2, projects_with_prometheus_alerts: 2 ) expect(described_class.uncached_data[:usage_activity_by_stage_monthly][:configure]).to eq( clusters_applications_cert_managers: 1, clusters_applications_helm: 1, clusters_applications_ingress: 1, clusters_applications_knative: 1, clusters_management_project: 1, clusters_disabled: 2, clusters_enabled: 6, clusters_platforms_gke: 1, clusters_platforms_eks: 1, clusters_platforms_user: 1, instance_clusters_disabled: 1, instance_clusters_enabled: 1, group_clusters_disabled: 1, group_clusters_enabled: 1, project_clusters_disabled: 1, project_clusters_enabled: 5, projects_slack_notifications_active: 1, projects_slack_slash_active: 1, projects_with_prometheus_alerts: 1 ) end end context 'for create' do it 'includes accurate usage_activity_by_stage data' do for_defined_days_back do user = create(:user) project = create(:project, :repository_private, :github_imported, :test_repo, :remote_mirror, creator: user) merge_request = create(:merge_request, source_project: project) create(:deploy_key, user: user) create(:key, user: user) create(:project, creator: user) create(:protected_branch, project: project) create(:remote_mirror, project: project) create(:snippet, author: user) create(:suggestion, note: create(:note, project: project)) create(:code_owner_rule, merge_request: merge_request, approvals_required: 3) create(:code_owner_rule, merge_request: merge_request, approvals_required: 7) create_list(:code_owner_rule, 3, approvals_required: 2) create_list(:code_owner_rule, 2) end expect(described_class.uncached_data[:usage_activity_by_stage][:create]).to eq( deploy_keys: 2, keys: 2, merge_requests: 12, projects_enforcing_code_owner_approval: 0, merge_requests_with_optional_codeowners: 4, merge_requests_with_required_codeowners: 8, projects_imported_from_github: 2, projects_with_repositories_enabled: 12, protected_branches: 2, remote_mirrors: 2, snippets: 2, suggestions: 2 ) expect(described_class.uncached_data[:usage_activity_by_stage_monthly][:create]).to eq( deploy_keys: 1, keys: 1, merge_requests: 6, projects_enforcing_code_owner_approval: 0, merge_requests_with_optional_codeowners: 2, merge_requests_with_required_codeowners: 4, projects_imported_from_github: 1, projects_with_repositories_enabled: 6, protected_branches: 1, remote_mirrors: 1, snippets: 1, suggestions: 1 ) end end context 'for manage' do it 'includes accurate usage_activity_by_stage data' do for_defined_days_back do user = create(:user) create(:event, author: user) create(:group_member, user: user) create(:key, type: 'LDAPKey', user: user) create(:group_member, ldap: true, user: user) create(:cycle_analytics_group_stage) end expect(described_class.uncached_data[:usage_activity_by_stage][:manage]).to eq( events: 2, groups: 2, ldap_keys: 2, ldap_users: 2, users_created: 6, value_stream_management_customized_group_stages: 2 ) expect(described_class.uncached_data[:usage_activity_by_stage_monthly][:manage]).to eq( events: 1, groups: 1, ldap_keys: 1, ldap_users: 1, users_created: 4, value_stream_management_customized_group_stages: 2 ) end end context 'for monitor' do it 'includes accurate usage_activity_by_stage data' do for_defined_days_back do user = create(:user, dashboard: 'operations') cluster = create(:cluster, user: user) project = create(:project, creator: user) create(:clusters_applications_prometheus, :installed, cluster: cluster) create(:users_ops_dashboard_project, user: user) create(:prometheus_service, project: project) create(:project_error_tracking_setting, project: project) create(:project_tracing_setting, project: project) end expect(described_class.uncached_data[:usage_activity_by_stage][:monitor]).to eq( clusters: 2, clusters_applications_prometheus: 2, operations_dashboard_default_dashboard: 2, operations_dashboard_users_with_projects_added: 2, projects_prometheus_active: 2, projects_with_error_tracking_enabled: 2, projects_with_tracing_enabled: 2 ) expect(described_class.uncached_data[:usage_activity_by_stage_monthly][:monitor]).to eq( clusters: 1, clusters_applications_prometheus: 1, operations_dashboard_default_dashboard: 1, operations_dashboard_users_with_projects_added: 1, projects_prometheus_active: 1, projects_with_error_tracking_enabled: 1, projects_with_tracing_enabled: 1 ) end end context 'for package' do it 'includes accurate usage_activity_by_stage data' do for_defined_days_back do create(:project, packages: [create(:package)] ) end expect(described_class.uncached_data[:usage_activity_by_stage][:package]).to eq( projects_with_packages: 2 ) expect(described_class.uncached_data[:usage_activity_by_stage_monthly][:package]).to eq( projects_with_packages: 1 ) end end context 'for plan' do it 'includes accurate usage_activity_by_stage data' do stub_licensed_features(board_assignee_lists: true, board_milestone_lists: true) for_defined_days_back do user = create(:user) project = create(:project, creator: user) issue = create(:issue, project: project, author: User.support_bot) create(:issue, project: project, author: user) board = create(:board, project: project) create(:user_list, board: board, user: user) create(:milestone_list, board: board, milestone: create(:milestone, project: project), user: user) create(:list, board: board, label: create(:label, project: project), user: user) create(:note, project: project, noteable: issue, author: user) create(:epic, author: user) create(:todo, project: project, target: issue, author: user) create(:jira_service, :jira_cloud_service, active: true, project: create(:project, :jira_dvcs_cloud, creator: user)) create(:jira_service, active: true, project: create(:project, :jira_dvcs_server, creator: user)) end expect(described_class.uncached_data[:usage_activity_by_stage][:plan]).to eq( assignee_lists: 2, epics: 2, issues: 3, label_lists: 2, milestone_lists: 2, notes: 2, projects: 2, projects_jira_active: 2, projects_jira_dvcs_cloud_active: 2, projects_jira_dvcs_server_active: 2, service_desk_enabled_projects: 2, service_desk_issues: 2, todos: 2 ) expect(described_class.uncached_data[:usage_activity_by_stage_monthly][:plan]).to eq( assignee_lists: 1, epics: 1, issues: 2, label_lists: 1, milestone_lists: 1, notes: 1, projects: 1, projects_jira_active: 1, projects_jira_dvcs_cloud_active: 1, projects_jira_dvcs_server_active: 1, service_desk_enabled_projects: 1, service_desk_issues: 1, todos: 1 ) end end context 'for release' do it 'includes accurate usage_activity_by_stage data' do for_defined_days_back do user = create(:user) create(:deployment, :failed, user: user) create(:project, :mirror, mirror_trigger_builds: true) create(:release, author: user) create(:deployment, :success, user: user) end expect(described_class.uncached_data[:usage_activity_by_stage][:release]).to eq( deployments: 2, failed_deployments: 2, projects_mirrored_with_pipelines_enabled: 2, releases: 2, successful_deployments: 2 ) expect(described_class.uncached_data[:usage_activity_by_stage_monthly][:release]).to eq( deployments: 1, failed_deployments: 1, projects_mirrored_with_pipelines_enabled: 1, releases: 1, successful_deployments: 1 ) end end context 'for secure' do let_it_be(:user) { create(:user, group_view: :security_dashboard) } before do for_defined_days_back do create(:ci_build, name: 'container_scanning', user: user) create(:ci_build, name: 'dast', user: user) create(:ci_build, name: 'dependency_scanning', user: user) create(:ci_build, name: 'license_management', user: user) create(:ci_build, name: 'sast', user: user) end end it 'includes accurate usage_activity_by_stage data' do expect(described_class.uncached_data[:usage_activity_by_stage_monthly][:secure]).to eq( user_preferences_group_overview_security_dashboard: 1, user_container_scanning_jobs: 1, user_dast_jobs: 1, user_dependency_scanning_jobs: 1, user_license_management_jobs: 1, user_sast_jobs: 1 ) end it 'combines license_scanning into license_management' do for_defined_days_back do create(:ci_build, name: 'license_scanning', user: user) end expect(described_class.uncached_data[:usage_activity_by_stage_monthly][:secure]).to eq( user_preferences_group_overview_security_dashboard: 1, user_container_scanning_jobs: 1, user_dast_jobs: 1, user_dependency_scanning_jobs: 1, user_license_management_jobs: 2, user_sast_jobs: 1 ) end it 'has to resort to 0 for counting license scan' do allow(Gitlab::Database::BatchCount).to receive(:batch_distinct_count).and_raise(ActiveRecord::StatementInvalid) allow(::Ci::Build).to receive(:distinct_count_by).and_raise(ActiveRecord::StatementInvalid) expect(described_class.uncached_data[:usage_activity_by_stage_monthly][:secure]).to eq( user_preferences_group_overview_security_dashboard: 1, user_container_scanning_jobs: -1, user_dast_jobs: -1, user_dependency_scanning_jobs: -1, user_license_management_jobs: -1, user_sast_jobs: -1 ) end end context 'for verify' do it 'includes accurate usage_activity_by_stage data' do for_defined_days_back do user = create(:user) create(:ci_build, user: user) create(:ci_empty_pipeline, source: :external, user: user) create(:ci_empty_pipeline, user: user) create(:ci_pipeline, :auto_devops_source, user: user) create(:ci_pipeline, :repository_source, user: user) create(:ci_pipeline_schedule, owner: user) create(:ci_trigger, owner: user) create(:clusters_applications_runner, :installed) create(:github_service) end expect(described_class.uncached_data[:usage_activity_by_stage][:verify]).to eq( ci_builds: 2, ci_external_pipelines: 2, ci_internal_pipelines: 2, ci_pipeline_config_auto_devops: 2, ci_pipeline_config_repository: 2, ci_pipeline_schedules: 2, ci_pipelines: 2, ci_triggers: 2, clusters_applications_runner: 2, projects_reporting_ci_cd_back_to_github: 2 ) expect(described_class.uncached_data[:usage_activity_by_stage_monthly][:verify]).to eq( ci_builds: 1, ci_external_pipelines: 1, ci_internal_pipelines: 1, ci_pipeline_config_auto_devops: 1, ci_pipeline_config_repository: 1, ci_pipeline_schedules: 1, ci_pipelines: 1, ci_triggers: 1, clusters_applications_runner: 1, projects_reporting_ci_cd_back_to_github: 1 ) end end end end end end def for_defined_days_back(days: [29, 2]) days.each do |n| Timecop.travel(n.days.ago) do yield end end end end
threathunterX/offline
src/test/java/com/threathunter/bordercollie/slot/compute/cache/wrapper/array/SecondaryCountsArrayCacheWrapperTest.java
package com.threathunter.bordercollie.slot.compute.cache.wrapper.array; import com.threathunter.bordercollie.slot.compute.cache.CacheType; import com.threathunter.bordercollie.slot.compute.cache.StorageType; import com.threathunter.bordercollie.slot.compute.cache.storage.ByteArrayCacheStore; import com.threathunter.bordercollie.slot.compute.cache.wrapper.CacheWrapperMeta; import com.threathunter.bordercollie.slot.util.HashType; import net.agkn.hll.HLL; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.mockito.stubbing.Answer; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; /** * */ @RunWith(PowerMockRunner.class) @PrepareForTest(ByteArrayCacheStore.class) public class SecondaryCountsArrayCacheWrapperTest { private static final String KEY_1 = "key1"; private static final String KEY_2 = "key2"; private static final String SUB_KEY_1 = "subkey1"; private static final String SUB_KEY_2 = "subkey2"; private static final String SUB_KEY_3 = "subkey3"; private ByteArrayCacheStore cacheStore = PowerMockito.mock(ByteArrayCacheStore.class); private Map<String, byte[]> data = new HashMap<>(); private Map<String, HLL> hllMap = new HashMap<>(); @Before public void setUp() { PowerMockito.doAnswer((Answer<byte[]>) mockArg -> data.get(KEY_1)).when(cacheStore).getCache(KEY_1); PowerMockito.doAnswer((Answer<byte[]>) mockArg -> data.get(KEY_2)).when(cacheStore).getCache(KEY_2); PowerMockito.doAnswer((Answer<byte[]>) mockArg -> { data.put(KEY_1, new byte[2000]); return data.get(KEY_1); }).when(cacheStore).allocate(KEY_1); PowerMockito.doAnswer((Answer<byte[]>) mockArg -> { data.put(KEY_2, new byte[2000]); return data.get(KEY_2); }).when(cacheStore).allocate(KEY_2); PowerMockito.doAnswer((Answer<HLL>) mockArg -> hllMap.get(mockArg.getArguments()[0])).when(cacheStore).getHLL(Mockito.anyString()); PowerMockito.doAnswer((Answer<HLL>) invocationOnMock -> { hllMap.put((String) invocationOnMock.getArguments()[0], new HLL(13, 5)); return hllMap.get(invocationOnMock.getArguments()[0]); }).when(cacheStore).allocateHLL(Mockito.anyString()); } @Test public void testSecondaryCountArrayCache() { CacheWrapperMeta meta = new CacheWrapperMeta(); meta.setStorageType(StorageType.BYTES_ARRAY); meta.setCacheType(CacheType.SECONDARY_COUNT); meta.setSecondaryKeyHashType(HashType.NORMAL); SecondaryCountsArrayCacheWrapper.SecondaryCountArrayCacheWrapper wrapper = new SecondaryCountsArrayCacheWrapper.SecondaryCountArrayCacheWrapper(meta); wrapper.updateStoreInfo(cacheStore, 21); System.out.println(wrapper.getCacheSize()); Assert.assertEquals(1, wrapper.addData(null, KEY_1, SUB_KEY_1).intValue()); Assert.assertEquals(2, wrapper.addData(null, KEY_1, SUB_KEY_1).intValue()); Assert.assertNull(wrapper.getData(KEY_1, SUB_KEY_2)); Assert.assertNull(wrapper.getData(KEY_2, SUB_KEY_2)); List<String> inserted = new LinkedList<>(); for (int i = 0; i < 30; i++) { String key = String.format("%s_%d", SUB_KEY_2, i); if (wrapper.addData("" + i, KEY_1, key) != null) { inserted.add(key); } } System.out.println(inserted); Assert.assertEquals(2, wrapper.getData(KEY_1, SUB_KEY_1).intValue()); for (int i = 0; i < 30; i++) { String key = String.format("%s_%d", SUB_KEY_2, i); if (inserted.contains(key)) { Assert.assertEquals(1, wrapper.getData(KEY_1, key).intValue()); } else { Assert.assertNull(wrapper.getData(KEY_1, SUB_KEY_2 + i)); } } Assert.assertEquals(18, inserted.size()); } @Test public void testSecondaryDistinctCountArrayCache() { CacheWrapperMeta meta = new CacheWrapperMeta(); meta.setStorageType(StorageType.BYTES_ARRAY); meta.setCacheType(CacheType.SECONDARY_DISTINCT_COUNT); meta.setSecondaryKeyHashType(HashType.NORMAL); meta.setValueHashType(HashType.NORMAL); SecondaryCountsArrayCacheWrapper.SecondaryDistinctCountArrayCacheWrapper wrapper = new SecondaryCountsArrayCacheWrapper.SecondaryDistinctCountArrayCacheWrapper(meta); wrapper.updateStoreInfo(cacheStore, 0); Assert.assertEquals(1, wrapper.addData("geo1", KEY_1, SUB_KEY_1).intValue()); Assert.assertEquals(1, wrapper.addData("geo1", KEY_1, SUB_KEY_1).intValue()); Assert.assertEquals(2, wrapper.addData("geo2", KEY_1, SUB_KEY_1).intValue()); Assert.assertEquals(2, wrapper.getData(KEY_1, SUB_KEY_1).intValue()); Assert.assertNull(wrapper.getData(KEY_1, SUB_KEY_2)); Assert.assertNull(wrapper.getData(KEY_2, SUB_KEY_2)); for (int i = 0; i < 30; i++) { String geo = String.format("%s_%d", "geo", i); wrapper.addData(geo, KEY_2, SUB_KEY_3); } Assert.assertEquals(30, wrapper.getData(KEY_2, SUB_KEY_3).intValue()); Assert.assertEquals(2, wrapper.getData(KEY_1, SUB_KEY_1).intValue()); Assert.assertNull(wrapper.getData(KEY_2, SUB_KEY_2)); } }
ckamtsikis/cmssw
TopQuarkAnalysis/TopJetCombination/python/TtFullHadHypKinFit_cff.py
import FWCore.ParameterSet.Config as cms # # produce kinFit hypothesis with all necessary # ingredients # ## std sequence to perform kinematic fit import TopQuarkAnalysis.TopKinFitter.TtFullHadKinFitProducer_cfi kinFitTtFullHadEventHypothesis = TopQuarkAnalysis.TopKinFitter.TtFullHadKinFitProducer_cfi.kinFitTtFullHadEvent.clone() ## configure kinFit hypothesis from TopQuarkAnalysis.TopJetCombination.TtFullHadHypKinFit_cfi import * ## make hypothesis makeHypothesis_kinFitTask = cms.Task( kinFitTtFullHadEventHypothesis, ttFullHadHypKinFit ) makeHypothesis_kinFit = cms.Sequence(makeHypothesis_kinFitTask)
wcharczuk/reactor
vendor/github.com/blend/go-sdk/logger/write_helpers.go
<reponame>wcharczuk/reactor package logger import ( "fmt" "io" "net/http" "time" "github.com/blend/go-sdk/ansi" "github.com/blend/go-sdk/stringutil" "github.com/blend/go-sdk/webutil" ) // WriteHTTPRequest is a helper method to write request start events to a writer. func WriteHTTPRequest(tf TextFormatter, wr io.Writer, req *http.Request) { if ip := webutil.GetRemoteAddr(req); len(ip) > 0 { io.WriteString(wr, ip) io.WriteString(wr, Space) } io.WriteString(wr, tf.Colorize(req.Method, ansi.ColorBlue)) io.WriteString(wr, Space) io.WriteString(wr, req.URL.Path) } // WriteHTTPResponse is a helper method to write request complete events to a writer. func WriteHTTPResponse(tf TextFormatter, wr io.Writer, req *http.Request, statusCode, contentLength int, contentType string, elapsed time.Duration) { io.WriteString(wr, webutil.GetRemoteAddr(req)) io.WriteString(wr, Space) io.WriteString(wr, tf.Colorize(req.Method, ansi.ColorBlue)) io.WriteString(wr, Space) io.WriteString(wr, req.URL.String()) io.WriteString(wr, Space) io.WriteString(wr, ColorizeStatusCode(statusCode)) io.WriteString(wr, Space) io.WriteString(wr, elapsed.String()) if len(contentType) > 0 { io.WriteString(wr, Space) io.WriteString(wr, contentType) } io.WriteString(wr, Space) io.WriteString(wr, stringutil.FileSize(contentLength)) } // WriteFields writes fields. func WriteFields(tf TextFormatter, wr io.Writer, fields map[string]string) { for key, value := range fields { io.WriteString(wr, fmt.Sprintf("%s=%s", key, value)) } } // MergeDecomposed merges sets of decomposed data. func MergeDecomposed(sets ...map[string]interface{}) map[string]interface{} { output := make(map[string]interface{}) for _, set := range sets { for key, value := range set { output[key] = value } } return output }
razie/diesel-hydra
app/razie/diesel/engine/exec/EEFormatter.scala
/* ____ __ ____ ____ ____,,___ ____ __ __ ____ * ( _ \ /__\ (_ )(_ _)( ___)/ __) ( _ \( )( )( _ \ Read * ) / /(__)\ / /_ _)(_ )__) \__ \ )___/ )(__)( ) _ < README.txt * (_)\_)(__)(__)(____)(____)(____)(___/ (__) (______)(____/ LICENSE.txt */ package razie.diesel.engine.exec import razie.clog import razie.diesel.Diesel import razie.diesel.dom.RDOM._ import razie.diesel.engine.RDExt.spec import razie.diesel.engine.nodes._ import razie.diesel.engine.{DomAst, InfoAccumulator} import razie.diesel.expr.ECtx import razie.wiki.Enc /** format template results: if the current message has a template for a "result" then apply it. * * If a message has a "payload" type template, this is it's executor. * * this is just a simple use of templates - equivalent to setting payload to a templatized value * * todo simpler mechanism, something like: * (payload = """tempalte ${ss}""" as Json) but that would not be recognized as a template by tspecs */ class EEFormatter extends EExecutor("formatter") { /** can I execute this task? */ override def test(ast: DomAst, m: EMsg, cole: Option[MatchCollector] = None)(implicit ctx: ECtx) = { // is there a "result" type template? spec(m).exists(m => ctx.findTemplate(m.ea).exists(x => x.tags.contains(Diesel.PAYLOAD) )) } /** execute the task then */ override def apply(in: EMsg, destSpec: Option[EMsg])(implicit ctx: ECtx): List[Any] = { val templateReq = ctx.findTemplate(in.ea, Diesel.PAYLOAD) // expanded template content val formattedTemplate = templateReq.map(_.content).map { content => EESnakk.prepStr2(content, in.attrs) } formattedTemplate.map {res=> var eres = new InfoAccumulator() clog << ("PAYLOAD: \n" + res) eres += EInfo("Payload", Enc.escapeHtml(res)) // todo respect template mimetypes val pos = (templateReq.map(_.pos)).orElse(spec(in).flatMap(_.pos)) ctx.put(new P(Diesel.PAYLOAD, res)) eres += new EVal(Diesel.PAYLOAD, res).withPos(pos) eres.eres } getOrElse EError("No formatting template found for " + in.toString) :: Nil } override def toString = "$executor::formatter " }
melven/pitts
src/pitts_common_pybind.hpp
/*! @file pitts_common_pybind.hpp * @brief header for python binding for PITTS common helper functionality * @author <NAME> <<EMAIL>> * @date 2020-06-26 * @copyright Deutsches Zentrum fuer Luft- und Raumfahrt e. V. (DLR), German Aerospace Center * **/ // include guard #ifndef PITTS_COMMON_PYBIND_HPP #define PITTS_COMMON_PYBIND_HPP // includes #include <pybind11/pybind11.h> namespace py = pybind11; //! namespace for the library PITTS (parallel iterative tensor train solvers) namespace PITTS { //! namespace for python bindings namespace pybind { //! create pybind11-wrapper for PITTS::initialize and PITTS::finalize void init_common(py::module& m); } } #endif // PITTS_COMMON_PYBIND_HPP
vlmillet/phantom
projects/Phantom/phantom/utils/Flags.hxx
#pragma once // haunt { // clang-format off #include "Flags.h" #if defined(_MSC_VER) # pragma warning(push, 0) #elif defined(__clang__) # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wall" # pragma clang diagnostic ignored "-Wextra" #endif #include <phantom/namespace> #include <phantom/package> #include <phantom/source> #include <phantom/class> #include <phantom/struct> #include <phantom/method> #include <phantom/constructor> #include <phantom/field> #include <phantom/property> #include <phantom/typedef> namespace phantom { PHANTOM_PACKAGE("phantom.utils") PHANTOM_SOURCE("Flags") #if PHANTOM_NOT_TEMPLATE PHANTOM_CLASS(Flag) { this_() .public_() .constructor<void(int)>()({"i"}) .method<int() const>("operator int", &_::operator notypedef<int>) ; } PHANTOM_CLASS(IncompatibleFlag) { this_() .public_() .constructor<void(int), explicit_>()({"i"}) .method<int() const>("operator int", &_::operator notypedef<int>) ; } #endif // PHANTOM_NOT_TEMPLATE PHANTOM_STRUCT_T((class), (Enum), FlagsBit) { this_() PHANTOM_IF((phantom::IsDefaultConstructible<PHANTOM_REFLECTED_TYPE>::value), .PHANTOM_T constructor<void()>() ) .PHANTOM_T constructor<void(Flags<Enum>*, Enum)>()({"a_Flags","a_Where"}) .PHANTOM_T method<void(bool)>("setValue", &_::setValue)({"a_bValue"}) .PHANTOM_T method<bool() const>("getValue", &_::getValue) .PHANTOM_T property<bool>("value", &_::getValue, &_::setValue) .protected_() .PHANTOM_T field("m_Flags", &_::m_Flags) .PHANTOM_T field("m_Where", &_::m_Where) ; } PHANTOM_STRUCT_T((class), (Enum), ConstFlagsBit) { this_() PHANTOM_IF((phantom::IsDefaultConstructible<PHANTOM_REFLECTED_TYPE>::value), .PHANTOM_T constructor<void()>() ) .PHANTOM_T constructor<void(const Flags<Enum>*, Enum)>()({"a_Flags","a_Where"}) .PHANTOM_T method<bool() const>("getValue", &_::getValue) .protected_() .PHANTOM_T field("m_Flags", &_::m_Flags) .PHANTOM_T field("m_Where", &_::m_Where) ; } PHANTOM_CLASS_T((class), (Enum), Flags) { using Bit = typedef_<PHANTOM_TYPENAME _::Bit>; using ConstBit = typedef_<PHANTOM_TYPENAME _::ConstBit>; using EnumType = typedef_<PHANTOM_TYPENAME _::EnumType>; using SelfType = typedef_<PHANTOM_TYPENAME _::SelfType>; using _Zero = typedef_<PHANTOM_TYPENAME _::_Zero>; this_() .public_() .PHANTOM_T typedef_<_Zero>("_Zero") .PHANTOM_T typedef_<SelfType>("SelfType") .PHANTOM_T typedef_<Bit>("Bit") .PHANTOM_T typedef_<ConstBit>("ConstBit") .PHANTOM_T typedef_<EnumType>("EnumType") .PHANTOM_T constructor<void(const SelfType&)>()({"f"}) .PHANTOM_T constructor<void(Enum)>()({"f"}) PHANTOM_IF((phantom::IsDefaultConstructible<PHANTOM_REFLECTED_TYPE>::value), .PHANTOM_T constructor<void(_Zero)>()({""})["0"] ) .PHANTOM_T constructor<void(Flag)>()({"f"}) .PHANTOM_T method<SelfType&(const SelfType&)>("operator=", &PHANTOM_REFLECTED_TYPE::operator=)({"f"}) .PHANTOM_T method<SelfType&(int)>("operator&=", &_::operator&=)({"mask"}) .PHANTOM_T method<SelfType&(unsigned int)>("operator&=", &_::operator&=)({"mask"}) .PHANTOM_T method<SelfType&(SelfType)>("operator|=", &_::operator|=)({"f"}) .PHANTOM_T method<SelfType&(Enum)>("operator|=", &_::operator|=)({"f"}) .PHANTOM_T method<SelfType&(SelfType)>("operator^=", &_::operator^=)({"f"}) .PHANTOM_T method<SelfType&(Enum)>("operator^=", &_::operator^=)({"f"}) .PHANTOM_T method<int() const>("operator int", &_::operator notypedef<int>) .PHANTOM_T method<SelfType(SelfType) const>("operator|", &_::operator|)({"f"}) .PHANTOM_T method<SelfType(Enum) const>("operator|", &_::operator|)({"f"}) .PHANTOM_T method<SelfType(SelfType) const>("operator^", &_::operator^)({"f"}) .PHANTOM_T method<SelfType(Enum) const>("operator^", &_::operator^)({"f"}) .PHANTOM_T method<SelfType(int) const>("operator&", &_::operator&)({"mask"}) .PHANTOM_T method<SelfType(unsigned int) const>("operator&", &_::operator&)({"mask"}) .PHANTOM_T method<SelfType(Enum) const>("operator&", &_::operator&)({"f"}) .PHANTOM_T method<SelfType() const>("operator~", &_::operator~) .PHANTOM_T method<bool() const>("operator!", &_::operator!) .PHANTOM_T method<bool(Enum) const>("testFlag", &_::testFlag)({"f"}) .PHANTOM_T method<Bit(Enum)>("operator[]", &_::operator[])({"f"}) .PHANTOM_T method<ConstBit(Enum) const>("operator[]", &_::operator[])({"f"}) ; } PHANTOM_END("Flags") PHANTOM_END("phantom.utils") } #if defined(_MSC_VER) # pragma warning(pop) #elif defined(__clang__) # pragma clang diagnostic pop #endif // clang-format on // haunt }
gavin2lee/incubator-gl
mnis/core/src/main/java/com/lachesis/mnis/core/nursing/NurseShiftEntity.java
<reponame>gavin2lee/incubator-gl<gh_stars>1-10 package com.lachesis.mnis.core.nursing; import java.util.Date; import java.util.List; public class NurseShiftEntity { private String nurseShiftId;// 护士交班本id private String patientId; private String patientName; private String deptCode; private String deptName; private String hospNo; private String bedNo; private String diagnose;// 诊断 private int tend;// 护理等级 private String criticalStatus;// 危机状态 private String shiftNurseId;// 交班护士id private String shiftNurseName;// 交班护士name private Date shiftDate;// 交班时间 private String successionNurseId;// 接班护士id private String successionNurseName;// 接班护士name private Date successionDate;// 接班时间 private Date shiftStartDate;// 时段开始时间 private Date shiftEndDate;// 时段结束时间 private String shiftStatus;// 交接班状态(0,1,2;未交班,已交班,已接班) private boolean valid; private List<NurseShiftRecordEntity> nurseShiftRecordEntities;// 交接班记录 public String getNurseShiftId() { return nurseShiftId; } public void setNurseShiftId(String nurseShiftId) { this.nurseShiftId = nurseShiftId; } public String getPatientId() { return patientId; } public void setPatientId(String patientId) { this.patientId = patientId; } public String getPatientName() { return patientName; } public void setPatientName(String patientName) { this.patientName = patientName; } public String getDeptCode() { return deptCode; } public void setDeptCode(String deptCode) { this.deptCode = deptCode; } public String getDeptName() { return deptName; } public void setDeptName(String deptName) { this.deptName = deptName; } public String getHospNo() { return hospNo; } public void setHospNo(String hospNo) { this.hospNo = hospNo; } public String getBedNo() { return bedNo; } public void setBedNo(String bedNo) { this.bedNo = bedNo; } public String getDiagnose() { return diagnose; } public void setDiagnose(String diagnose) { this.diagnose = diagnose; } public int getTend() { return tend; } public void setTend(int tend) { this.tend = tend; } public String getCriticalStatus() { return criticalStatus; } public void setCriticalStatus(String criticalStatus) { this.criticalStatus = criticalStatus; } public String getShiftNurseId() { return shiftNurseId; } public void setShiftNurseId(String shiftNurseId) { this.shiftNurseId = shiftNurseId; } public String getShiftNurseName() { return shiftNurseName; } public void setShiftNurseName(String shiftNurseName) { this.shiftNurseName = shiftNurseName; } public String getSuccessionNurseId() { return successionNurseId; } public void setSuccessionNurseId(String successionNurseId) { this.successionNurseId = successionNurseId; } public String getSuccessionNurseName() { return successionNurseName; } public void setSuccessionNurseName(String successionNurseName) { this.successionNurseName = successionNurseName; } public String getShiftStatus() { return shiftStatus; } public void setShiftStatus(String shiftStatus) { this.shiftStatus = shiftStatus; } public boolean isValid() { return valid; } public void setValid(boolean valid) { this.valid = valid; } public List<NurseShiftRecordEntity> getNurseShiftRecordEntities() { return nurseShiftRecordEntities; } public void setNurseShiftRecordEntities( List<NurseShiftRecordEntity> nurseShiftRecordEntities) { this.nurseShiftRecordEntities = nurseShiftRecordEntities; } public Date getShiftDate() { return shiftDate; } public void setShiftDate(Date shiftDate) { this.shiftDate = shiftDate; } public Date getSuccessionDate() { return successionDate; } public void setSuccessionDate(Date successionDate) { this.successionDate = successionDate; } public Date getShiftStartDate() { return shiftStartDate; } public void setShiftStartDate(Date shiftStartDate) { this.shiftStartDate = shiftStartDate; } public Date getShiftEndDate() { return shiftEndDate; } public void setShiftEndDate(Date shiftEndDate) { this.shiftEndDate = shiftEndDate; } }
Vanya112/BSUIR_Labs
4 term/Personal-Computer-Architecture/Lab 5/Source.cpp
#include <dos.h> #include <stdio.h> #include <conio.h> #include <io.h> #define PLAY_SOUND() _asm { _asm mov bx,0 _asm mov ax, 0E07h _asm int 10h } unsigned int globalCount = 0; void _interrupt _far(*oldVector)(); void _interrupt _far newVector(); void interrupt(*oldAlarm) (); void reset() { if (oldAlarm != NULL) { setvect(0x4A, oldAlarm); outp(0xA1, (inp(0xA0) | 0x01)); // deny real time clock interrupt outp(0x70, 0x05); //hours outp(0x71, 0x00); //reset outp(0x70, 0x03); //minutes outp(0x71, 0x00); //reset outp(0x70, 0x01); //seconds outp(0x71, 0x00); //reset outp(0x70, 0xB); outp(0x71, (inp(0x71) & 0xDF)); // block alarm interrupt } } void _interrupt _far newVector() { globalCount++; outp(0x70, 0x0C); //inp(0x71); outp(0x20, 0x20); outp(0xA0, 0x20); } void interrupt newAlarm() { write(1, "\nALARM TRIGGERED!", 17); //PLAY_SOUND(); //PLAY_SOUND(); //PLAY_SOUND(); //PLAY_SOUND(); //PLAY_SOUND(); //PLAY_SOUND(); //PLAY_SOUND(); } int bcdToDecimal(int number) { return ((number / 16 * 10) + (number % 16)); } int decimalToBCD(int number) { return ((number / 10 * 16) + (number % 10)); } void getTime() { outp(0x70, 0x04); //hours printf("%02d:", bcdToDecimal(inp(0x71))); outp(0x70, 0x02); //minutes printf("%02d:", bcdToDecimal(inp(0x71))); outp(0x70, 0x00); //seconds printf("%02d\n", bcdToDecimal(inp(0x71))); } void getDate() { outp(0x70, 0x07); //day printf("%02d.", bcdToDecimal(inp(0x71))); outp(0x70, 0x08); //month printf("%02d.", bcdToDecimal(inp(0x71))); outp(0x70, 0x32); //century printf("%02d", bcdToDecimal(inp(0x71))); outp(0x70, 0x09); //year printf("%02d\n", bcdToDecimal(inp(0x71))); } void setTime(int flag) { int hours; do { rewind(stdin); printf("H: "); scanf("%i", &hours); } while ((hours > 23 || hours < 0)); hours = decimalToBCD(hours); int minutes; do { rewind(stdin); printf("M: "); scanf("%i", &minutes); } while (minutes > 59 || minutes < 0); minutes = decimalToBCD(minutes); int seconds; do { rewind(stdin); printf("S: "); scanf("%i", &seconds); } while (seconds > 59 || seconds < 0); seconds = decimalToBCD(seconds); if (flag) { int i = 0; outp(0x70, 0x0A); for (; (inp(0x71) & 0x80) && i < 10000; i++) //seventh A bit signals that time data are redy for extraction if 0 { outp(0x70, 0x0A); } if (i == 10000) { printf("error!"); return; } outp(0x70, 0xB); outp(0x71, inp(0x71) | 0x80); // deny time update outp(0x70, 0x04); outp(0x71, hours); outp(0x70, 0x02); outp(0x71, minutes); outp(0x70, 0x00); outp(0x71, seconds); outp(0x70, 0xB); outp(0x71, inp(0x71) & 0x7F); // allow RTC update } else { outp(0x70, 0x05); outp(0x71, hours); outp(0x70, 0x03); outp(0x71, minutes); outp(0x70, 0x01); outp(0x71, seconds); outp(0x70, 0xB); outp(0x71, (inp(0x71) | 0x20)); // allow alarm interrupt oldAlarm = getvect(0x4A); setvect(0x4A, newAlarm); outp(0xA1, (inp(0xA0) & 0xFE)); // allow RTC interrupt } } void delay(unsigned int ms) { disable(); oldVector = _dos_getvect(0x70); _dos_setvect(0x70, newVector); enable(); //Unmask slave IRQ line outp(0xA1, inp(0xA1) & 0xFE); // allow RTC int outp(0x70, 0xB); outp(0x71, inp(0x71) | 0x40); //allow periodic int globalCount = 0; while (globalCount <= ms); disable(); _dos_setvect(0x70, oldVector); enable(); return; } int main() { while (1) { getDate(); getTime(); printf("1. Set Time\n"); printf("2. Set Alarm\n"); printf("3. Sleep\n"); printf("0. Exit\n\n"); switch (getch()) { case '1': setTime(1); break; case '2': setTime(0); break; case '3': int ms; rewind(stdin); printf("Input ms: "); scanf("%d", &ms); printf("Sleep...\n"); delay(ms); printf("Continue working\n"); break; case '0': reset(); return 0; } default: continue; } }
Indexyz/Sakura
app/middleware/coinhive.js
<reponame>Indexyz/Sakura 'use strict'; module.exports = options => { return function* (next) { if (this.request.method === 'POST') { if (options.site_key !== '') { const { token } = this.request.body; if (!(yield this.service.coinhive.verify(token))) { this.status = 401; this.body = { success: 0, error: this.__('auth.errors.tokenError') }; return; } } } return yield next; }; };
Garlov/OpenJam.CatsOrDogs
src/components/events/canEmit.js
<reponame>Garlov/OpenJam.CatsOrDogs import store from 'root/store'; import Phaser from 'phaser'; import createListener from 'core/createListener'; const canEmit = function canEmitFunc(state) { const localEmitter = new Phaser.Events.EventEmitter(); const listeners = []; function emitGlobal(event, data) { store.messageBus.emit(event, data); } function emit(event, data) { localEmitter.emit(event, data); } function on(event, fn, context) { localEmitter.on(event, fn, context); const listener = createListener(event, fn, false, state); listeners.push(listener); return listener; } function once(event, fn, context) { localEmitter.once(event, fn, context); const listener = createListener(event, fn, true, state); listeners.push(listener); return listener; } function off(listener) { if (listeners.indexOf(listener) >= 0) { localEmitter.off(listener.event, listener.fn, listener.once); listeners.splice(listeners.indexOf(listener), 1); } } function removeAllListeners() { if (localEmitter) { listeners.forEach((l) => { l.drop(); }); } } function destroy() { if (localEmitter) { state.removeAllListeners(); localEmitter.destroy(); } } return { // props // methods emitGlobal, emit, on, once, off, removeAllListeners, destroy, }; }; export default canEmit;
proglang/dts-generate-results
results/4_extract-code/code/irc/irc_1.js
<reponame>proglang/dts-generate-results<gh_stars>1-10 var irc = require('irc'); var client = new irc.Client('irc.yourserver.com', 'myNick', { channels: ['#channel'], });
matti/webdriver
lib/webdriver/cookie.rb
<reponame>matti/webdriver<filename>lib/webdriver/cookie.rb module Webdriver class Cookie attr_reader :name def initialize(name, connection) @name = name @session_connection = connection @connection = Webdriver::PrefixConnection.new "cookie/#{@name}", connection end def delete! @connection.delete self end def domain __refresh["domain"] end def expiry __refresh["expiry"] end def http_only __refresh["httpOnly"] end def path __refresh["path"] end def same_site __refresh["sameSite"] end def secure __refresh["secure"] end def value __refresh["value"] end private def __refresh @connection.get end end end
sir-maniac/Cobalt
src/main/java/org/squiddev/cobalt/OrphanedThreadException.java
/* * The MIT License (MIT) * * Original Source: Copyright (c) 2009-2011 Luaj.org. All rights reserved. * Modifications: Copyright (c) 2015-2020 SquidDev * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.squiddev.cobalt; /** * An {@link InterruptedException} subclass that indicates a Lua thread that is no longer referenced has been detected. * * The Java thread in which this is thrown should correspond to a {@link LuaThread} being used as a coroutine that could * not possibly be resumed again because there are no more references to the coroutine with which it is associated. * Rather than locking up resources forever, this error is thrown, and should fall through all the way to top level of * the executor. * * Java code mixed with the Lua VM should not catch this error. This may be thrown at any time, including when other * coroutines from the same VM are running, and so you run the risk of breaking thread-safety. */ public class OrphanedThreadException extends InterruptedException { private static final long serialVersionUID = -611369749534243472L; OrphanedThreadException() { super("Orphaned thread"); } }
egrosclaude/IC2016
plugin/function-plot/node_modules/interval-arithmetic-eval/index.js
<reponame>egrosclaude/IC2016 /* * interval-arithmetic-eval * * Copyright (c) 2015 <NAME> * Licensed under the MIT license. */ 'use strict' module.exports = require('./lib/eval')
bigmiguel/VIRMCorp
Resources/android/alloy/controllers/slideMenu.js
function Controller() { function _MenuIzquierdo() { true == $.btnMenu.toggle ? cierraMenuIzquierdo() : abreMenuIzquierdo(); } function _MenuDerecho() { true == $.btnMenuDer.toggle ? cierraMenuDerecho() : abreMenuDerecho(); } function abreMenuIzquierdo() { $.leftMenu.show(); $.rightMenu.hide(); $.movableview.animate({ left: "60%", duration: 400, curve: Ti.UI.ANIMATION_CURVE_EASE_IN_OUT }); $.btnMenu.toggle = true; } function cierraMenuIzquierdo() { $.movableview.setWidth(Titanium.Platform.displayCaps.platformWidth); $.movableview.animate({ left: 0, duration: 400, curve: Ti.UI.ANIMATION_CURVE_EASE_IN_OUT }); $.btnMenu.toggle = false; } function abreMenuDerecho() { $.leftMenu.hide(); $.rightMenu.show(); $.movableview.animate({ left: "-80%", duration: 400, curve: Ti.UI.ANIMATION_CURVE_EASE_IN_OUT }); $.btnMenuDer.toggle = true; } function cierraMenuDerecho() { $.movableview.setWidth(Titanium.Platform.displayCaps.platformWidth); $.movableview.animate({ left: 0, duration: 400, curve: Ti.UI.ANIMATION_CURVE_EASE_IN_OUT }); $.btnMenuDer.toggle = false; } function muestraCargando() { $.cargando.show(); $.vwCarga.show(); } require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments)); this.__controllerPath = "slideMenu"; arguments[0] ? arguments[0]["__parentSymbol"] : null; arguments[0] ? arguments[0]["$model"] : null; arguments[0] ? arguments[0]["__itemTemplate"] : null; var $ = this; var exports = {}; $.__views.wnSlideMenu = Ti.UI.createWindow({ navBarHidden: "true", id: "wnSlideMenu" }); $.__views.wnSlideMenu && $.addTopLevelView($.__views.wnSlideMenu); $.__views.vwTopIOS = Ti.UI.createView({ backgroundColor: "#FFFFFF", id: "vwTopIOS", top: "0" }); $.__views.wnSlideMenu.add($.__views.vwTopIOS); $.__views.containerview = Ti.UI.createView({ id: "containerview" }); $.__views.wnSlideMenu.add($.__views.containerview); $.__views.leftMenu = Ti.UI.createView({ top: "0dp", left: "0dp", width: "60%", zIndex: "0", backgroundColor: "#333333", layout: "vertical", id: "leftMenu" }); $.__views.containerview.add($.__views.leftMenu); $.__views.leftTableView = Ti.UI.createScrollView({ id: "leftTableView", layout: "vertical" }); $.__views.leftMenu.add($.__views.leftTableView); $.__views.rightMenu = Ti.UI.createView({ top: "0dp", right: "0dp", width: "80%", zIndex: "0", backgroundGradient: { type: "linear", startPoint: { x: "100%", y: "70%" }, endPoint: { x: "100%", y: "100%" }, colors: [ { color: "#4E6EAD", offset: .01 }, { color: "#95ABD6", offset: 1 } ] }, layout: "vertical", id: "rightMenu", visible: "false" }); $.__views.containerview.add($.__views.rightMenu); $.__views.movableview = Ti.UI.createView({ id: "movableview" }); $.__views.containerview.add($.__views.movableview); $.__views.shadowview = Ti.UI.createView({ shadowColor: "black", shadowOffset: { x: "0", y: "0" }, shadowRadius: "5", id: "shadowview" }); $.__views.movableview.add($.__views.shadowview); $.__views.navview = Ti.UI.createView({ top: "0dp", left: "0dp", width: Ti.Platform.displayCaps.platformWidth, height: "10%", backgroundColor: "#00359C", color: "#FFF", id: "navview" }); $.__views.shadowview.add($.__views.navview); $.__views.btnMenu = Ti.UI.createView({ backgroundColor: "none", left: 0, top: 0, width: "40%", height: "100%", style: "none", zIndex: 2, id: "btnMenu" }); $.__views.navview.add($.__views.btnMenu); $.__views.imgMenu = Ti.UI.createButton({ backgroundColor: "none", color: "#FFF", borderStyle: Ti.UI.INPUT_BORDERSTYLE_ROUNDED, borderWidth: 0, borderRadius: 5, backgroundImage: "/images/ButtonMenu.png", width: "30%", left: "2%", zIndex: 1, id: "imgMenu" }); $.__views.btnMenu.add($.__views.imgMenu); $.__views.btnMenuDer = Ti.UI.createView({ backgroundColor: "none", right: 0, top: 0, width: "40%", height: "100%", style: "none", zIndex: 2, id: "btnMenuDer", visible: "false" }); $.__views.navview.add($.__views.btnMenuDer); $.__views.imgMenuDer = Ti.UI.createButton({ backgroundColor: "none", color: "#FFF", borderStyle: Ti.UI.INPUT_BORDERSTYLE_ROUNDED, borderWidth: 0, borderRadius: 5, backgroundImage: "/images/ButtonMenuDer.png", width: "30%", right: "4%", zIndex: 1, id: "imgMenuDer" }); $.__views.btnMenuDer.add($.__views.imgMenuDer); $.__views.lblTitulo = Ti.UI.createLabel({ width: Ti.UI.FILL, height: Ti.UI.SIZE, color: "#FFFFFF", textAlign: "center", shadowColor: "#000000", shadowOffset: { x: 0, y: 3 }, zIndex: 0, text: "Medica VRIM", id: "lblTitulo", backgroundColor: "none", backgroundGradient: "none" }); $.__views.navview.add($.__views.lblTitulo); $.__views.contentview = Ti.UI.createView({ left: "0dp", width: Ti.Platform.displayCaps.platformWidth, height: Ti.UI.Fill, top: "10%", backgroundColor: "white", zindex: 2, id: "contentview", moving: "false", axis: "0" }); $.__views.shadowview.add($.__views.contentview); $.__views.vwCarga = Ti.UI.createView({ width: Ti.API.FILL, height: Ti.API.FILL, top: 0, backgroundColor: "#000000", zIndex: 99999, opacity: ".65", color: "#FFFFFF", id: "vwCarga" }); $.__views.containerview.add($.__views.vwCarga); $.__views.cargando = Ti.UI.createActivityIndicator({ opacity: "1", color: "#FFFFFF", id: "cargando", zIndex: "9999", message: "Cargando..." }); $.__views.vwCarga.add($.__views.cargando); exports.destroy = function() {}; _.extend($, $.__views); var Util = require("utils"); $.vwTopIOS.setHeight(Util.isiOS7Plus() ? 20 : 0); $.containerview.top = Util.isiOS7Plus() ? 20 : 0; $.lblTitulo.applyProperties($.createStyle(Alloy.FuenteTitulo())); Titanium.Platform.displayCaps.platformHeight; Ti.Platform.displayCaps.platformWidth; var user = Util.user(); muestraCargando(); var MenuSI = [ { icon: "/images/user.png", titulo: void 0 == user.NOMBRE_TARJETA ? "No tienes tarjete" : user.NOMBRE_TARJETA, vista: null, params: null, banTitulo: true }, { icon: "/images/membresia.png", titulo: "Mi Membresía", vista: "membresia", params: null, banTitulo: false }, { icon: "/images/medicos.png", titulo: "# Emergencia", vista: "vwNumEmergencia", banTitulo: false }, { icon: "/images/ambulancias.png", titulo: "Ambulancia", vista: "", params: null, banTitulo: false, banAmbulancia: true }, { icon: "/images/user.png", titulo: "Red Médica", vista: null, params: null, banTitulo: true }, { icon: "/images/medicos.png", titulo: "Medicos", vista: "redMedicos", params: { idAfiliacion: "2", idTipoBusqueda: "1" }, banTitulo: false }, { icon: "/images/ambulancias.png", titulo: "Serviciòs", vista: "redMedicos", params: { idAfiliacion: "2", idTipoBusqueda: "2" }, banTitulo: false }, { icon: "/images/labicon.png", titulo: "Laboratorios", vista: "redMedicos", params: { idAfiliacion: "2", idTipoBusqueda: "4" }, banTitulo: false }, { icon: "/images/tdc.png", titulo: "Red TDC", vista: null, params: null, banTitulo: true }, { icon: "/images/tdc.png", titulo: "Descuentos TDC", vista: "redMedicos", params: { idAfiliacion: "2", idTipoBusqueda: "3" }, banTitulo: false }, { icon: "/images/tdc.png", titulo: "Cupones", vista: "vwCupones", params: null, banTitulo: false }, { icon: "/images/salud_interactiva.png", titulo: "Otros Servicios", vista: null, params: null, banTitulo: true }, { icon: "/images/PLM.png", titulo: "Medicamentos", vista: "vwPLMBusqueda", params: null, banTitulo: false }, { icon: "/images/link.png", titulo: "Se<NAME>", vista: null, params: { link: "https://medicavrim.com/PublicFiles/PrivacidadVRIM.pdf" }, banTitulo: false, banLink: true }, { icon: "/images/link.png", titulo: "Aviso de Privacidad", vista: null, params: { link: "http://imagenes.medicallhome.com.mx/docs/restriccionesinbursa.pdf" }, banTitulo: false, banLink: true } ]; for (var i = 0; MenuSI.length > i; i++) { var _parametros = MenuSI[i]; var _menuFila = Alloy.createController("menurow", _parametros).getView(); $.leftTableView.add(_menuFila); _parametros.banTitulo ? _menuFila.backgroundColor = "#333333" : _parametros.banAmbulancia ? _menuFila.addEventListener("click", function() { var dialog = Ti.UI.createAlertDialog({ cancel: 1, buttonNames: [ "Llamar", "Cancelar" ], message: "4209 3205", title: "Ambulancia" }); dialog.addEventListener("click", function(e) { 0 === e.index && Ti.Platform.openURL("tel:42093205"); }); dialog.show(); }) : _parametros.banLink ? _menuFila.addEventListener("click", function() { Ti.Platform.openURL(_parametros.params.link); }) : _menuFila.addEventListener("click", function(e) { cierraMenuIzquierdo(); muestraCargando(); Alloy.Globals.current.destroy(); $.contentview.remove(_currentView); if (null != vistaDer) { $.rightMenu.remove(vistaDer); vistaDer = null; } $.btnMenuDer.hide(); var nuevaVista = Alloy.createController(e.source.vista, e.source.params).getView(); $.contentview.add(nuevaVista); _currentView = nuevaVista; $.contentview.setZIndex(2); }); } Ti.App.addEventListener("muestraCargando", function() { muestraCargando(); }); Ti.App.addEventListener("ocultaCargando", function() { $.vwCarga.hide(); }); var vistaDer = null; Ti.App.addEventListener("muestraSubMenu", function(e) { $.rightMenu.removeAllChildren(); $.btnMenuDer.show(); vistaDer = Alloy.createController(e.vista, e.parametros).getView(); $.rightMenu.add(vistaDer); }); Ti.App.addEventListener("cierraMenuDer", function() { cierraMenuDerecho(); }); var vistaDet = null; Ti.App.addEventListener("MuestraDetalleProveedor", function(e) { setTimeout(function() { $.btnMenuDer.toogle || abreMenuDerecho(); }, 100); $.rightMenu.removeAllChildren(); vistaDet = null; vistaDet = Alloy.createController("detalleProveedor", e).getView(); $.rightMenu.add(vistaDet); }); Ti.App.addEventListener("regresaBusqueda", function() { null != vistaDet && $.rightMenu.remove(vistaDet); $.rightMenu.add(vistaDer); vistaDet = null; }); $.wnSlideMenu.addEventListener("android:back", function() { var activity = Titanium.Android.currentActivity; activity.finish(); }); var _currentView = Alloy.createController("membresia").getView(); $.contentview.add(_currentView); $.imgMenu.addEventListener("click", _MenuIzquierdo); $.btnMenuDer.addEventListener("click", _MenuDerecho); _.extend($, exports); } var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._; module.exports = Controller;
antarikshray/websiterudra
node_modules/react-icons/io/ios-location.js
<gh_stars>1-10 import React from 'react' import Icon from 'react-icon-base' const IoIosLocation = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m19.8 2.5c6.2 0 11.2 5 11.2 11.3 0 8.7-11.2 23.7-11.2 23.7s-11.3-15-11.3-23.7c0-6.3 5-11.3 11.3-11.3z m0 14.9c2 0 3.6-1.6 3.6-3.6s-1.6-3.7-3.6-3.7-3.7 1.6-3.7 3.7 1.6 3.6 3.7 3.6z"/></g> </Icon> ) export default IoIosLocation
iris-mobile-accessibility-repair/geohashdroid
app/src/main/java/net/exclaimindustries/geohashdroid/services/package-info.java
<reponame>iris-mobile-accessibility-repair/geohashdroid<filename>app/src/main/java/net/exclaimindustries/geohashdroid/services/package-info.java /** * Here be services. There be no escape. * * @author <NAME> */ package net.exclaimindustries.geohashdroid.services;
zburke/ui-inn-reach
src/settings/components/CentralServersConfiguration/CentralServersConfigurationForm/components/Footer/Footer.js
import React from 'react'; import PropTypes from 'prop-types'; import { Button, PaneFooter, } from '@folio/stripes-components'; import { FormattedMessage, } from 'react-intl'; const Footer = ({ pristine, invalid, onCancel, onHandleSubmit, }) => { const cancelButton = ( <Button data-testid="cancel-button" buttonStyle="default mega" onClick={onCancel} > <FormattedMessage id="ui-inn-reach.settings.central-server-configuration.create-edit.button.cancel" /> </Button> ); const saveButton = ( <Button data-testid="save-button" buttonStyle="primary mega" type="submit" disabled={invalid || pristine} onClick={onHandleSubmit} > <FormattedMessage id="ui-inn-reach.settings.central-server-configuration.create-edit.button.save&close" /> </Button> ); return ( <PaneFooter renderStart={cancelButton} renderEnd={saveButton} /> ); }; Footer.propTypes = { invalid: PropTypes.bool.isRequired, pristine: PropTypes.bool.isRequired, onCancel: PropTypes.func.isRequired, onHandleSubmit: PropTypes.func.isRequired, }; export default Footer;
DevSabb/java-algorand-sdk
src/main/java/com/algorand/algosdk/v2/client/model/EvalDeltaKeyValue.java
package com.algorand.algosdk.v2.client.model; import java.util.Objects; import com.algorand.algosdk.v2.client.common.PathResponse; import com.fasterxml.jackson.annotation.JsonProperty; /** * Key-value pairs for StateDelta. */ public class EvalDeltaKeyValue extends PathResponse { @JsonProperty("key") public String key; /** * Represents a TEAL value delta. */ @JsonProperty("value") public EvalDelta value; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null) return false; EvalDeltaKeyValue other = (EvalDeltaKeyValue) o; if (!Objects.deepEquals(this.key, other.key)) return false; if (!Objects.deepEquals(this.value, other.value)) return false; return true; } }
kaustubhhiware/Java_lin
22/MSlist2.java
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class MSlist2 extends JFrame{ private JList leftlist; private JList rightlist; private JButton button; private static String[] foods = {"dhokla","khandwa","fafda","jilebi","chiwda","more"}; //#hamare gujarat main aisa hi hota hai public MSlist2(){ super("The title"); setLayout(new FlowLayout()); leftlist = new JList(foods); leftlist.setVisibleRowCount(7); leftlist.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); add(new JScrollPane(leftlist)); button = new JButton("MOVE----->"); button.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent event){ extracted(); } private void extracted() { rightlist.setListData(leftlist.getSelectedValues()); } } ); add(button); rightlist = new JList(); rightlist.setVisibleRowCount(7); rightlist.setFixedCellWidth(100); rightlist.setFixedCellHeight(15); rightlist.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); add(new JScrollPane(rightlist)); } }
zhangkn/iOS14Header
usr/libexec/fmflocatord/FMDGainsboroughPairedDeviceSimulation.h
<reponame>zhangkn/iOS14Header // // Generated by classdumpios 1.0.1 (64 bit) (iOS port by DreamDevLost)(Debug version compiled Sep 26 2020 13:48:20). // // Copyright (C) 1997-2019 <NAME>. // #import <objc/NSObject.h> @interface FMDGainsboroughPairedDeviceSimulation : NSObject { } - (id)pairedDeviceInfo; // IMP=0x0000000100030ae0 - (id)lastActiveDate:(id)arg1; // IMP=0x0000000100030a34 - (id)wristStatusString:(id)arg1; // IMP=0x0000000100030978 - (id)connectionStatusString:(id)arg1; // IMP=0x0000000100030890 - (id)deviceName:(id)arg1; // IMP=0x000000010003087c - (id)udid:(id)arg1; // IMP=0x0000000100030808 - (_Bool)isPairedDeviceSimulationActive; // IMP=0x0000000100030780 @end
WuYifanX/leetcode
problems/leetcode1_TwoSum/Solution2.java
<reponame>WuYifanX/leetcode<gh_stars>0 package leetcode1_TwoSum; public class Solution2 { private int[] memo; public int getRabbit(int n) { if (n == 0) return 0; memo = new int[n + 1]; memo[1] = 1; memo[2] = 1; for (int i = 3; i <= n; i++) { memo[i] = memo[i - 1] + memo[i - 2]; } return memo[n]; } }
XiaoBoya/pkg
apis/meta/v1alpha1/objectreference_test.go
<reponame>XiaoBoya/pkg<filename>apis/meta/v1alpha1/objectreference_test.go /* Copyright 2021 The Katanomi 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 v1alpha1 import ( "testing" "github.com/google/go-cmp/cmp" . "github.com/onsi/gomega" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" ) func TestObjectReferenceIsTheSame(t *testing.T) { tests := map[string]struct { Object *corev1.ObjectReference Compared *corev1.ObjectReference Expected bool }{ "Both Nil": { Object: nil, Compared: nil, Expected: true, }, "Both Not Nil": { Object: &corev1.ObjectReference{}, Compared: &corev1.ObjectReference{}, Expected: true, }, "Mixed Nil": { Object: nil, Compared: &corev1.ObjectReference{}, Expected: false, }, "Reversed Mixed Nil": { Object: &corev1.ObjectReference{}, Compared: nil, Expected: false, }, "Same reference": { Object: &corev1.ObjectReference{ Name: "abc", Namespace: "default", }, Compared: &corev1.ObjectReference{ Name: "abc", Namespace: "default", }, Expected: true, }, "Different reference": { Object: &corev1.ObjectReference{ Name: "def", Namespace: "default", }, Compared: &corev1.ObjectReference{ Name: "abc", Namespace: "default", }, Expected: false, }, } for name, test := range tests { t.Run(name, func(t *testing.T) { g := NewGomegaWithT(t) g.Expect((IsTheSameObjectReference(test.Object, test.Compared))).To(Equal(test.Expected)) }) } } func TestGetObjectReferenceFromObject(t *testing.T) { g := NewGomegaWithT(t) pod := &corev1.Pod{ TypeMeta: metav1.TypeMeta{ APIVersion: "v1", Kind: "Pod", }, ObjectMeta: metav1.ObjectMeta{ Name: "pod", Namespace: "default", UID: types.UID("abc"), }, } ref := GetObjectReferenceFromObject(pod) g.Expect(ref.Name).To(Equal("pod")) g.Expect(ref.Namespace, ref.APIVersion, ref.Kind, ref.UID).To(BeEmpty()) ref = GetObjectReferenceFromObject(pod, ObjectRefWithTypeMeta(), ObjectRefWithNamespace(), ObjectRefWithUID()) g.Expect(ref.Name).To(Equal("pod")) g.Expect(ref.Namespace).To(Equal("default")) g.Expect(ref.APIVersion).To(Equal("v1")) g.Expect(ref.Kind).To(Equal("Pod")) g.Expect(ref.UID).To(Equal(types.UID("abc"))) } func TestGetNamespacedNameFromRef(t *testing.T) { table := map[string]struct { Object *corev1.ObjectReference Result types.NamespacedName }{ "Simple secret object": { Object: &corev1.ObjectReference{Name: "secret", Namespace: "default"}, Result: types.NamespacedName{Name: "secret", Namespace: "default"}, }, "Nil object": { Object: nil, Result: types.NamespacedName{}, }, } for name, item := range table { test := item t.Run(name, func(t *testing.T) { g := NewGomegaWithT(t) result := GetNamespacedNameFromRef(test.Object) diff := cmp.Diff(test.Result, result) g.Expect(diff).To(BeEmpty()) }) } }
grische/OpenSPH
test/utils/Approx.cpp
#include "tests/Approx.h" #include "catch.hpp" using namespace Sph; TEST_CASE("Approx float", "[approx]") { // some sanity checks REQUIRE(0._f == approx(0._f)); REQUIRE(0._f == approx(0._f, 0._f)); REQUIRE(1._f == approx(1._f)); REQUIRE(1._f == approx(1._f + EPS)); REQUIRE_FALSE(1._f == approx(0.5_f)); REQUIRE_FALSE(0._f == approx(0.5_f)); REQUIRE(1._f != approx(0.5_f)); REQUIRE(0._f != approx(0.5_f)); // test around 1 REQUIRE(2._f == approx(1.999_f, 1.e-3_f)); REQUIRE(2._f == approx(2.001_f, 1.e-3_f)); REQUIRE(2._f != approx(1.999_f, EPS)); REQUIRE(2._f != approx(2.001_f, EPS)); // test huge values REQUIRE(5.e12_f == approx(4.5e12_f, 0.2_f)); REQUIRE(5.e12_f == approx(5.5e12_f, 0.2_f)); REQUIRE(5.e12_f != approx(4.5e12_f, EPS)); REQUIRE(5.e12_f != approx(5.5e12_f, 0.01_f)); // test small values REQUIRE(3.e-12_f == approx(3.01e-12_f, 1.e-2_f)); REQUIRE(3.e-12_f == approx(2.99e-12_f, 1.e-2_f)); REQUIRE(3.e-12_f != approx(0._f, 1.e-12_f)); REQUIRE(3.e-12_f != approx(0._f, 1.e-12_f)); } // these are more or less checked by almostEqual test of vector, so test here just few basic cases TEST_CASE("Approx vector", "[approx]") { Vector v1(0.5_f, 2._f, -1._f); REQUIRE(v1 == approx(v1)); REQUIRE(v1 == approx((1._f + EPS) * v1)); REQUIRE(v1 == approx(Vector(0.5_f, 2._f, -1.01_f), 1e-2_f)); REQUIRE(v1 != approx(0.5_f * v1)); REQUIRE(v1 == approx(0.8_f * v1, 0.4_f)); } TEST_CASE("Approx tensor", "[approx]") { SymmetricTensor t1(Vector(1._f, 2._f, 3._f), Vector(-1._f, -2._f, -3._f)); REQUIRE(t1 == approx(t1)); REQUIRE(t1 == approx((1._f + EPS) * t1)); REQUIRE(t1 != approx(t1 + SymmetricTensor::identity() * 0.01_f)); REQUIRE(t1 == approx(t1 + SymmetricTensor::identity() * 0.01_f, 0.01_f)); REQUIRE(t1 != approx(0.5_f * t1)); REQUIRE(t1 == approx(0.8_f * t1, 0.4_f)); } TEST_CASE("Approx traceless tensor", "[approx]") { TracelessTensor t1(Vector(1._f, 2._f, 3._f), Vector(2._f, -5._f, -1._f), Vector(3._f, -1._f, 4._f)); REQUIRE(t1 == approx(t1)); REQUIRE(t1 == approx((1._f + EPS) * t1)); TracelessTensor t2(Vector(1._f, 0._f, 0._f), Vector(0._f, 0._f, 0._f), Vector(0._f, 0._f, -1._f)); REQUIRE(t1 != approx(t1 + t2 * 0.01_f)); REQUIRE(t1 == approx(t1 + t2 * 0.01_f, 0.01_f)); REQUIRE(t1 != approx(0.5_f * t1)); REQUIRE(t1 == approx(0.8_f * t1, 0.4_f)); }
huuuuusy/Programming-Practice-Everyday
LeetCode/python-R1/0027-移除元素/V2.py
""" @Author: huuuuusy @GitHub: https://github.com/huuuuusy 系统: Ubuntu 18.04 IDE: VS Code 1.36 工具: python == 3.7.3 """ """ 思路: 使用filter + lambda对数组进行筛选 结果: 本地运行可以,但是无法通过测试,猜测网站测试不允许对nums进行filter操作 本思路可以作为日常使用的参考 """ class Solution: def removeElement(self, nums, val): nums = filter(lambda num : num != val, nums) nums = [num for num in nums] return len(nums) if __name__ == "__main__": nums = [3,2,2,3] val = 3 answer = Solution().removeElement(nums, val) print(answer)
PudgyPoppins/caps
cal/migrations/0022_auto_20200812_0019.py
<filename>cal/migrations/0022_auto_20200812_0019.py<gh_stars>0 # Generated by Django 3.0.8 on 2020-08-12 00:19 import datetime from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('cal', '0021_attendee_email'), ] operations = [ migrations.AddField( model_name='event', name='end_date', field=models.DateField(default=datetime.date.today, verbose_name='ending date'), ), migrations.AddField( model_name='event', name='start_date', field=models.DateField(default=datetime.date.today, verbose_name='starting date'), ), migrations.AlterField( model_name='event', name='end_time', field=models.TimeField(default=django.utils.timezone.now, null=True, verbose_name='ending time'), ), migrations.AlterField( model_name='event', name='start_time', field=models.TimeField(default=django.utils.timezone.now, null=True, verbose_name='starting time'), ), ]
perfectrecall/aws-sdk-cpp
aws-cpp-sdk-braket/include/aws/braket/model/CreateQuantumTaskRequest.h
<filename>aws-cpp-sdk-braket/include/aws/braket/model/CreateQuantumTaskRequest.h<gh_stars>1-10 /** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/braket/Braket_EXPORTS.h> #include <aws/braket/BraketRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/core/utils/memory/stl/AWSMap.h> #include <utility> #include <aws/core/utils/UUID.h> namespace Aws { namespace Braket { namespace Model { /** */ class AWS_BRAKET_API CreateQuantumTaskRequest : public BraketRequest { public: CreateQuantumTaskRequest(); // Service request name is the Operation name which will send this request out, // each operation should has unique request name, so that we can get operation's name from this request. // Note: this is not true for response, multiple operations may have the same response name, // so we can not get operation's name from response. inline virtual const char* GetServiceRequestName() const override { return "CreateQuantumTask"; } Aws::String SerializePayload() const override; /** * <p>The action associated with the task.</p> */ inline const Aws::String& GetAction() const{ return m_action; } /** * <p>The action associated with the task.</p> */ inline bool ActionHasBeenSet() const { return m_actionHasBeenSet; } /** * <p>The action associated with the task.</p> */ inline void SetAction(const Aws::String& value) { m_actionHasBeenSet = true; m_action = value; } /** * <p>The action associated with the task.</p> */ inline void SetAction(Aws::String&& value) { m_actionHasBeenSet = true; m_action = std::move(value); } /** * <p>The action associated with the task.</p> */ inline void SetAction(const char* value) { m_actionHasBeenSet = true; m_action.assign(value); } /** * <p>The action associated with the task.</p> */ inline CreateQuantumTaskRequest& WithAction(const Aws::String& value) { SetAction(value); return *this;} /** * <p>The action associated with the task.</p> */ inline CreateQuantumTaskRequest& WithAction(Aws::String&& value) { SetAction(std::move(value)); return *this;} /** * <p>The action associated with the task.</p> */ inline CreateQuantumTaskRequest& WithAction(const char* value) { SetAction(value); return *this;} /** * <p>The client token associated with the request.</p> */ inline const Aws::String& GetClientToken() const{ return m_clientToken; } /** * <p>The client token associated with the request.</p> */ inline bool ClientTokenHasBeenSet() const { return m_clientTokenHasBeenSet; } /** * <p>The client token associated with the request.</p> */ inline void SetClientToken(const Aws::String& value) { m_clientTokenHasBeenSet = true; m_clientToken = value; } /** * <p>The client token associated with the request.</p> */ inline void SetClientToken(Aws::String&& value) { m_clientTokenHasBeenSet = true; m_clientToken = std::move(value); } /** * <p>The client token associated with the request.</p> */ inline void SetClientToken(const char* value) { m_clientTokenHasBeenSet = true; m_clientToken.assign(value); } /** * <p>The client token associated with the request.</p> */ inline CreateQuantumTaskRequest& WithClientToken(const Aws::String& value) { SetClientToken(value); return *this;} /** * <p>The client token associated with the request.</p> */ inline CreateQuantumTaskRequest& WithClientToken(Aws::String&& value) { SetClientToken(std::move(value)); return *this;} /** * <p>The client token associated with the request.</p> */ inline CreateQuantumTaskRequest& WithClientToken(const char* value) { SetClientToken(value); return *this;} /** * <p>The ARN of the device to run the task on.</p> */ inline const Aws::String& GetDeviceArn() const{ return m_deviceArn; } /** * <p>The ARN of the device to run the task on.</p> */ inline bool DeviceArnHasBeenSet() const { return m_deviceArnHasBeenSet; } /** * <p>The ARN of the device to run the task on.</p> */ inline void SetDeviceArn(const Aws::String& value) { m_deviceArnHasBeenSet = true; m_deviceArn = value; } /** * <p>The ARN of the device to run the task on.</p> */ inline void SetDeviceArn(Aws::String&& value) { m_deviceArnHasBeenSet = true; m_deviceArn = std::move(value); } /** * <p>The ARN of the device to run the task on.</p> */ inline void SetDeviceArn(const char* value) { m_deviceArnHasBeenSet = true; m_deviceArn.assign(value); } /** * <p>The ARN of the device to run the task on.</p> */ inline CreateQuantumTaskRequest& WithDeviceArn(const Aws::String& value) { SetDeviceArn(value); return *this;} /** * <p>The ARN of the device to run the task on.</p> */ inline CreateQuantumTaskRequest& WithDeviceArn(Aws::String&& value) { SetDeviceArn(std::move(value)); return *this;} /** * <p>The ARN of the device to run the task on.</p> */ inline CreateQuantumTaskRequest& WithDeviceArn(const char* value) { SetDeviceArn(value); return *this;} /** * <p>The parameters for the device to run the task on.</p> */ inline const Aws::String& GetDeviceParameters() const{ return m_deviceParameters; } /** * <p>The parameters for the device to run the task on.</p> */ inline bool DeviceParametersHasBeenSet() const { return m_deviceParametersHasBeenSet; } /** * <p>The parameters for the device to run the task on.</p> */ inline void SetDeviceParameters(const Aws::String& value) { m_deviceParametersHasBeenSet = true; m_deviceParameters = value; } /** * <p>The parameters for the device to run the task on.</p> */ inline void SetDeviceParameters(Aws::String&& value) { m_deviceParametersHasBeenSet = true; m_deviceParameters = std::move(value); } /** * <p>The parameters for the device to run the task on.</p> */ inline void SetDeviceParameters(const char* value) { m_deviceParametersHasBeenSet = true; m_deviceParameters.assign(value); } /** * <p>The parameters for the device to run the task on.</p> */ inline CreateQuantumTaskRequest& WithDeviceParameters(const Aws::String& value) { SetDeviceParameters(value); return *this;} /** * <p>The parameters for the device to run the task on.</p> */ inline CreateQuantumTaskRequest& WithDeviceParameters(Aws::String&& value) { SetDeviceParameters(std::move(value)); return *this;} /** * <p>The parameters for the device to run the task on.</p> */ inline CreateQuantumTaskRequest& WithDeviceParameters(const char* value) { SetDeviceParameters(value); return *this;} /** * <p>The token for an Amazon Braket job that associates it with the quantum * task.</p> */ inline const Aws::String& GetJobToken() const{ return m_jobToken; } /** * <p>The token for an Amazon Braket job that associates it with the quantum * task.</p> */ inline bool JobTokenHasBeenSet() const { return m_jobTokenHasBeenSet; } /** * <p>The token for an Amazon Braket job that associates it with the quantum * task.</p> */ inline void SetJobToken(const Aws::String& value) { m_jobTokenHasBeenSet = true; m_jobToken = value; } /** * <p>The token for an Amazon Braket job that associates it with the quantum * task.</p> */ inline void SetJobToken(Aws::String&& value) { m_jobTokenHasBeenSet = true; m_jobToken = std::move(value); } /** * <p>The token for an Amazon Braket job that associates it with the quantum * task.</p> */ inline void SetJobToken(const char* value) { m_jobTokenHasBeenSet = true; m_jobToken.assign(value); } /** * <p>The token for an Amazon Braket job that associates it with the quantum * task.</p> */ inline CreateQuantumTaskRequest& WithJobToken(const Aws::String& value) { SetJobToken(value); return *this;} /** * <p>The token for an Amazon Braket job that associates it with the quantum * task.</p> */ inline CreateQuantumTaskRequest& WithJobToken(Aws::String&& value) { SetJobToken(std::move(value)); return *this;} /** * <p>The token for an Amazon Braket job that associates it with the quantum * task.</p> */ inline CreateQuantumTaskRequest& WithJobToken(const char* value) { SetJobToken(value); return *this;} /** * <p>The S3 bucket to store task result files in.</p> */ inline const Aws::String& GetOutputS3Bucket() const{ return m_outputS3Bucket; } /** * <p>The S3 bucket to store task result files in.</p> */ inline bool OutputS3BucketHasBeenSet() const { return m_outputS3BucketHasBeenSet; } /** * <p>The S3 bucket to store task result files in.</p> */ inline void SetOutputS3Bucket(const Aws::String& value) { m_outputS3BucketHasBeenSet = true; m_outputS3Bucket = value; } /** * <p>The S3 bucket to store task result files in.</p> */ inline void SetOutputS3Bucket(Aws::String&& value) { m_outputS3BucketHasBeenSet = true; m_outputS3Bucket = std::move(value); } /** * <p>The S3 bucket to store task result files in.</p> */ inline void SetOutputS3Bucket(const char* value) { m_outputS3BucketHasBeenSet = true; m_outputS3Bucket.assign(value); } /** * <p>The S3 bucket to store task result files in.</p> */ inline CreateQuantumTaskRequest& WithOutputS3Bucket(const Aws::String& value) { SetOutputS3Bucket(value); return *this;} /** * <p>The S3 bucket to store task result files in.</p> */ inline CreateQuantumTaskRequest& WithOutputS3Bucket(Aws::String&& value) { SetOutputS3Bucket(std::move(value)); return *this;} /** * <p>The S3 bucket to store task result files in.</p> */ inline CreateQuantumTaskRequest& WithOutputS3Bucket(const char* value) { SetOutputS3Bucket(value); return *this;} /** * <p>The key prefix for the location in the S3 bucket to store task results * in.</p> */ inline const Aws::String& GetOutputS3KeyPrefix() const{ return m_outputS3KeyPrefix; } /** * <p>The key prefix for the location in the S3 bucket to store task results * in.</p> */ inline bool OutputS3KeyPrefixHasBeenSet() const { return m_outputS3KeyPrefixHasBeenSet; } /** * <p>The key prefix for the location in the S3 bucket to store task results * in.</p> */ inline void SetOutputS3KeyPrefix(const Aws::String& value) { m_outputS3KeyPrefixHasBeenSet = true; m_outputS3KeyPrefix = value; } /** * <p>The key prefix for the location in the S3 bucket to store task results * in.</p> */ inline void SetOutputS3KeyPrefix(Aws::String&& value) { m_outputS3KeyPrefixHasBeenSet = true; m_outputS3KeyPrefix = std::move(value); } /** * <p>The key prefix for the location in the S3 bucket to store task results * in.</p> */ inline void SetOutputS3KeyPrefix(const char* value) { m_outputS3KeyPrefixHasBeenSet = true; m_outputS3KeyPrefix.assign(value); } /** * <p>The key prefix for the location in the S3 bucket to store task results * in.</p> */ inline CreateQuantumTaskRequest& WithOutputS3KeyPrefix(const Aws::String& value) { SetOutputS3KeyPrefix(value); return *this;} /** * <p>The key prefix for the location in the S3 bucket to store task results * in.</p> */ inline CreateQuantumTaskRequest& WithOutputS3KeyPrefix(Aws::String&& value) { SetOutputS3KeyPrefix(std::move(value)); return *this;} /** * <p>The key prefix for the location in the S3 bucket to store task results * in.</p> */ inline CreateQuantumTaskRequest& WithOutputS3KeyPrefix(const char* value) { SetOutputS3KeyPrefix(value); return *this;} /** * <p>The number of shots to use for the task.</p> */ inline long long GetShots() const{ return m_shots; } /** * <p>The number of shots to use for the task.</p> */ inline bool ShotsHasBeenSet() const { return m_shotsHasBeenSet; } /** * <p>The number of shots to use for the task.</p> */ inline void SetShots(long long value) { m_shotsHasBeenSet = true; m_shots = value; } /** * <p>The number of shots to use for the task.</p> */ inline CreateQuantumTaskRequest& WithShots(long long value) { SetShots(value); return *this;} /** * <p>Tags to be added to the quantum task you're creating.</p> */ inline const Aws::Map<Aws::String, Aws::String>& GetTags() const{ return m_tags; } /** * <p>Tags to be added to the quantum task you're creating.</p> */ inline bool TagsHasBeenSet() const { return m_tagsHasBeenSet; } /** * <p>Tags to be added to the quantum task you're creating.</p> */ inline void SetTags(const Aws::Map<Aws::String, Aws::String>& value) { m_tagsHasBeenSet = true; m_tags = value; } /** * <p>Tags to be added to the quantum task you're creating.</p> */ inline void SetTags(Aws::Map<Aws::String, Aws::String>&& value) { m_tagsHasBeenSet = true; m_tags = std::move(value); } /** * <p>Tags to be added to the quantum task you're creating.</p> */ inline CreateQuantumTaskRequest& WithTags(const Aws::Map<Aws::String, Aws::String>& value) { SetTags(value); return *this;} /** * <p>Tags to be added to the quantum task you're creating.</p> */ inline CreateQuantumTaskRequest& WithTags(Aws::Map<Aws::String, Aws::String>&& value) { SetTags(std::move(value)); return *this;} /** * <p>Tags to be added to the quantum task you're creating.</p> */ inline CreateQuantumTaskRequest& AddTags(const Aws::String& key, const Aws::String& value) { m_tagsHasBeenSet = true; m_tags.emplace(key, value); return *this; } /** * <p>Tags to be added to the quantum task you're creating.</p> */ inline CreateQuantumTaskRequest& AddTags(Aws::String&& key, const Aws::String& value) { m_tagsHasBeenSet = true; m_tags.emplace(std::move(key), value); return *this; } /** * <p>Tags to be added to the quantum task you're creating.</p> */ inline CreateQuantumTaskRequest& AddTags(const Aws::String& key, Aws::String&& value) { m_tagsHasBeenSet = true; m_tags.emplace(key, std::move(value)); return *this; } /** * <p>Tags to be added to the quantum task you're creating.</p> */ inline CreateQuantumTaskRequest& AddTags(Aws::String&& key, Aws::String&& value) { m_tagsHasBeenSet = true; m_tags.emplace(std::move(key), std::move(value)); return *this; } /** * <p>Tags to be added to the quantum task you're creating.</p> */ inline CreateQuantumTaskRequest& AddTags(const char* key, Aws::String&& value) { m_tagsHasBeenSet = true; m_tags.emplace(key, std::move(value)); return *this; } /** * <p>Tags to be added to the quantum task you're creating.</p> */ inline CreateQuantumTaskRequest& AddTags(Aws::String&& key, const char* value) { m_tagsHasBeenSet = true; m_tags.emplace(std::move(key), value); return *this; } /** * <p>Tags to be added to the quantum task you're creating.</p> */ inline CreateQuantumTaskRequest& AddTags(const char* key, const char* value) { m_tagsHasBeenSet = true; m_tags.emplace(key, value); return *this; } private: Aws::String m_action; bool m_actionHasBeenSet; Aws::String m_clientToken; bool m_clientTokenHasBeenSet; Aws::String m_deviceArn; bool m_deviceArnHasBeenSet; Aws::String m_deviceParameters; bool m_deviceParametersHasBeenSet; Aws::String m_jobToken; bool m_jobTokenHasBeenSet; Aws::String m_outputS3Bucket; bool m_outputS3BucketHasBeenSet; Aws::String m_outputS3KeyPrefix; bool m_outputS3KeyPrefixHasBeenSet; long long m_shots; bool m_shotsHasBeenSet; Aws::Map<Aws::String, Aws::String> m_tags; bool m_tagsHasBeenSet; }; } // namespace Model } // namespace Braket } // namespace Aws
scottwedge/gd.py
gd/api/__init__.py
<reponame>scottwedge/gd.py from gd.api.enums import * from gd.api.loader import * from gd.api.editor import * from gd.api.struct import * from gd.api.hsv import * from gd.api.save import * from gd.api.utils import *
carefree0910/carefree-learn
setup.py
<filename>setup.py from setuptools import setup, find_packages VERSION = "0.2.0" DESCRIPTION = "Deep Learning with PyTorch made easy" with open("README.md", encoding="utf-8") as f: LONG_DESCRIPTION = f.read() setup( name="carefree-learn", version=VERSION, packages=find_packages(exclude=("tests",)), install_requires=[ "ftfy", "regex", "lmdb", "einops", "albumentations", "scikit-image", "numba>=0.50", "mlflow", "onnx", "onnx-simplifier", "onnxruntime", "plotly", "carefree-data>=0.2.5", "carefree-toolkit>=0.2.8", "dill", "future", "psutil", "cython>=0.29.12", "numpy>=1.19.2", "scipy>=1.2.1", "scikit-learn>=0.23.1", "matplotlib>=3.0.3", ], author="carefree0910", author_email="<EMAIL>", url="https://github.com/carefree0910/carefree-learn", download_url=f"https://github.com/carefree0910/carefree-learn/archive/v{VERSION}.tar.gz", description=DESCRIPTION, long_description=LONG_DESCRIPTION, long_description_content_type="text/markdown", keywords="python machine-learning deep-learning solution PyTorch", )
antoineFrau/design-pattern-java
TD-PatternStrategy/src/com/td1/armes/Couteau.java
<filename>TD-PatternStrategy/src/com/td1/armes/Couteau.java package com.td1.armes; public class Couteau implements Arme { @Override public String seBattre() { return "utilise son couteau pour se battre"; } }
Nabila118/DBProject
demos/React/app/tabs/fluidsize/app.js
<gh_stars>0 import React from 'react'; import ReactDOM from 'react-dom'; import JqxTabs from '../../../jqwidgets-react/react_jqxtabs.js'; class App extends React.Component { render () { let tabsHTML = ` <ul> <li style="margin-left: 30px;">Node.js</li> <li>JavaServer Pages</li> <li>Active Server Pages</li> </ul> <div> Node.js is an event-driven I/O server-side JavaScript environment based on V8. It is intended for writing scalable network programs such as web servers. It was created by <NAME> in 2009, and its growth is sponsored by Joyent, which employs Dahl. Similar environments written in other programming languages include Twisted for Python, Perl Object Environment for Perl, libevent for C and EventMachine for Ruby. Unlike most JavaScript, it is not executed in a web browser, but is instead a form of server-side JavaScript. Node.js implements some CommonJS specifications. Node.js includes a REPL environment for interactive testing. </div> <div> JavaServer Pages (JSP) is a Java technology that helps software developers serve dynamically generated web pages based on HTML, XML, or other document types. Released in 1999 as Sun's answer to ASP and PHP,[citation needed] JSP was designed to address the perception that the Java programming environment didn't provide developers with enough support for the Web. To deploy and run, a compatible web server with servlet container is required. The Java Servlet and the JavaServer Pages (JSP) specifications from Sun Microsystems and the JCP (Java Community Process) must both be met by the container. </div> <div> ASP.NET is a web application framework developed and marketed by Microsoft to allow programmers to build dynamic web sites, web applications and web services. It was first released in January 2002 with version 1.0 of the .NET Framework, and is the successor to Microsoft's Active Server Pages (ASP) technology. ASP.NET is built on the Common Language Runtime (CLR), allowing programmers to write ASP.NET code using any supported .NET language. The ASP.NET SOAP extension framework allows ASP.NET components to process SOAP messages. </div> `; return ( <JqxTabs ref='myTabs' template={tabsHTML} width={'100%'} height={'100%'} /> ) } } ReactDOM.render(<App />, document.getElementById('app'));
sivashanek/litigait-web
app/blocks/records/constants.js
<filename>app/blocks/records/constants.js /* * * constants * */ export default function constants(name) { const url = `lg/${name}`; return { LOAD_RECORD: `${url}/LOAD_RECORD`, LOAD_RECORD_SUCCESS: `${url}/LOAD_RECORD_SUCCESS`, LOAD_RECORD_ERROR: `${url}/LOAD_RECORD_ERROR`, LOAD_RECORDS: `${url}/LOAD_RECORDS`, LOAD_RECORDS_SUCCESS: `${url}/LOAD_RECORDS_SUCCESS`, LOAD_RECORDS_ERROR: `${url}/LOAD_RECORDS_ERROR`, CREATE_RECORD: `${url}/CREATE_RECORD`, CREATE_RECORD_SUCCESS: `${url}/CREATE_RECORD_SUCCESS`, CREATE_RECORD_ERROR: `${url}/CREATE_RECORD_ERROR`, UPDATE_RECORD: `${url}/UPDATE_RECORD`, UPDATE_RECORD_SUCCESS: `${url}/UPDATE_RECORD_SUCCESS`, UPDATE_RECORD_ERROR: `${url}/UPDATE_RECORD_ERROR`, DELETE_RECORD: `${url}/DELETE_RECORD`, DELETE_RECORD_SUCCESS: `${url}/DELETE_RECORD_SUCCESS`, DELETE_RECORD_ERROR: `${url}/DELETE_RECORD_ERROR`, LOAD_RECORDS_VALID_CACHE: `${url}/LOAD_RECORDS_VALID_CACHE`, }; }
SCSLaboratory/BearOS
usr/include/swint.h
<reponame>SCSLaboratory/BearOS #pragma once #include <sys/swint.h>
bellcliff/appium
test/functional/ios/uicatalog/find-by-xpath-specs.js
"use strict"; var setup = require("../../common/setup-base") , desired = require('././desired') , Q = require("q") , _ = require("underscore") , spinWait = require("../../../helpers/spin.js").spinWait; describe('uicatalog - find by xpath @skip-ios6', function () { var driver; setup(this, desired).then(function (d) { driver = d; }); describe('individual calls', function () { var setupXpath = function (driver) { return driver.elementByXPath("//UIAStaticText[contains(@label,'Buttons')]") .click(); }; afterEach(function (done) { driver .elementByName('UICatalog').click() .sleep(1000) .nodeify(done); }); it('should return the last button', function (done) { driver .resolve(setupXpath(driver)) .elementByXPath("//UIAButton[last()]").text() .should.become("Button") // this is the name of the last button .nodeify(done); }); it('should return a single element', function (done) { driver .resolve(setupXpath(driver)) .elementByXPath("//UIAButton").text() .should.become("UICatalog") .nodeify(done); }); it('should return multiple elements', function (done) { driver .resolve(setupXpath(driver)) .elementsByXPath("//UIAButton") .should.eventually.have.length.above(5) .nodeify(done); }); it('should filter by name', function (done) { driver .resolve(setupXpath(driver)) .elementByXPath("//UIAButton[@name='X Button']").text() .should.become("X Button") .nodeify(done); }); it('should know how to restrict root-level elements', function (done) { driver .resolve(setupXpath(driver)) .elementByXPath("/UIAButton") .should.be.rejectedWith(/status: 7/) .nodeify(done); }); it('should search an extended path by child', function (done) { driver .resolve(setupXpath(driver)) .then(function () { return spinWait(function () { return driver.elementByXPath("//UIANavigationBar/UIAStaticText") .text().should.become('Buttons'); }); }).nodeify(done); }); it('should search an extended path by descendant', function (done) { driver .resolve(setupXpath(driver)) .elementsByXPath("//UIATableCell//UIAButton").then(function (els) { return Q.all(_(els).map(function (el) { return el.text(); })); }).then(function (texts) { texts.should.not.include("UICatalog"); texts.should.include("X Button"); }).nodeify(done); }); it('should filter by indices', function (done) { driver .resolve(setupXpath(driver)) .elementByXPath("//UIATableCell[4]/UIAButton[1]") .getAttribute('name').should.become("X Button") .nodeify(done); }); it('should filter by partial text', function (done) { driver .resolve(setupXpath(driver)) .elementByXPath("//UIATableCell//UIAButton[contains(@name, 'X ')]").text() .should.become("X Button") .nodeify(done); }); describe('duplicate text field', function () { it('should find only one text field', function (done) { driver .waitForElementByName('*Text Fields*', 3000, 500).click() .sleep(2000) .elementsByXPath('//UIATableView["Empty list"]/UIATableCell[1]/UIATextField') .should.eventually.have.length(1) .nodeify(done); }); it('should find only one text field when doing relative search', function (done) { driver .waitForElementByName('*Text Fields*', 3000, 500).click() .sleep(2000) .elementsByXPath('//UIATableView["Empty list"]') .elementsByXPath('>', '//UIATableCell[1]/UIATextField') .should.eventually.have.length(1) .nodeify(done); }); it('should find only one secure text field', function (done) { driver .waitForElementByName('*Text Fields*', 3000, 500).click() .sleep(2000) .elementsByXPath('//UIATableView["Empty list"]/UIATableCell[3]/UIASecureTextField') .should.eventually.have.length(1) .nodeify(done); }); }); }); describe('multiple calls', function () { var runs = 5; var test = function (path, minLength) { return function () { it('should not crash', function (done) { driver .elementsByXPath(path) .should.eventually.have.length.above(minLength) .nodeify(done); }); }; }; describe('finding specific path', function () { for (var n = 0; n < runs; n++) { describe('test ' + (n + 1), test("//UIAApplication[1]/UIAWindow/UIATableView/UIATableCell", 17)); } }); describe('finding //*', function () { for (var n = 0; n < runs; n++) { describe('test ' + (n + 1), test("//*", 52)); } }); }); });
aryan-gupta/ECGR4181
HW1/deprecated/DinReader.cpp
<filename>HW1/deprecated/DinReader.cpp #include <string> #include "DinReader.hpp" // Every impl I take a look at shows me that there is no way to convert a // byte buffer into a string stream to parse using op>> without copying. // So low lever stuff here I come... DinReader::DinReader(std::string file) : mFile{ file }, mBuffer{ new byte_t[BUFF_SZ] }, mLoc{ mBuffer.get() } { nextBuffer(); } void DinReader::nextBuffer() { mFile.read(mBuffer.get(), BUFF_SZ - 1); mBuffer[BUFF_SZ - 1] = '\0'; // set last byte to \0 for str parsing } std::pair<Ops, uint64_t> DinReader::getLine() { return { }; }
mixit-craftsmanship/mixit-craftsmanship
test/server/libs/cacheFactoryTest.js
<filename>test/server/libs/cacheFactoryTest.js var cacheFactory = require('../../../libs/cacheFactory'); var promise = require('promise'); describe('Cache module', function () { describe('Given empty cache', function () { it('When call getOrExecute then execute function and return result', function (done) { var executed = false; var cache = cacheFactory.create(); cache.getOrExecute('essai', function(){ executed = true; return 5; }).then(function (result) { executed.should.be.true; result.should.equal(5); done(); }).catch(done); }); it('When call getOrExecute with promise then execute function and return result', function (done) { var cache = cacheFactory.create(); var executed = false; cache.getOrExecute('essai', function(){ return new promise(function(resolve){ executed = true; resolve(5); }); }).then(function (result) { executed.should.be.true; result.should.equal(5); done(); }).catch(done); }); it('When call getOrExecute with promise then execute function and return result', function (done) { var cache = cacheFactory.create(); var executed = false; cache.getOrExecute('essai', function(){ return new promise(function(resolve){ executed = true; resolve(5); }); }).then(function (result) { executed.should.be.true; result.should.equal(5); done(); }).catch(done); }); it('When call getOrExecute with error function then execute function and raise exception', function (done) { var cache = cacheFactory.create(); cache.getOrExecute('essai', function(){ return new promise(function(resolve, reject){ reject('error'); }); }).then(function () { done('Not raise exception'); }).catch(function(error){ error.should.be.ok; done(); }); }); it('When call getOrExecute with error function then result is not in cache', function (done) { var cache = cacheFactory.create(); cache.getOrExecute('essai', function(){ return new promise(function(resolve, reject){ reject('error'); }); }).then(function () { done('Not raise exception'); }).catch(function(error){ return cache.getOrExecute('essai', function(){ return 50; }).then(function(result){ result.should.equal(50); done(); }); }).catch(done); }); }); describe('Given a cache with key essai', function () { var cacheKey = 'essai'; var cacheValue = 5; var cache; beforeEach(function(done){ cache = cacheFactory.create(); cache.getOrExecute(cacheKey, function(){ return cacheValue; }).then(function(){ done(); }).catch(done); }); it('When call getOrExecute then not execute function and return cacheValue', function (done) { var executed = false; cache.getOrExecute(cacheKey, function(){ executed = true; return 10; }).then(function (result) { executed.should.be.false; result.should.equal(cacheValue); done(); }).catch(done); }); it('When clean then clean cache', function (done) { var executed = false; cache.clean(cacheKey); cache.getOrExecute(cacheKey, function(){ executed = true; return 10; }).then(function (result) { executed.should.be.true; result.should.equal(10); done(); }).catch(done); }); it('When call getOrExecute with other key then execute function and return result', function (done) { var executed = false; cache.getOrExecute("otherCache", function(){ executed = true; return 10; }).then(function (result) { executed.should.be.true; result.should.equal(10); done(); }).catch(done); }); it('When clean with other key then not clean cache of key', function (done) { var executed = false; cache.clean("otherCache"); cache.getOrExecute(cacheKey, function(){ executed = true; return 10; }).then(function (result) { executed.should.be.false; result.should.equal(5); done(); }).catch(done); }); }); });
ExcitedBlob/simorgh
cypress/integration/pages/mostReadPage/tests.js
import path from 'ramda/src/path'; import config from '../../../support/config/services'; export default ({ service, pageType, variant }) => { describe(`No testsToAlwaysRun to run for ${service} ${pageType}`, () => { describe(`Tests for ${service} ${pageType}`, () => { describe('Most Read component', () => { before(() => { cy.getToggles(config[service].name); }); // Allows constructing most watched path with variant const serviceVariant = variant === 'default' ? '' : `/${variant}`; const mostReadPath = `/${config[service].name}/mostread${serviceVariant}.json`; it('should show/not show the Most Read component if the toggle is enabled for the service', function test() { // Find if the service has component enabled in toggles, unless it is live environment which does not have mostRead toggle if (Cypress.env('APP_ENV') !== 'live') { cy.fixture(`toggles/${config[service].name}.json`).then(toggles => { const mostReadIsEnabled = path(['mostRead', 'enabled'], toggles); cy.log(`Service toggle enabled ${mostReadIsEnabled}`); // If toggle is enabled for that service, also check there are more than 0 records to show if (mostReadIsEnabled) { cy.request(mostReadPath).then(({ body: mostReadJson }) => { if (mostReadJson.totalRecords > 0) { cy.get('[data-e2e="most-read"]').within(() => { cy.get('li').should('exist'); }); } else { cy.log('Not enough records to show component'); cy.task('log', 'Not enough records to show component'); cy.get('[data-e2e="most-read"]').within(() => { cy.get('li').should('not.exist'); }); } }); } }); } else { cy.request(mostReadPath).then(({ body: mostReadJson }) => { if (mostReadJson.totalRecords > 0) { cy.get('[data-e2e="most-read"]').within(() => { cy.get('li').should('exist'); }); } else { cy.log('Not enough records to show component'); cy.task('log', 'Not enough records to show component'); cy.get('[data-e2e="most-read"]').within(() => { cy.get('li').should('not.exist'); }); } }); } }); }); }); }); };
nhl/link-move
link-move/src/main/java/com/nhl/link/move/annotation/AfterFksResolved.java
package com.nhl.link.move.annotation; import java.lang.annotation.*; /** * Annotation of a data segment transformation stage listener method that should be called after FK values * are resolved to objects. * * @since 2.12 */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited public @interface AfterFksResolved { }
aaliomer/exos
sys/dpf/output.c
/* * Copyright (C) 1997 Massachusetts Institute of Technology * * This software is being provided by the copyright holders under the * following license. By obtaining, using and/or copying this software, * you agree that you have read, understood, and will comply with the * following terms and conditions: * * Permission to use, copy, modify, distribute, and sell this software * and its documentation for any purpose and without fee or royalty is * hereby granted, provided that the full text of this NOTICE appears on * ALL copies of the software and documentation or portions thereof, * including modifications, that you make. * * THIS SOFTWARE IS PROVIDED "AS IS," AND COPYRIGHT HOLDERS MAKE NO * REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, * BUT NOT LIMITATION, COPYRIGHT HOLDERS MAKE NO REPRESENTATIONS OR * WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR * THAT THE USE OF THE SOFTWARE OR DOCUMENTATION WILL NOT INFRINGE ANY * THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. COPYRIGHT * HOLDERS WILL BEAR NO LIABILITY FOR ANY USE OF THIS SOFTWARE OR * DOCUMENTATION. * * The name and trademarks of copyright holders may NOT be used in * advertising or publicity pertaining to the software without specific, * written prior permission. Title to copyright in this software and any * associated documentation will at all times remain with copyright * holders. See the file AUTHORS which should have accompanied this software * for a list of all copyright holders. * * This file may be derived from previously copyrighted software. This * copyright applies only to those changes made by the copyright * holders listed in the AUTHORS file. The rest of this file is covered by * the copyright notices, if any, listed below. */ #include <dpf/dpf-internal.h> #include <dpf/demand.h> #include <xok/printf.h> static void dump(Atom p, int n); static void indent(int n) { while(n-- > 0) printf(" "); } /* Print out the tree. */ void dpf_output(void) { if(!dpf_base->kids.lh_first) { printf("Nil trie\n"); return; } printf("\nDumping ir.\n"); printf("base: \n"); dpf_dump(dpf_iptr); printf("rest: \n"); dump(dpf_base->kids.lh_first, 3); } static void dump_eqnode(Atom p, int n, int bits) { struct ir *ir; /* have to handle hash table as well. */ ir = &p->ir; if(!p->ht) { indent(n); printf("eq: a: %x sib: %x msg[%d:%d] & 0x%x == 0x%x, refcnt = %d, level = %d, align = %d", (int)p, (int)p->sibs.le_next, ir->u.eq.offset, bits, ir->u.eq.mask, ir->u.eq.val, p->refcnt, ir->level, ir->alignment); if(p->pid) printf(", pid = %d\n", p->pid); printf("\n"); dpf_dump(p->code); dump(p->kids.lh_first, n + 5); } else { Atom hte, h; int i, sz; Ht ht; printf("ht: \n"); dpf_dump(p->code); for(ht = p->ht, i = 0, sz = ht->htsz; i < sz; i++) { if(!(hte = ht->ht[i])) continue; indent(n); printf("{ val = 0x%x, ref = %d", hte->ir.u.eq.val, hte->refcnt); if(hte->pid) printf(", pid = %d", hte->pid); printf(" }\n"); dump(hte->kids.lh_first, n + 5); dpf_dump(hte->code); for(h = hte->next; h; h = h->next) { indent(n); printf("-> { val = 0x%x, ref = %d", h->ir.u.eq.val, h->refcnt); if(h->pid) printf(", pid = %d", h->pid); printf("}\n"); dump(h->kids.lh_first, n + 5); dpf_dump(h->code); } } indent(n); printf(" == msg[%d:%d] & 0x%x, refcnt = %d, level = %d\n", ir->u.eq.offset, bits, ir->u.eq.mask, p->refcnt, ir->level); } } static void dump_shiftnode(Atom p, int n, int bits) { struct ir *ir; indent(n); ir = &p->ir; printf("msg + msg[%d:%d] & 0x%x << %d, align = %d, refcnt = %d, level = %d", ir->u.shift.offset, bits, ir->u.shift.mask, ir->u.shift.shift, ir->u.shift.align, p->refcnt, ir->level); if(p->pid) printf(", pid = %d\n", p->pid); printf("\n"); dpf_dump(p->code); dump(p->kids.lh_first, n + 5); } static void dump(Atom p, int n) { if(!p) return; for(;; p = p->sibs.le_next) { if(dpf_iseq(&p->ir)) dump_eqnode(p, n, p->ir.u.eq.nbits); else if(dpf_isshift(&p->ir)) dump_shiftnode(p, n, p->ir.u.shift.nbits); else if(dpf_isaction(&p->ir)) { indent(n); printf("action\n"); dump(p->kids.lh_first, n+5); } else if (dpf_isstateeq(&p->ir)){ indent(n); printf("stateeq\n"); dump(p->kids.lh_first, n+5); } else { indent(n); printf("other\n"); dump(p->kids.lh_first, n+5); } if(!p->sibs.le_next) return; indent(n - 2); printf("OR\n"); } }
WietseGielen/Pong-Node.js
node_modules/opnr/example.js
var http = require('http') require('getport')(function(err, port) { if (err) throw err var server = http.createServer(function(req, res) { res.end('hello') }) server.listen(port, function(err) { if (err) throw err console.log(JSON.stringify({ url: 'localhost:'+port, type: 'connect', message: 'server running on '+port })) }) })
dsalinux/open-imob
src/main/java/br/com/softop/imobiliaria/entity/Login.java
<filename>src/main/java/br/com/softop/imobiliaria/entity/Login.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package br.com.softop.imobiliaria.entity; import java.io.Serializable; import java.util.Date; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; /** * * @author danilo */ @Entity @Table(name = "login") @XmlRootElement public class Login implements Serializable { private static final long serialVersionUID = 1L; public enum Permissao { ADMIN("Administrador"), USER("Usuario"); private String descricao; Permissao(String descricao){ this.descricao = descricao; } public String getDescricao() { return descricao; } public String getName(){ return name(); } } @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "id") private Integer id; @Basic(optional = false) @NotNull @Size(min = 1, max = 100) @Column(name = "login") private String login; @Basic(optional = false) @NotNull @Size(min = 1, max = 100) @Column(name = "senha") private String senha; // @Pattern(regexp="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", message="E-mail inválido")//if the field contains email address consider using this annotation to enforce field validation @Basic(optional = false) @NotNull @Size(min = 1, max = 45) @Column(name = "email") private String email; @Column(name = "data_desativacao") @Temporal(TemporalType.TIMESTAMP) private Date dataDesativacao; @Basic(optional = false) @NotNull @Column(name = "data_cadastro") @Temporal(TemporalType.TIMESTAMP) private Date dataCadastro; @Size(max = 30) @Column(name = "tema") private String tema; @Basic(optional = false) @NotNull @Column(name = "alterar_senha") private boolean alterarSenha; @Enumerated(EnumType.STRING) @Column(name="permissao") private Permissao permissao_; public Login() { } public Login(Integer id) { this.id = id; } public Login(Integer id, String login, String senha, String email, Date dataCadastro, boolean alterarSenha, Permissao permissao) { this.id = id; this.login = login; this.senha = senha; this.email = email; this.dataCadastro = dataCadastro; this.alterarSenha = alterarSenha; this.permissao_ = permissao; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public String getSenha() { return senha; } public void setSenha(String senha) { this.senha = senha; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Date getDataDesativacao() { return dataDesativacao; } public void setDataDesativacao(Date dataDesativacao) { this.dataDesativacao = dataDesativacao; } public Date getDataCadastro() { return dataCadastro; } public void setDataCadastro(Date dataCadastro) { this.dataCadastro = dataCadastro; } public String getTema() { return tema; } public void setTema(String tema) { this.tema = tema; } public boolean getAlterarSenha() { return alterarSenha; } public void setAlterarSenha(boolean alterarSenha) { this.alterarSenha = alterarSenha; } public Permissao getPermissao_() { return permissao_; } public void setPermissao_(Permissao permissao_) { this.permissao_ = permissao_; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Login)) { return false; } Login other = (Login) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "br.com.softop.projetobase.entity.Login[ id=" + id + " ]"; } }
muxanick/scala-native-java-stubs
javax/naming/event/NamingExceptionEvent.scala
<filename>javax/naming/event/NamingExceptionEvent.scala<gh_stars>0 package javax.naming.event import java.lang.Object import java.util.EventObject import javax.naming.NamingException import scala.scalanative.annotation.stub /** This class represents an event fired when the procedures/processes * used to collect information for notifying listeners of * NamingEvents threw a NamingException. * This can happen, for example, if the server which the listener is using * aborts subsequent to the addNamingListener() call. */ class NamingExceptionEvent extends EventObject { /** Constructs an instance of NamingExceptionEvent using * the context in which the NamingException was thrown and the exception * that was thrown. */ @stub def this(source: EventContext, exc: NamingException) = ??? /** Invokes the namingExceptionThrown() method on * a listener using this event. */ @stub def dispatch(listener: NamingListener): Unit = ??? /** Retrieves the EventContext that fired this event. */ @stub def getEventContext(): EventContext = ??? /** Retrieves the exception that was thrown. */ @stub def getException(): NamingException = ??? }
MrDML/LinKingSDKWLZG
LinKingSDK/Products/LinKingSDK.framework/Headers/LKUseAgreementView.h
// // LKUseAgreementView.h // LinKingSDK // // Created by leoan on 2020/7/31. // Copyright © 2020 <EMAIL>. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface LKUseAgreementView : UIView @property (weak, nonatomic) IBOutlet UIView *view_content; @property (weak, nonatomic) IBOutlet UIButton *button_checkBox; @property (weak, nonatomic) IBOutlet UIButton *button_ok; @property (weak, nonatomic) IBOutlet UILabel *label_title; @property (nonatomic,copy)void(^sureCallBack)(BOOL isSelect); + (instancetype)instanceUseAgreementView; @end NS_ASSUME_NONNULL_END
AlexeyKashintsev/PlatypusJS
web-client/src/platypus/src/com/eas/client/form/grid/columns/header/ModelHeaderNode.java
package com.eas.client.form.grid.columns.header; import com.bearsoft.gwt.ui.widgets.grid.DraggableHeader; import com.bearsoft.gwt.ui.widgets.grid.header.HeaderNode; import com.eas.client.form.grid.columns.ModelColumn; import com.eas.client.form.published.HasJsName; import com.eas.client.form.published.HasPublished; import com.eas.client.form.published.PublishedColor; import com.eas.client.form.published.PublishedFont; import com.eas.client.form.published.widgets.model.ModelDecoratorBox; import com.eas.client.form.published.widgets.model.ModelFormattedField; import com.google.gwt.core.client.JavaScriptObject; public class ModelHeaderNode extends HeaderNode<JavaScriptObject> implements HasJsName, HasPublished { protected JavaScriptObject published; protected String name; public ModelHeaderNode() { super(); column = new ModelColumn(); ((ModelColumn)column).setEditor(new ModelFormattedField()); header = new DraggableHeader<JavaScriptObject>("", null, column, this); } @Override public ModelHeaderNode lightCopy(){ ModelHeaderNode copied = new ModelHeaderNode(); copied.setColumn(column); copied.setHeader(header); return copied; } public PublishedColor getBackground() { return ((DraggableHeader<?>)header).getBackground(); } public void setBackground(PublishedColor aValue) { ((DraggableHeader<?>)header).setBackground(aValue); } public PublishedColor getForeground() { return ((DraggableHeader<?>)header).getForeground(); } public void setForeground(PublishedColor aValue) { ((DraggableHeader<?>)header).setForeground(aValue); } public PublishedFont getFont() { return ((DraggableHeader<?>)header).getFont(); } public void setFont(PublishedFont aValue) { ((DraggableHeader<?>)header).setFont(aValue); } public double getMinWidth() { return ((ModelColumn) column).getMinWidth(); } public void setMinWidth(double aValue) { ((ModelColumn) column).setMinWidth(aValue); } public double getMaxWidth() { return ((ModelColumn) column).getMaxWidth(); } public void setMaxWidth(double aValue) { ((ModelColumn) column).setMaxWidth(aValue); } public double getPreferredWidth() { return ((ModelColumn) column).getDesignedWidth(); } public void setPreferredWidth(double aValue) { ((ModelColumn) column).setWidth(aValue); } public String getField() { return ((ModelColumn) column).getField(); } public void setField(String aValue) { ((ModelColumn) column).setField(aValue); } public String getTitle() { return ((DraggableHeader<JavaScriptObject>) header).getTitle(); } public void setTitle(String aValue) { ((DraggableHeader<JavaScriptObject>) header).setTitle(aValue); } public boolean isResizable() { return ((DraggableHeader<JavaScriptObject>) header).isResizable(); } public void setResizable(boolean aValue) { ((DraggableHeader<JavaScriptObject>) header).setResizable(aValue); } public boolean isMoveable() { return ((DraggableHeader<JavaScriptObject>) header).isMoveable(); } public void setMoveable(boolean aValue) { ((DraggableHeader<JavaScriptObject>) header).setMoveable(aValue); } public boolean isVisible() { return ((ModelColumn) column).isVisible(); } public void setVisible(boolean aValue) { ((ModelColumn) column).setVisible(aValue); } @Override public String getJsName() { return name; } @Override public void setJsName(String aValue) { name = aValue; } public double getWidth() { return ((ModelColumn) column).getWidth(); } public void setWidth(double aValue) { ((ModelColumn) column).setWidth(aValue); } public boolean isReadonly() { return ((ModelColumn) column).isReadonly(); } public void setReadonly(boolean aValue) { ((ModelColumn) column).setReadonly(aValue); } public boolean isSortable() { return ((ModelColumn) column).isSortable(); } public String getSortField() { return ((ModelColumn) column).getSortField(); } public void setSortField(String aValue) { ((ModelColumn) column).setSortField(aValue); } public void setSortable(boolean aValue) { ((ModelColumn) column).setSortable(aValue); } public JavaScriptObject getOnRender() { return ((ModelColumn) column).getOnRender(); } public void setOnRender(JavaScriptObject aValue) { ((ModelColumn) column).setOnRender(aValue); } public JavaScriptObject getOnSelect() { return ((ModelColumn) column).getOnSelect(); } public void setOnSelect(JavaScriptObject aValue) { ((ModelColumn) column).setOnSelect(aValue); } @Override public JavaScriptObject getPublished() { return published; } @Override public void setPublished(JavaScriptObject aValue) { if (published != aValue) { published = aValue; ((ModelColumn) column).setPublished(published); if (published != null) { publish(this, published); } } } public void sort(){ ((ModelColumn) column).sort(); } public void sortDesc(){ ((ModelColumn) column).sortDesc(); } public void unsort(){ ((ModelColumn) column).unsort(); } public JavaScriptObject getJsEditor(){ return ((ModelColumn) column).getEditor().getPublished(); } public void setEditor(ModelDecoratorBox<?> aEditor){ ((ModelColumn) column).setEditor(aEditor); } private static native void publish(ModelHeaderNode aColumn, JavaScriptObject aPublished)/*-{ Object.defineProperty(aPublished, "editor", { get : function() { return aColumn.@com.eas.client.form.grid.columns.header.ModelHeaderNode::getJsEditor()(); }, set : function(aValue) { aColumn.@com.eas.client.form.grid.columns.header.ModelHeaderNode::setEditor(Lcom/eas/client/form/published/widgets/model/ModelDecoratorBox;)(aValue && aValue.unwrap ? aValue.unwrap() : null); } }); Object.defineProperty(aPublished, "field", { get : function() { return aColumn.@com.eas.client.form.grid.columns.header.ModelHeaderNode::getField()(); }, set : function(aValue) { aColumn.@com.eas.client.form.grid.columns.header.ModelHeaderNode::setField(Ljava/lang/String;)(aValue != null ? ''+aValue : ''); } }); Object.defineProperty(aPublished, "visible", { get : function() { return aColumn.@com.eas.client.form.grid.columns.header.ModelHeaderNode::isVisible()(); }, set : function(aValue) { aColumn.@com.eas.client.form.grid.columns.header.ModelHeaderNode::setVisible(Z)((false != aValue)); } }); Object.defineProperty(aPublished, "minWidth", { get : function() { return aColumn.@com.eas.client.form.grid.columns.header.ModelHeaderNode::getMinWidth()(); }, set : function(aValue) { aColumn.@com.eas.client.form.grid.columns.header.ModelHeaderNode::setMinWidth(D)(aValue != null ? aValue : 0); } }); Object.defineProperty(aPublished, "maxWidth", { get : function() { return aColumn.@com.eas.client.form.grid.columns.header.ModelHeaderNode::getMaxWidth()(); }, set : function(aValue) { aColumn.@com.eas.client.form.grid.columns.header.ModelHeaderNode::setMaxWidth(D)(aValue != null ? aValue : 0); } }); Object.defineProperty(aPublished, "preferredWidth", { get : function() { return aColumn.@com.eas.client.form.grid.columns.header.ModelHeaderNode::getPreferredWidth()(); }, set : function(aValue) { aColumn.@com.eas.client.form.grid.columns.header.ModelHeaderNode::setPreferredWidth(D)(aValue != null ? aValue : 0); } }); Object.defineProperty(aPublished, "width", { get : function() { return aColumn.@com.eas.client.form.grid.columns.header.ModelHeaderNode::getWidth()(); }, set : function(aValue) { aColumn.@com.eas.client.form.grid.columns.header.ModelHeaderNode::setWidth(D)(aValue != null ? aValue : 0); } }); Object.defineProperty(aPublished, "title", { get : function() { return aColumn.@com.eas.client.form.grid.columns.header.ModelHeaderNode::getTitle()(); }, set : function(aValue) { aColumn.@com.eas.client.form.grid.columns.header.ModelHeaderNode::setTitle(Ljava/lang/String;)(aValue != null ? ''+aValue : ''); } }); Object.defineProperty(aPublished, "resizable", { get : function() { return aColumn.@com.eas.client.form.grid.columns.header.ModelHeaderNode::isResizable()(); }, set : function(aValue) { aColumn.@com.eas.client.form.grid.columns.header.ModelHeaderNode::setResizable(Z)(!!aValue); } }); Object.defineProperty(aPublished, "movable", { get : function() { return aColumn.@com.eas.client.form.grid.columns.header.ModelHeaderNode::isMoveable()(); }, set : function(aValue) { aColumn.@com.eas.client.form.grid.columns.header.ModelHeaderNode::setMoveable(Z)(!!aValue); } }); Object.defineProperty(aPublished, "readonly", { get : function() { return aColumn.@com.eas.client.form.grid.columns.header.ModelHeaderNode::isReadonly()(); }, set : function(aValue) { aColumn.@com.eas.client.form.grid.columns.header.ModelHeaderNode::setReadonly(Z)(!!aValue); } }); Object.defineProperty(aPublished, "sortable", { get : function() { return aColumn.@com.eas.client.form.grid.columns.header.ModelHeaderNode::isSortable()(); }, set : function(aValue) { aColumn.@com.eas.client.form.grid.columns.header.ModelHeaderNode::setSortable(Z)(!!aValue); } }); Object.defineProperty(aPublished, "sortField", { get : function() { return aColumn.@com.eas.client.form.grid.columns.header.ModelHeaderNode::getSortField()(); }, set : function(aValue) { aColumn.@com.eas.client.form.grid.columns.header.ModelHeaderNode::setSortField(Ljava/lang/String;)(aValue != null ? ''+aValue : ''); } }); Object.defineProperty(aPublished, "foreground", { get : function() { return aColumn.@com.eas.client.form.grid.columns.header.ModelHeaderNode::getForeground()()(); }, set : function(aValue) { aColumn.@com.eas.client.form.grid.columns.header.ModelHeaderNode::setForeground(Lcom/eas/client/form/published/PublishedColor;)(aValue); } }); Object.defineProperty(aPublished, "background", { get : function() { return aColumn.@com.eas.client.form.grid.columns.header.ModelHeaderNode::getBackground()()(); }, set : function(aValue) { aColumn.@com.eas.client.form.grid.columns.header.ModelHeaderNode::setBackground(Lcom/eas/client/form/published/PublishedColor;)(aValue); } }); Object.defineProperty(aPublished, "font", { get : function() { return aColumn.@com.eas.client.form.grid.columns.header.ModelHeaderNode::getFont()()(); }, set : function(aValue) { aColumn.@com.eas.client.form.grid.columns.header.ModelHeaderNode::setFont(Lcom/eas/client/form/published/PublishedFont;)(aValue); } }); Object.defineProperty(aPublished, "onRender", { get : function() { return aColumn.@com.eas.client.form.grid.columns.header.ModelHeaderNode::getOnRender()(); }, set : function(aValue) { aColumn.@com.eas.client.form.grid.columns.header.ModelHeaderNode::setOnRender(Lcom/google/gwt/core/client/JavaScriptObject;)(aValue); } }); Object.defineProperty(aPublished, "onSelect", { get : function() { return aColumn.@com.eas.client.form.grid.columns.header.ModelHeaderNode::getOnSelect()(); }, set : function(aValue) { aColumn.@com.eas.client.form.grid.columns.header.ModelHeaderNode::setOnSelect(Lcom/google/gwt/core/client/JavaScriptObject;)(aValue); } }); aPublished.sort = function() { aColumn.@com.eas.client.form.grid.columns.header.ModelHeaderNode::sort()(); }; aPublished.sortDesc = function() { aColumn.@com.eas.client.form.grid.columns.header.ModelHeaderNode::sortDesc()(); }; aPublished.unsort = function() { aColumn.@com.eas.client.form.grid.columns.header.ModelHeaderNode::unsort()(); }; aPublished.removeColumnNode = function(aColumnFacade){ if(aColumnFacade && aColumnFacade.unwrap) return aColumn.@com.eas.client.form.grid.columns.header.ModelHeaderNode::removeColumnNode(Lcom/bearsoft/gwt/ui/widgets/grid/header/HeaderNode;)(aColumnFacade.unwrap()); else return false; }; aPublished.addColumnNode = function(aColumnFacade){ if(aColumnFacade && aColumnFacade.unwrap) aColumn.@com.eas.client.form.grid.columns.header.ModelHeaderNode::addColumnNode(Lcom/bearsoft/gwt/ui/widgets/grid/header/HeaderNode;)(aColumnFacade.unwrap()); }; aPublished.insertColumnNode = function(aIndex, aColumnFacade){ if(aColumnFacade && aColumnFacade.unwrap) aColumn.@com.eas.client.form.grid.columns.header.ModelHeaderNode::insertColumnNode(ILcom/bearsoft/gwt/ui/widgets/grid/header/HeaderNode;)(aIndex, aColumnFacade.unwrap()); }; aPublished.columnNodes = function(){ var nChildren = aColumn.@com.eas.client.form.grid.columns.header.ModelHeaderNode::getChildren()(); var nChildrenCount = nChildren.@java.util.List::size()(); var res = []; for(var c = 0; c < nChildrenCount; c++){ var nNode = nChildren.@java.util.List::get(I)(c); var jsNode = nNode.@com.eas.client.form.published.HasPublished::getPublished()(); res.push(jsNode); } return res; }; }-*/; }
femtoio/femtousb-blink-example
blinky/common/services/gfx/gfx.h
<reponame>femtoio/femtousb-blink-example<filename>blinky/common/services/gfx/gfx.h /** * \file * * \brief Graphical library API header file * * This files includes the correct header files for the graphics service * * Copyright (c) 2012-2014 Atmel Corporation. All rights reserved. * * \asf_license_start * * \page License * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name of Atmel may not be used to endorse or promote products derived * from this software without specific prior written permission. * * 4. This software may only be redistributed and used in connection with an * Atmel microcontroller product. * * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. * * \asf_license_stop * */ /** * Support and FAQ: visit <a href="http://www.atmel.com/design-support/">Atmel Support</a> */ #ifndef GFX_H_INCLUDED #define GFX_H_INCLUDED #include <assert.h> #include <compiler.h> #include <stdint.h> #ifdef __cplusplus extern "C" { #endif /* UC3 & ARM does not have PROGMEM, declare PROGMEM as const variables */ #ifndef PROGMEM_DECLARE # define PROGMEM_DECLARE(type, name) const type name # define PROGMEM_T const # define PROGMEM_PTR_T const * # define PROGMEM_READ_BYTE(x) *(x) #endif #if defined(CONF_GFX_HX8347A_ET024006DHU) # include "gfx_hx8347a_et024006dhu.h" # include "gfx_generic.h" # define CONF_GFX_USE_CLIPPING #elif defined(CONF_GFX_ILI9341_SDT028ATFT) # include "gfx_ili9341_sdt028atft.h" # include "gfx_generic.h" # define CONF_GFX_USE_CLIPPING #elif defined(CONF_GFX_HX8347A_ET024006DHU_EBI) # include "gfx_hx8347a_et024006dhu_ebi.h" # include "gfx_generic.h" # define CONF_GFX_USE_CLIPPING #elif defined(CONF_GFX_ILI9325_FTM280C34D) # include "gfx_ili9325_ftm280c34d.h" # include "gfx_generic.h" #elif defined(CONF_GFX_ILI93XX) # include "gfx_ili93xx.h" # include "gfx_generic.h" #else # error "Configuration for display controller/panel not selected" #endif /** * \defgroup gfx_group Graphical display system * This service provides an interface to drawing graphics on a graphical display * * The graphics service consists of the following: * - Display driver interface (gfx.h) * - General graphics drawing primitives (gfx_generic.h) * - Display and controller specific implementation (ex. * gfx_hx8347a_et024006dhu.h) * - Display controller driver (ex. hx8347a.c/h) * * The display driver interface provides an general interface to be used by * the application or by libraries. * * The generic drawing primitives is a library of functions for drawing * graphics primitives such as lines, rectangles and circles. It uses * other functions implemented by the display driver for drawing the * primitives. The implementation of these functions can optionally be * used by a display driver, but if the hardware of the display allows * faster handling of any of the primitives, the display driver can * implement it directly. * * The display specific drivers provides an interface to the graphical * display via the display controller. It implements the low level * communication with the display hardware, putting pixels on the display * and drawing primitives such as lines, circles and rectangles. Depending * on the display driver implementation, drawing the graphics primitives * might be handled by the generic graphics drawing primitives rather than the * display driver itself. * * @{ */ /** \name Driver-specific Definitions */ /** @{ */ /** * \typedef gfx_color_t * \brief Data type for color values native to the display. */ /** * \typedef gfx_coord_t * \brief Data type representing a coordinate on the screen. */ /** * \def GFX_COLOR(r, g, b) * \brief Generate a display-native color value from constant RGB * components. * * This macro does the same job as \ref gfx_color(), except that the RGB * values must be constant, and that it is usable as a static * initializer. */ /** * \def GFX_COLOR_INVALID * \brief Value returned by \ref gfx_get_pixel() for pixels outside clipping * region. */ /** * \def GFX_COLOR_TRANSPARENT * \brief Value used as input to font functions to give a transparent background * region. */ /** \name Standard Color Definitions */ /** @{ */ #define GFX_COLOR_BLACK GFX_COLOR( 0, 0, 0) #define GFX_COLOR_WHITE GFX_COLOR(255, 255, 255) #define GFX_COLOR_GRAY GFX_COLOR(128, 128, 128) #define GFX_COLOR_RED GFX_COLOR(255, 0, 0) #define GFX_COLOR_DK_RED GFX_COLOR(128, 0, 0) #define GFX_COLOR_GREEN GFX_COLOR( 0, 255, 0) #define GFX_COLOR_DK_GREEN GFX_COLOR( 0, 128, 0) #define GFX_COLOR_BLUE GFX_COLOR( 0, 0, 255) #define GFX_COLOR_DK_BLUE GFX_COLOR( 0, 0, 128) #define GFX_COLOR_MAGENTA GFX_COLOR(255, 0, 255) #define GFX_COLOR_DK_MAGENTA GFX_COLOR(128, 0, 128) #define GFX_COLOR_YELLOW GFX_COLOR(255, 255, 0) #define GFX_COLOR_DK_YELLOW GFX_COLOR(128, 128, 0) #define GFX_COLOR_CYAN GFX_COLOR( 0, 255, 255) #define GFX_COLOR_DK_CYAN GFX_COLOR( 0, 128, 128) /** @} */ /** @} */ /** \name Circle Sector Definitions */ /** @{ */ /** Bitmask for drawing circle octant 0. */ #define GFX_OCTANT0 (1 << 0) /** Bitmask for drawing circle octant 1. */ #define GFX_OCTANT1 (1 << 1) /** Bitmask for drawing circle octant 2. */ #define GFX_OCTANT2 (1 << 2) /** Bitmask for drawing circle octant 3. */ #define GFX_OCTANT3 (1 << 3) /** Bitmask for drawing circle octant 4. */ #define GFX_OCTANT4 (1 << 4) /** Bitmask for drawing circle octant 5. */ #define GFX_OCTANT5 (1 << 5) /** Bitmask for drawing circle octant 6. */ #define GFX_OCTANT6 (1 << 6) /** Bitmask for drawing circle octant 7. */ #define GFX_OCTANT7 (1 << 7) /** Bitmask for drawing circle quadrant 0. */ #define GFX_QUADRANT0 (GFX_OCTANT0 | GFX_OCTANT1) /** Bitmask for drawing circle quadrant 1. */ #define GFX_QUADRANT1 (GFX_OCTANT2 | GFX_OCTANT3) /** Bitmask for drawing circle quadrant 2. */ #define GFX_QUADRANT2 (GFX_OCTANT4 | GFX_OCTANT5) /** Bitmask for drawing circle quadrant 3. */ #define GFX_QUADRANT3 (GFX_OCTANT6 | GFX_OCTANT7) /** Bitmask for drawing left half of circle. */ #define GFX_LEFTHALF (GFX_QUADRANT3 | GFX_QUADRANT0) /** Bitmask for drawing top half of circle. */ #define GFX_TOPHALF (GFX_QUADRANT0 | GFX_QUADRANT1) /** Bitmask for drawing right half of circle. */ #define GFX_RIGHTHALF (GFX_QUADRANT1 | GFX_QUADRANT2) /** Bitmask for drawing bottom half of circle. */ #define GFX_BOTTOMHALF (GFX_QUADRANT2 | GFX_QUADRANT3) /** Bitmask for drawing whole circle. */ #define GFX_WHOLE 0xFF /** @} */ /** \name Flags for gfx_set_orientation() */ /*@{ */ /** Bitmask for flipping X for \ref gfx_set_orientation() */ #define GFX_FLIP_X 1 /** Bitmask for flipping Y for \ref gfx_set_orientation() */ #define GFX_FLIP_Y 2 /** Bitmask for swapping X and Y for \ref gfx_set_orientation() */ #define GFX_SWITCH_XY 4 /** @} */ /** * \name Screen geometry and clipping variables * \internal * * These global variables should not be accessed directly. They cannot be * marked as private/static since they are shared within multiple C files * of the graphics drivers. * * Use \ref gfx_set_clipping() to change clipping region. */ /** @{ */ #if defined(CONF_GFX_USE_CLIPPING) || defined(__DOXYGEN__) extern gfx_coord_t gfx_min_x; /**< Minimum X of current clipping region. */ extern gfx_coord_t gfx_min_y; /**< Maximum Y of current clipping region. */ extern gfx_coord_t gfx_max_x; /**< Minimum X of current clipping region. */ extern gfx_coord_t gfx_max_y; /**< Maximum Y of current clipping region. */ #endif extern gfx_coord_t gfx_width; /**< Current width of screen. */ extern gfx_coord_t gfx_height; /**< Current height of screen. */ /** @} */ #if defined(__DOXYGEN__) /** * \name Bitmap functions and structures */ /** @{ */ /** * \brief Draw a bitmap * * Draw a bitmap to the screen on the given display coordinates * * \param bmp Pointer to bitmap \ref gfx_bitmap * \param x Display X coordinate * \param y Display Y coordinate */ void gfx_draw_bitmap(const struct gfx_bitmap *bmp, gfx_coord_t x, gfx_coord_t y); /** * \brief Draw a bitmap to the screen tiled to cover the output area. * * The function starts at the tile origin and searches to find the coordinate * closest to the top left of the output area that is a multiple of the bitmap * width/height. It then draws the bitmap as many times as needed to cover * the entire output area. * * To draw a bitmap tiled on the entire screen, regardless of the bitmap * size, the function can be used like this: * * \code gfx_draw_bitmap_tiled(bmp, 0, 0, gfx_get_width(), gfx_get_height(), 0, ,0); \endcode * * The function is used by the "window system" to redraw the * background of a parent window when a transparent child window needs to be * redrawn. In this case the full parent window does not need redrawing, * only the area of the parent window that is under the child window. * The tiles of the background image will for all windows start at the top left * corner of the window, so the function is used like this: * * \code gfx_draw_bitmap_tiled(parent_background_bmp, child_window_x1, child_window_y1, child_window_x2, child_window_y2, parent_window_origin_x, parent_window_origin_y); \endcode * * \note If CONF_GFX_USE_CLIPPING is used, the output is clipped to the * output area and nothing will be drawn outside the output area. * * \param bmp Pointer to bitmap * \param x1 Output area left coordinate * \param y1 Output area top coordinate * \param x2 Output area right coordinate * \param y2 Output area bottom coordinate * \param tile_origin_x Tile origin left coordinate * \param tile_origin_y Tile origin top coordinate */ void gfx_draw_bitmap_tiled(const struct gfx_bitmap *bmp, gfx_coord_t x1, gfx_coord_t y1, gfx_coord_t x2, gfx_coord_t y2, gfx_coord_t tile_origin_x, gfx_coord_t tile_origin_y); /** * \brief Write a rectangular block of pixels from a bitmap to * the screen. * * This function draws a subset of a bitmap to the screen. The subset * is given by (map_x, map_y, width, height), and is outputted * to the screen at the screen coordinates (x, y). * * If the area to write is outside the clipping region, those pixels * will not be written. * * \note This function fails if the width or height is negative or the * pixel rectangle is outside the pixmap buffer extents. Clipping * is only performed on the screen, not inside the pixmap buffer itself. * * \note There is no checking if the pixel rectangle exceeds the bottom of * the pixmap buffer. * * \param bmp Pointer to bitmap. * \param map_x X coordinate inside pixel buffer. * \param map_y Y coordinate inside pixel buffer. * \param x X coordinate on screen. * \param y Y coordinate on screen. * \param width Width of pixel rectangle to copy. * \param height Height of pixel rectangle to copy. */ void gfx_put_bitmap(const struct gfx_bitmap *bmp, gfx_coord_t map_x, gfx_coord_t map_y, gfx_coord_t x, gfx_coord_t y, gfx_coord_t width, gfx_coord_t height); /** @} */ /** \name Display driver management functions */ /** @{ */ /** * \brief Synchronize access to the display * * In case of a graphics driver implementation that queues graphics * operations, this function will make sure all pending operations are * completed before exiting. That way, if you want to read pixels from * the display, you can be sure that the display information is fresh * and updated. For implementations that does not queue operations, * this function may do nothing, but for portability it should always be * called before reading pixels, or performing other operations which * rely on all pending drawing operations having actually been * completed. */ void gfx_sync(void); /** @} */ /** \name Display Geometry */ /** @{ */ /** * \brief Change display orientation * * Changes the display orientation for displays that support this. * Check the driver specific documentation if this is supported. * * The following masks are available and can be ORed together: * - #GFX_FLIP_X Flip X axis * - #GFX_FLIP_Y Flip Y axis * - #GFX_SWITCH_XY Switch X/Y * * Note that rotating the screen 90 degrees means switching X/Y _and_ * mirroring one of the axes. It is not enough to just switch X/Y. * * \param flags A bitmask of which axes to flip and/or switch. */ void gfx_set_orientation(uint8_t flags); /** * \brief Return the current width of the screen * * Return the current width of the screen for the current orientation. Screen * can be rotated runtime on supported displays with \ref gfx_set_orientation. * * \return Width of the screen in pixels. */ gfx_coord_t gfx_get_width(void); /** * \brief Return the current height of the screen * * Return the current height of the screen for the current orientation. Screen * can be rotated runtime on supported displays with \ref gfx_set_orientation. * * \return Height of the screen in pixels. */ gfx_coord_t gfx_get_height(void); /** * \name Display Clipping * * The display driver uses software and hardware clipping. In the graphics * drivers software clipping is referred to as clipping and hardware clipping * as limits. * * Software clipping is used to ensure that nothing outside the set * region is draw to the screen by any of the drawing functions. Eliminating * unwanted drawing to the display will give a higher performance on * displays which has a low bandwidth from the CPU. * Software is enabled by the CONF_GFX_USE_CLIPPING configuration symbol. * Clipping region is set with the \ref gfx_set_clipping() function. * * Hardware clipping is used in the supported display drivers to efficiently * draw primitives on a subset of the display. Example: when drawing a * filled rectangle the limits is set to the size of the rectangle, and the * driver sends the correct number of pixels to fill the entire rectangle. * Without hardware clipping/limits the driver will have to to move the * graphics ram (GRAM) position/pointer manually. * Hardware clipping/limits is not used like software clipping to eliminate * drawing outside a given region. * Hardware clipping is set with the \ref gfx_set_top_left_limit, * \ref gfx_set_bottom_right_limit and \ref gfx_set_limits functions. * In display drivers that do not use hardware clipping these functions * will not have any effect. */ /** @{ */ /** * \brief Set the clipping region * * Set the clipping region for all subsequent graphics operations. * Nothing will be drawn outside the clipping region. Clipping is handled * in software, and is enabled with CONF_GFX_USE_CLIPPING. * * \param min_x Left edge of region. * \param min_y Top edge of region. * \param max_x Right edge of region. * \param max_y Bottom edge of region. */ void gfx_set_clipping(gfx_coord_t min_x, gfx_coord_t min_y, gfx_coord_t max_x, gfx_coord_t max_y); /** * \brief Set the top-left limit for the display. * * Set top-left clipping limit for displays that needs to set a hardware * clipping region. * * \param x Top left x coordinate. * \param y Top left y coordinate. */ void gfx_set_top_left_limit(gfx_coord_t x, gfx_coord_t y); /** * \brief Set the bottom-right limit for the display. * * Set bottom-right clipping limit for displays that needs to set a hardware * clipping region. * * \param x Bottom right x coordinate. * \param y Bottom right y coordinate. */ void gfx_set_bottom_right_limit(gfx_coord_t x, gfx_coord_t y); /** * \brief Set the limits for the display. * * Set clipping limit for displays that needs to set a hardware * clipping region. * * \param x1 Top left x coordinate. * \param y1 Top left y coordinate. * \param x2 Bottom right x coordinate. * \param y2 Bottom right y coordinate. */ void gfx_set_limits(gfx_coord_t x1, gfx_coord_t y1, gfx_coord_t x2, gfx_coord_t y2); /** @} */ /** \name Low-level pixel drawing operations */ /** @{ */ /** * \brief Generate native color value from R/G/B values. * * Converts 8-bit R/G/B values to a color value native to the display. * The format of the resulting color value depends on the display. * * The macro \ref GFX_COLOR does the same, only allows the preprocessor to * handle the calculations. * * \param r 8-bit red value. * \param g 8-bit green value. * \param b 8-bit blue value. * * \return Color value in display native format. */ gfx_color_t gfx_color(uint8_t r, uint8_t g, uint8_t b); /** * \brief Draw a single pixel on the screen * * Draw a single pixel on screen setting top and bottom limits. * If outside the clipping region, nothing is drawn. * * \param x X coordinate of the pixel to be drawn. * \param y Y coordinate of the pixel to be drawn. * \param color Color value of the pixel in display native format. */ void gfx_draw_pixel(gfx_coord_t x, gfx_coord_t y, gfx_color_t color); /** * \brief Draw a single pixel on the screen * * This function draws a single pixel on screen only setting top limit * which makes it more suitable for line drawing. * If outside the clipping region, nothing is drawn. * * \param x X coordinate of the pixel to be drawn. * \param y Y coordinate of the pixel to be drawn. * \param color Color value of the pixel in display native format. */ void gfx_draw_line_pixel(gfx_coord_t x, gfx_coord_t y, gfx_color_t color); /** * \brief Get the color of a pixel on the display. * * \param x X coordinate of the pixel to be sampled. * \param y Y coordinate of the pixel to be sampled. * * \return Color value of the pixel at (x, y) in display native format, * or #GFX_COLOR_INVALID if outside the clipping region. */ gfx_color_t gfx_get_pixel(gfx_coord_t x, gfx_coord_t y); /** * \brief Draw multiple pixels all having the same color. * * Draw \a count pixels using \a color within the current clipping * limits. * * \param color Color value in display native format. * \param count Number of times to write the color */ void gfx_duplicate_pixel(gfx_color_t color, uint32_t count); /** * \brief Copy a block of pixels from data memory to screen. * * Copy pixels from RAM to the screen, given current limits. * * \param pixels An array of pixel values in display native format. * \param count Number of pixels to copy from the array. */ void gfx_copy_pixels_to_screen(const gfx_color_t *pixels, uint32_t count); /** * \brief Copy a block of pixels from program memory to screen. * * Copy a block of pixels from program memory to screen, given current * limits. * * \param pixels An array of pixel values in display native format, * stored in program (flash) memory. * \param count Number of pixels to copy from the array. */ void gfx_copy_progmem_pixels_to_screen(gfx_color_t PROGMEM_PTR_T pixels, uint32_t count); /** * \brief Copy a block of pixels from screen to data memory. * * Copy a block of pixels from the screen into RAM, given current limits * * \param pixels Array into which the pixel values are to be stored. * \param count Number of pixels to copy into the array. */ void gfx_copy_pixels_from_screen(gfx_color_t *pixels, uint32_t count); /** * \brief Set bitmap draw function with custom interface. * * Set bitmap draw function with customer interface. This allows to use the extended * draw functions defined by the application. For example, do the draw bitmap function * though a filesystem. * * \param gfx_ext_draw_handler Pointer to custom bitmap draw handler. */ void gfx_set_ext_handler(gfx_ext_draw_handler_t gfx_ext_draw_handler); /** @} */ /** \name Graphics Drawing Primitives */ /** @{ */ /** * \def gfx_draw_horizontal_line(x, y, length, color) * \brief Draw a horizontal line, one pixel wide. * * \param x X coordinate of leftmost pixel. * \param y Y coordinate of the line. * \param length Length of the line in pixels. * \param color Color of the line, in display native format. */ /** * \def gfx_draw_vertical_line(x, y, length, color) * \brief Draw a vertical line, one pixel wide. * * \param x X coordinate of the line. * \param y Y coordinate of the topmost pixel. * \param length Length of the line in pixels. * \param color Color of the line, in display native format. */ /** * \def gfx_draw_line(x1, y1, x2, y2, color) * \brief Draw a line between two arbitrary points. * * \param x1 Start X coordinate. * \param y1 Start Y coordinate. * \param x2 End X coordinate. * \param y2 End Y coordinate. * \param color Color of the line, in display native format. */ /** * \def gfx_draw_rect(x, y, width, height, color) * \brief Draw an outline of a rectangle. * * \param x X coordinate of the left side. * \param y Y coordinate of the top side. * \param width Width of the rectangle. * \param height Height of the rectangle. * \param color Color of the rectangle, in display native format. */ /** * \def gfx_draw_filled_rect(x, y, width, height, color) * \brief Draw a filled rectangle. * * \param x X coordinate of the left side. * \param y Y coordinate of the top side. * \param width Width of the rectangle. * \param height Height of the rectangle. * \param color Color of the rectangle, in display native format. */ /** * \def gfx_draw_circle(x, y, radius, color, octant_mask) * \brief Draw an outline of a circle or arc. * * The radius is the distance from the center to the circumference, * which means that the total width or height of a circle will be * (radius*2+1). * * The octant_mask parameter is a bitmask that decides which octants of * the circle to draw. Use the GFX_OCTANTn, GFX_QUADRANTn, GFX_xHALF and * GFX_WHOLE constants and OR them together if required. Radius equal to * zero gives a single pixel. * * \param x X coordinate of center. * \param y Y coordinate of center. * \param radius Circle radius in pixels. * \param color Circle color in display native format. * \param octant_mask Bitmask indicating which octants to draw. */ /** * \def gfx_draw_filled_circle(x, y, radius, color, quadrant_mask) * \brief Draw a filled circle or sector. * * The radius is the distance from the center to the circumference, * which means that the total width or height of a circle will be * (radius*2+1). * * The quadrant_mask parameter is a bitmask that decides which quadrants * of the circle to draw. Use the GFX_QUADRANTn, GFX_xHALF and * GFX_WHOLE constants and OR them together if required. Radius equal to * zero gives a single pixel. * * \note This function only supports quadrants while gfx_draw_circle() * supports octants. This is to improve performance on drawing * filled circles. * * \param x X coordinate of center. * \param y Y coordinate of center. * \param radius Circle radius in pixels. * \param color Circle color in display native format. * \param quadrant_mask Bitmask indicating which quadrants to draw. */ /** * \def gfx_get_pixmap(pixmap, map_width, map_x, map_y, x, y, width, height) * \brief Read a rectangular block of pixels from the screen into data * memory. * * If the area to read is outside the clipping region, those pixels will * not be read, and the corresponding data memory will be left * untouched. Note that this function fails if width or height is * negative or the pixel rectangle is outside the pixmap buffer extents. * Clipping is only performed on the screen, not inside the pixmap * buffer itself. Note that there is no checking if the pixel rectangle * exceeds the bottom of the pixmap buffer. * * \param pixmap Pointer to pixel buffer in data memory. * \param map_width Width of the pixel buffer. * \param map_x X coordinate inside pixel buffer. * \param map_y Y coordinate inside pixel buffer. * \param x X coordinate on screen. * \param y Y coordinate on screen. * \param width Width of pixel rectangle to copy. * \param height Height of pixel rectangle to copy. */ /** * \def gfx_put_pixmap(pixmap, map_width, map_x, map_y, x, y, width, height); * \brief Write a rectangular block of pixels stored in data memory to * the screen. * * If the area to write is outside the clipping region, those pixels * will not be written. Note that this function fails if the width or * height is negative or the pixel rectangle is outside the pixmap * buffer extents. Clipping is only performed on the screen, not inside * the pixmap buffer itself. Note that there is no checking if the * pixel rectangle exceeds the bottom of the pixmap buffer. * * \param pixmap Pointer to pixel buffer in data memory. * \param map_width Width of the pixel buffer. * \param map_x X coordinate inside pixel buffer. * \param map_y Y coordinate inside pixel buffer. * \param x X coordinate on screen. * \param y Y coordinate on screen. * \param width Width of pixel rectangle to copy. * \param height Height of pixel rectangle to copy. */ /** @} */ /** @} */ /** * \page gfx_quickstart Quick Start Guide for the graphics service * * This is the quick start guide for the \ref gfx_group "Graphics (GFX) * service", with step-by-step instructions on how to configure and use * it for a specific use case. * * * \section gfx_quickstart_basic Basic usage of the graphics service * This use case will demonstrate initializing the graphics service and then * drawing a red line on the screen from coordinate X=10, Y=10 to X=20, Y=20. * * \section gfx_basic_usage Usage steps * \subsection gfx_basic_usage_code Example code * Add to, e.g., the main function in the application C-file: * \code board_init(); sysclk_init(); gfx_init(); gfx_draw_line(10, 10, 20, 20, GFX_COLOR(0xFF, 0, 0)); \endcode * * \subsection gfx_basic_usage Workflow * -# Initialize board IO: * - \code board_init(); \endcode * -# Initialize clocks: * - \code sysclk_init(); \endcode * -# Initialize graphics service * - \code gfx_init(); \endcode * - \note This will call the init function for the low level display * controller driver and initialize the screen to a white background. * -# Draw a red line from 10,10 to 20,20: * - \code gfx_draw_line(10, 10, 20, 20, GFX_COLOR(0xFF, 0, 0)); \endcode * - \attention This uses the \ref GFX_COLOR macro to convert a RGB * (Red,Green,Blue) * value to a color value native to the display. In this case the color is * a constant, so we use the macro. If you need to create the color from a * non-constant value you must use the \ref gfx_color function to generate the * color. */ #else gfx_coord_t gfx_get_width(void); gfx_coord_t gfx_get_height(void); void gfx_set_clipping(gfx_coord_t min_x, gfx_coord_t min_y, gfx_coord_t max_x, gfx_coord_t max_y); #endif #ifdef __cplusplus } #endif #endif /* GFX_H_INCLUDED */
omerlesh/go-archive-extractor
vendor/github.com/blakesmith/ar/writer_test.go
<reponame>omerlesh/go-archive-extractor<gh_stars>1-10 /* Copyright (c) 2013 <NAME> <<EMAIL>> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package ar import ( "bytes" "io/ioutil" "os" "testing" "time" ) func TestGlobalHeaderWrite(t *testing.T) { var buf bytes.Buffer writer := NewWriter(&buf) if err := writer.WriteGlobalHeader(); err != nil { t.Errorf(err.Error()) } globalHeader := buf.Bytes() expectedHeader := []byte("!<arch>\n") if !bytes.Equal(globalHeader, expectedHeader) { t.Errorf("Global header should be %s but is %s", expectedHeader, globalHeader) } } func TestSimpleFile(t *testing.T) { hdr := new(Header) body := "Hello world!\n" hdr.ModTime = time.Unix(1361157466, 0) hdr.Name = "hello.txt" hdr.Size = int64(len(body)) hdr.Mode = 0644 hdr.Uid = 501 hdr.Gid = 20 var buf bytes.Buffer writer := NewWriter(&buf) writer.WriteGlobalHeader() writer.WriteHeader(hdr) _, err := writer.Write([]byte(body)) if err != nil { t.Errorf(err.Error()) } f, _ := os.Open("./fixtures/hello.a") defer f.Close() b, err := ioutil.ReadAll(f) if err != nil { t.Errorf(err.Error()) } actual := buf.Bytes() if !bytes.Equal(b, actual) { t.Errorf("Expected %s to equal %s", actual, b) } } func TestWriteTooLong(t *testing.T) { body := "Hello world!\n" hdr := new(Header) hdr.Size = 1 var buf bytes.Buffer writer := NewWriter(&buf) writer.WriteHeader(hdr) _, err := writer.Write([]byte(body)) if err != ErrWriteTooLong { t.Errorf("Error should have been: %s", ErrWriteTooLong) } }
Sedl/docsis-pnm
internal/types/cmstatus.go
package types import "github.com/sedl/docsis-pnm/internal/constants" type CmStatus int var cmStatusString = []string{ "Unknown", "Other", "Ranging", "RangingAborted", "RangingComplete", "IpComplete", "RegistrationComplete", "AccessDenied", "Operational", "RegisteredBPIInitializing", } func (status CmStatus) String() string { if status < 1 || status > constants.CmStatusRegisteredBPIInitializing { return "Unknown" } return cmStatusString[status] }
kravitz/transims4
ArcProblem/ArcProblem.hpp
<reponame>kravitz/transims4<filename>ArcProblem/ArcProblem.hpp //********************************************************* // ArcProblem.hpp - ArcView Problem Files //********************************************************* #ifndef ARCPROBLEM_HPP #define ARCPROBLEM_HPP #include "Demand_Service.hpp" #include "Projection_Service.hpp" #include "Arcview_File.hpp" #include "Time_Range.hpp" #include "Utility.hpp" #include "Problem_Service.hpp" #include "Integer_Array.hpp" #include "Problem_File.hpp" //--------------------------------------------------------- // ArcProblem - execution class definition //--------------------------------------------------------- class ArcProblem : public Demand_Service, public Problem_Service { public: ArcProblem (void); virtual ~ArcProblem (void); virtual void Execute (void); protected: static char * PROBLEM_FILE; static char * PROBLEM_FORMAT; static char * ARCVIEW_PROBLEM_FILE; static char * LANE_WIDTH; static char * CENTER_ONEWAY_LINKS; static char * DRAW_VEHICLE_SHAPES; static char * DRAW_TRIP_OD_LINKS; static char * TIME_OF_DAY_FORMAT; static char * SELECT_TIME_PERIODS; static char * SELECT_TIME_INCREMENT; static char * SELECT_LINKS; static char * SELECT_PROBLEM_TYPES; static char * SELECT_SUBAREA_POLYGON; virtual void Program_Control (void); private: Problem_File problem_file; Arcview_File arcview_problem; Arcview_File select_subarea; Point_Data points; double lane_width; bool center_flag, link_flag, type_flag, time_flag, shape_flag, subarea_flag, location_flag, od_flag; Data_Range links, types; Time_Range times; Projection_Service projection; char shapename [FILE_NAME_SIZE]; //---- methods ---- void Read_Problem (void); }; #endif
beida101/PublicCMS
publiccms-admin-by-maven/src/main/java/com/publiccms/admin/views/controller/IndexAdminController.java
<gh_stars>0 package com.publiccms.admin.views.controller; import static com.publiccms.common.constants.FreeMakerConstants.CONTEXT_PATH; import static org.apache.commons.lang3.StringUtils.isNotBlank; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.util.UrlPathHelper; import com.sanluan.common.base.BaseController; /** * * IndexAdminController 统一分发Controller * */ @Controller public class IndexAdminController extends BaseController { private UrlPathHelper urlPathHelper = new UrlPathHelper(); private static final String SEPARATOR = "/"; /** * 页面请求统一分发 * * @param request * @param model * @return */ @RequestMapping("/**") public String page(HttpServletRequest request, ModelMap model) { String path = urlPathHelper.getLookupPathForRequest(request); if (isNotBlank(path)) { if (SEPARATOR.equals(path) || path.endsWith(SEPARATOR)) { path += "index.html"; } int index = path.lastIndexOf("."); path = path.substring(path.indexOf(SEPARATOR) > 0 ? 0 : 1, index > -1 ? index : path.length()); } model.addAttribute(CONTEXT_PATH, path); return path; } }
DeepHealthyChain/dapp-backend
dist/server/services/jkbapp/score.service.js
<reponame>DeepHealthyChain/dapp-backend 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); // getContent // const getIpfsContent = async hash => await getContent(hash); /** * 根据用户id获取对应积分 * @param {*} req * @param {*} res */ var getScores = function () { var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(userId) { var user, score; return regeneratorRuntime.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return _user2.default.get(userId); case 2: user = _context.sent; score = user.score; // let score = await Score.getByUserId(userId); // if (score === null) { // score = await create(userId); // score = await Score.getByUserId(userId); // } // let content = await getIpfsContent(score.ipfsHash); // if (content) { // score.content = content; // } else { // content = await getIpfsContent(score.ipfsHash); // score.content = content; // } // content = JSON.parse(score.content); // if (content.score === null) { // content.score = 0; // score.content = content; // } return _context.abrupt('return', score); case 5: case 'end': return _context.stop(); } } }, _callee, this); })); return function getScores(_x) { return _ref.apply(this, arguments); }; }(); /** * 为新用户创建积分记录 * @param {*} userid */ var create = function () { var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(userid) { var ipfsData, hash, score, newScore; return regeneratorRuntime.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: // 定义ipfs中存储的数据 ipfsData = { userId: userid, score: 0 }; // 上传到IPFS _context2.next = 3; return (0, _ipfsFile.addContent)(ipfsData); case 3: hash = _context2.sent; // 定义mongo存储的数据 score = new _score2.default({ ipfsHash: hash, userId: userid }); // 保存数据库 _context2.next = 7; return _score2.default.create(score); case 7: newScore = _context2.sent; return _context2.abrupt('return', newScore); case 9: case 'end': return _context2.stop(); } } }, _callee2, this); })); return function create(_x2) { return _ref2.apply(this, arguments); }; }(); /** * 更新积分 * @param {*} userid * @param {*} taskType */ var update = function () { var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3(userid, taskType) { var user, addScore, oldScore, newScore; return regeneratorRuntime.wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: _context3.next = 2; return _user2.default.get(userid); case 2: user = _context3.sent; if (user) { _context3.next = 5; break; } return _context3.abrupt('return', new _responseData2.default(null, true, '用户不存在')); case 5: _context3.next = 7; return _task2.default.getScoreByTaskType(taskType); case 7: addScore = _context3.sent; // 获取DHC不能超过10000 // if (addScore < 10000) { // console.log('addScore', addScore); // // 产生交易 // const tokenContract = new TokenContract(); // await tokenContract.transferToken(user.publicKey, addScore); // // if (resultBody.error) { // // console.log('积分没有发送成功。'); // // // return new ResData(null, true, '操作失败,请重新操作。'); // // } // } else { // console.log('发送的积分超过10000。'); // // return new ResData(null, true, '操作失败,请重新操作。'); // } // 根据用户id获取用户历史积分 oldScore = user.score; if (!oldScore) { oldScore = 0; } // 积分累加 newScore = parseInt(oldScore, 10) + parseInt(addScore, 10); // 更新积分 console.log(user.mobileNumber, taskType, oldScore, addScore, newScore); console.log('-----------------------------------------------'); _context3.next = 15; return _user2.default.findByIdAndUpdate({ _id: userid }, { $set: { score: newScore } }); case 15: return _context3.abrupt('return', '修改成功'); case 16: case 'end': return _context3.stop(); } } }, _callee3, this); })); return function update(_x3, _x4) { return _ref3.apply(this, arguments); }; }(); /** * 获取积分日志 * @param {*} userid */ var getScoreLogs = function () { var _ref4 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4(userid, pageSize, page, looked) { var total, scoreLogs, pagination, result; return regeneratorRuntime.wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: _context4.next = 2; return _scorelog2.default.countByUserId(userid, looked); case 2: total = _context4.sent; _context4.next = 5; return _scorelog4.default.getList(userid, pageSize, page, looked); case 5: scoreLogs = _context4.sent; // 组装分页结果 pagination = { pageSize: Number(pageSize), current: Number(page), total: Number(total) }; // eslint-disable-line // 下次app发版是解开 result = { list: scoreLogs, pagination: pagination }; return _context4.abrupt('return', result); case 9: case 'end': return _context4.stop(); } } }, _callee4, this); })); return function getScoreLogs(_x5, _x6, _x7, _x8) { return _ref4.apply(this, arguments); }; }(); /** * 获取积分排名 * @param {*} userid */ var getScoreRanking = function () { var _ref5 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee5(pageSize, page, order) { var scorelist, todayStartDate, list; return regeneratorRuntime.wrap(function _callee5$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: scorelist = void 0; _context5.t0 = order; _context5.next = _context5.t0 === 'today' ? 4 : _context5.t0 === 'total' ? 9 : 13; break; case 4: // 获取今日开始时间 todayStartDate = _dateUtil2.default.getDayStartDate(); _context5.next = 7; return _user2.default.getRankingAndCreatedDateGrateBy(pageSize, page, todayStartDate); case 7: scorelist = _context5.sent; return _context5.abrupt('break', 14); case 9: _context5.next = 11; return _user2.default.getRanking(pageSize, page); case 11: scorelist = _context5.sent; return _context5.abrupt('break', 14); case 13: return _context5.abrupt('break', 14); case 14: list = scorelist.map(function (item, index) { var name = ''; if (item.nickname) { name = item.nickname; } var score = 0; if (item.score !== null) { score = item.score; } return { index: index + 1, username: name, mobile: item.mobileNumber, score: score }; }); return _context5.abrupt('return', Promise.all(list)); case 16: case 'end': return _context5.stop(); } } }, _callee5, this); })); return function getScoreRanking(_x9, _x10, _x11) { return _ref5.apply(this, arguments); }; }(); /** * 设置积分日志已阅读 * @param {*} scoreLogId */ var lookScoreLog = function () { var _ref6 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee6(userId, scoreLogId) { var resultBody, taskType, scoreResultBody; return regeneratorRuntime.wrap(function _callee6$(_context6) { while (1) { switch (_context6.prev = _context6.next) { case 0: _context6.next = 2; return _scorelog4.default.lookScoreLog(scoreLogId); case 2: resultBody = _context6.sent; if (resultBody.error) { _context6.next = 10; break; } taskType = resultBody.result.scoreType; // 添加积分 _context6.next = 7; return update(userId, taskType); case 7: scoreResultBody = _context6.sent; if (!(scoreResultBody !== null && scoreResultBody.error)) { _context6.next = 10; break; } return _context6.abrupt('return', new _responseData2.default(null, true, scoreResultBody.message)); case 10: return _context6.abrupt('return', new _responseData2.default(null, false, '已阅读')); case 11: case 'end': return _context6.stop(); } } }, _callee6, this); })); return function lookScoreLog(_x12, _x13) { return _ref6.apply(this, arguments); }; }(); /** * 批量 设置积分日志已阅读 * @param {*} scoreLogId */ var lookScoreLogs = function () { var _ref7 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee7(userId, scoreLogIds) { var scoreLogsTemp, scoreLogs, scoresTemp, scores, totalScore, user, score; return regeneratorRuntime.wrap(function _callee7$(_context7) { while (1) { switch (_context7.prev = _context7.next) { case 0: scoreLogsTemp = scoreLogIds.map(function (item) { return _scorelog4.default.lookScoreLog(item); }); _context7.next = 3; return Promise.all(scoreLogsTemp); case 3: scoreLogs = _context7.sent; scoresTemp = scoreLogs.map(function (item) { return _task2.default.getScoreByTaskType(item.scoreType); }); _context7.next = 7; return Promise.all(scoresTemp); case 7: scores = _context7.sent; totalScore = scores.reduce(function (previousValue, currentValue) { return previousValue + currentValue; }); if (!(totalScore > 0)) { _context7.next = 16; break; } _context7.next = 12; return _user2.default.get(userId); case 12: user = _context7.sent; score = Number(user.score) + Number(totalScore); _context7.next = 16; return _user2.default.findByIdAndUpdate({ _id: user._id }, { score: score }); case 16: return _context7.abrupt('return', new _responseData2.default(null, false, '已阅读')); case 17: case 'end': return _context7.stop(); } } }, _callee7, this); })); return function lookScoreLogs(_x14, _x15) { return _ref7.apply(this, arguments); }; }(); /** * 根据积分日志id获取详情 * @param {*} scoreLogId */ var getScoreLogInfoById = function () { var _ref8 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee8(scoreLogId) { var result; return regeneratorRuntime.wrap(function _callee8$(_context8) { while (1) { switch (_context8.prev = _context8.next) { case 0: _context8.next = 2; return _scorelog4.default.getScoreLogInfoById(scoreLogId); case 2: result = _context8.sent; return _context8.abrupt('return', result); case 4: case 'end': return _context8.stop(); } } }, _callee8, this); })); return function getScoreLogInfoById(_x16) { return _ref8.apply(this, arguments); }; }(); var aa = function () { var _ref9 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee9() { var result; return regeneratorRuntime.wrap(function _callee9$(_context9) { while (1) { switch (_context9.prev = _context9.next) { case 0: _context9.next = 2; return _scorelog4.default.aa(); case 2: result = _context9.sent; return _context9.abrupt('return', result); case 4: case 'end': return _context9.stop(); } } }, _callee9, this); })); return function aa() { return _ref9.apply(this, arguments); }; }(); var _ipfsFile = require('../../utils/ipfsFile'); var _score = require('../../models/jkbapp/score.model'); var _score2 = _interopRequireDefault(_score); var _user = require('../../models/user.model'); var _user2 = _interopRequireDefault(_user); var _scorelog = require('../../models/jkbapp/scorelog.model'); var _scorelog2 = _interopRequireDefault(_scorelog); var _scorelog3 = require('../../services/jkbapp/scorelog.service'); var _scorelog4 = _interopRequireDefault(_scorelog3); var _responseData = require('../../helpers/responseData'); var _responseData2 = _interopRequireDefault(_responseData); var _task = require('../jkbapp/task.service'); var _task2 = _interopRequireDefault(_task); var _dateUtil = require('../../utils/dateUtil'); var _dateUtil2 = _interopRequireDefault(_dateUtil); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } // import TokenContract from '../../helpers/tokenContract'; exports.default = { getScores: getScores, update: update, create: create, getScoreLogs: getScoreLogs, getScoreRanking: getScoreRanking, lookScoreLog: lookScoreLog, lookScoreLogs: lookScoreLogs, getScoreLogInfoById: getScoreLogInfoById, aa: aa }; //# sourceMappingURL=score.service.js.map
webkinder/FlipClock
src/js/Languages/fi-fi.js
<reponame>webkinder/FlipClock /** * @classdesc Finnish Language Pack * @desc This class will used to translate tokens into the Finnish language. * @namespace Languages.Finnish */ /** * @constant dictionary * @type {object} * @memberof Languages.Finnish */ export const dictionary = { 'years' : 'Vuotta', 'months' : 'Kuukautta', 'days' : 'Päivää', 'hours' : 'Tuntia', 'minutes' : 'Minuuttia', 'seconds' : 'Sekuntia' }; /** * @constant aliases * @type {array} * @memberof Languages.Finnish */ export const aliases = ['fi', 'fi-fi', 'finnish'];
mhenderson-so/go-blackbox
cmd/blackbox/edit.go
package main import ( "fmt" "io/ioutil" "os" blackbox "github.com/mhenderson-so/go-blackbox/cmd/go-blackbox" "github.com/urfave/cli" ) // editStart decrypts a list of files. They will need to be re-encrypted manually. func editStart(args cli.Args) error { if len(args) == 0 { //If there are no filenames specified, error return fmt.Errorf("No filenames specified") } passphrase, err := preworkPassphrase() if err != nil { return err } //Attempt to start decryption of each file in turn for _, filename := range args { filename = stripGpgExtension(filename) if _, err := os.Stat(filename); err == nil { return fmt.Errorf("SKIPPING: %s Will not overwrite existing files", filename) } content, err := preworkDecode(filename, passphrase) if err != nil { return err } ioutil.WriteFile(filename, content, 0644) } return nil } func editEnd(args cli.Args) error { if len(args) == 0 { //If there are no filenames specified, error return fmt.Errorf("No filenames specified") } //Attempt to start encryption of each file in turn for _, filename := range args { plainFile := stripGpgExtension(filename) gpgFile := fmt.Sprintf("%s.gpg", plainFile) setup(plainFile) //Read our plaintext file in plaintext, err := ioutil.ReadFile(filename) if err != nil { return err } //Encode it encodedbytes, err := blackbox.Encode(plaintext) if err != nil { return err } //Write it out err = ioutil.WriteFile(gpgFile, encodedbytes, 0644) if err != nil { return err } //Clean up //os.Remove(plainFile) } return nil }
WickhamWei/WickhamsPlugin
src/wickhamsPlugin/command/TpAll.java
<filename>src/wickhamsPlugin/command/TpAll.java package wickhamsPlugin.command; import java.util.Collection; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class TpAll implements CommandExecutor { @Override public boolean onCommand(CommandSender sender, Command cmd, String arg2, String[] data) { if (sender instanceof Player && data.length == 0) { Collection<? extends Player> allPlayer = sender.getServer().getOnlinePlayers(); if (!(allPlayer.size() <= 1)) { for (Player a : allPlayer) { a.teleport((Player) sender); } sender.sendMessage(ChatColor.GREEN + "已传送所有人到你身边"); return true; } else { sender.sendMessage(ChatColor.YELLOW + "整个服务器只有你一个人。。。。"); return true; } } else { return false; } } }
NoahChian/Devops
src/main/java/org/iii/ideas/catering_service/rest/api/UpdateSchoolSeasoningDetailResponse.java
package org.iii.ideas.catering_service.rest.api; public class UpdateSchoolSeasoningDetailResponse extends AbstractApiResponse { }
mpastern/datameer-gcs-connector
gcs/src/main/java/com/kenshoo/integrations/plugins/connectors/GCSFileProtocol.java
// // Copyright (c) 2014 Ken<EMAIL> // // 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.kenshoo.integrations.plugins.connectors; import static com.kenshoo.integrations.plugins.connectors.oauth.OAuth2Setup.PROPERTY_KEY_REFRESH_TOKEN; import static com.kenshoo.integrations.plugins.connectors.oauth.OAuth2Setup.PROPERTY_KEY_OAUTH_RELAY_URL; import static com.kenshoo.integrations.plugins.connectors.oauth.OAuth2Setup.PROPERTY_KEY_OAUTH_CLIENT_ID; import static com.kenshoo.integrations.plugins.connectors.oauth.OAuth2Setup.PROPERTY_KEY_OAUTH_SECRET; import static com.kenshoo.integrations.plugins.connectors.oauth.OAuthSetup.PROPERTY_KEY_ACCESS_TOKEN; import static com.kenshoo.integrations.plugins.connectors.oauth.OAuthSetup.PROPERTY_KEY_ACCESS_TOKEN_CREATION_TIME; import static com.kenshoo.integrations.plugins.connectors.oauth.OAuthSetup.PROPERTY_KEY_ACCESS_TOKEN_EXPIRES_AFTER; import java.net.URI; import java.util.List; import org.apache.hadoop.conf.Configuration; import com.kenshoo.integrations.plugins.connectors.util.PathUtil; import datameer.com.google.common.collect.Lists; import datameer.dap.sdk.common.GenericConfiguration; import datameer.dap.sdk.datastore.FileProtocol; import datameer.dap.sdk.entity.DataStore; import datameer.dap.sdk.property.PropertyGroupDefinition; public class GCSFileProtocol extends FileProtocol { public static final long serialVersionUID = 1L; public static final String FS_DUMMY_HOST = "storage.google.com"; public static final String FS_DUMMY_HOST_LABEL = "Host"; public static final String FS_SCHEME = "gcsfs"; public static final String FILE_SYSTEM_NAME = "Google Cloud Storage"; public GCSFileProtocol() { super(FS_SCHEME, FS_DUMMY_HOST_LABEL, false); } @Override protected void addDetailsProperties(PropertyGroupDefinition connectionDetailsGroup) { addTransferProtocolProperty(connectionDetailsGroup); } @Override public List<URI> getUris(DataStore dataStore) { return Lists.newArrayList(new URI[] { newUri(getScheme(dataStore), null, FS_DUMMY_HOST, getPort(dataStore), PathUtil.DEFAULT_ROOT) }); } @Override public void setupAuthentication(GenericConfiguration genericConfiguration, Configuration configuration, String arg1, String arg2) { configuration.setBoolean("fs.gcsfs.impl.disable.cache", true); configuration.setStrings("fs.gcsfs.impl", "com.kenshoo.integrations.plugins.connectors.GCSFileSystem"); String accessToken = genericConfiguration.getStringProperty(PROPERTY_KEY_ACCESS_TOKEN, null); if (accessToken != null) { configuration.setStrings(PROPERTY_KEY_ACCESS_TOKEN, accessToken); } String refreshToken = genericConfiguration.getStringProperty(PROPERTY_KEY_REFRESH_TOKEN, null); if (refreshToken != null) { configuration.setStrings(PROPERTY_KEY_REFRESH_TOKEN, refreshToken); } Long accessTokenCreationTime = genericConfiguration.getLongProperty(PROPERTY_KEY_ACCESS_TOKEN_CREATION_TIME, null); if (accessTokenCreationTime != null) { configuration.setLong(PROPERTY_KEY_ACCESS_TOKEN_CREATION_TIME, accessTokenCreationTime); } Long accessTokenExpirationAfter = genericConfiguration.getLongProperty(PROPERTY_KEY_ACCESS_TOKEN_EXPIRES_AFTER, null); if (accessTokenExpirationAfter != null) { configuration.setLong(PROPERTY_KEY_ACCESS_TOKEN_EXPIRES_AFTER, accessTokenExpirationAfter); } String relayURL = genericConfiguration.getStringProperty(PROPERTY_KEY_OAUTH_RELAY_URL, null); if (relayURL != null) { configuration.setStrings(PROPERTY_KEY_OAUTH_RELAY_URL, relayURL); } String clientId = genericConfiguration.getStringProperty(PROPERTY_KEY_OAUTH_CLIENT_ID, null); if (clientId != null) { configuration.setStrings(PROPERTY_KEY_OAUTH_CLIENT_ID, clientId); } String secret = genericConfiguration.getStringProperty(PROPERTY_KEY_OAUTH_SECRET, null); if (secret != null) { configuration.setStrings(PROPERTY_KEY_OAUTH_SECRET, secret); } } @Override public String getName() { return FILE_SYSTEM_NAME; } }
koordinates/react-redux-grid
dist/components/core/menu/MenuItem.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.ConnectedMenuItem = exports.MenuItem = undefined; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _propTypes = require('prop-types'); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _prefix = require('../../../util/prefix'); var _emptyFn = require('../../../util/emptyFn'); var _GridConstants = require('../../../constants/GridConstants'); var _MenuActions = require('../../../actions/plugins/actioncolumn/MenuActions'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var MenuItem = function (_Component) { _inherits(MenuItem, _Component); function MenuItem() { _classCallCheck(this, MenuItem); return _possibleConstructorReturn(this, (MenuItem.__proto__ || Object.getPrototypeOf(MenuItem)).apply(this, arguments)); } _createClass(MenuItem, [{ key: 'render', value: function render() { var _this2 = this; var _gridConfig = (0, _GridConstants.gridConfig)(), CLASS_NAMES = _gridConfig.CLASS_NAMES; var _props = this.props, data = _props.data, disabled = _props.disabled, metaData = _props.metaData, menuItemsTypes = _props.menuItemsTypes, stateKey = _props.stateKey; var menuItemProps = { className: (0, _prefix.prefix)(CLASS_NAMES.GRID_ACTIONS.MENU.ITEM, data.disabled ? CLASS_NAMES.GRID_ACTIONS.DISABLED : ''), disabled: data.disabled, onClick: function onClick(e) { return _this2.handleMenuItemClick(data, disabled, metaData, stateKey, e); } }; var checkboxComponent = data.menuItemType === menuItemsTypes.checkbox ? this.getCheckbox(data) : null; return _react2.default.createElement( 'li', menuItemProps, checkboxComponent, data.text ); } }, { key: 'handleMenuItemClick', value: function handleMenuItemClick(data, disabled, metaData, stateKey, reactEvent) { if (reactEvent && reactEvent.stopPropagation) { reactEvent.stopPropagation(); } if (disabled) { return false; } var dismiss = data.dismissOnClick !== undefined ? data.dismissOnClick : true; var store = this.props.store; if (dismiss) { store.dispatch((0, _MenuActions.hideMenu)({ stateKey: stateKey })); } if (data.EVENT_HANDLER) { return data.EVENT_HANDLER({ data: data, metaData: metaData, reactEvent: reactEvent }); } } }, { key: 'getCheckbox', value: function getCheckbox(data) { var readOnly = data.hideable !== undefined ? !data.hideable : false; var checkboxProps = { type: this.props.menuItemsTypes.checkbox, checked: data.checked, disabled: readOnly, onChange: data.onCheckboxChange || _emptyFn.emptyFn }; return _react2.default.createElement('input', checkboxProps); } }]); return MenuItem; }(_react.Component); MenuItem.propTypes = { data: _propTypes2.default.object, disabled: _propTypes2.default.bool, menuItemsTypes: _propTypes2.default.object, metaData: _propTypes2.default.object, stateKey: _propTypes2.default.string, store: _propTypes2.default.object }; MenuItem.defaultProps = { menuItemsTypes: { checkbox: 'checkbox' }, metaData: {} }; var ConnectedMenuItem = MenuItem; exports.MenuItem = MenuItem; exports.ConnectedMenuItem = ConnectedMenuItem; ; var _temp = function () { if (typeof __REACT_HOT_LOADER__ === 'undefined') { return; } __REACT_HOT_LOADER__.register(MenuItem, 'MenuItem', 'src/components/core/menu/MenuItem.jsx'); __REACT_HOT_LOADER__.register(ConnectedMenuItem, 'ConnectedMenuItem', 'src/components/core/menu/MenuItem.jsx'); }(); ;