repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
JeppeSRC/Frodo
src/Frodo-core/graphics/texture/sampler.h
<reponame>JeppeSRC/Frodo<filename>src/Frodo-core/graphics/texture/sampler.h #pragma once #include <platforms/platform.h> #include <core/enums.h> #include <core/types.h> namespace fd { namespace graphics { namespace texture { class Sampler { protected: VkSampler sampler; public: Sampler(SamplerFilter magFilter, SamplerFilter minFilter, SamplerAddressMode addressU, SamplerAddressMode addressV, SamplerAddressMode addressW, bool anisotropy, float32 maxAnisotropy, SamplerBorderColor borderColor, bool normalizedCoordinates = true); ~Sampler(); inline VkSampler GetSampler() const { return sampler; } }; } } }
sbhachu/Android
audio-player/app/src/main/java/com/sbhachu/audioplayer/presentation/view/GenreItemAdapterView.java
<reponame>sbhachu/Android package com.sbhachu.audioplayer.presentation.view; import android.content.Context; import android.widget.LinearLayout; import android.widget.TextView; import com.sbhachu.audioplayer.R; import com.sbhachu.audioplayer.data.model.media.Genre; import org.androidannotations.annotations.EViewGroup; import org.androidannotations.annotations.ViewById; import org.apache.commons.lang3.text.WordUtils; /** * Created by sbhachu on 24/12/2014. */ @EViewGroup(R.layout.view_genre_item) public class GenreItemAdapterView extends LinearLayout { @ViewById(R.id.genre_name_tv) public TextView genreNameTextView; public GenreItemAdapterView(Context context) { super(context); } public void bind(Genre genre) { genreNameTextView.setText(WordUtils.capitalize(genre.getName())); } }
Auzqy/design-pattern-GOF23-study
src/main/java/top/auzqy/design/pattern/behavioral/chainofresponsibility/example2/Boss.java
<filename>src/main/java/top/auzqy/design/pattern/behavioral/chainofresponsibility/example2/Boss.java<gh_stars>1-10 package top.auzqy.design.pattern.behavioral.chainofresponsibility.example2; /** * description: 老板 * createTime: 2019-08-05 16:48 * @author zqy */ public class Boss extends Leader { @Override void approve(Salary salary) { if (salary.getMoney() > 3000) { System.out.println("我是【" + this.getClass().getSimpleName() + "】,这个数归我管,但是老纸不批"); }else { System.out.println("我是【" + this.getClass().getSimpleName() + "】, 不归我管,别烦我!"); if (leader != null) { leader.approve(salary); } } } }
openDSME/CometOS
src/communication/ipv6/coap/ResourceList.h
/* * CometOS --- a component-based, extensible, tiny operating system * for wireless networks * * Copyright (c) 2015, Institute of Telematics, Hamburg University of Technology * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /** * @author: <NAME>, <NAME> */ #ifndef RESOURCELIST_H_ #define RESOURCELIST_H_ #include "CoAPResource.h" namespace cometos_v6 { template<uint8_t N> class ResourceList { public: ResourceList() { for (uint8_t i = 0; i < N; i++) { resources[i] = NULL; } } ~ResourceList() { for(uint8_t i = 0; i < N; i++){ if(resources[i] != NULL){ resources[i] = NULL; } } } bool deleteResource(CoAPResource* deleteMe){ if(deleteMe == NULL) { return false; } for(uint8_t i = 0; i < N; i++) { if(resources[i] == deleteMe){ delete deleteMe; resources[i] = NULL; return true; } } return false; } CoAPResource* findMatchingResource(CoAPMessage* request){ char* path = NULL; uint16_t pathLen = request->getPathString(path); if (pathLen == 0) return NULL; LOG_DEBUG(path); for(uint8_t i = 0; i < N; i++) { if ((resources[i] != NULL) && (resources[i]->hasPath(path))) { delete[] path; return resources[i]; } } delete[] path; return NULL; } bool insertResource(CoAPResource* insertMe, CoAPLayer* owner, CoAPBuffer_t* buffer){ if(insertMe == NULL) { return false; } for(uint8_t i = 0; i < N; i++) { if(resources[i] == NULL){ insertMe->setBuffer(buffer); insertMe->init(owner); resources[i] = insertMe; return true; } } return false; } uint16_t getResourceDiscoveryList(char*& payload) { uint16_t pathLength = 0; //and send their paths as a response for(uint8_t i = 0; i < N; i++){ //To do so, we first need the size of all strings added if(resources[i] != NULL && !resources[i]->isHiddenFromResourceDiscovery()) { pathLength += resources[i]->getPathLength() + 3; //pathLength + strlen(<>,) if(resources[i]->getResourceType() != NULL && strlen(resources[i]->getResourceType()) > 0) pathLength += strlen(resources[i]->getResourceType()) + 6; //pathLength + strlen(;rt="") } } if (pathLength == 0) return 0; uint16_t skip = 0; payload = new char[pathLength]; //allocate a buffer with that size for(uint8_t i = 0; i < N; i++){ //and parse the paths into a simple CoRE Link Format if(resources[i] != NULL && resources[i]->getResourceType() != NULL && !resources[i]->isHiddenFromResourceDiscovery()) { payload[skip] = '<'; resources[i]->printPath(&payload[++skip], resources[i]->getPathLength()); skip += resources[i]->getPathLength(); payload[skip] = '>'; if(strlen(resources[i]->getResourceType())){ payload[++skip] = ';'; payload[++skip] = 'r'; payload[++skip] = 't'; payload[++skip] = '='; payload[++skip] = '"'; memcpy(&payload[++skip], resources[i]->getResourceType(), strlen(resources[i]->getResourceType())); skip += strlen(resources[i]->getResourceType()) - 1; payload[skip] = '"'; } payload[++skip] = ','; skip++; } } payload[skip - 1] = '\0'; return pathLength; } protected: CoAPResource* resources[N]; }; } #endif /* RESOURCELIST_H_ */
teddywest32/intellij-community
platform/core-impl/src/com/intellij/psi/impl/FakePsiElement.java
<gh_stars>0 /* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.psi.impl; import com.intellij.lang.ASTNode; import com.intellij.lang.Language; import com.intellij.navigation.ItemPresentation; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiManager; import com.intellij.psi.PsiNamedElement; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; /** * @author <NAME> */ public abstract class FakePsiElement extends PsiElementBase implements PsiNamedElement, ItemPresentation { @Override public ItemPresentation getPresentation() { return this; } @Override @NotNull public Language getLanguage() { return Language.ANY; } @Override @NotNull public PsiElement[] getChildren() { return PsiElement.EMPTY_ARRAY; } @Override @Nullable public PsiElement getFirstChild() { return null; } @Override @Nullable public PsiElement getLastChild() { return null; } @Override @Nullable public PsiElement getNextSibling() { return null; } @Override @Nullable public PsiElement getPrevSibling() { return null; } @Override @Nullable public TextRange getTextRange() { return null; } @Override public int getStartOffsetInParent() { return 0; } @Override public int getTextLength() { return 0; } @Override @Nullable public PsiElement findElementAt(int offset) { return null; } @Override public int getTextOffset() { return 0; } @Override @Nullable @NonNls public String getText() { return null; } @Override @NotNull public char[] textToCharArray() { return new char[0]; } @Override public boolean textContains(char c) { return false; } @Override @Nullable public ASTNode getNode() { return null; } @Override public String getPresentableText() { return getName(); } @Override @Nullable public String getLocationString() { return null; } @Override public final Icon getIcon(final int flags) { return super.getIcon(flags); } @Override protected final Icon getElementIcon(final int flags) { return super.getElementIcon(flags); } @Override @Nullable public Icon getIcon(boolean open) { return null; } @Override public PsiElement setName(@NonNls @NotNull String name) throws IncorrectOperationException { return null; } @Override public PsiElement replace(@NotNull PsiElement newElement) throws IncorrectOperationException { throw new UnsupportedOperationException(getClass().getName()); } @Override public void checkAdd(@NotNull PsiElement element) throws IncorrectOperationException { throw new UnsupportedOperationException(getClass().getName()); } @Override public PsiElement add(@NotNull PsiElement element) throws IncorrectOperationException { throw new UnsupportedOperationException(getClass().getName()); } @Override public PsiElement addBefore(@NotNull PsiElement element, PsiElement anchor) throws IncorrectOperationException { throw new UnsupportedOperationException(getClass().getName()); } @Override public PsiElement addAfter(@NotNull PsiElement element, PsiElement anchor) throws IncorrectOperationException { throw new UnsupportedOperationException(getClass().getName()); } @Override public void checkDelete() throws IncorrectOperationException { throw new UnsupportedOperationException(getClass().getName()); } @Override public void delete() throws IncorrectOperationException { throw new UnsupportedOperationException(getClass().getName()); } @Override public PsiElement copy() { return (PsiElement)clone(); } @Override public PsiManager getManager() { final PsiElement parent = getParent(); return parent != null ? parent.getManager() : null; } @Override public boolean isPhysical() { return false; } }
lechium/iOS1351Headers
System/Library/Frameworks/SafariServices.framework/SFFormAutoFillFrame.h
/* * This header is generated by classdump-dyld 1.5 * on Friday, April 30, 2021 at 11:36:35 AM Mountain Standard Time * Operating System: Version 13.5.1 (Build 17F80) * Image Source: /System/Library/Frameworks/SafariServices.framework/SafariServices * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. Updated by <NAME>. */ #import <SafariServices/SafariServices-Structs.h> #import <libobjc.A.dylib/WBSFormAutoFillFrame.h> @class WKWebProcessPlugInFrame, NSString; @interface SFFormAutoFillFrame : NSObject <WBSFormAutoFillFrame> { WKWebProcessPlugInFrame* _plugInFrame; } @property (nonatomic,readonly) WKWebProcessPlugInFrame * plugInFrame; //@synthesize plugInFrame=_plugInFrame - In the implementation block @property (readonly) unsigned long long hash; @property (readonly) Class superclass; @property (copy,readonly) NSString * description; @property (copy,readonly) NSString * debugDescription; +(id)autoFillFrameWithWebProcessPlugInFrame:(id)arg1 ; -(BOOL)isEqual:(id)arg1 ; -(unsigned long long)hash; -(id)committedURL; -(BOOL)containsAnyFormElements; -(WKWebProcessPlugInFrame *)plugInFrame; -(id)initWithWebProcessPlugInFrame:(id)arg1 ; -(id)_pageContoller; -(id)_formMetadataController; -(OpaqueFormAutoFillFrameRef)frameRef; -(OpaqueJSContextRef)jsContextForMetadataControllerScriptWorld; -(OpaqueJSValueRef)jsWrapperInMetadataControllerScriptWorldForNode:(id)arg1 ; -(void)enumerateChildFramesUsingBlock:(/*^block*/id)arg1 ; -(id)pageMainFrame; @end
moogacs/aws-sdk-go-v2
service/grafana/api_op_DisassociateLicense.go
<reponame>moogacs/aws-sdk-go-v2 // Code generated by smithy-go-codegen DO NOT EDIT. package grafana import ( "context" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" "github.com/aws/aws-sdk-go-v2/aws/signer/v4" "github.com/aws/aws-sdk-go-v2/service/grafana/types" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) // Removes the Grafana Enterprise license from a workspace. func (c *Client) DisassociateLicense(ctx context.Context, params *DisassociateLicenseInput, optFns ...func(*Options)) (*DisassociateLicenseOutput, error) { if params == nil { params = &DisassociateLicenseInput{} } result, metadata, err := c.invokeOperation(ctx, "DisassociateLicense", params, optFns, c.addOperationDisassociateLicenseMiddlewares) if err != nil { return nil, err } out := result.(*DisassociateLicenseOutput) out.ResultMetadata = metadata return out, nil } type DisassociateLicenseInput struct { // The type of license to remove from the workspace. // // This member is required. LicenseType types.LicenseType // The ID of the workspace to remove the Grafana Enterprise license from. // // This member is required. WorkspaceId *string noSmithyDocumentSerde } type DisassociateLicenseOutput struct { // A structure containing information about the workspace. // // This member is required. Workspace *types.WorkspaceDescription // Metadata pertaining to the operation's result. ResultMetadata middleware.Metadata noSmithyDocumentSerde } func (c *Client) addOperationDisassociateLicenseMiddlewares(stack *middleware.Stack, options Options) (err error) { err = stack.Serialize.Add(&awsRestjson1_serializeOpDisassociateLicense{}, middleware.After) if err != nil { return err } err = stack.Deserialize.Add(&awsRestjson1_deserializeOpDisassociateLicense{}, middleware.After) if err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { return err } if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { return err } if err = addRetryMiddlewares(stack, options); err != nil { return err } if err = addHTTPSignerV4Middleware(stack, options); err != nil { return err } if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { return err } if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { return err } if err = addClientUserAgent(stack); err != nil { return err } if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { return err } if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } if err = addOpDisassociateLicenseValidationMiddleware(stack); err != nil { return err } if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDisassociateLicense(options.Region), middleware.Before); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { return err } if err = addResponseErrorMiddleware(stack); err != nil { return err } if err = addRequestResponseLogging(stack, options); err != nil { return err } return nil } func newServiceMetadataMiddleware_opDisassociateLicense(region string) *awsmiddleware.RegisterServiceMetadata { return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, SigningName: "grafana", OperationName: "DisassociateLicense", } }
Sunrisepeak/Linux2.6-Reading
drivers/spi/spi-dw-dma.c
<gh_stars>10-100 // SPDX-License-Identifier: GPL-2.0-only /* * Special handling for DW DMA core * * Copyright (c) 2009, 2014 Intel Corporation. */ #include <linux/completion.h> #include <linux/dma-mapping.h> #include <linux/dmaengine.h> #include <linux/irqreturn.h> #include <linux/jiffies.h> #include <linux/module.h> #include <linux/pci.h> #include <linux/platform_data/dma-dw.h> #include <linux/spi/spi.h> #include <linux/types.h> #include "spi-dw.h" #define DW_SPI_RX_BUSY 0 #define DW_SPI_RX_BURST_LEVEL 16 #define DW_SPI_TX_BUSY 1 #define DW_SPI_TX_BURST_LEVEL 16 static bool dw_spi_dma_chan_filter(struct dma_chan *chan, void *param) { struct dw_dma_slave *s = param; if (s->dma_dev != chan->device->dev) return false; chan->private = s; return true; } static void dw_spi_dma_maxburst_init(struct dw_spi *dws) { struct dma_slave_caps caps; u32 max_burst, def_burst; int ret; def_burst = dws->fifo_len / 2; ret = dma_get_slave_caps(dws->rxchan, &caps); if (!ret && caps.max_burst) max_burst = caps.max_burst; else max_burst = DW_SPI_RX_BURST_LEVEL; dws->rxburst = min(max_burst, def_burst); dw_writel(dws, DW_SPI_DMARDLR, dws->rxburst - 1); ret = dma_get_slave_caps(dws->txchan, &caps); if (!ret && caps.max_burst) max_burst = caps.max_burst; else max_burst = DW_SPI_TX_BURST_LEVEL; /* * Having a Rx DMA channel serviced with higher priority than a Tx DMA * channel might not be enough to provide a well balanced DMA-based * SPI transfer interface. There might still be moments when the Tx DMA * channel is occasionally handled faster than the Rx DMA channel. * That in its turn will eventually cause the SPI Rx FIFO overflow if * SPI bus speed is high enough to fill the SPI Rx FIFO in before it's * cleared by the Rx DMA channel. In order to fix the problem the Tx * DMA activity is intentionally slowed down by limiting the SPI Tx * FIFO depth with a value twice bigger than the Tx burst length. */ dws->txburst = min(max_burst, def_burst); dw_writel(dws, DW_SPI_DMATDLR, dws->txburst); } static void dw_spi_dma_sg_burst_init(struct dw_spi *dws) { struct dma_slave_caps tx = {0}, rx = {0}; dma_get_slave_caps(dws->txchan, &tx); dma_get_slave_caps(dws->rxchan, &rx); if (tx.max_sg_burst > 0 && rx.max_sg_burst > 0) dws->dma_sg_burst = min(tx.max_sg_burst, rx.max_sg_burst); else if (tx.max_sg_burst > 0) dws->dma_sg_burst = tx.max_sg_burst; else if (rx.max_sg_burst > 0) dws->dma_sg_burst = rx.max_sg_burst; else dws->dma_sg_burst = 0; } static int dw_spi_dma_init_mfld(struct device *dev, struct dw_spi *dws) { struct dw_dma_slave dma_tx = { .dst_id = 1 }, *tx = &dma_tx; struct dw_dma_slave dma_rx = { .src_id = 0 }, *rx = &dma_rx; struct pci_dev *dma_dev; dma_cap_mask_t mask; /* * Get pci device for DMA controller, currently it could only * be the DMA controller of Medfield */ dma_dev = pci_get_device(PCI_VENDOR_ID_INTEL, 0x0827, NULL); if (!dma_dev) return -ENODEV; dma_cap_zero(mask); dma_cap_set(DMA_SLAVE, mask); /* 1. Init rx channel */ rx->dma_dev = &dma_dev->dev; dws->rxchan = dma_request_channel(mask, dw_spi_dma_chan_filter, rx); if (!dws->rxchan) goto err_exit; /* 2. Init tx channel */ tx->dma_dev = &dma_dev->dev; dws->txchan = dma_request_channel(mask, dw_spi_dma_chan_filter, tx); if (!dws->txchan) goto free_rxchan; dws->master->dma_rx = dws->rxchan; dws->master->dma_tx = dws->txchan; init_completion(&dws->dma_completion); dw_spi_dma_maxburst_init(dws); dw_spi_dma_sg_burst_init(dws); return 0; free_rxchan: dma_release_channel(dws->rxchan); dws->rxchan = NULL; err_exit: return -EBUSY; } static int dw_spi_dma_init_generic(struct device *dev, struct dw_spi *dws) { dws->rxchan = dma_request_slave_channel(dev, "rx"); if (!dws->rxchan) return -ENODEV; dws->txchan = dma_request_slave_channel(dev, "tx"); if (!dws->txchan) { dma_release_channel(dws->rxchan); dws->rxchan = NULL; return -ENODEV; } dws->master->dma_rx = dws->rxchan; dws->master->dma_tx = dws->txchan; init_completion(&dws->dma_completion); dw_spi_dma_maxburst_init(dws); dw_spi_dma_sg_burst_init(dws); return 0; } static void dw_spi_dma_exit(struct dw_spi *dws) { if (dws->txchan) { dmaengine_terminate_sync(dws->txchan); dma_release_channel(dws->txchan); } if (dws->rxchan) { dmaengine_terminate_sync(dws->rxchan); dma_release_channel(dws->rxchan); } } static irqreturn_t dw_spi_dma_transfer_handler(struct dw_spi *dws) { dw_spi_check_status(dws, false); complete(&dws->dma_completion); return IRQ_HANDLED; } static bool dw_spi_can_dma(struct spi_controller *master, struct spi_device *spi, struct spi_transfer *xfer) { struct dw_spi *dws = spi_controller_get_devdata(master); return xfer->len > dws->fifo_len; } static enum dma_slave_buswidth dw_spi_dma_convert_width(u8 n_bytes) { if (n_bytes == 1) return DMA_SLAVE_BUSWIDTH_1_BYTE; else if (n_bytes == 2) return DMA_SLAVE_BUSWIDTH_2_BYTES; return DMA_SLAVE_BUSWIDTH_UNDEFINED; } static int dw_spi_dma_wait(struct dw_spi *dws, unsigned int len, u32 speed) { unsigned long long ms; ms = len * MSEC_PER_SEC * BITS_PER_BYTE; do_div(ms, speed); ms += ms + 200; if (ms > UINT_MAX) ms = UINT_MAX; ms = wait_for_completion_timeout(&dws->dma_completion, msecs_to_jiffies(ms)); if (ms == 0) { dev_err(&dws->master->cur_msg->spi->dev, "DMA transaction timed out\n"); return -ETIMEDOUT; } return 0; } static inline bool dw_spi_dma_tx_busy(struct dw_spi *dws) { return !(dw_readl(dws, DW_SPI_SR) & DW_SPI_SR_TF_EMPT); } static int dw_spi_dma_wait_tx_done(struct dw_spi *dws, struct spi_transfer *xfer) { int retry = DW_SPI_WAIT_RETRIES; struct spi_delay delay; u32 nents; nents = dw_readl(dws, DW_SPI_TXFLR); delay.unit = SPI_DELAY_UNIT_SCK; delay.value = nents * dws->n_bytes * BITS_PER_BYTE; while (dw_spi_dma_tx_busy(dws) && retry--) spi_delay_exec(&delay, xfer); if (retry < 0) { dev_err(&dws->master->dev, "Tx hanged up\n"); return -EIO; } return 0; } /* * dws->dma_chan_busy is set before the dma transfer starts, callback for tx * channel will clear a corresponding bit. */ static void dw_spi_dma_tx_done(void *arg) { struct dw_spi *dws = arg; clear_bit(DW_SPI_TX_BUSY, &dws->dma_chan_busy); if (test_bit(DW_SPI_RX_BUSY, &dws->dma_chan_busy)) return; complete(&dws->dma_completion); } static int dw_spi_dma_config_tx(struct dw_spi *dws) { struct dma_slave_config txconf; memset(&txconf, 0, sizeof(txconf)); txconf.direction = DMA_MEM_TO_DEV; txconf.dst_addr = dws->dma_addr; txconf.dst_maxburst = dws->txburst; txconf.src_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES; txconf.dst_addr_width = dw_spi_dma_convert_width(dws->n_bytes); txconf.device_fc = false; return dmaengine_slave_config(dws->txchan, &txconf); } static int dw_spi_dma_submit_tx(struct dw_spi *dws, struct scatterlist *sgl, unsigned int nents) { struct dma_async_tx_descriptor *txdesc; dma_cookie_t cookie; int ret; txdesc = dmaengine_prep_slave_sg(dws->txchan, sgl, nents, DMA_MEM_TO_DEV, DMA_PREP_INTERRUPT | DMA_CTRL_ACK); if (!txdesc) return -ENOMEM; txdesc->callback = dw_spi_dma_tx_done; txdesc->callback_param = dws; cookie = dmaengine_submit(txdesc); ret = dma_submit_error(cookie); if (ret) { dmaengine_terminate_sync(dws->txchan); return ret; } set_bit(DW_SPI_TX_BUSY, &dws->dma_chan_busy); return 0; } static inline bool dw_spi_dma_rx_busy(struct dw_spi *dws) { return !!(dw_readl(dws, DW_SPI_SR) & DW_SPI_SR_RF_NOT_EMPT); } static int dw_spi_dma_wait_rx_done(struct dw_spi *dws) { int retry = DW_SPI_WAIT_RETRIES; struct spi_delay delay; unsigned long ns, us; u32 nents; /* * It's unlikely that DMA engine is still doing the data fetching, but * if it's let's give it some reasonable time. The timeout calculation * is based on the synchronous APB/SSI reference clock rate, on a * number of data entries left in the Rx FIFO, times a number of clock * periods normally needed for a single APB read/write transaction * without PREADY signal utilized (which is true for the DW APB SSI * controller). */ nents = dw_readl(dws, DW_SPI_RXFLR); ns = 4U * NSEC_PER_SEC / dws->max_freq * nents; if (ns <= NSEC_PER_USEC) { delay.unit = SPI_DELAY_UNIT_NSECS; delay.value = ns; } else { us = DIV_ROUND_UP(ns, NSEC_PER_USEC); delay.unit = SPI_DELAY_UNIT_USECS; delay.value = clamp_val(us, 0, USHRT_MAX); } while (dw_spi_dma_rx_busy(dws) && retry--) spi_delay_exec(&delay, NULL); if (retry < 0) { dev_err(&dws->master->dev, "Rx hanged up\n"); return -EIO; } return 0; } /* * dws->dma_chan_busy is set before the dma transfer starts, callback for rx * channel will clear a corresponding bit. */ static void dw_spi_dma_rx_done(void *arg) { struct dw_spi *dws = arg; clear_bit(DW_SPI_RX_BUSY, &dws->dma_chan_busy); if (test_bit(DW_SPI_TX_BUSY, &dws->dma_chan_busy)) return; complete(&dws->dma_completion); } static int dw_spi_dma_config_rx(struct dw_spi *dws) { struct dma_slave_config rxconf; memset(&rxconf, 0, sizeof(rxconf)); rxconf.direction = DMA_DEV_TO_MEM; rxconf.src_addr = dws->dma_addr; rxconf.src_maxburst = dws->rxburst; rxconf.dst_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES; rxconf.src_addr_width = dw_spi_dma_convert_width(dws->n_bytes); rxconf.device_fc = false; return dmaengine_slave_config(dws->rxchan, &rxconf); } static int dw_spi_dma_submit_rx(struct dw_spi *dws, struct scatterlist *sgl, unsigned int nents) { struct dma_async_tx_descriptor *rxdesc; dma_cookie_t cookie; int ret; rxdesc = dmaengine_prep_slave_sg(dws->rxchan, sgl, nents, DMA_DEV_TO_MEM, DMA_PREP_INTERRUPT | DMA_CTRL_ACK); if (!rxdesc) return -ENOMEM; rxdesc->callback = dw_spi_dma_rx_done; rxdesc->callback_param = dws; cookie = dmaengine_submit(rxdesc); ret = dma_submit_error(cookie); if (ret) { dmaengine_terminate_sync(dws->rxchan); return ret; } set_bit(DW_SPI_RX_BUSY, &dws->dma_chan_busy); return 0; } static int dw_spi_dma_setup(struct dw_spi *dws, struct spi_transfer *xfer) { u16 imr, dma_ctrl; int ret; if (!xfer->tx_buf) return -EINVAL; /* Setup DMA channels */ ret = dw_spi_dma_config_tx(dws); if (ret) return ret; if (xfer->rx_buf) { ret = dw_spi_dma_config_rx(dws); if (ret) return ret; } /* Set the DMA handshaking interface */ dma_ctrl = DW_SPI_DMACR_TDMAE; if (xfer->rx_buf) dma_ctrl |= DW_SPI_DMACR_RDMAE; dw_writel(dws, DW_SPI_DMACR, dma_ctrl); /* Set the interrupt mask */ imr = DW_SPI_INT_TXOI; if (xfer->rx_buf) imr |= DW_SPI_INT_RXUI | DW_SPI_INT_RXOI; dw_spi_umask_intr(dws, imr); reinit_completion(&dws->dma_completion); dws->transfer_handler = dw_spi_dma_transfer_handler; return 0; } static int dw_spi_dma_transfer_all(struct dw_spi *dws, struct spi_transfer *xfer) { int ret; /* Submit the DMA Tx transfer */ ret = dw_spi_dma_submit_tx(dws, xfer->tx_sg.sgl, xfer->tx_sg.nents); if (ret) goto err_clear_dmac; /* Submit the DMA Rx transfer if required */ if (xfer->rx_buf) { ret = dw_spi_dma_submit_rx(dws, xfer->rx_sg.sgl, xfer->rx_sg.nents); if (ret) goto err_clear_dmac; /* rx must be started before tx due to spi instinct */ dma_async_issue_pending(dws->rxchan); } dma_async_issue_pending(dws->txchan); ret = dw_spi_dma_wait(dws, xfer->len, xfer->effective_speed_hz); err_clear_dmac: dw_writel(dws, DW_SPI_DMACR, 0); return ret; } /* * In case if at least one of the requested DMA channels doesn't support the * hardware accelerated SG list entries traverse, the DMA driver will most * likely work that around by performing the IRQ-based SG list entries * resubmission. That might and will cause a problem if the DMA Tx channel is * recharged and re-executed before the Rx DMA channel. Due to * non-deterministic IRQ-handler execution latency the DMA Tx channel will * start pushing data to the SPI bus before the Rx DMA channel is even * reinitialized with the next inbound SG list entry. By doing so the DMA Tx * channel will implicitly start filling the DW APB SSI Rx FIFO up, which while * the DMA Rx channel being recharged and re-executed will eventually be * overflown. * * In order to solve the problem we have to feed the DMA engine with SG list * entries one-by-one. It shall keep the DW APB SSI Tx and Rx FIFOs * synchronized and prevent the Rx FIFO overflow. Since in general the tx_sg * and rx_sg lists may have different number of entries of different lengths * (though total length should match) let's virtually split the SG-lists to the * set of DMA transfers, which length is a minimum of the ordered SG-entries * lengths. An ASCII-sketch of the implemented algo is following: * xfer->len * |___________| * tx_sg list: |___|____|__| * rx_sg list: |_|____|____| * DMA transfers: |_|_|__|_|__| * * Note in order to have this workaround solving the denoted problem the DMA * engine driver should properly initialize the max_sg_burst capability and set * the DMA device max segment size parameter with maximum data block size the * DMA engine supports. */ static int dw_spi_dma_transfer_one(struct dw_spi *dws, struct spi_transfer *xfer) { struct scatterlist *tx_sg = NULL, *rx_sg = NULL, tx_tmp, rx_tmp; unsigned int tx_len = 0, rx_len = 0; unsigned int base, len; int ret; sg_init_table(&tx_tmp, 1); sg_init_table(&rx_tmp, 1); for (base = 0, len = 0; base < xfer->len; base += len) { /* Fetch next Tx DMA data chunk */ if (!tx_len) { tx_sg = !tx_sg ? &xfer->tx_sg.sgl[0] : sg_next(tx_sg); sg_dma_address(&tx_tmp) = sg_dma_address(tx_sg); tx_len = sg_dma_len(tx_sg); } /* Fetch next Rx DMA data chunk */ if (!rx_len) { rx_sg = !rx_sg ? &xfer->rx_sg.sgl[0] : sg_next(rx_sg); sg_dma_address(&rx_tmp) = sg_dma_address(rx_sg); rx_len = sg_dma_len(rx_sg); } len = min(tx_len, rx_len); sg_dma_len(&tx_tmp) = len; sg_dma_len(&rx_tmp) = len; /* Submit DMA Tx transfer */ ret = dw_spi_dma_submit_tx(dws, &tx_tmp, 1); if (ret) break; /* Submit DMA Rx transfer */ ret = dw_spi_dma_submit_rx(dws, &rx_tmp, 1); if (ret) break; /* Rx must be started before Tx due to SPI instinct */ dma_async_issue_pending(dws->rxchan); dma_async_issue_pending(dws->txchan); /* * Here we only need to wait for the DMA transfer to be * finished since SPI controller is kept enabled during the * procedure this loop implements and there is no risk to lose * data left in the Tx/Rx FIFOs. */ ret = dw_spi_dma_wait(dws, len, xfer->effective_speed_hz); if (ret) break; reinit_completion(&dws->dma_completion); sg_dma_address(&tx_tmp) += len; sg_dma_address(&rx_tmp) += len; tx_len -= len; rx_len -= len; } dw_writel(dws, DW_SPI_DMACR, 0); return ret; } static int dw_spi_dma_transfer(struct dw_spi *dws, struct spi_transfer *xfer) { unsigned int nents; int ret; nents = max(xfer->tx_sg.nents, xfer->rx_sg.nents); /* * Execute normal DMA-based transfer (which submits the Rx and Tx SG * lists directly to the DMA engine at once) if either full hardware * accelerated SG list traverse is supported by both channels, or the * Tx-only SPI transfer is requested, or the DMA engine is capable to * handle both SG lists on hardware accelerated basis. */ if (!dws->dma_sg_burst || !xfer->rx_buf || nents <= dws->dma_sg_burst) ret = dw_spi_dma_transfer_all(dws, xfer); else ret = dw_spi_dma_transfer_one(dws, xfer); if (ret) return ret; if (dws->master->cur_msg->status == -EINPROGRESS) { ret = dw_spi_dma_wait_tx_done(dws, xfer); if (ret) return ret; } if (xfer->rx_buf && dws->master->cur_msg->status == -EINPROGRESS) ret = dw_spi_dma_wait_rx_done(dws); return ret; } static void dw_spi_dma_stop(struct dw_spi *dws) { if (test_bit(DW_SPI_TX_BUSY, &dws->dma_chan_busy)) { dmaengine_terminate_sync(dws->txchan); clear_bit(DW_SPI_TX_BUSY, &dws->dma_chan_busy); } if (test_bit(DW_SPI_RX_BUSY, &dws->dma_chan_busy)) { dmaengine_terminate_sync(dws->rxchan); clear_bit(DW_SPI_RX_BUSY, &dws->dma_chan_busy); } } static const struct dw_spi_dma_ops dw_spi_dma_mfld_ops = { .dma_init = dw_spi_dma_init_mfld, .dma_exit = dw_spi_dma_exit, .dma_setup = dw_spi_dma_setup, .can_dma = dw_spi_can_dma, .dma_transfer = dw_spi_dma_transfer, .dma_stop = dw_spi_dma_stop, }; void dw_spi_dma_setup_mfld(struct dw_spi *dws) { dws->dma_ops = &dw_spi_dma_mfld_ops; } EXPORT_SYMBOL_NS_GPL(dw_spi_dma_setup_mfld, SPI_DW_CORE); static const struct dw_spi_dma_ops dw_spi_dma_generic_ops = { .dma_init = dw_spi_dma_init_generic, .dma_exit = dw_spi_dma_exit, .dma_setup = dw_spi_dma_setup, .can_dma = dw_spi_can_dma, .dma_transfer = dw_spi_dma_transfer, .dma_stop = dw_spi_dma_stop, }; void dw_spi_dma_setup_generic(struct dw_spi *dws) { dws->dma_ops = &dw_spi_dma_generic_ops; } EXPORT_SYMBOL_NS_GPL(dw_spi_dma_setup_generic, SPI_DW_CORE);
wallamejorge/WirelessSensorGas
rtl/wirelessUSBDrivers/Linux/2010_0709_RT2870_Linux_STA_v2.4.0.1/common/crypt_hmac.c
/* ************************************************************************* * Ralink Tech Inc. * 5F., No.36, Taiyuan St., Jhubei City, * Hsinchu County 302, * Taiwan, R.O.C. * * (c) Copyright 2002-2007, Ralink Technology, Inc. * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * * *************************************************************************/ #include "crypt_hmac.h" #if defined(__cplusplus) extern "C" { #endif /* initialise the HMAC context to zero */ void hmac_sha_begin(hmac_ctx cx[1]) { memset(cx, 0, sizeof(hmac_ctx)); } /* input the HMAC key (can be called multiple times) */ int hmac_sha_key(const unsigned char key[], unsigned int key_len, hmac_ctx cx[1]) { if(cx->klen == HMAC_IN_DATA) /* error if further key input */ return HMAC_BAD_MODE; /* is attempted in data mode */ if(cx->klen + key_len > HASH_INPUT_SIZE) /* if the key has to be hashed */ { if(cx->klen <= HASH_INPUT_SIZE) /* if the hash has not yet been */ { /* started, initialise it and */ sha_begin(cx->ctx); /* hash stored key characters */ sha_hash(cx->key, cx->klen, cx->ctx); } sha_hash(key, key_len, cx->ctx); /* hash long key data into hash */ } else /* otherwise store key data */ memcpy(cx->key + cx->klen, key, key_len); cx->klen += key_len; /* update the key length count */ return HMAC_OK; } /* input the HMAC data (can be called multiple times) - */ /* note that this call terminates the key input phase */ void hmac_sha_data(const unsigned char data[], unsigned int data_len, hmac_ctx cx[1]) { unsigned int i; if(cx->klen != HMAC_IN_DATA) /* if not yet in data phase */ { if(cx->klen > HASH_INPUT_SIZE) /* if key is being hashed */ { /* complete the hash and */ sha_end(cx->key, cx->ctx); /* store the result as the */ cx->klen = HASH_OUTPUT_SIZE; /* key and set new length */ } /* pad the key if necessary */ memset(cx->key + cx->klen, 0, HASH_INPUT_SIZE - cx->klen); /* xor ipad into key value */ for(i = 0; i < (HASH_INPUT_SIZE >> 2); ++i) ((unsigned int*)cx->key)[i] ^= 0x36363636; /* and start hash operation */ sha_begin(cx->ctx); sha_hash(cx->key, HASH_INPUT_SIZE, cx->ctx); /* mark as now in data mode */ cx->klen = HMAC_IN_DATA; } /* hash the data (if any) */ if(data_len) sha_hash(data, data_len, cx->ctx); } /* compute and output the MAC value */ void hmac_sha_end(unsigned char mac[], unsigned int mac_len, hmac_ctx cx[1]) { unsigned char dig[HASH_OUTPUT_SIZE]; unsigned int i; /* if no data has been entered perform a null data phase */ if(cx->klen != HMAC_IN_DATA) hmac_sha_data((const unsigned char*)0, 0, cx); sha_end(dig, cx->ctx); /* complete the inner hash */ /* set outer key value using opad and removing ipad */ for(i = 0; i < (HASH_INPUT_SIZE >> 2); ++i) ((unsigned int*)cx->key)[i] ^= 0x36363636 ^ 0x5c5c5c5c; /* perform the outer hash operation */ sha_begin(cx->ctx); sha_hash(cx->key, HASH_INPUT_SIZE, cx->ctx); sha_hash(dig, HASH_OUTPUT_SIZE, cx->ctx); sha_end(dig, cx->ctx); /* output the hash value */ for(i = 0; i < mac_len; ++i) mac[i] = dig[i]; } /* 'do it all in one go' subroutine */ void hmac_sha(const unsigned char key[], unsigned int key_len, const unsigned char data[], unsigned int data_len, unsigned char mac[], unsigned int mac_len) { hmac_ctx cx[1]; hmac_sha_begin(cx); hmac_sha_key(key, key_len, cx); hmac_sha_data(data, data_len, cx); hmac_sha_end(mac, mac_len, cx); } #if defined(__cplusplus) } #endif /* End of crypt_hmac.c */
valoeghese/Zoesteria
src/main/java/valoeghese/valoeghesesbe/world/biomes/alpha3/macro/BiomeGrasslandsLakeless.java
package valoeghese.valoeghesesbe.world.biomes.alpha3.macro; import valoeghese.valoeghesesbe.world.worldtype.ILakeRemover; public class BiomeGrasslandsLakeless extends BiomeGrasslands implements ILakeRemover { public BiomeGrasslandsLakeless(BiomeProperties properties, Variant plainsType) { super(properties, plainsType); } }
bowlofstew/vespa
clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/util/JSONObjectWrapperTest.java
<filename>clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/util/JSONObjectWrapperTest.java<gh_stars>0 // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.clustercontroller.utils.util; import junit.framework.TestCase; public class JSONObjectWrapperTest extends TestCase { public void testExceptionWrapping() { JSONObjectWrapper wrapper = new JSONObjectWrapper(); try{ wrapper.put(null, "foo"); } catch (NullPointerException e) { assertEquals("Null key.", e.getMessage()); } } }
copslock/broadcom_cpri
sdk-6.5.20/include/shared/swstate/layout/sw_state_dpp_soc_arad_pp_occupation_layout.h
/* * * This license is set out in https://raw.githubusercontent.com/Broadcom-Network-Switching-Software/OpenBCM/master/Legal/LICENSE file. * * Copyright 2007-2020 Broadcom Inc. All rights reserved. * * DO NOT EDIT THIS FILE! * This file is auto-generated. * Edits to this file will be lost when it is regenerated. */ #ifndef _SHR_sw_state_dpp_soc_arad_pp_occupation_H_ #define _SHR_sw_state_dpp_soc_arad_pp_occupation_H_ #define SW_STATE_DPP_SOC_ARAD_PP_OCCUPATION_INLIF_PROFILE_LAYOUT_NOF_MAX_LAYOUT_NODES (1) #define SW_STATE_DPP_SOC_ARAD_PP_OCCUPATION_OUTLIF_PROFILE_LAYOUT_NOF_MAX_LAYOUT_NODES (1) #define SW_STATE_DPP_SOC_ARAD_PP_OCCUPATION_RIF_PROFILE_LAYOUT_NOF_MAX_LAYOUT_NODES (1) #define SW_STATE_DPP_SOC_ARAD_PP_OCCUPATION_LAYOUT_NOF_MAX_LAYOUT_NODES (1 + SW_STATE_DPP_SOC_ARAD_PP_OCCUPATION_INLIF_PROFILE_LAYOUT_NOF_MAX_LAYOUT_NODES + SW_STATE_DPP_SOC_ARAD_PP_OCCUPATION_OUTLIF_PROFILE_LAYOUT_NOF_MAX_LAYOUT_NODES + SW_STATE_DPP_SOC_ARAD_PP_OCCUPATION_RIF_PROFILE_LAYOUT_NOF_MAX_LAYOUT_NODES) #ifdef BCM_PETRA_SUPPORT #if defined(BCM_PETRA_SUPPORT) int sw_state_dpp_soc_arad_pp_occupation_layout_node_create(int unit, int* root_node_id, uint32* next_free_node_id); #endif /* defined(BCM_PETRA_SUPPORT)*/ #endif /* BCM_PETRA_SUPPORT*/ #ifdef BCM_PETRA_SUPPORT #if defined(BCM_PETRA_SUPPORT) int sw_state_dpp_soc_arad_pp_occupation_inlif_profile_layout_node_create(int unit, int* root_node_id, uint32* next_free_node_id); #endif /* defined(BCM_PETRA_SUPPORT)*/ #endif /* BCM_PETRA_SUPPORT*/ #ifdef BCM_PETRA_SUPPORT #if defined(BCM_PETRA_SUPPORT) int sw_state_dpp_soc_arad_pp_occupation_outlif_profile_layout_node_create(int unit, int* root_node_id, uint32* next_free_node_id); #endif /* defined(BCM_PETRA_SUPPORT)*/ #endif /* BCM_PETRA_SUPPORT*/ #ifdef BCM_PETRA_SUPPORT #if defined(BCM_PETRA_SUPPORT) int sw_state_dpp_soc_arad_pp_occupation_rif_profile_layout_node_create(int unit, int* root_node_id, uint32* next_free_node_id); #endif /* defined(BCM_PETRA_SUPPORT)*/ #endif /* BCM_PETRA_SUPPORT*/ #endif /* _SHR_sw_state_dpp_soc_arad_pp_occupation_H_ */
viewdy/phantomjs
src/qt/qtwebkit/Source/WebCore/Modules/filesystem/DOMFileSystemBase.cpp
<reponame>viewdy/phantomjs<filename>src/qt/qtwebkit/Source/WebCore/Modules/filesystem/DOMFileSystemBase.cpp /* * Copyright (C) 2010 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "DOMFileSystemBase.h" #if ENABLE(FILE_SYSTEM) #include "DOMFilePath.h" #include "DirectoryEntry.h" #include "DirectoryReaderBase.h" #include "EntriesCallback.h" #include "EntryArray.h" #include "EntryBase.h" #include "EntryCallback.h" #include "ErrorCallback.h" #include "FileError.h" #include "FileSystemCallbacks.h" #include "MetadataCallback.h" #include "ScriptExecutionContext.h" #include "VoidCallback.h" #include <wtf/OwnPtr.h> namespace WebCore { const char DOMFileSystemBase::persistentPathPrefix[] = "persistent"; const size_t DOMFileSystemBase::persistentPathPrefixLength = sizeof(DOMFileSystemBase::persistentPathPrefix) - 1; const char DOMFileSystemBase::temporaryPathPrefix[] = "temporary"; const size_t DOMFileSystemBase::temporaryPathPrefixLength = sizeof(DOMFileSystemBase::temporaryPathPrefix) - 1; const char DOMFileSystemBase::isolatedPathPrefix[] = "isolated"; const size_t DOMFileSystemBase::isolatedPathPrefixLength = sizeof(DOMFileSystemBase::isolatedPathPrefix) - 1; DOMFileSystemBase::DOMFileSystemBase(ScriptExecutionContext* context, const String& name, FileSystemType type, const KURL& rootURL, PassOwnPtr<AsyncFileSystem> asyncFileSystem) : m_context(context) , m_name(name) , m_type(type) , m_filesystemRootURL(rootURL) , m_clonable(false) , m_asyncFileSystem(asyncFileSystem) { } DOMFileSystemBase::~DOMFileSystemBase() { } #if !PLATFORM(BLACKBERRY) // static bool DOMFileSystemBase::isValidType(FileSystemType type) { return type == FileSystemTypeTemporary || type == FileSystemTypePersistent; } // static bool DOMFileSystemBase::crackFileSystemURL(const KURL& url, FileSystemType& type, String& filePath) { if (!url.protocolIs("filesystem")) return false; if (!url.innerURL()) return false; String typeString = url.innerURL()->path().substring(1); if (typeString == temporaryPathPrefix) type = FileSystemTypeTemporary; else if (typeString == persistentPathPrefix) type = FileSystemTypePersistent; else return false; filePath = decodeURLEscapeSequences(url.path()); return true; } bool DOMFileSystemBase::supportsToURL() const { ASSERT(isValidType(m_type)); return true; } KURL DOMFileSystemBase::createFileSystemURL(const String& fullPath) const { ASSERT(DOMFilePath::isAbsolute(fullPath)); KURL url = m_filesystemRootURL; // Remove the extra leading slash. url.setPath(url.path() + encodeWithURLEscapeSequences(fullPath.substring(1))); return url; } #endif SecurityOrigin* DOMFileSystemBase::securityOrigin() const { return m_context->securityOrigin(); } KURL DOMFileSystemBase::createFileSystemURL(const EntryBase* entry) const { return createFileSystemURL(entry->fullPath()); } bool DOMFileSystemBase::getMetadata(const EntryBase* entry, PassRefPtr<MetadataCallback> successCallback, PassRefPtr<ErrorCallback> errorCallback) { m_asyncFileSystem->readMetadata(createFileSystemURL(entry), MetadataCallbacks::create(successCallback, errorCallback)); return true; } static bool verifyAndGetDestinationPathForCopyOrMove(const EntryBase* source, EntryBase* parent, const String& newName, String& destinationPath) { ASSERT(source); if (!parent || !parent->isDirectory()) return false; if (!newName.isEmpty() && !DOMFilePath::isValidName(newName)) return false; const bool isSameFileSystem = (*source->filesystem() == *parent->filesystem()); // It is an error to try to copy or move an entry inside itself at any depth if it is a directory. if (source->isDirectory() && isSameFileSystem && DOMFilePath::isParentOf(source->fullPath(), parent->fullPath())) return false; // It is an error to copy or move an entry into its parent if a name different from its current one isn't provided. if (isSameFileSystem && (newName.isEmpty() || source->name() == newName) && DOMFilePath::getDirectory(source->fullPath()) == parent->fullPath()) return false; destinationPath = parent->fullPath(); if (!newName.isEmpty()) destinationPath = DOMFilePath::append(destinationPath, newName); else destinationPath = DOMFilePath::append(destinationPath, source->name()); return true; } static bool pathToAbsolutePath(FileSystemType type, const EntryBase* base, String path, String& absolutePath) { ASSERT(base); if (!DOMFilePath::isAbsolute(path)) path = DOMFilePath::append(base->fullPath(), path); absolutePath = DOMFilePath::removeExtraParentReferences(path); if ((type == FileSystemTypeTemporary || type == FileSystemTypePersistent) && !DOMFilePath::isValidPath(absolutePath)) return false; return true; } bool DOMFileSystemBase::move(const EntryBase* source, EntryBase* parent, const String& newName, PassRefPtr<EntryCallback> successCallback, PassRefPtr<ErrorCallback> errorCallback) { String destinationPath; if (!verifyAndGetDestinationPathForCopyOrMove(source, parent, newName, destinationPath)) return false; m_asyncFileSystem->move(createFileSystemURL(source), parent->filesystem()->createFileSystemURL(destinationPath), EntryCallbacks::create(successCallback, errorCallback, parent->filesystem(), destinationPath, source->isDirectory())); return true; } bool DOMFileSystemBase::copy(const EntryBase* source, EntryBase* parent, const String& newName, PassRefPtr<EntryCallback> successCallback, PassRefPtr<ErrorCallback> errorCallback) { String destinationPath; if (!verifyAndGetDestinationPathForCopyOrMove(source, parent, newName, destinationPath)) return false; m_asyncFileSystem->copy(createFileSystemURL(source), parent->filesystem()->createFileSystemURL(destinationPath), EntryCallbacks::create(successCallback, errorCallback, parent->filesystem(), destinationPath, source->isDirectory())); return true; } bool DOMFileSystemBase::remove(const EntryBase* entry, PassRefPtr<VoidCallback> successCallback, PassRefPtr<ErrorCallback> errorCallback) { ASSERT(entry); // We don't allow calling remove() on the root directory. if (entry->fullPath() == String(DOMFilePath::root)) return false; m_asyncFileSystem->remove(createFileSystemURL(entry), VoidCallbacks::create(successCallback, errorCallback)); return true; } bool DOMFileSystemBase::removeRecursively(const EntryBase* entry, PassRefPtr<VoidCallback> successCallback, PassRefPtr<ErrorCallback> errorCallback) { ASSERT(entry && entry->isDirectory()); // We don't allow calling remove() on the root directory. if (entry->fullPath() == String(DOMFilePath::root)) return false; m_asyncFileSystem->removeRecursively(createFileSystemURL(entry), VoidCallbacks::create(successCallback, errorCallback)); return true; } bool DOMFileSystemBase::getParent(const EntryBase* entry, PassRefPtr<EntryCallback> successCallback, PassRefPtr<ErrorCallback> errorCallback) { ASSERT(entry); String path = DOMFilePath::getDirectory(entry->fullPath()); m_asyncFileSystem->directoryExists(createFileSystemURL(path), EntryCallbacks::create(successCallback, errorCallback, this, path, true)); return true; } bool DOMFileSystemBase::getFile(const EntryBase* entry, const String& path, const FileSystemFlags& flags, PassRefPtr<EntryCallback> successCallback, PassRefPtr<ErrorCallback> errorCallback) { String absolutePath; if (!pathToAbsolutePath(m_type, entry, path, absolutePath)) return false; OwnPtr<EntryCallbacks> callbacks = EntryCallbacks::create(successCallback, errorCallback, this, absolutePath, false); if (flags.create) m_asyncFileSystem->createFile(createFileSystemURL(absolutePath), flags.exclusive, callbacks.release()); else m_asyncFileSystem->fileExists(createFileSystemURL(absolutePath), callbacks.release()); return true; } bool DOMFileSystemBase::getDirectory(const EntryBase* entry, const String& path, const FileSystemFlags& flags, PassRefPtr<EntryCallback> successCallback, PassRefPtr<ErrorCallback> errorCallback) { String absolutePath; if (!pathToAbsolutePath(m_type, entry, path, absolutePath)) return false; OwnPtr<EntryCallbacks> callbacks = EntryCallbacks::create(successCallback, errorCallback, this, absolutePath, true); if (flags.create) m_asyncFileSystem->createDirectory(createFileSystemURL(absolutePath), flags.exclusive, callbacks.release()); else m_asyncFileSystem->directoryExists(createFileSystemURL(absolutePath), callbacks.release()); return true; } bool DOMFileSystemBase::readDirectory(PassRefPtr<DirectoryReaderBase> reader, const String& path, PassRefPtr<EntriesCallback> successCallback, PassRefPtr<ErrorCallback> errorCallback) { ASSERT(DOMFilePath::isAbsolute(path)); m_asyncFileSystem->readDirectory(createFileSystemURL(path), EntriesCallbacks::create(successCallback, errorCallback, reader, path)); return true; } } // namespace WebCore #endif // ENABLE(FILE_SYSTEM)
lenxin/spring-security
oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2RefreshTokenGrantRequestTests.java
package org.springframework.security.oauth2.client.endpoint; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import org.junit.Before; import org.junit.Test; import org.springframework.security.oauth2.client.registration.ClientRegistration; import org.springframework.security.oauth2.client.registration.TestClientRegistrations; import org.springframework.security.oauth2.core.OAuth2AccessToken; import org.springframework.security.oauth2.core.OAuth2RefreshToken; import org.springframework.security.oauth2.core.TestOAuth2AccessTokens; import org.springframework.security.oauth2.core.TestOAuth2RefreshTokens; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link OAuth2RefreshTokenGrantRequest}. * * @author <NAME> */ public class OAuth2RefreshTokenGrantRequestTests { private ClientRegistration clientRegistration; private OAuth2AccessToken accessToken; private OAuth2RefreshToken refreshToken; @Before public void setup() { this.clientRegistration = TestClientRegistrations.clientRegistration().build(); this.accessToken = TestOAuth2AccessTokens.scopes("read", "write"); this.refreshToken = TestOAuth2RefreshTokens.refreshToken(); } @Test public void constructorWhenClientRegistrationIsNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException() .isThrownBy(() -> new OAuth2RefreshTokenGrantRequest(null, this.accessToken, this.refreshToken)) .withMessage("clientRegistration cannot be null"); } @Test public void constructorWhenAccessTokenIsNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException() .isThrownBy(() -> new OAuth2RefreshTokenGrantRequest(this.clientRegistration, null, this.refreshToken)) .withMessage("accessToken cannot be null"); } @Test public void constructorWhenRefreshTokenIsNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException() .isThrownBy(() -> new OAuth2RefreshTokenGrantRequest(this.clientRegistration, this.accessToken, null)) .withMessage("refreshToken cannot be null"); } @Test public void constructorWhenValidParametersProvidedThenCreated() { Set<String> scopes = new HashSet<>(Arrays.asList("read", "write")); OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest( this.clientRegistration, this.accessToken, this.refreshToken, scopes); assertThat(refreshTokenGrantRequest.getClientRegistration()).isSameAs(this.clientRegistration); assertThat(refreshTokenGrantRequest.getAccessToken()).isSameAs(this.accessToken); assertThat(refreshTokenGrantRequest.getRefreshToken()).isSameAs(this.refreshToken); assertThat(refreshTokenGrantRequest.getScopes()).isEqualTo(scopes); } }
xformation/xformation-compliancemanager-service
compliancemanager-server/src/main/java/com/synectiks/process/server/plugin/MessageSummary.java
<reponame>xformation/xformation-compliancemanager-service /* * */ package com.synectiks.process.server.plugin; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.joda.time.DateTime; import java.util.Collection; import java.util.HashSet; import java.util.Map; /** * MessageSummary is being used as a return value for AlarmCallbacks. */ public class MessageSummary { // for these fields we define individual json properties private static final HashSet<String> RESERVED_FIELDS = Sets.newHashSet(Message.FIELD_ID, Message.FIELD_MESSAGE, Message.FIELD_SOURCE, Message.FIELD_TIMESTAMP, Message.FIELD_STREAMS); @JsonIgnore private final String index; @JsonIgnore private final Message message; public MessageSummary(String index, Message message) { this.index = index; this.message = message; } @JsonProperty public String getIndex() { return index; } @JsonProperty public String getId() { return message.getId(); } @JsonProperty public String getSource() { return message.getSource(); } @JsonProperty public String getMessage() { return message.getMessage(); } @JsonProperty public DateTime getTimestamp() { return message.getTimestamp(); } @JsonProperty public Collection<String> getStreamIds() { return message.getStreamIds(); } @JsonProperty public Map<String, Object> getFields() { Map<String, Object> genericFields = Maps.newHashMap(); // strip out common "fields" that we report as individual properties for (Map.Entry<String, Object> entry : message.getFieldsEntries()) { if (!RESERVED_FIELDS.contains(entry.getKey())) { genericFields.put(entry.getKey(), entry.getValue()); } } return genericFields; } @JsonIgnore public boolean hasField(String key) { return message.hasField(key); } @JsonIgnore public Object getField(String key) { return message.getField(key); } @JsonIgnore public Message getRawMessage() { return message;} }
nanoxd/homebrew-cask
Casks/virustotaluploader.rb
<reponame>nanoxd/homebrew-cask class Virustotaluploader < Cask version '1.1' sha256 'e757f8eb49592dfe67169a5582bcc3cca01c8ecc6634853398813a2aa92f24a7' url 'https://www.virustotal.com/static/bin/VirusTotalUploader_1.1.dmg' homepage 'https://www.virustotal.com/' link 'VirusTotalUploader.app' end
yerkortiz/Algorithm-Design-Notes
ayt-08/secuenciasSaltarinas.java
import java.util.*; import java.lang.*; public class Main { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int n = stdin.nextInt(); int[] arr = new int[n]; boolean[] check = new boolean[n]; for(int i = 0; i < n; ++i)// leer elementos del arreglo arr[i] = stdin.nextInt(); for(int i = 1, a = 0; i < n; ++i) { a = Math.abs(arr[i] - arr[i - 1]); // valor absoluto de la diferencia if(a < n && check[a] == false) check[a] = true; // setear tabla en true } for(int i = 1; i < n; ++i) { if (check[i] == false) { System.out.println("Not Jolly"); break; } if(i == n - 1 && check[i] == true) { System.out.println("Jolly"); } } } }
pa-mahe/cdap
cdap-watchdog/src/main/java/co/cask/cdap/metrics/store/DefaultMetricDatasetFactory.java
/* * Copyright 2015-2017 <NAME>, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package co.cask.cdap.metrics.store; import co.cask.cdap.api.dataset.DatasetProperties; import co.cask.cdap.api.dataset.table.TableProperties; import co.cask.cdap.common.conf.CConfiguration; import co.cask.cdap.common.conf.Constants; import co.cask.cdap.data2.datafabric.dataset.DatasetsUtil; import co.cask.cdap.data2.dataset2.DatasetFramework; import co.cask.cdap.data2.dataset2.lib.table.MetricsTable; import co.cask.cdap.data2.dataset2.lib.table.hbase.CombinedHBaseMetricsTable; import co.cask.cdap.data2.dataset2.lib.table.hbase.HBaseTableAdmin; import co.cask.cdap.data2.dataset2.lib.timeseries.EntityTable; import co.cask.cdap.data2.dataset2.lib.timeseries.FactTable; import co.cask.cdap.hbase.wd.RowKeyDistributorByHashPrefix; import co.cask.cdap.metrics.process.MetricsConsumerMetaTable; import co.cask.cdap.proto.id.DatasetId; import co.cask.cdap.proto.id.NamespaceId; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableMap; import com.google.gson.Gson; import com.google.inject.Inject; /** * Default implementation of {@link MetricDatasetFactory}, which uses {@link DatasetFramework} for acquiring * {@link MetricsTable} instances. */ public class DefaultMetricDatasetFactory implements MetricDatasetFactory { private static final Gson GSON = new Gson(); private final CConfiguration cConf; private final Supplier<EntityTable> entityTable; private final DatasetFramework dsFramework; @Inject public DefaultMetricDatasetFactory(final CConfiguration cConf, DatasetFramework dsFramework) { this.cConf = cConf; this.dsFramework = dsFramework; this.entityTable = Suppliers.memoize(new Supplier<EntityTable>() { @Override public EntityTable get() { String tableName = cConf.get(Constants.Metrics.ENTITY_TABLE_NAME, Constants.Metrics.DEFAULT_ENTITY_TABLE_NAME); return new EntityTable(getOrCreateMetricsTable(tableName, DatasetProperties.EMPTY)); } }); } // todo: figure out roll time based on resolution from config? See DefaultMetricsTableFactory for example @Override public FactTable getOrCreateFactTable(int resolution) { String v3TableName = cConf.get(Constants.Metrics.METRICS_TABLE_PREFIX, Constants.Metrics.DEFAULT_METRIC_V3_TABLE_PREFIX) + ".ts." + resolution; TableProperties.Builder props = TableProperties.builder(); // don't add TTL for MAX_RESOLUTION table. CDAP-1626 if (resolution != Integer.MAX_VALUE) { int ttl = cConf.getInt(Constants.Metrics.RETENTION_SECONDS + resolution + Constants.Metrics.RETENTION_SECONDS_SUFFIX); if (ttl > 0) { props.setTTL(ttl); } } // for efficient counters props.setReadlessIncrementSupport(true); // configuring pre-splits props.add(HBaseTableAdmin.PROPERTY_SPLITS, GSON.toJson(FactTable.getSplits(DefaultMetricStore.AGGREGATIONS.size()))); // Disable auto split props.add(HBaseTableAdmin.SPLIT_POLICY, cConf.get(Constants.Metrics.METRICS_TABLE_HBASE_SPLIT_POLICY)); MetricsTable table = getOrCreateResolutionMetricsTable(v3TableName, props, resolution); return new FactTable(table, entityTable.get(), resolution, getRollTime(resolution)); } @Override public MetricsConsumerMetaTable createConsumerMeta() { String tableName = cConf.get(Constants.Metrics.KAFKA_META_TABLE); MetricsTable table = getOrCreateMetricsTable(tableName, DatasetProperties.EMPTY); return new MetricsConsumerMetaTable(table); } protected MetricsTable getOrCreateMetricsTable(String tableName, DatasetProperties props) { // metrics tables are in the system namespace DatasetId metricsDatasetInstanceId = NamespaceId.SYSTEM.dataset(tableName); MetricsTable table = null; try { table = DatasetsUtil.getOrCreateDataset(dsFramework, metricsDatasetInstanceId, MetricsTable.class.getName(), props, null); } catch (Exception e) { Throwables.propagate(e); } return table; } protected MetricsTable getOrCreateResolutionMetricsTable(String v3TableName, TableProperties.Builder props, int resolution) { try { String v2TableName = cConf.get(Constants.Metrics.METRICS_TABLE_PREFIX, Constants.Metrics.DEFAULT_METRIC_TABLE_PREFIX + ".ts." + resolution); // metrics tables are in the system namespace DatasetId v2TableId = NamespaceId.SYSTEM.dataset(v2TableName); MetricsTable v2Table = dsFramework.getDataset(v2TableId, ImmutableMap.of(), null); props.add(HBaseTableAdmin.PROPERTY_SPLITS, GSON.toJson(getV3MetricsTableSplits(cConf.getInt(Constants.Metrics.METRICS_HBASE_TABLE_SPLITS)))); props.add(Constants.Metrics.METRICS_HBASE_TABLE_SPLITS, cConf.getInt(Constants.Metrics.METRICS_HBASE_TABLE_SPLITS)); DatasetId v3TableId = NamespaceId.SYSTEM.dataset(v3TableName); MetricsTable v3Table = DatasetsUtil.getOrCreateDataset(dsFramework, v3TableId, MetricsTable.class.getName(), props.build(), null); if (v2Table != null) { // the cluster is upgraded, so use Combined Metrics Table return new CombinedHBaseMetricsTable(v2Table, v3Table, resolution, cConf, dsFramework); } return v3Table; } catch (Exception e) { throw Throwables.propagate(e); } } private static byte[][] getV3MetricsTableSplits(int splits) { RowKeyDistributorByHashPrefix rowKeyDistributor = new RowKeyDistributorByHashPrefix( new RowKeyDistributorByHashPrefix.OneByteSimpleHash(splits)); return rowKeyDistributor.getSplitKeys(splits, splits); } /** * Creates the metrics tables and kafka-meta table using the factory {@link DefaultMetricDatasetFactory} * <p> * It is primarily used by upgrade and data-migration tool. * * @param factory : metrics dataset factory */ public static void setupDatasets(DefaultMetricDatasetFactory factory) { // adding all fact tables factory.getOrCreateFactTable(Constants.Metrics.SECOND_RESOLUTION); factory.getOrCreateFactTable(Constants.Metrics.MINUTE_RESOLUTION); factory.getOrCreateFactTable(Constants.Metrics.HOUR_RESOLUTION); factory.getOrCreateFactTable(Integer.MAX_VALUE); // adding kafka consumer meta factory.createConsumerMeta(); } private int getRollTime(int resolution) { String key = Constants.Metrics.TIME_SERIES_TABLE_ROLL_TIME + "." + resolution; String value = cConf.get(key); if (value != null) { return cConf.getInt(key, Constants.Metrics.DEFAULT_TIME_SERIES_TABLE_ROLL_TIME); } return cConf.getInt(Constants.Metrics.TIME_SERIES_TABLE_ROLL_TIME, Constants.Metrics.DEFAULT_TIME_SERIES_TABLE_ROLL_TIME); } }
redherd-project/redherd-framework
herd-server/models/rdhd-mdl-module_gateway.js
'use strict'; const fs = require('fs'); const path = require('path'); class ModuleGateway { constructor(repo) { this.repo = repo; } // Specialized decorator findByName(name) { let current = false; fs.readdirSync(this.repo).forEach(f => { if (path.extname(f).toUpperCase() == ".INFO") { let jdata = JSON.parse(fs.readFileSync(path.join(this.repo, f))); if (jdata.name.toUpperCase() == name.toUpperCase()) { current = jdata; } } }); return current; } // Specialized decorator findByTopic(topic) { let modules = []; fs.readdirSync(this.repo).forEach(f => { if (path.extname(f).toUpperCase() == ".INFO") { let current = JSON.parse(fs.readFileSync(path.join(this.repo, f))); if (current.topic.toUpperCase() == topic.toUpperCase()) { modules.push(current); } } }); return modules; } // Specialized decorator findAll() { let modules = []; fs.readdirSync(this.repo).forEach(f => { if (path.extname(f).toUpperCase() == ".INFO") { modules.push(JSON.parse(fs.readFileSync(path.join(this.repo, f)))); } }); return modules; } } module.exports = ModuleGateway;
fox91/himan
himan-plugins/source/auxiliary_plugin.cpp
/* * auxiliary_plugin.cpp * */ #include "auxiliary_plugin.h"
DaftMat/Draft-Engine
src/Engine/Geometry/Primitives/ParticleSystem/Particle.hpp
<reponame>DaftMat/Draft-Engine /** * Created by mathis on 06/05/2020. */ #ifndef DAFT_ENGINE_PARTICLE_HPP #define DAFT_ENGINE_PARTICLE_HPP #include <src/Engine/Geometry/MeshObject.hpp> #include <src/Engine/Cameras/camera.h> /** class for particles. * billboard. */ class Particle : public MeshObject { public: Particle(const glm::vec3 &position, const glm::vec3 &speed, float size, float gravity, const glm::mat4 &view) : m_position { position }, m_speed { speed }, m_size { size }, m_gravity {gravity} { buildMesh(view); } glm::mat4 model() const override { return glm::translate(glm::mat4(1.f), m_position); } void update(float dt) override; void draw(const Shader &shader) override; float getSetting() const override { return m_lifetime; } private: void buildMesh(const glm::mat4 &view); glm::vec3 m_position; glm::vec3 m_speed; float m_size; float m_gravity; float m_lifetime { 0.f }; ///< current lifetime }; #endif //DAFT_ENGINE_PARTICLE_HPP
windows-development/Windows-classic-samples
Samples/Win7Samples/dataaccess/oledb/tablecopy/property.h
//----------------------------------------------------------------------------- // Microsoft OLE DB TABLECOPY Sample // Copyright (C) 1991-2000 Microsoft Corporation // // @doc // // @module PROPERTY.H // //----------------------------------------------------------------------------- #ifndef _PROPERTY_H_ #define _PROPERTY_H_ /////////////////////////////////////////////////////////////// // Includes // /////////////////////////////////////////////////////////////// #include "common.h" //////////////////////////////////////////////////////////////////////////// // Properties // //////////////////////////////////////////////////////////////////////////// //Property Info HRESULT GetPropInfo(IUnknown* pIUnknown, DBPROPID PropertyID, GUID guidPropertySet, DBPROPINFO** ppPropInfo); DBPROPFLAGS GetPropInfoFlags(IUnknown* pIUnknown, DBPROPID PropertyID, GUID guidPropertySet); //Property Flags BOOL IsSupportedProperty(IUnknown* pIUnknown, DBPROPID PropertyID, GUID guidPropertySet); BOOL IsSettableProperty(IUnknown* pIUnknown, DBPROPID PropertyID, GUID guidPropertySet); //Get Property HRESULT GetProperty(IUnknown* pIUnknown, DBPROPID PropertyID, GUID guidPropertySet, WCHAR** ppwszValue); HRESULT GetProperty(IUnknown* pIUnknown, DBPROPID PropertyID, GUID guidPropertySet, DBPROP** ppProperty); HRESULT GetProperty(IUnknown* pIUnknown, DBPROPID PropertyID, GUID guidPropertySet, WCHAR* pwszValue); HRESULT GetProperty(IUnknown* pIUnknown, DBPROPID PropertyID, GUID guidPropertySet, ULONG* pcValue); HRESULT GetProperty(IUnknown* pIUnknown, DBPROPID PropertyID, GUID guidPropertySet, BOOL* pbValue); //Set Property HRESULT SetProperty(DBPROPID PropertyID, GUID guidPropertySet, ULONG* pcPropSets, DBPROPSET** prgPropSets, DBTYPE wType, ULONG_PTR ulValue, DBPROPOPTIONS dwOptions = DBPROPOPTIONS_REQUIRED, DBID colid = DB_NULLID); HRESULT SetProperty(DBPROPID PropertyID, GUID guidPropertySet, ULONG* pcPropSets, DBPROPSET** prgPropSets, DBTYPE wType, void* pv, DBPROPOPTIONS dwOptions = DBPROPOPTIONS_REQUIRED, DBID colid = DB_NULLID); //Free Property HRESULT FreeProperties(ULONG cPropSets, DBPROPSET* rgPropSets); HRESULT FreeProperties(ULONG cProperties, DBPROP* rgProperties); //Variants HRESULT InitVariants(ULONG cVariants, VARIANT* rgVariants); HRESULT FreeVariants(ULONG cVariants, VARIANT* rgVariants); //Restrictions HRESULT SetRestriction(VARIANT* pRestriction, WCHAR* pwszValue); #endif //_PROPERTY_H_
aliostad/deep-learning-lang-detection
data/train/go/5c9bdd2d5fd87b2f7b443a78bd36cbbe01eb647edispatch.go
package resp import ( "bytes" "fmt" "reflect" "strings" ) // Dispatch provides case-insensitivity support type dispatch struct { recv interface{} recvValue reflect.Value commands map[string]*reflect.Method } func normalizeMethodName(name string) string { return strings.ToLower(name) } // newDispatch creates a dispatcher against an interface func newDispatch(receiver interface{}) (d *dispatch, err error) { d = new(dispatch) d.recv = receiver d.recvValue = reflect.ValueOf(d.recv) d.commands = make(map[string]*reflect.Method) rval := reflect.TypeOf(receiver) for i := 0; i < rval.NumMethod(); i++ { method := rval.Method(i) d.commands[normalizeMethodName(method.Name)] = &method err = validateMethod(&method) if err != nil { return } } return } // Ensure the specified method takes and returns types compatible with RESP func validateMethod(method *reflect.Method) (err error) { // ... return } // Call parses and executes the function call against the receiver. func (d *dispatch) Call(line string) (res string, err error) { var methodName string methodName, line, err = nextToken(line) method, ok := d.commands[normalizeMethodName(methodName)] if !ok { err = fmt.Errorf("Unknown command %q", methodName) return } fn := method.Func ins := make([]reflect.Value, method.Type.NumIn()) for i := range ins { t := method.Type.In(i) if i == 0 { ins[i] = d.recvValue continue } line, ins[i], err = parse(t.Kind(), line) if err != nil { return } } var bb bytes.Buffer outs := fn.Call(ins) // Methods which return null if len(outs) == 0 { _, err = writeOk(&bb) res = bb.String() return } for i := range outs { o := outs[i] _, err = write(&bb, method.Type.Out(i).Kind(), o) if err != nil { return } } res = bb.String() return }
brayanmf/top-v13
projects/sequelize-mysql/server.js
const express = require("express"); const { sync, createProduct, getAllProjects, deleteProject, updateProject, } = require("./modules/api"); const app = express(); // GET app.get("/products", async (req, res) => { await sync(); const projects = await getAllProjects(); res.json(projects); }); // POST app.post("/product/create", async (req, res) => { await sync(); const result = await createProduct({ idProject: 1, name: "<NAME>", description: "This is a test project", }); res.json(result); }); // DELETE app.delete("/product/delete/:id", async (req, res) => { const { id } = req.params; const result = await deleteProject(Number(id)); res.json(result); }); // UPDATE app.put("/product/update/:id", async (req, res) => { const { id } = req.params; const obj = { name: "<NAME>" }; const result = await updateProject(id, obj); res.json(result); }); app.listen(4001, () => { console.log("Server mysql api ok!"); });
lachrist/candlekeep
global/Array/prototype/pop.js
<gh_stars>1-10 Array.prototype.pop = function () { var last = this[this.length-1]; this.length = this.length-1; return last; }
fszgmbh/primereact
src/__tests__/components/Button.test.js
import React from 'react'; import { render } from '@testing-library/react'; import { Button } from '../../components/button/Button'; describe('Button Component', () => { test('should display the Button', () => { const { container } = render(<Button />); const buttonElement = container.firstChild; expect(container).toBeInTheDocument(); expect(buttonElement).toBeInTheDocument(); expect(buttonElement).toHaveClass('p-button'); }); test('should display the label', () => { const { container } = render(<Button label="PrimeReact" />); const labelElement = container.querySelector('.p-button-label'); expect(labelElement).toBeInTheDocument(); expect(labelElement.textContent).toContain('PrimeReact'); expect(labelElement).toHaveClass('p-c'); }); test('should be disabled', () => { const { container } = render(<Button disabled />); const buttonElement = container.firstChild; expect(buttonElement).toBeInTheDocument(); expect(buttonElement).toHaveClass('p-disabled'); expect(buttonElement).toHaveProperty('disabled'); }); });
ty-porter/hyde
hyde/token.py
from enum import Enum, auto, unique @unique class TokenType(Enum): # Single-character tokens LEFT_PAREN = auto() RIGHT_PAREN = auto() LEFT_BRACE = auto() RIGHT_BRACE = auto() COMMA = auto() DOT = auto() MINUS = auto() PLUS = auto() SEMICOLON = auto() SLASH = auto() STAR = auto() POUND = auto() # One or two character tokens BANG = auto() BANG_EQUAL = auto() EQUAL = auto() EQUAL_EQUAL = auto() GREATER = auto() GREATER_EQUAL = auto() LESS = auto() LESS_EQUAL = auto() # Literals IDENTIFIER = auto() STRING = auto() NUMBER = auto() # Keywords AND = auto() CLASS = auto() ELSE = auto() FALSE = auto() FUN = auto() FOR = auto() IF = auto() LOAD = auto() NONE = auto() OR = auto() PRINT = auto() RETURN = auto() SUPER = auto() THIS = auto() TRUE = auto() VAR = auto() WHILE = auto() # EOF EOF = auto() class Token: def __init__(self, token_type, lexeme, literal, line): self.type = token_type self.lexeme = lexeme self.literal = literal self.line = line def __str__(self): return f'{self.type.name} {self.lexeme} {self.literal}'
Taig/schelm
core/src/main/scala/io/taig/schelm/Children.scala
<filename>core/src/main/scala/io/taig/schelm/Children.scala<gh_stars>1-10 package io.taig.schelm import cats._ import cats.implicits._ import scala.collection.immutable.ListMap sealed abstract class Children[A] extends Product with Serializable { final def isEmpty: Boolean = this match { case Children.Indexed(values) => values.isEmpty case Children.Identified(values) => values.isEmpty } final def length: Int = this match { case Children.Indexed(values) => values.length case Children.Identified(values) => values.size } def ++(children: Children[A]): Children[A] = (this, children) match { case (Children.Indexed(x), Children.Indexed(y)) => Children.Indexed(x ++ y) case (Children.Identified(x), Children.Identified(y)) => Children.Identified(x ++ y) case (Children.Indexed(x), Children.Identified(y)) => Children.Identified(ListMap(x.zipWithIndex.map { case (value, index) => (String.valueOf(index), value) }: _*) ++ y) case (Children.Identified(x), Children.Indexed(y)) => Children.Identified(x ++ ListMap(y.zipWithIndex.map { case (value, index) => (String.valueOf(index), value) }: _*)) } def indexOf(key: Key): Option[Int] = (key, this) match { case (Key.Index(index), _) => index.some case (Key.Identifier(identifier), Children.Identified(values)) => values.keysIterator.indexOf(identifier).some case (Key.Identifier(_), Children.Indexed(_)) => None } def map[B](f: (Key, A) => B): Children[B] = this match { case Children.Indexed(values) => Children.indexed(values.zipWithIndex.map { case (value, index) => f(Key.Index(index), value) }) case Children.Identified(values) => Children.identified(values.map { case (key, value) => (key, f(Key.Identifier(key), value)) }) } def collect[B](f: PartialFunction[(Key, A), B]): Children[B] = this match { case Children.Indexed(values) => Children.indexed(values.zipWithIndex.mapFilter { case (value, index) => f.lift((Key.Index(index), value)) }) case Children.Identified(values) => Children.identified(values.toList.mapFilter { case (key, value) => f.lift((Key.Identifier(key), value)).tupleLeft(key) }) } def append(key: Key, value: A): Children[A] = (key, this) match { case (_, Children.Indexed(values)) => Children.Indexed(values :+ value) case (Key.Identifier(identifier), Children.Identified(values)) => Children.Identified(values.updated(identifier, value)) case _ => this } def updated(key: Key, value: A): Children[A] = (key, this) match { case (Key.Index(index), Children.Indexed(values)) => try Children.Indexed(values.updated(index, value)) catch { case _: IndexOutOfBoundsException => this } case (Key.Identifier(identifier), Children.Identified(values)) => Children.Identified(values.updated(identifier, value)) case _ => this } def remove(key: Key): Children[A] = (key, this) match { case (Key.Index(index), Children.Indexed(values)) => Children.Indexed(values.patch(index, Nil, 1)) case (Key.Identifier(identifier), Children.Identified(values)) => Children.Identified(values - identifier) case _ => this } def foldLeft[B](initial: B)(f: (B, Key, A) => B): B = toList.foldLeft(initial) { case (result, (key, value)) => f(result, key, value) } def traverse[G[_]: Applicative, B](f: (Key, A) => G[B]): G[Children[B]] = this match { case Children.Indexed(values) => values.zipWithIndex .traverse { case (value, index) => f(Key.Index(index), value) } .map(Children.indexed) case Children.Identified(values) => values.toList .traverse { case (key, value) => f(Key.Identifier(key), value).tupleLeft(key) } .map(Children.identified) } def traverse_[G[_]: Applicative, B](f: (Key, A) => G[B]): G[Unit] = this match { case Children.Indexed(values) => values.zipWithIndex.traverse_ { case (value, index) => f(Key.Index(index), value) } case Children.Identified(values) => values.toList.traverse_ { case (key, value) => f(Key.Identifier(key), value).tupleLeft(key) } } def flatTraverse[G[_]: Applicative, B]( f: (Key, A) => G[List[B]] ): G[List[B]] = toList.flatTraverse { case (key, child) => f(key, child) } def get(key: Key): Option[A] = (key, this) match { case (Key.Index(index), Children.Indexed(values)) => values.lift(index) case (Key.Identifier(identifier), Children.Identified(values)) => values.get(identifier) case _ => None } def toList: List[(Key, A)] = this match { case Children.Indexed(values) => values.zipWithIndex.map { case (value, index) => Key.Index(index) -> value } case Children.Identified(values) => values.toList.map { case (identifier, value) => Key.Identifier(identifier) -> value } } def keys: List[Key] = this match { case Children.Indexed(values) => values.zipWithIndex.map { case (_, index) => Key.Index(index) } case Children.Identified(values) => values.keys.toList.map(Key.Identifier) } def values: List[A] = this match { case Children.Indexed(values) => values case Children.Identified(values) => values.values.toList } } object Children { final case class Indexed[A](raw: List[A]) extends Children[A] final case class Identified[A](raw: ListMap[String, A]) extends Children[A] def empty[A]: Children[A] = Indexed(List.empty) def of[A](children: A*): Children[A] = indexed(children) def indexed[A](children: Iterable[A]): Children[A] = Indexed(children.toList) def identified[A](children: Iterable[(String, A)]): Children[A] = Identified(ListMap(children.toSeq: _*)) }
Songpon74250/CodeTester-IDEA
CodeTester-IntelliJ-IDEA/src/main/java/de/fxnm/web/grabber/access_token/LoginTokenGrabber.java
<reponame>Songpon74250/CodeTester-IDEA<filename>CodeTester-IntelliJ-IDEA/src/main/java/de/fxnm/web/grabber/access_token/LoginTokenGrabber.java package de.fxnm.web.grabber.access_token; import com.google.gson.Gson; import com.intellij.openapi.project.Project; import org.jetbrains.annotations.NotNull; import okhttp3.FormBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import okhttp3.ResponseBody; import java.io.IOException; import java.net.HttpURLConnection; import de.fxnm.exceptions.InternetConnectionException; import de.fxnm.web.components.token.LoginToken; import de.fxnm.web.grabber.CommonUrl; public final class LoginTokenGrabber { private LoginTokenGrabber() throws IllegalAccessException { throw new IllegalAccessException(); } public static LoginToken getToken(final Project project, @NotNull final String username, @NotNull final String password) throws IOException, InternetConnectionException { final OkHttpClient httpClient = new OkHttpClient(); final RequestBody formBody = new FormBody.Builder() .add("username", username) .add("password", password) .build(); final Request request = new Request.Builder() .url(CommonUrl.LOGIN.getUrl(project)) .post(formBody) .build(); final Response response = httpClient.newCall(request).execute(); final int responseCode = response.code(); if (responseCode != HttpURLConnection.HTTP_OK) { response.close(); throw new InternetConnectionException("Invalid response code:" + response.code()); } final ResponseBody responseBody = response.body(); if (responseBody == null) { response.close(); throw new InternetConnectionException("null response body"); } final String responseBodyAsString = responseBody.string(); response.close(); return new Gson().fromJson(responseBodyAsString, LoginToken.class); } }
Bing1012/3
src/pyscaffold/identification.py
"""Internal library for manipulating, creating and dealing with names, or more generally identifiers. """ import keyword import re from typing import Callable, Iterable, List, TypeVar from .exceptions import InvalidIdentifier T = TypeVar("T") def is_valid_identifier(string: str) -> bool: """Check if string is a valid package name Args: string: package name Returns: True if string is valid package name else False """ if not re.match("[_A-Za-z][_a-zA-Z0-9]*$", string): return False if keyword.iskeyword(string): return False return True def make_valid_identifier(string: str) -> str: """Try to make a valid package name identifier from a string Args: string: invalid package name Returns: Valid package name as string or :obj:`RuntimeError` Raises: :obj:`InvalidIdentifier`: raised if identifier can not be converted """ string = str(string).strip() string = string.replace("-", "_") string = string.replace(" ", "_") string = re.sub("[^_a-zA-Z0-9]", "", string) string = string.lower() if is_valid_identifier(string): return string raise InvalidIdentifier("String cannot be converted to a valid identifier.") # from https://en.wikibooks.org/, Creative Commons Attribution-ShareAlike 3.0 def levenshtein(s1: str, s2: str) -> int: """Calculate the Levenshtein distance between two strings Args: s1: first string s2: second string Returns: Distance between s1 and s2 """ if len(s1) < len(s2): return levenshtein(s2, s1) # len(s1) >= len(s2) if len(s2) == 0: return len(s1) previous_row = list(range(len(s2) + 1)) for i, c1 in enumerate(s1): current_row = [i + 1] for j, c2 in enumerate(s2): insertions = previous_row[j + 1] + 1 deletions = current_row[j] + 1 substitutions = previous_row[j] + (c1 != c2) current_row.append(min(insertions, deletions, substitutions)) previous_row = current_row return previous_row[-1] def dasherize(word: str) -> str: """Replace underscores with dashes in the string. Example:: >>> dasherize("foo_bar") "foo-bar" Args: word (str): input word Returns: input word with underscores replaced by dashes """ return word.replace("_", "-") CAMEL_CASE_SPLITTER = re.compile(r"\W+|([A-Z][^A-Z\W]*)") def underscore(word: str) -> str: """Convert CamelCasedStrings or dasherized-strings into underscore_strings. Example:: >>> underscore("FooBar-foo") "foo_bar_foo" """ return "_".join(w for w in CAMEL_CASE_SPLITTER.split(word) if w).lower() def deterministic_name(obj): """Private API that returns an string that can be used to deterministically deduplicate and sort sequences of objects. """ mod_name = getattr(obj, "__module__", "..") qual_name = getattr(obj, "__qualname__", obj.__class__.__qualname__) return f"{mod_name}.{qual_name}" def deterministic_sort(sequence: Iterable[T]) -> List[T]: """Private API that order a sequence of objects lexicographically (by :obj:`deterministic_name`), removing duplicates, which is needed for determinism. The main purpose of this function is to deterministically sort a sequence of PyScaffold extensions (it will also sort internal extensions before external: "pyscaffold.*" < "pyscaffoldext.*"). """ deduplicated = {deterministic_name(x): x for x in sequence} # ^ duplicated keys will overwrite each other, so just one of them is left return [v for (_k, v) in sorted(deduplicated.items())] def get_id(function: Callable) -> str: """Given a function, calculate its identifier. A identifier is a string in the format ``<module name>:<function name>``, similarly to the convention used for setuptools entry points. Note: This function does not return a Python 3 ``__qualname__`` equivalent. If the function is nested inside another function or class, the parent name is ignored. Args: function (callable): function object """ return f"{function.__module__}:{function.__name__}"
fniederl/dswarm
persistence/src/test/java/org/dswarm/persistence/service/job/test/FilterServiceTest.java
/** * Copyright (C) 2013 – 2016 SLUB Dresden & Avantgarde Labs GmbH (<<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 org.dswarm.persistence.service.job.test; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.dswarm.persistence.model.job.Filter; import org.dswarm.persistence.model.job.proxy.ProxyFilter; import org.dswarm.persistence.service.job.FilterService; import org.dswarm.persistence.service.job.test.utils.FilterServiceTestUtils; import org.dswarm.persistence.service.test.BasicJPAServiceTest; public class FilterServiceTest extends BasicJPAServiceTest<ProxyFilter, Filter, FilterService> { private static final Logger LOG = LoggerFactory.getLogger(FilterServiceTest.class); private FilterServiceTestUtils filterServiceTestUtils; public FilterServiceTest() { super("filter", FilterService.class); } @Override protected void initObjects() { super.initObjects(); filterServiceTestUtils = new FilterServiceTestUtils(); } @Test @Override public void testSimpleObject() throws Exception { final Filter filter = filterServiceTestUtils.createAndPersistDefaultObject(); final Filter updatedFilter = filterServiceTestUtils.updateAndCompareObject(filter, filter); logObjectJSON(updatedFilter); } }
Amber-Williams/smartwaiter-server
api/controllers/subscriptions/actions.js
const { pubsub } = require('../../subscriptions'); // import pubsub object for subscriptions to work const emit = (channel, options) => { switch (channel) { case 'onCustomerOrder': return pubsub.publish('onCustomerOrder', { onCustomerOrder: options, }); case 'onCustomerConnection': return pubsub.publish('onCustomerConnection', { onCustomerConnection: options, }); case 'onProductOrderChanged': console.log('channel!', channel); console.log(options); return pubsub.publish('onProductOrderChanged', { onProductOrderChanged: options, }); case 'onCustomerCallsWaiter': return pubsub.publish('onCustomerCallsWaiter', { onCustomerCallsWaiter: options, }); default: } }; module.exports = { emit, };
taydy/go-leetcode
easy/9.go
<gh_stars>1-10 package easy // https://leetcode-cn.com/problems/palindrome-number/ // 判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。 // // 示例 1: // 输入: 121 // 输出: true // // 示例 2: // 输入: -121 // 输出: false // 解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。 // // 示例 3: // 输入: 10 // 输出: false // 解释: 从右向左读, 为 01 。因此它不是一个回文数。 // // 思路: // 1. 负数和个数数字为零的整数(0 除外)明显不是回文数; // 2. 将整数的后半段翻转后如果和前半段相等(长度为偶数的情况下),或者后半段翻转后去掉个位数字和前半段相等(长度为奇数的情况下),则表明是回文数 // // 执行用时 : 32 ms, 在Palindrome Number的Go提交中击败了97.94% 的用户 // 内存消耗 : 5.1 MB, 在Palindrome Number的Go提交中击败了66.21% 的用户 func IsPalindrome(x int) bool { // 0 是回文数 if x == 0 { return true } // 负数和个数数字为零的整数(0 除外)明显不是回文数 if x < 0 || x%10 == 0 { return false } revertedNumber := 0 // 依次翻转后半段 for revertedNumber < x { revertedNumber = revertedNumber*10 + x%10 x = x / 10 } // 后半段翻转后与前半段相等或者后半段翻转后的数字去掉个位和前半段相等,说明是回文数 return x == revertedNumber || x == revertedNumber/10 }
uit-plus/vspehere-jdk
src/main/java/com/vmware/vim25/ArrayOfOvfResourceMap.java
<filename>src/main/java/com/vmware/vim25/ArrayOfOvfResourceMap.java package com.vmware.vim25; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for ArrayOfOvfResourceMap complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="ArrayOfOvfResourceMap"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="OvfResourceMap" type="{urn:vim25}OvfResourceMap" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ArrayOfOvfResourceMap", propOrder = { "ovfResourceMap" }) public class ArrayOfOvfResourceMap { @XmlElement(name = "OvfResourceMap") protected List<OvfResourceMap> ovfResourceMap; /** * Gets the value of the ovfResourceMap property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the ovfResourceMap property. * * <p> * For example, to add a new item, do as follows: * <pre> * getOvfResourceMap().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link OvfResourceMap } * * */ public List<OvfResourceMap> getOvfResourceMap() { if (ovfResourceMap == null) { ovfResourceMap = new ArrayList<OvfResourceMap>(); } return this.ovfResourceMap; } }
PraneethReddy-sc20prc/gralog
gralog-np-completeness/src/main/java/gralog/npcompleteness/algorithm/Clique.java
<gh_stars>10-100 /* This file is part of Gralog, Copyright (c) 2016-2018 LaS group, TU Berlin. * License: https://www.gnu.org/licenses/gpl.html GPL version 3 or later. */ package gralog.npcompleteness.algorithm; import gralog.structure.*; import gralog.algorithm.*; import gralog.progresshandler.ProgressHandler; import java.util.Set; import java.util.HashSet; /** * */ @AlgorithmDescription( name = "Maximum Clique", text = "Finds a maximum Clique", url = "https://en.wikipedia.org/wiki/Clique_problem") public class Clique extends Algorithm { static boolean findClique(UndirectedGraph s, int k, Set<Vertex> clique, Set<Vertex> candidates) { if (k < 1) return true; if (candidates.isEmpty()) return false; for (Vertex candidate : candidates) { if (clique.contains(candidate)) continue; Set<Vertex> nextCandidates = new HashSet<>(); for (Edge e : candidate.getIncidentEdges()) { // candidates ∩ N[candidate] if (candidates.contains(e.getSource())) nextCandidates.add(e.getSource()); if (candidates.contains(e.getTarget())) nextCandidates.add(e.getTarget()); } clique.add(candidate); if (findClique(s, k - 1, clique, nextCandidates)) return true; clique.remove(candidate); } return false; } public static Set<Vertex> findMaximumClique(UndirectedGraph s) { Set<Vertex> result = new HashSet<>(); for (int k = 1;; k++) { Set<Vertex> V = new HashSet<>(); for (Vertex v : s.getVertices()) V.add(v); Set<Vertex> clique = new HashSet<>(); if (!findClique(s, k, clique, V)) break; result.clear(); result.addAll(clique); } return result; } public Object run(UndirectedGraph s, AlgorithmParameters p, Set<Object> selection, ProgressHandler onprogress) throws Exception { return findMaximumClique(s); } }
kazuya-ddt/Fotoapparat-1.4.1-edit
fotoapparat/src/main/java/io/fotoapparat/lens/CaptureResultState.java
<filename>fotoapparat/src/main/java/io/fotoapparat/lens/CaptureResultState.java package io.fotoapparat.lens; /** * The result of an attempt to capture a photo. */ public enum CaptureResultState { /** * The camera failed to capture a photo. */ FAILURE, /** * The camera succeeded to capture a photo. */ SUCCESS }
henryxm/autumn
autumn-lib/src/main/java/cn/org/autumn/site/Factory.java
package cn.org.autumn.site; import cn.org.autumn.utils.SpringContextUtils; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.core.annotation.Order; import java.lang.reflect.Method; import java.util.*; public class Factory { private static final Logger log = LoggerFactory.getLogger(Factory.class); /** * 排序缺省值 */ public static final int DEFAULT_ORDER = Integer.MAX_VALUE / 1000; /** * 查找所有实现了T类型的接口的Bean,并对Bean方法注解中指定的方法上的的Order进行排序 * <p> * 根据从小到大的顺序执行Bean方法,达到根据排序进行先后有序执行的效果。 * * @param t Bean Class * @param name 方法名 * @param <T> Bean Class * @return ordered Beans */ public static <T> Map<Integer, List<T>> getOrdered(Class<T> t, String name, Class<?>... parameterTypes) { ApplicationContext applicationContext = SpringContextUtils.getApplicationContext(); if (null == applicationContext) return null; Map<String, T> map = applicationContext.getBeansOfType(t); Map<Integer, List<T>> ordered = new TreeMap<>(new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { if (o1 == Integer.MIN_VALUE) return -1; return o1 - o2; } }); for (Map.Entry<String, T> k : map.entrySet()) { T init = k.getValue(); Method method = null; Order order = null; //获取实例中的排序Order,如果没找到,你从超类中寻找 try { Class<?> clazz = init.getClass(); while (null != clazz && null == order && !clazz.equals(Object.class)) { if (StringUtils.isNotBlank(name)) { method = clazz.getMethod(name, parameterTypes); order = method.getAnnotation(Order.class); } if (null == order) { order = clazz.getAnnotation(Order.class); } clazz = clazz.getSuperclass(); } } catch (Exception e) { if (log.isDebugEnabled()) log.debug("getOrdered", e); } //如果从实例中没有找到Order,则寻找接口中的Order if (null == order) { try { if (StringUtils.isNotBlank(name)) { method = t.getMethod(name, parameterTypes); order = method.getAnnotation(Order.class); } if (null == order) order = t.getAnnotation(Order.class); } catch (Exception e) { if (log.isDebugEnabled()) log.debug("getOrdered", e); } } List<T> list = null; int value = Integer.MAX_VALUE / 100; if (null != order) { list = ordered.get(order.value()); value = order.value(); } else { list = ordered.get(value); } if (null == list) { list = new ArrayList<>(); ordered.put(value, list); } list.add(init); } return ordered; } /** * 调用所有实现了接口T的Bean的方法 * 有小到大的顺序执行 * * @param t Bean Class * @param name 方法名 * @param <T> Bean Class */ public <T> void invoke(Class<T> t, String name) { Map<Integer, List<T>> ordered = getOrdered(t, name); if (null == ordered || ordered.size() == 0) return; for (Map.Entry<Integer, List<T>> entry : ordered.entrySet()) { List<T> list = entry.getValue(); for (T obj : list) { try { Method m = obj.getClass().getMethod(name); m.invoke(obj); } catch (Exception e) { log.error(obj.getClass().getSimpleName() + "." + name, e); } } } } public <T> List<T> getOrderList(Class<T> t) { return getOrderList(t, null); } public <T> List<T> getOrderList(Class<T> t, String name, Class<?>... parameterTypes) { List<T> tmp = new ArrayList<>(); Map<Integer, List<T>> ordered = getOrdered(t, name, parameterTypes); if (null != ordered && ordered.size() > 0) { for (Map.Entry<Integer, List<T>> entry : ordered.entrySet()) { List<T> list = entry.getValue(); tmp.addAll(list); } } return tmp; } }
SimonAlong/Neo
src/main/java/com/simonalong/neo/tenant/TenantContextHolder.java
<reponame>SimonAlong/Neo<gh_stars>10-100 package com.simonalong.neo.tenant; import com.alibaba.ttl.TransmittableThreadLocal; import lombok.experimental.UtilityClass; /** * @author shizi * @since 2021-05-06 14:09:40 */ @UtilityClass public class TenantContextHolder { private final TransmittableThreadLocal<String> context = new TransmittableThreadLocal<>(); public void setTenantId(String tenantId) { context.set(tenantId); } public String getTenantId() { return context.get(); } }
IceCubeOpenSource/USSR
python/asteria/matter.py
# -*- coding: utf-8 -*- """Module for Earth and stellar density models. """ import numpy as np from astropy import units as u from abc import ABC, abstractmethod class Body(ABC): """Base class defining the interface for matter interactions.""" def __init__(self): pass @abstractmethod def density(self, r): """Return density as a function of distance from the core.""" pass @abstractmethod def y_e(self, r): """Return electron fraction as a function of distance from the core.""" pass class PREM(Body): """Preliminary Reference Earth Model: <NAME> and <NAME>, PEPI 25:297-356, 1981. """ def __init__(self): # Radial bin edges, in units of km. self._rbins = np.asarray( [ 0.0, 1221.5, 3480.0, 3630.0, 5701.0, 5771.0, 5971.0, 6151.0, 6346.6, 6356.0, 6368.0, 6371.0]) # Density coefficients in units of kg/m3, kg/m4, kg/m5. self._dcoef = np.asarray( [[1.3088e4, 1.9110e-8, -2.1773e-10], [1.2346e4, 1.3976e-4, -2.4123e-10], [7.3067e3, -5.0007e-4, 0.0000], [6.7823e3, -2.4441e-4, -3.0922e-11], [5.3197e3, -2.3286e-4, 0.0000], [1.1249e4, -1.2603e-3, 0.0000], [7.1083e3, -5.9706e-4, 0.0000], [2.6910e3, 1.0869e-4, 0.0000], [2.9000e3, 0.0000, 0.0000], [2.6000e3, 0.0000, 0.0000], [1.0200e3, 0.0000, 0.0000], [0.0000, 0.0000, 0.0000]]) # Electron fraction values: inner/outer core and mantle. self._ye = np.asarray([ 0.4656, 0.4957 ]) def density(self, r): """Return density as a function of distance from the core. Parameters ---------- r : float or ndarray Radial distance from core, in length units (astropy). Returns ------- rho : float or ndarray Density at radial position(s) r. """ index = np.digitize(r.to('km').value, self._rbins) - 1 if type(r.value) in [list, np.ndarray]: rho = [] for i, x in enumerate(r.to('m').value): j = index[i] c0, c1, c2 = self._dcoef[j] rho.append(1e-3 * (c0 + c1*x + c2*x**2)) return np.asarray(rho) * u.g / u.cm**3 else: x = r.to('m').value c0, c1, c2 = self._dcoef[index] return 1e-3 * (c0 + c1*x + c2*x**2) * u.g / u.cm**3 def y_e(self, r): """Return electron fraction as a function of distance from the core. Parameters ---------- r : float or ndarray Radial distance from core, in length units (astropy). Returns ------- Y_e : float or ndarray Electron fraction at radial position(s) r. """ idx = np.digitize(r.to('km').value, [0., 3480., 6371.]) - 1 return self._ye[idx] class SimpleEarth(Body): """A constant-density 13-layer approximation of the Preliminary Reference Earth Model: <NAME> and <NAME>, PEPI 25:297-356, 1981. """ def __init__(self): # Radial bin edges, in units of km. self._rbins = np.asarray( [0.0, 1221.5, 1786.125, 2350.75 , 2915.375, 3480.0, 4220.3, 4960.7, 5701.0, 5771.0, 5971.0, 6151.0, 6346.0, 6356.0, 6368.0, 6371.0]) # Constant density values, in units of g/cm3. self._rho = np.asarray( [12.9792, 12.0042, 11.5966, 11.0351, 10.3155, 5.3828, 5.0073, 4.5988, 3.9840, 3.8496, 3.4894, 3.3701, 2.9000, 2.6000, 1.0200, 0.0000]) # Electron fraction values: inner/outer core and mantle. self._ye = np.asarray([ 0.4656, 0.4957 ]) def density(self, r): """Return density as a function of distance from the core. Parameters ---------- r : float or ndarray Radial distance from core, in length units (astropy). Returns ------- rho : float or ndarray Density at radial position(s) r. """ idx = np.digitize(r.to('km').value, self._rbins) - 1 return self._rho[idx] * u.g / u.cm**3 def y_e(self, r): """Return electron fraction as a function of distance from the core. Parameters ---------- r : float or ndarray Radial distance from core, in length units (astropy). Returns ------- Y_e : float or ndarray Electron fraction at radial position(s) r. """ idx = np.digitize(r.to('km').value, [0., 3480., 6371.]) - 1 return self._ye[idx] class TwoLayerModel(Body): """A simple two-layered model for the densities of the core and the mantle """ def __init__(self): # Radial bin edges, in units of km. self._rbins = np.asarray( [0.0, 3480.0, 6371.0]) # Constant density values, in units of g/cm3. self._rho = np.asarray( [11.5000, 4.5000, 0.0000]) # Electron fraction values: inner/outer core and mantle. self._ye = np.asarray([ 0.4656, 0.4957 ]) def density(self, r): """Return density as a function of distance from the core. Parameters ---------- r : float or ndarray Radial distance from core, in length units (astropy). Returns ------- rho : float or ndarray Density at radial position(s) r. """ idx = np.digitize(r.to('km').value, self._rbins) - 1 return self._rho[idx] * u.g / u.cm**3 def y_e(self, r): """Return electron fraction as a function of distance from the core. Parameters ---------- r : float or ndarray Radial distance from core, in length units (astropy). Returns ------- Y_e : float or ndarray Electron fraction at radial position(s) r. """ idx = np.digitize(r.to('km').value, [0., 3480., 6371.]) - 1 return self._ye[idx]
vvteplygin/ignite
modules/geospatial/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/GeoSpatialIndex.java
<filename>modules/geospatial/src/main/java/org/apache/ignite/internal/processors/query/h2/opt/GeoSpatialIndex.java /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.internal.processors.query.h2.opt; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.internal.cache.query.index.Index; import org.apache.ignite.internal.cache.query.index.sorted.IndexRow; import org.apache.ignite.internal.util.lang.GridCursor; import org.h2.table.TableFilter; import org.locationtech.jts.geom.Geometry; /** * Interface for geo spatial indexes. */ public interface GeoSpatialIndex extends Index { /** * Finds index rows in specifed segment with table filtering. * * @param segment Number of segment to find. * @param filter Table filter. * @return Cursor of found index rows. */ public GridCursor<IndexRow> find(int segment, TableFilter filter); /** * Finds index rows in specifed segment with table filtering. * * @param segment Number of segment to find. * @param filter Table filter. * @param intersection Intersection geometry to find rows within it. * @return Cursor of found index rows. */ public GridCursor<IndexRow> findByGeometry(int segment, TableFilter filter, Geometry intersection); /** * Finds first or last index row for specified segment. * * @param firstOrLast if {@code true} then return first index row or otherwise last row. * @param segment Number of segment to find. * @return Cursor of found index rows. */ public GridCursor<IndexRow> findFirstOrLast(int segment, boolean firstOrLast); /** * Counts index rows for all segments. * * @return total count of index rows. */ public long totalCount() throws IgniteCheckedException; }
Tatsh-archive/tynder
headers/3rdparty/ChipmunkMultiGrab.h
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>. // #import "NSObject.h" @class ChipmunkSpace, NSArray, NSMutableArray; @interface ChipmunkMultiGrab : NSObject { ChipmunkSpace *_space; NSMutableArray *_grabs; float _smoothing; float _grabForce; float _grabFriction; float _grabRotaryFriction; float _grabRadius; struct cpShapeFilter filter; CDUnknownBlockType _grabFilter; CDUnknownBlockType _grabSort; _Bool _pushMode; _Bool _pullMode; float _pushMass; float _pushFriction; float _pushElasticity; id _pushCollisionType; id _group; struct cpShapeFilter _filter; } - (id)beginLocation:(struct CGPoint)arg1; - (void)dealloc; - (id)endLocation:(struct CGPoint)arg1; @property(nonatomic) struct cpShapeFilter filter; // @synthesize filter=_filter; @property(copy, nonatomic) CDUnknownBlockType grabFilter; // @synthesize grabFilter=_grabFilter; @property(nonatomic) float grabForce; // @synthesize grabForce=_grabForce; @property(nonatomic) float grabFriction; // @synthesize grabFriction=_grabFriction; @property(nonatomic) float grabRadius; // @synthesize grabRadius=_grabRadius; @property(nonatomic) float grabRotaryFriction; // @synthesize grabRotaryFriction=_grabRotaryFriction; @property(copy, nonatomic) CDUnknownBlockType grabSort; // @synthesize grabSort=_grabSort; @property(readonly, nonatomic) NSArray *grabs; @property(nonatomic) id group; // @synthesize group=_group; - (id)initForSpace:(id)arg1 withSmoothing:(float)arg2 withGrabForce:(float)arg3; @property(nonatomic) _Bool pullMode; // @synthesize pullMode=_pullMode; @property(nonatomic) id pushCollisionType; // @synthesize pushCollisionType=_pushCollisionType; @property(nonatomic) float pushElasticity; // @synthesize pushElasticity=_pushElasticity; @property(nonatomic) float pushFriction; // @synthesize pushFriction=_pushFriction; @property(nonatomic) float pushMass; // @synthesize pushMass=_pushMass; @property(nonatomic) _Bool pushMode; // @synthesize pushMode=_pushMode; @property(nonatomic) float smoothing; // @synthesize smoothing=_smoothing; - (id)updateLocation:(struct CGPoint)arg1; @end
mnowotnik/fovris
src/Eval/JoinProjection.cc
<reponame>mnowotnik/fovris #include "Eval/JoinProjection.h" namespace fovris{ } // fovris
killerbee1998/webdev-lesson-files
l13/13-12.js
<gh_stars>1-10 //Evaluate these: //#1 console.log([2] === [2]); //false console.log({} === {} );//false //#2 what is the value of property a for each object. const object1 = { a: 5 };//4 const object2 = object1; //4 const object3 = object2; //4 const object4 = { a: 5}; //5 object1.a = 4; console.log(object1.a); console.log(object2.a); console.log(object3.a); console.log(object4.a); //#3 create two classes: an Animal class and a Mamal class. // create a cow that accepts a name, type and color and has a sound method that moo's her name, type and color. class Animal{ constructor(name,type,color){ this.name = name; this.type = type; this.color = color; } moo(){ console.log("MOO I\'m " + this.name); console.log("MOO I\'m a " + this.type); console.log("MOO I\'m also" + this.color); } } class Mamal extends Animal{ constructor(name,color){ super(name ,"Mamal" , color); } moo(){ console.log("MOO I\'m " + this.name); console.log("MOO I\'m a " + this.type); console.log("MOO I\'m also" + this.color); } } let cow = new Mamal("Shelly", "Red"); console.log(cow);
zipated/src
headless/public/util/in_memory_request_job.cc
<reponame>zipated/src // Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "headless/public/util/in_memory_request_job.h" #include "base/threading/thread_task_runner_handle.h" #include "headless/public/util/in_memory_protocol_handler.h" #include "net/base/io_buffer.h" #include "net/base/net_errors.h" #include "net/url_request/url_request_status.h" namespace headless { InMemoryRequestJob::InMemoryRequestJob( net::URLRequest* request, net::NetworkDelegate* network_delegate, const InMemoryProtocolHandler::Response* response) : net::URLRequestJob(request, network_delegate), response_(response), data_offset_(0), weak_factory_(this) {} InMemoryRequestJob::~InMemoryRequestJob() = default; void InMemoryRequestJob::Start() { // Start reading asynchronously so that all error reporting and data // callbacks happen as they would for network requests. base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&InMemoryRequestJob::StartAsync, weak_factory_.GetWeakPtr())); } void InMemoryRequestJob::StartAsync() { if (!response_) { NotifyStartError(net::URLRequestStatus(net::URLRequestStatus::FAILED, net::ERR_FILE_NOT_FOUND)); return; } NotifyHeadersComplete(); } void InMemoryRequestJob::Kill() { weak_factory_.InvalidateWeakPtrs(); URLRequestJob::Kill(); } int InMemoryRequestJob::ReadRawData(net::IOBuffer* buf, int buf_size) { DCHECK(response_); DCHECK_LE(data_offset_, response_->data.size()); int remaining = base::checked_cast<int>(response_->data.size() - data_offset_); if (buf_size > remaining) buf_size = remaining; memcpy(buf->data(), response_->data.data() + data_offset_, buf_size); data_offset_ += buf_size; return buf_size; } bool InMemoryRequestJob::GetMimeType(std::string* mime_type) const { *mime_type = response_->mime_type; return true; } } // namespace headless
RobertLara/jInstagram
src/main/java/org/jinstagram/entity/common/ImageData.java
package org.jinstagram.entity.common; import com.google.gson.annotations.SerializedName; /** * A class to denote the ImageData. * * @author <NAME> * @version 1.0 */ public class ImageData { @SerializedName("height") private int imageHeight; @SerializedName("url") private String imageUrl; @SerializedName("width") private int imageWidth; /** * @return the imageUrl */ public String getImageUrl() { return imageUrl; } /** * @param imageUrl the imageUrl to set */ public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } /** * @return the imageWidth */ public int getImageWidth() { return imageWidth; } /** * @param imageWidth the imageWidth to set */ public void setImageWidth(int imageWidth) { this.imageWidth = imageWidth; } /** * @return the imageHeight */ public int getImageHeight() { return imageHeight; } /** * @param imageHeight the imageHeight to set */ public void setImageHeight(int imageHeight) { this.imageHeight = imageHeight; } @Override public String toString() { return String.format("ImageData [imageHeight=%s, imageUrl=%s, imageWidth=%s]", imageHeight, imageUrl, imageWidth); } }
Saknet/SensorObservationFrontend
node_modules/edges-to-adjacency-list/test/test.js
<filename>node_modules/edges-to-adjacency-list/test/test.js "use strict" var tape = require("tape") var e2a = require("../e2a") tape("edges-to-adjacency-list", function(t) { t.same(e2a([ [0,1], [1,2], [2,3] ]), [ [1], [0,2], [1,3], [2] ]) t.end() })
marrmartin/onesaitplatform-cloud
sources/services/config-services/src/main/java/com/minsait/onesait/platform/config/services/configuration/ConfigurationServiceImpl.java
/** * Copyright Indra Soluciones Tecnologías de la Información, S.L.U. * 2013-2019 SPAIN * * 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.minsait.onesait.platform.config.services.configuration; import java.util.Arrays; import java.util.List; import java.util.Map; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; import com.minsait.onesait.platform.config.components.AllConfiguration; import com.minsait.onesait.platform.config.components.GitlabConfiguration; import com.minsait.onesait.platform.config.components.GlobalConfiguration; import com.minsait.onesait.platform.config.components.GoogleAnalyticsConfiguration; import com.minsait.onesait.platform.config.components.JenkinsConfiguration; import com.minsait.onesait.platform.config.components.MailConfiguration; import com.minsait.onesait.platform.config.components.ModulesUrls; import com.minsait.onesait.platform.config.components.OpenshiftConfiguration; import com.minsait.onesait.platform.config.components.RancherConfiguration; import com.minsait.onesait.platform.config.components.TwitterConfiguration; import com.minsait.onesait.platform.config.components.Urls; import com.minsait.onesait.platform.config.model.Configuration; import com.minsait.onesait.platform.config.model.Configuration.Type; import com.minsait.onesait.platform.config.model.User; import com.minsait.onesait.platform.config.repository.ConfigurationRepository; import com.minsait.onesait.platform.config.services.exceptions.ConfigServiceException; import lombok.extern.slf4j.Slf4j; @Service @Slf4j public class ConfigurationServiceImpl implements ConfigurationService { @Autowired private ConfigurationRepository configurationRepository; private static final String DEFAULT = "default"; @Override public List<Configuration> getAllConfigurations() { return configurationRepository.findAll(); } @Override public List<Configuration> getAllConfigurations(User user) { return configurationRepository.findByUser(user); } @Override @Transactional public void deleteConfiguration(String id) { configurationRepository.deleteById(id); } @Override public List<Type> getAllConfigurationTypes() { return Arrays.asList(Configuration.Type.values()); } @Override public Configuration getConfiguration(String id) { return configurationRepository.findById(id); } @Override public Configuration createConfiguration(Configuration configuration) { Configuration oldConfiguration = configurationRepository.findById(configuration.getId()); if (oldConfiguration != null) throw new ConfigServiceException( "You cann´t create a Configuration that exists:" + configuration.toString()); oldConfiguration = configurationRepository.findByTypeAndEnvironmentAndSuffix(configuration.getType(), configuration.getEnvironment(), configuration.getSuffix()); if (oldConfiguration != null) throw new ConfigServiceException( "Exist a configuration of this type for the environment and suffix:" + configuration.toString()); oldConfiguration = new Configuration(); oldConfiguration.setUser(configuration.getUser()); oldConfiguration.setType(configuration.getType()); oldConfiguration.setYmlConfig(configuration.getYmlConfig()); oldConfiguration.setDescription(configuration.getDescription()); oldConfiguration.setSuffix(configuration.getSuffix()); oldConfiguration.setEnvironment(configuration.getEnvironment()); return configurationRepository.save(oldConfiguration); } @Override public void updateConfiguration(Configuration configuration) { final Configuration oldConfiguration = configurationRepository.findById(configuration.getId()); if (oldConfiguration != null) { oldConfiguration.setYmlConfig(configuration.getYmlConfig()); oldConfiguration.setDescription(configuration.getDescription()); oldConfiguration.setSuffix(configuration.getSuffix()); oldConfiguration.setEnvironment(configuration.getEnvironment()); configurationRepository.save(oldConfiguration); } else { throw new ConfigServiceException("You cann´t update a Configuration:" + configuration.toString()); } } @Override public TwitterConfiguration getTwitterConfiguration(String environment, String suffix) { try { final Configuration config = this.getConfiguration(Configuration.Type.TWITTER, environment, suffix); AllConfiguration conf = getAllConfigurationFromDBConfig(config); if (conf==null) return null; return conf.getTwitter(); } catch (final Exception e) { log.error("Error getting TwitterConfiguration", e); throw new ConfigServiceException("Error getting TwitterConfiguration", e); } } @Override public boolean existsConfiguration(Configuration configuration) { return (configurationRepository.findById(configuration.getId()) != null); } @Override public Map fromYaml(String yaml) { final Yaml yamlParser = new Yaml(); return (Map) yamlParser.load(yaml); } @Override public boolean isValidYaml(final String yml) { try { final Yaml yamlParser = new Yaml(); yamlParser.load(yml); return true; } catch (final Exception e) { log.error("Error parsing file:" + e.getMessage()); return false; } } @Override public List<Configuration> getConfigurations(Configuration.Type type) { return configurationRepository.findByType(type); } @Override public List<Configuration> getConfigurations(Configuration.Type type, User user) { return configurationRepository.findByTypeAndUser(type, user); } @Override public Configuration getConfiguration(Configuration.Type type, String environment, String suffix) { if (suffix == null) return configurationRepository.findByTypeAndEnvironment(type, environment); else return configurationRepository.findByTypeAndEnvironmentAndSuffix(type, environment, suffix); } @Override public Configuration getConfigurationByDescription(String description) { return configurationRepository.findByDescription(description); } @Override public Urls getEndpointsUrls(String environment) { final Configuration config = configurationRepository .findByTypeAndEnvironment(Configuration.Type.ENDPOINT_MODULES, environment); final Constructor constructor = new Constructor(ModulesUrls.class); final Yaml yamlUrls = new Yaml(constructor); return yamlUrls.loadAs(config.getYmlConfig(), ModulesUrls.class).getOnesaitplatform().get("urls"); } @Override public GitlabConfiguration getGitlabConfiguration(String id) { final Configuration config = configurationRepository.findById(id); if (config == null) return null; return getAllConfigurationFromDBConfig(config).getGitlab(); } @Override public GitlabConfiguration getGitlabConfiguration(String suffix, String environment) { final Configuration config = configurationRepository.findByTypeAndEnvironmentAndSuffix(Type.GITLAB, environment, suffix); if (config == null) return null; return getAllConfigurationFromDBConfig(config).getGitlab(); } @Override public GitlabConfiguration getDefautlGitlabConfiguration() { return getGitlabConfiguration("", DEFAULT); } @Override public RancherConfiguration getRancherConfiguration(String id) { final Configuration config = configurationRepository.findById(id); if (config == null) return null; return getAllConfigurationFromDBConfig(config).getRancher(); } @Override public OpenshiftConfiguration getOpenshiftConfiguration(String id) { final Configuration config = configurationRepository.findById(id); if (config == null) return null; return getAllConfigurationFromDBConfig(config).getOpenshift(); } @Override public Configuration getConfiguration(Type configurationType, String suffix) { return configurationRepository.findByTypeAndSuffixIgnoreCase(configurationType, suffix); } @Override public MailConfiguration getMailConfiguration(String environment) { final Configuration configuration = configurationRepository.findByTypeAndEnvironment(Type.MAIL, environment); if (configuration == null) return null; return getAllConfigurationFromDBConfig(configuration).getMail(); } @Override public GoogleAnalyticsConfiguration getGoogleAnalyticsConfiguration(String environment) { final Configuration configuration = configurationRepository.findByTypeAndEnvironment(Type.GOOGLE_ANALYTICS, environment); if (configuration == null) return null; return getAllConfigurationFromDBConfig(configuration).getGoogleanalytics(); } @Override public RancherConfiguration getRancherConfiguration(String suffix, String environment) { final Configuration config = configurationRepository .findByTypeAndEnvironmentAndSuffix(Configuration.Type.RANCHER, environment, suffix); if (config == null) return null; else return getAllConfigurationFromDBConfig(config).getRancher(); } @Override public RancherConfiguration getDefaultRancherConfiguration() { return getRancherConfiguration("", DEFAULT); } @Override public GlobalConfiguration getGlobalConfiguration(String environment) { final Configuration config = configurationRepository.findByTypeAndEnvironment(Type.OPEN_PLATFORM, environment); if (config == null) return null; return getAllConfigurationFromDBConfig(config).getOnesaitplatform(); } @Override public JenkinsConfiguration getJenkinsConfiguration(String environment) { final Configuration config = configurationRepository.findByTypeAndEnvironmentAndSuffix(Type.JENKINS, environment, "jenkins"); if (config == null) return null; return getAllConfigurationFromDBConfig(config).getJenkins(); } @Override public JenkinsConfiguration getDefaultJenkinsConfiguration() { return getJenkinsConfiguration(DEFAULT); } private AllConfiguration getAllConfigurationFromDBConfig(Configuration config) { if (config == null) return null; final Constructor constructor = new Constructor(AllConfiguration.class); final Yaml yaml = new Yaml(constructor); return yaml.loadAs(config.getYmlConfig(), AllConfiguration.class); } @Override public String getDefaultJenkinsXML(String suffix) { final Configuration configuration = this.getConfiguration(Type.JENKINS, DEFAULT, suffix); if (configuration == null) return ""; return configuration.getYmlConfig(); } }
gregstewart/hearthstone-tracker
app/scripts/actions/win-streak.js
<gh_stars>1-10 import * as types from '../constants/action-types'; export function updateWinStreak (winStreak) { return { type: types.UPDATE_WIN_STREAK, winStreak }; }
Spacebody/SPN-and-Image-Completion
Implementation/tests/spn/test_instance.cpp
<reponame>Spacebody/SPN-and-Image-Completion #include <iostream> #include "../../codes/spn/instance.hpp" int main(int argc, char *argv[]) { Instance inst; std::cout << "Instance mean: " << inst.mean << std::endl; std::cout << "Instance var: " << inst.std << std::endl; return 0; }
kupl/starlab-benchmarks
Benchmarks_with_Safety_Bugs/C/inetutils-1.9.4/src/libtelnet/encrypt.h
<reponame>kupl/starlab-benchmarks<gh_stars>0 /* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015 Free Software Foundation, Inc. This file is part of GNU Inetutils. GNU Inetutils is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. GNU Inetutils is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see `http://www.gnu.org/licenses/'. */ /* * Copyright (c) 1991, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * Copyright (C) 1990 by the Massachusetts Institute of Technology * * Export of this software from the United States of America is assumed * to require a specific license from the United States Government. * It is the responsibility of any person or organization contemplating * export to obtain such a license before exporting. * * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and * distribute this software and its documentation for any purpose and * without fee is hereby granted, provided that the above copyright * notice appear in all copies and that both that copyright notice and * this permission notice appear in supporting documentation, and that * the name of M.I.T. not be used in advertising or publicity pertaining * to distribution of the software without specific, written prior * permission. M.I.T. makes no representations about the suitability of * this software for any purpose. It is provided "as is" without express * or implied warranty. */ #ifdef ENCRYPTION # ifndef __ENCRYPTION__ # define __ENCRYPTION__ # define DIR_DECRYPT 1 # define DIR_ENCRYPT 2 /* Cope with variants of <arpa/telnet.h>. */ # if !defined ENCTYPE_ANY && defined TELOPT_ENCTYPE_NULL # define ENCTYPE_ANY TELOPT_ENCTYPE_NULL # endif # if !defined ENCTYPE_DES_CFB64 && defined TELOPT_ENCTYPE_DES_CFB64 # define ENCTYPE_DES_CFB64 TELOPT_ENCTYPE_DES_CFB64 # endif # if !defined ENCTYPE_DES_OFB64 && defined TELOPT_ENCTYPE_DES_OFB64 # define ENCTYPE_DES_OFB64 TELOPT_ENCTYPE_DES_OFB64 # endif # if !defined ENCTYPE_CNT && defined TELOPT_ENCTYPE_CNT # define ENCTYPE_CNT TELOPT_ENCTYPE_CNT # endif /* * Our capabilities are restricted to the encryption types * DES_CFB64 and DES_OFB64. The latter type is sometimes * missing in <arpa/telnet.h>. On the other hand, the same * header file may indicate more encryption types than are * supported by the present code. */ # ifndef ENCTYPE_DES_OFB64 # define ENCTYPE_DES_OFB64 2 /* RFC 2953 */ # endif # undef ENCTYPE_CNT # define ENCTYPE_CNT 3 /* Up to DES_OFB64. */ # undef ENCTYPE_NAME_OK # define ENCTYPE_NAME_OK(x) ((unsigned int)(x) < ENCTYPE_CNT) typedef unsigned char Block[8]; typedef unsigned char *BlockT; # ifndef HAVE_ARPA_TELNET_H_SCHEDULE typedef struct { Block _; } Schedule[16]; # endif /* !HAVE_ARPA_TELNET_H_SCHEDULE */ # ifndef VALIDKEY # define VALIDKEY(key) ( key[0] | key[1] | key[2] | key[3] | \ key[4] | key[5] | key[6] | key[7]) # endif # define SAMEKEY(k1, k2) (!memcmp ((void *) k1, (void *) k2, sizeof (Block))) # ifndef HAVE_ARPA_TELNET_H_SESSION_KEY typedef struct { short type; int length; const unsigned char *data; } Session_Key; # endif /* !HAVE_ARPA_TELNET_H_SESSION_KEY */ typedef struct { char *name; int type; void (*output) (unsigned char *, int); int (*input) (int); void (*init) (int); int (*start) (int, int); int (*is) (unsigned char *, int); int (*reply) (unsigned char *, int); void (*session) (Session_Key *, int); int (*keyid) (int, unsigned char *, int *); void (*printsub) (unsigned char *, int, char *, int); } Encryptions; # define SK_DES 1 /* Matched Kerberos v5 KEYTYPE_DES */ # define SK_OTHER 2 /* Non-DES key. */ # include "enc-proto.h" extern int encrypt_debug_mode; extern int (*decrypt_input) (int); extern void (*encrypt_output) (unsigned char *, int); # endif /* __ENCRYPTION__ */ #endif /* ENCRYPTION */
gianglaodai/file-manager
src/main/java/com/leo/prj/controller/TemplateController.java
package com.leo.prj.controller; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.leo.prj.bean.EditorPageData; import com.leo.prj.bean.FileInfo; import com.leo.prj.enumeration.Template; import com.leo.prj.service.template.TemplateService; @CrossOrigin @RestController @RequestMapping("/template") public class TemplateController { @Autowired private TemplateService templateService; @GetMapping("/getAll/{catalog}") public ResponseEntity<List<FileInfo>> getAll(@PathVariable int catalog) { return ResponseEntity.ok(templateService.getAllByCatalog(Integer.valueOf(catalog), Stream.of(Template.values()).map(t -> t.getValue()).collect(Collectors.toList()))); } @GetMapping("/load/{catalog}") public ResponseEntity<EditorPageData> load(@PathVariable int catalog, @RequestParam String fileName) { return ResponseEntity.ok(templateService.loadFromCatalog(catalog, fileName).get()); } @PostMapping("/save/{catalog}") public ResponseEntity<Boolean> save(@PathVariable int catalog, @RequestBody EditorPageData data) { return ResponseEntity.ok(templateService.saveToCatalog(catalog, data)); } @GetMapping("/preview/{catalog}") public String preview(@PathVariable int catalog, @RequestParam String fileName) { return templateService.preview(fileName, catalog); } }
mschwartz/amos
kernel/Exec/BDevice.hpp
#ifndef BDEVICE_H #define BDEVICE_H #include <Exec/MessagePort.hpp> class BDevice : public BNodePri { public: BDevice(const char *aNodeName); ~BDevice(); }; class DeviceList : public BListPri { public: DeviceList(); ~DeviceList(); public: void AddDevice(BDevice &aDevice); BDevice *FindDevice(const char *aName); public: BDevice *RemHead() { return (BDevice *)BListPri::RemHead(); } BDevice *First() { return (BDevice *)mNext; } BDevice *Next(BDevice *aCurrent) { return (BDevice *)aCurrent->mNext; } BDevice *Last() { return (BDevice *)mPrev; } BDevice *Prev(BDevice *aCurrent) { return (BDevice *)aCurrent->mPrev; } TBool End(BDevice *aCurrent) { return aCurrent == (BDevice *)this; } public: void Lock() { return mSpinLock.Acquire(); } void Unlock() { return mSpinLock.Release(); } protected: SpinLock mSpinLock; }; class BDeviceMessage : public BMessage { public: BDeviceMessage(MessagePort *aReplyPort) : BMessage(aReplyPort) { // } ~BDeviceMessage() {} }; #endif
mahaplatform/mahaplatform.com
src/lib/admin/components/emojis/panel.js
<reponame>mahaplatform/mahaplatform.com import categories from './categories' import PropTypes from 'prop-types' import React from 'react' class Emojis extends React.Component { static propTypes = { changing: PropTypes.bool, skinTone: PropTypes.string, skinToneIndex: PropTypes.number, status: PropTypes.string, onChangeSkinTone: PropTypes.func, onChoose: PropTypes.func, onClose: PropTypes.func, onLoadSkinTone: PropTypes.func, onSaveSkinTone: PropTypes.func } static defaultProps = { onChoose: () => {}, onClose: () => {} } _handleChangeSkinTone = this._handleChangeSkinTone.bind(this) _handleSaveSkinTone = this._handleSaveSkinTone.bind(this) render() { const { changing, skinTone, status } = this.props if(status !== 'loaded') return null return ( <div className="maha-emojis-panel"> <div className="maha-emojis-body"> { categories.map((category, i) => ( <div className="maha-emojis-category" key={`category_${i}`}> <div className="maha-emojis-category-title">{ category.title }</div> <div className="maha-emojis-category-emojis"> { category.emojis.map((emoji, j) => ( <div className="maha-emojis-category-emoji" key={`emoji_${j}`} onClick={ this._handleChoose.bind(this, emoji) }> <span className={`emoji emoji-${this._getWithSkinTone(emoji)}`} /> </div> ))} </div> </div> ))} </div> { changing ? <div className="maha-emojis-footer"> <div className="maha-emojis-footer-label"> Skin Tone: </div> <div className="maha-emojis-footer-emoji" onClick={ this._handleSaveSkinTone.bind(this, null) }> <span className="emoji emoji-1f91a" /> </div> <div className="maha-emojis-footer-emoji" onClick={ this._handleSaveSkinTone.bind(this, 0) }> <span className="emoji emoji-1f91a-1f3fb" /> </div> <div className="maha-emojis-footer-emoji" onClick={ this._handleSaveSkinTone.bind(this, 1) }> <span className="emoji emoji-1f91a-1f3fc" /> </div> <div className="maha-emojis-footer-emoji" onClick={ this._handleSaveSkinTone.bind(this, 2) }> <span className="emoji emoji-1f91a-1f3fd" /> </div> <div className="maha-emojis-footer-emoji" onClick={ this._handleSaveSkinTone.bind(this, 3) }> <span className="emoji emoji-1f91a-1f3fe" /> </div> <div className="maha-emojis-footer-emoji" onClick={ this._handleSaveSkinTone.bind(this, 4) }> <span className="emoji emoji-1f91a-1f3ff" /> </div> </div> : <div className="maha-emojis-footer"> <div className="maha-emojis-footer-label"> Skin Tone: </div> <div className="maha-emojis-footer-emoji" onClick={ this._handleChangeSkinTone }> <span className={`emoji emoji-1f91a${skinTone ? `-${skinTone}` : ''}`} /> </div> </div> } </div> ) } _getWithSkinTone(emoji) { if(!emoji.skin)return emoji.code const { skinTone } = this.props if(skinTone === null) return emoji.code const parts = emoji.code.split('-') if(parts.length === 1) return `${emoji.code}-${skinTone}` if(parts.length === 2) return `${parts[0]}-${skinTone}` if(parts.length === 5) return `${parts[0]}-${skinTone}-${parts.slice(2).join('-')}` if(parts.length < 6) return `${parts[0]}-${skinTone}-${parts.slice(1).join('-')}` return `${parts.slice(0, -1)}-${skinTone}` } _handleChangeSkinTone() { this.props.onChangeSkinTone() } _handleSaveSkinTone(index) { this.props.onSaveSkinTone(index) } _handleChoose(emoji) { const code = this._getWithSkinTone(emoji) const unicode = code.split('-').map(code => String.fromCodePoint(`0x${code}`)).join('') this.props.onChoose(unicode) } } export default Emojis
tomas-krupa/ansi_iso_accuracy_test
src/CSV/CSVIterator.hpp
/** * @file CSVIterator.hpp * * @remarks https://stackoverflow.com/a/1120224 * * @copyright Copyright (c) 2020 Innovatrics s.r.o. All rights reserved. * * @maintainer <NAME> <<EMAIL>> * @created 20.08.2020 * */ #pragma once #include "CSVRow.hpp" class CSVIterator { public: using iterator_category = std::input_iterator_tag; using value_type = CSVRow; using difference_type = std::size_t; using pointer = CSVRow *; using reference = CSVRow &; CSVIterator(std::istream &str) : _str(str.good() ? &str : nullptr) { ++(*this); } CSVIterator() : _str(NULL) {} // Pre Increment CSVIterator &operator++() { if (_str) { if (not((*_str) >> _row)) { _str = nullptr; }} return *this; } // Post increment CSVIterator operator++(int) { CSVIterator tmp(*this); ++(*this); return tmp; } CSVRow const &operator*() const { return _row; } CSVRow const *operator->() const { return &_row; } bool operator==(CSVIterator const &rhs) { return ((this == &rhs) || ((this->_str == nullptr) && (rhs._str == nullptr))); } bool operator!=(CSVIterator const &rhs) { return not((*this) == rhs); } private: std::istream *_str; CSVRow _row; };
sjamboro/kogito-runtimes
quarkus/extensions/kogito-quarkus-serverless-workflow-extension/kogito-quarkus-serverless-workflow-integration-test/src/test/java/org/kie/kogito/quarkus/workflows/AbstractCallbackStateIT.java
/* * Copyright 2022 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kie.kogito.quarkus.workflows; import java.net.URI; import java.time.OffsetDateTime; import java.util.UUID; import org.eclipse.microprofile.config.inject.ConfigProperty; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.kie.kogito.test.quarkus.kafka.KafkaTestClient; import org.kie.kogito.testcontainers.quarkus.KafkaQuarkusTestResource; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import io.cloudevents.core.builder.CloudEventBuilder; import io.cloudevents.jackson.JsonCloudEventData; import io.cloudevents.jackson.JsonFormat; import io.restassured.path.json.JsonPath; import static org.assertj.core.api.Assertions.assertThat; import static org.kie.kogito.quarkus.workflows.ExternalServiceMock.GENERATE_ERROR_QUERY; import static org.kie.kogito.quarkus.workflows.ExternalServiceMock.SUCCESSFUL_QUERY; import static org.kie.kogito.quarkus.workflows.WorkflowTestUtils.assertProcessInstanceExists; import static org.kie.kogito.quarkus.workflows.WorkflowTestUtils.assertProcessInstanceHasFinished; import static org.kie.kogito.quarkus.workflows.WorkflowTestUtils.assertProcessInstanceNotExists; import static org.kie.kogito.quarkus.workflows.WorkflowTestUtils.newProcessInstance; import static org.kie.kogito.quarkus.workflows.WorkflowTestUtils.newProcessInstanceAndGetId; abstract class AbstractCallbackStateIT { static final String ANSWER = "ANSWER"; @ConfigProperty(name = KafkaQuarkusTestResource.KOGITO_KAFKA_PROPERTY) String kafkaBootstrapServers; ObjectMapper objectMapper; KafkaTestClient kafkaClient; @BeforeEach void setup() { kafkaClient = new KafkaTestClient(kafkaBootstrapServers); objectMapper = new ObjectMapper() .registerModule(new JavaTimeModule()) .registerModule(JsonFormat.getCloudEventJacksonModule()) .disable(com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); } void executeCallbackStateSuccessfulPath(String callbackProcessPostUrl, String callbackProcessGetByIdUrl, String answer, String callbackEventType, String callbackEventTopic) throws Exception { // start a new process instance by sending the post query and collect the process instance id. String processInput = buildProcessInput(SUCCESSFUL_QUERY); String processInstanceId = newProcessInstanceAndGetId(callbackProcessPostUrl, processInput); // double check that the process instance is there. assertProcessInstanceExists(callbackProcessGetByIdUrl, processInstanceId); // prepare and send the response to the created process via kafka String response = objectMapper.writeValueAsString(CloudEventBuilder.v1() .withId(UUID.randomUUID().toString()) .withSource(URI.create("")) .withType(callbackEventType) .withTime(OffsetDateTime.now()) .withExtension( "kogitoprocrefid", processInstanceId) .withData(JsonCloudEventData.wrap(objectMapper.createObjectNode().put("answer", answer))) .build()); kafkaClient.produce(response, callbackEventTopic); // give some time for the event to be processed and the process to finish. assertProcessInstanceHasFinished(callbackProcessGetByIdUrl, processInstanceId, 1, 180); } void executeCallbackStateWithErrorPath(String callbackProcessPostUrl, String callbackProcessGetByIdUrl) { // start a new process instance and collect the results. String processInput = buildProcessInput(GENERATE_ERROR_QUERY); JsonPath result = newProcessInstance(callbackProcessPostUrl, processInput); String processInstanceId = result.get("id"); // ensure the process has failed as expected since GENERATE_ERROR_QUERY was used. String lastExecutedState = result.getString("workflowdata.lastExecutedState"); assertThat(lastExecutedState).isEqualTo("FinalizeWithError"); // the process instance should not be there since an end state was reached. assertProcessInstanceNotExists(callbackProcessGetByIdUrl, processInstanceId); } @AfterEach void cleanUp() { kafkaClient.shutdown(); } protected static String buildProcessInput(String query) { return "{\"workflowdata\": {\"query\": \"" + query + "\"} }"; } }
NASA-PDS-Incubator/registry
src/main/java/gov/nasa/pds/registry/mgr/util/solr/SolrCursor.java
package gov.nasa.pds.registry.mgr.util.solr; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocumentList; import org.apache.solr.common.params.CursorMarkParams; public class SolrCursor { private SolrClient client; private String collectionName; private SolrQuery query; private boolean done; private String cursorMark; private QueryResponse response; public SolrCursor(SolrClient client, String collectionName, SolrQuery query) { this.client = client; this.collectionName = collectionName; this.query = query; this.done = false; this.cursorMark = CursorMarkParams.CURSOR_MARK_START; } public boolean next() throws Exception { if(done) return false; query.set(CursorMarkParams.CURSOR_MARK_PARAM, cursorMark); response = client.query(collectionName, query); String nextCursorMark = response.getNextCursorMark(); if(cursorMark.equals(nextCursorMark)) { done = true; } cursorMark = nextCursorMark; return true; } public SolrDocumentList getResults() { return response.getResults(); } }
addstone/JCEngine
src/main/java/pers/jc/util/JCLogger.java
package pers.jc.util; import java.io.File; import java.io.FileWriter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicInteger; public class JCLogger { private static int level = 1; public static final int LEVEL_DEBUG = 0; public static final int LEVEL_INFO = 1; public static final int LEVEL_WARN = 2; public static final int LEVEL_ERROR = 3; private static final String LEVEL_DEBUG_SIGN = "DEBUG"; private static final String LEVEL_INFO_SIGN = "INFO"; private static final String LEVEL_WARN_SIGN = "WARN"; private static final String LEVEL_ERROR_SIGN = "ERROR"; private static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,SSS"); private static File logCatalog; private static File logFile; private static AtomicInteger logFileID = new AtomicInteger(); private static long logFileLength; private static long logOutputInterval; private static boolean logWriterStart; private static final ConcurrentLinkedQueue<String> logQueue = new ConcurrentLinkedQueue<>(); public static void setLogCatalog(String catalog) { setLogCatalog(catalog, 4 * 1024 * 1024, 1000); } public static void setLogCatalog(String catalog, long fileLength, long outputInterval) { try { logCatalog = new File(catalog); if (!logCatalog.exists() && !logCatalog.mkdirs()) { throw new Exception(); } createLogFile(); logFileLength = fileLength; logOutputInterval = outputInterval; createLogWriter(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { System.out.println(logFileID.addAndGet(1)); System.out.println(logFileID.intValue()); } private static void createLogFile() throws Exception { String logFileName = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss_").format(new Date()) + logFileID.addAndGet(1) + ".log"; String logFilePath = logCatalog.getPath() + File.separator + logFileName; logFile = new File(logFilePath); if (!logFile.exists() && !logFile.createNewFile()) { throw new Exception(); } } private static void createLogWriter() { new Thread(() -> { logWriterStart = true; while (true) { try { Thread.sleep(logOutputInterval); String log; FileWriter fileWriter = new FileWriter(logFile, true); while ((log = logQueue.poll()) != null) { if (logFile.length() >= logFileLength) { fileWriter.close(); createLogFile(); fileWriter = new FileWriter(logFile, true); } fileWriter.write(log); } fileWriter.close(); } catch (Exception e) { e.printStackTrace(); } } }).start(); } public static void setLevel(int level) { JCLogger.level = level; } private static String getLog(Object[] msg, String levelSign, boolean showStackTrace) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("[").append(levelSign).append("] "); stringBuilder.append(simpleDateFormat.format(new Date())); stringBuilder.append("\n"); for (Object str : msg) { stringBuilder.append(str).append("\t"); } stringBuilder.append("\n"); if (showStackTrace) { StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace(); for (int i = 3; i < stackTraceElements.length; i++) { StackTraceElement stackTraceElement = stackTraceElements[i]; stringBuilder.append("@").append(stackTraceElement.getClassName()); stringBuilder.append(".").append(stackTraceElement.getMethodName()); stringBuilder.append("(").append(stackTraceElement.getFileName()); stringBuilder.append(":").append(stackTraceElement.getLineNumber()).append(")"); stringBuilder.append("\n"); } } String log = stringBuilder.toString(); if (logWriterStart) { logQueue.add(log); } return log; } public static void debug(Object... msg) { if (level > LEVEL_DEBUG) { return; } System.out.print(getLog(msg, LEVEL_DEBUG_SIGN, false)); } public static void info(Object... msg) { if (level > LEVEL_INFO) { return; } System.out.print(getLog(msg, LEVEL_INFO_SIGN, false)); } public static void warn(Object... msg) { if (level > LEVEL_WARN) { return; } System.out.print(getLog(msg, LEVEL_WARN_SIGN, false)); } public static void error(Object... msg) { if (level > LEVEL_ERROR) { return; } System.err.print(getLog(msg, LEVEL_ERROR_SIGN, false)); } public static void errorStackTrace(Object... msg) { if (level > LEVEL_ERROR) { return; } System.err.print(getLog(msg, LEVEL_ERROR_SIGN, true)); } }
Discord-Wiz/dyno-bot-master
dyno-bot-master/Dyno-premium/src/commands/Moderator/Ignored.js
<reponame>Discord-Wiz/dyno-bot-master 'use strict'; const Command = Loader.require('./core/structures/Command'); class Ignored extends Command { constructor(...args) { super(...args); this.aliases = ['ignored']; this.group = 'Moderator'; this.description = 'List channels and users where commands are ignored.'; this.usage = 'ignored'; this.permissions = 'serverMod'; this.overseerEnabled = true; this.disableDM = true; this.expectedArgs = 0; } execute({ message, args, guildConfig }) { let ignoredChannels = guildConfig.ignoredChannels || null, ignoredUsers = guildConfig.ignoredUsers || null; if (ignoredChannels) { ignoredChannels = ignoredChannels.map(id => message.guild.channels.get(id)); } if (ignoredUsers) { ignoredUsers = ignoredUsers.map(id => message.guild.members.get(id)); } const embed = { fields: [ { name: 'Ignored Channels', value: ignoredChannels ? ignoredChannels.map(c => `${c.mention}`).join('\n') : 'None' }, { name: 'Ignored Users', value: ignoredUsers ? ignoredUsers.map(u => `${u.mention} (${utils.fullName(u)})`) : 'None' }, ], timestamp: new Date(), }; return this.sendMessage(message.channel, { embed }); } } module.exports = Ignored;
DongerZone/o3de
Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Logic/Multiplexer.cpp
/* * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include "Multiplexer.h" namespace ScriptCanvas { namespace Nodes { namespace Logic { Multiplexer::Multiplexer() {} void Multiplexer::OnInputSignal(const SlotId& slotId) { auto slotIndex = FindSlotIndex(slotId); if (!slotIndex) { AZ_Warning("Script Canvas", false, "Could not find slot with Id %s", slotId.ToString().c_str()); return; } // These are generated from CodeGen, they essentially // check if there's anything connected on the slot and // they assign the local member with the value, otherwise // they use the default property value. const AZ::s64 selectedIndex = MultiplexerProperty::GetIndex(this); if (selectedIndex == slotIndex) { const SlotId outSlotId = MultiplexerProperty::GetOutSlotId(this); SignalOutput(outSlotId); } } } } }
safchain/contrail-controller
src/vnsw/agent/contrail/contrail_agent_init.h
/* * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved. */ #ifndef vnsw_contrail_agent_init_hpp #define vnsw_contrail_agent_init_hpp class Agent; class AgentParam; // The class to drive agent initialization. // Defines control parameters used to enable/disable agent features class ContrailAgentInit { public: ContrailAgentInit() : agent_(NULL), params_(NULL), trigger_() { } ~ContrailAgentInit() { trigger_->Reset(); } bool Run(); void Start(); void Shutdown(); void InitLogging(); void InitCollector(); void CreateModules(); void CreateDBTables(); void CreateDBClients(); void InitModules(); void InitPeers(); void CreateVrf(); void CreateNextHops(); void CreateInterfaces(); void InitDiscovery(); void InitDone(); void InitVmwareInterface(); void Init(AgentParam *param, Agent *agent, const boost::program_options::variables_map &var_map); private: Agent *agent_; AgentParam *params_; std::auto_ptr<TaskTrigger> trigger_; DISALLOW_COPY_AND_ASSIGN(ContrailAgentInit); }; #endif // vnsw_contrail_agent_init_hpp
rmathis/openEQUELLA
autotest/Tests/src/main/java/com/tle/webtests/pageobject/remoterepo/sru/RemoteRepoViewSRUResultPage.java
<gh_stars>10-100 package com.tle.webtests.pageobject.remoterepo.sru; import com.tle.webtests.framework.PageContext; import com.tle.webtests.pageobject.remoterepo.RemoteRepoViewResultPage; import org.openqa.selenium.By; public class RemoteRepoViewSRUResultPage extends RemoteRepoViewResultPage<RemoteRepoViewSRUResultPage> { public RemoteRepoViewSRUResultPage(PageContext context) { super(context, By.xpath("//button[contains(@id, '_importButton')]")); } public RemoteRepoSRUSearchPage clickRemoteRepoBreadcrumb(String repo) { driver.findElement(By.xpath("id('breadcrumbs')//a[text()='" + repo + "']")).click(); return new RemoteRepoSRUSearchPage(context); } }
lisurui6/MIRTK
Modules/Registration/include/mirtk/IntensityCorrelationRatioYX.h
<gh_stars>100-1000 /* * Medical Image Registration ToolKit (MIRTK) * * Copyright 2016 Imperial College London * Copyright 2016 <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. */ #ifndef MIRTK_IntensityCorrelationRatioYX_H #define MIRTK_IntensityCorrelationRatioYX_H #include "mirtk/HistogramImageSimilarity.h" namespace mirtk { /** * Correlation ratio of target (X) and source (Y) image intensities */ class IntensityCorrelationRatioYX : public HistogramImageSimilarity { mirtkEnergyTermMacro(IntensityCorrelationRatioYX, EM_CR_YX); // --------------------------------------------------------------------------- // Construction/Destruction public: /// Constructor IntensityCorrelationRatioYX(const char * = ""); /// Copy constructor IntensityCorrelationRatioYX(const IntensityCorrelationRatioYX &); /// Assignment operator IntensityCorrelationRatioYX &operator =(const IntensityCorrelationRatioYX &); /// Destructor ~IntensityCorrelationRatioYX(); // --------------------------------------------------------------------------- // Evaluation protected: /// Evaluate similarity of images virtual double Evaluate(); }; } // namespace mirtk #endif // MIRTK_IntensityCorrelationRatioYX_H
furkanisitan/country-city-api
src/main/java/com/furkanisitan/core/exceptions/InvalidValueException.java
<reponame>furkanisitan/country-city-api package com.furkanisitan.core.exceptions; import lombok.Getter; /** * An exception representing that the specified value is not valid for field. */ @Getter public class InvalidValueException extends RuntimeException { private final String field; private final String value; /** * Creates a new {@link InvalidValueException}. * * @param field the field name. * @param value the value for query. */ public InvalidValueException(String field, String value) { super(String.format("%s: value must be valid. (rejectedValue: %s)", field, value)); this.field = field; this.value = value; } }
keypad00/CRUD-API-DEALER-MOTOR
models/motor.js
/** * motor Schema */ const mongoose = require('mongoose') const Schema = mongoose.Schema let motorSchema = new Schema ({ motor: String, brand: String, price: Number, dealer: String, created_at: { type:Date, default:Date.now }, updated_at: { type: Date, default: Date.now } }) let Motor = mongoose.model("Motor", motorSchema) module.exports = Motor
henriquegemignani/PrimeWorldEditor
src/Core/Resource/Model/CBasicModel.h
#ifndef CBASICMODEL_H #define CBASICMODEL_H #include "SSurface.h" #include "Core/Resource/CResource.h" #include "Core/OpenGL/CVertexBuffer.h" #include <Common/Math/CAABox.h> class CBasicModel : public CResource { DECLARE_RESOURCE_TYPE(Model) protected: CAABox mAABox; uint32 mVertexCount; uint32 mTriangleCount; bool mBuffered; bool mHasOwnMaterials; bool mHasOwnSurfaces; CVertexBuffer mVBO; std::vector<SSurface*> mSurfaces; public: CBasicModel(CResourceEntry *pEntry = 0); ~CBasicModel(); uint32 GetVertexCount(); uint32 GetTriangleCount(); CAABox AABox(); bool IsBuffered(); uint32 GetSurfaceCount(); CAABox GetSurfaceAABox(uint32 Surface); SSurface* GetSurface(uint32 Surface); virtual void ClearGLBuffer() = 0; }; #endif // CBASICMODEL_H
gtri/typesafeconfig-extensions
factory/src/main/java/edu/gatech/gtri/typesafeconfigextensions/factory/PathSpecification.java
<gh_stars>1-10 /* * Copyright 2013 Georgia Tech Applied Research Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.gatech.gtri.typesafeconfigextensions.factory; /** * Strategy for finding a filesystem {@link java.nio.file.Path Path}. * * <p>This type is intended for use as a field on a {@link ConfigSource} * implementation to help implement {@link ConfigSource#load(Bindings)}.</p> * * <p>Some default implementations are constructed by the static methods * available on {@link PathSpecifications}.</p> */ public interface PathSpecification { OptionalPath path(Bindings bindings); /** * A name that can be used to derive * {@link ConfigSourceName#name() the name of a ConfigSource}. */ String name(); }
moritzhertler/TimeSheetGenerator
src/test/java/checker/MiLoGCheckerDayTimeBoundsTest.java
package checker; import static org.junit.Assert.*; import java.time.LocalDate; import java.time.Month; import java.time.YearMonth; import java.util.Random; import org.junit.Before; import org.junit.Test; import data.Employee; import data.Entry; import data.TimeSheet; import data.Profession; import data.TimeSpan; import data.WorkingArea; public class MiLoGCheckerDayTimeBoundsTest { private static TimeSpan CHECKER_WORKDAY_LOWER_BOUND; private static TimeSpan CHECKER_WORKDAY_UPPER_BOUND; //Exclusively. Refer to https://docs.oracle.com/javase/8/docs/api/java/util/Random.html private static final int RANDOM_HOUR_BOUND = 24; private static final int RANDOM_MINUTES_BOUND = 60; ////Placeholder for time sheet construction private static final Employee EMPLOYEE = new Employee("<NAME>", 1234567); private static final Profession PROFESSION = new Profession("Fakultät für Informatik", WorkingArea.UB, new TimeSpan(40, 0), 10.31); private static final YearMonth YEAR_MONTH = YearMonth.of(2019, Month.NOVEMBER); private static final TimeSpan zeroTs = new TimeSpan(0, 0); @Before public void init() { CHECKER_WORKDAY_LOWER_BOUND = MiLoGChecker.getWorkdayLowerBound(); CHECKER_WORKDAY_UPPER_BOUND = MiLoGChecker.getWorkdayUpperBound(); } @Test public void testValidLowerBound() { ////Test values TimeSpan start = CHECKER_WORKDAY_LOWER_BOUND; TimeSpan end = CHECKER_WORKDAY_UPPER_BOUND; TimeSpan pause = new TimeSpan(0, 0); //We just want to test the lower bound for now. end = end.subtract(new TimeSpan(1, 0)); ////Checker initialization Entry entry = new Entry("Test", LocalDate.of(2019, 11, 22), start, end, pause, false); Entry[] entries = {entry}; TimeSheet timeSheet = new TimeSheet(EMPLOYEE, PROFESSION, YEAR_MONTH, entries, zeroTs, zeroTs); MiLoGChecker checker = new MiLoGChecker(timeSheet); ////Execution checker.checkDayTimeBounds(); ////Assertions assertEquals(CheckerReturn.VALID, checker.getResult()); assertTrue(checker.getErrors().isEmpty()); } @Test public void testOutOfLowerBound() { ////Test values TimeSpan start = CHECKER_WORKDAY_LOWER_BOUND; TimeSpan end = CHECKER_WORKDAY_UPPER_BOUND; TimeSpan pause = new TimeSpan(0, 0); //This is done to lower the start one minute below the legal lower bound. start = start.subtract(new TimeSpan(0, 1)); //We just want to test the lower bound for now. end = end.subtract(new TimeSpan(1, 0)); ////Checker initialization Entry entry = new Entry("Test", LocalDate.of(2019, 11, 22), start, end, pause, false); Entry[] entries = {entry}; TimeSheet timeSheet = new TimeSheet(EMPLOYEE, PROFESSION, YEAR_MONTH, entries, zeroTs, zeroTs); MiLoGChecker checker = new MiLoGChecker(timeSheet); ////Execution checker.checkDayTimeBounds(); ////Expectation String error = MiLoGChecker.MiLoGCheckerErrorMessageProvider.TIME_OUTOFBOUNDS.getErrorMessage(entry.getDate()); ////Assertions assertEquals(CheckerReturn.INVALID, checker.getResult()); assertTrue(checker.getErrors().stream().anyMatch(item -> item.getErrorMessage().equals(error))); } @Test public void testValidUpperBound() { ////Test values TimeSpan start = CHECKER_WORKDAY_LOWER_BOUND; TimeSpan end = CHECKER_WORKDAY_UPPER_BOUND; TimeSpan pause = new TimeSpan(0, 0); //We just want to test the upper bound for now. start = start.add(new TimeSpan(1, 0)); ////Checker initialization Entry entry = new Entry("Test", LocalDate.of(2019, 11, 22), start, end, pause, false); Entry[] entries = {entry}; TimeSheet timeSheet = new TimeSheet(EMPLOYEE, PROFESSION, YEAR_MONTH, entries, zeroTs, zeroTs); MiLoGChecker checker = new MiLoGChecker(timeSheet); ////Execution checker.checkDayTimeBounds(); ////Assertions assertEquals(CheckerReturn.VALID, checker.getResult()); assertTrue(checker.getErrors().isEmpty()); } @Test public void testOutOfUpperBound() { ////Test values TimeSpan start = CHECKER_WORKDAY_LOWER_BOUND; TimeSpan end = CHECKER_WORKDAY_UPPER_BOUND; TimeSpan pause = new TimeSpan(0, 0); //This is done to raise the end one minute above the legal upper bound. end = end.add(new TimeSpan(0, 1)); //We just want to test the upper bound for now. start = start.add(new TimeSpan(1, 0)); ////Checker initialization Entry entry = new Entry("Test", LocalDate.of(2019, 11, 22), start, end, pause, false); Entry[] entries = {entry}; TimeSheet timeSheet = new TimeSheet(EMPLOYEE, PROFESSION, YEAR_MONTH, entries, zeroTs, zeroTs); MiLoGChecker checker = new MiLoGChecker(timeSheet); ////Execution checker.checkDayTimeBounds(); ////Expectation String error = MiLoGChecker.MiLoGCheckerErrorMessageProvider.TIME_OUTOFBOUNDS.getErrorMessage(entry.getDate()); ////Assertions assertEquals(CheckerReturn.INVALID, checker.getResult()); assertTrue(checker.getErrors().stream().anyMatch(item -> item.getErrorMessage().equals(error))); } @Test public void testValidBothBounds() { ////Test values TimeSpan start = CHECKER_WORKDAY_LOWER_BOUND; TimeSpan end = CHECKER_WORKDAY_UPPER_BOUND; TimeSpan pause = new TimeSpan(0, 0); ////Checker initialization Entry entry = new Entry("Test", LocalDate.of(2019, 11, 22), start, end, pause, false); Entry[] entries = {entry}; TimeSheet timeSheet = new TimeSheet(EMPLOYEE, PROFESSION, YEAR_MONTH, entries, zeroTs, zeroTs); MiLoGChecker checker = new MiLoGChecker(timeSheet); ////Execution checker.checkDayTimeBounds(); ////Assertions assertEquals(CheckerReturn.VALID, checker.getResult()); assertTrue(checker.getErrors().isEmpty()); } @Test public void testOutOfLowerBoundRandom() { ////Random Random rand = new Random(); ////Test values TimeSpan start = new TimeSpan(rand.nextInt(CHECKER_WORKDAY_UPPER_BOUND.getHour()), rand.nextInt(RANDOM_MINUTES_BOUND)); TimeSpan end = CHECKER_WORKDAY_UPPER_BOUND; TimeSpan pause = new TimeSpan(0, 0); ////Checker initialization Entry entry = new Entry("Test", LocalDate.of(2019, 11, 22), start, end, pause, false); Entry[] entries = {entry}; TimeSheet timeSheet = new TimeSheet(EMPLOYEE, PROFESSION, YEAR_MONTH, entries, zeroTs, zeroTs); MiLoGChecker checker = new MiLoGChecker(timeSheet); ////Execution checker.checkDayTimeBounds(); ////Expectation (on error) String error = MiLoGChecker.MiLoGCheckerErrorMessageProvider.TIME_OUTOFBOUNDS.getErrorMessage(entry.getDate()); ////Assertions if (start.compareTo(CHECKER_WORKDAY_LOWER_BOUND) < 0) { assertEquals(CheckerReturn.INVALID, checker.getResult()); assertTrue(checker.getErrors().stream().anyMatch(item -> item.getErrorMessage().equals(error))); } else { assertEquals(CheckerReturn.VALID, checker.getResult()); assertTrue(checker.getErrors().isEmpty()); } } @Test public void testOutOfBoundsRandom() { ////Random Random rand = new Random(); ////Test values TimeSpan start = new TimeSpan(rand.nextInt(CHECKER_WORKDAY_UPPER_BOUND.getHour()), 0); TimeSpan end = new TimeSpan(start.getHour() + rand.nextInt(RANDOM_HOUR_BOUND - start.getHour()), 0); TimeSpan pause = new TimeSpan(0, 0); ////Checker initialization Entry entry = new Entry("Test", LocalDate.of(2019, 11, 22), start, end, pause, false); Entry[] entries = {entry}; TimeSheet timeSheet = new TimeSheet(EMPLOYEE, PROFESSION, YEAR_MONTH, entries, zeroTs, zeroTs); MiLoGChecker checker = new MiLoGChecker(timeSheet); ////Execution checker.checkDayTimeBounds(); ////Expectation (on error) String error = MiLoGChecker.MiLoGCheckerErrorMessageProvider.TIME_OUTOFBOUNDS.getErrorMessage(entry.getDate()); ////Assertions if (start.compareTo(CHECKER_WORKDAY_LOWER_BOUND) < 0 || end.compareTo(CHECKER_WORKDAY_UPPER_BOUND) > 0) { assertEquals(CheckerReturn.INVALID, checker.getResult()); assertTrue(checker.getErrors().stream().anyMatch(item -> item.getErrorMessage().equals(error))); } else { assertEquals(CheckerReturn.VALID, checker.getResult()); assertTrue(checker.getErrors().isEmpty()); } } @Test public void testOutOfBoundsMultiple() { ////Test values TimeSpan start0 = CHECKER_WORKDAY_LOWER_BOUND.subtract(new TimeSpan(0, 1)); TimeSpan end0 = CHECKER_WORKDAY_UPPER_BOUND.subtract(new TimeSpan(1, 0)); TimeSpan pause0 = new TimeSpan(0, 0); Entry entry0 = new Entry("Test", LocalDate.of(2019, 11, 20), start0, end0, pause0, false); TimeSpan start1 = CHECKER_WORKDAY_LOWER_BOUND.add(new TimeSpan(1, 0)); TimeSpan end1 = CHECKER_WORKDAY_UPPER_BOUND.add(new TimeSpan(0, 1)); TimeSpan pause1 = new TimeSpan(0, 0); Entry entry1 = new Entry("Test", LocalDate.of(2019, 11, 22), start1, end1, pause1, false); Entry[] entries = {entry0, entry1}; TimeSheet fullDoc = new TimeSheet(EMPLOYEE, PROFESSION, YEAR_MONTH, entries, zeroTs, zeroTs); MiLoGChecker checker = new MiLoGChecker(fullDoc); ////Execution checker.checkDayTimeBounds(); ////Expectation (on error) String error0 = MiLoGChecker.MiLoGCheckerErrorMessageProvider.TIME_OUTOFBOUNDS.getErrorMessage(entry0.getDate()); String error1 = MiLoGChecker.MiLoGCheckerErrorMessageProvider.TIME_OUTOFBOUNDS.getErrorMessage(entry1.getDate()); ////Assertions assertEquals(CheckerReturn.INVALID, checker.getResult()); assertTrue(checker.getErrors().stream().anyMatch(item -> item.getErrorMessage().equals(error0))); assertTrue(checker.getErrors().stream().anyMatch(item -> item.getErrorMessage().equals(error1))); } }
mrjj/protobuf-jsonschema-validate
src/__tests__/enum alias.js
const { validateData } = require('../testsUtils'); describe('const', () => { test('enum alias - const - valid', () => expect( validateData('EnumAliasConst', 'TestEnumAlias_C') ).toBe(true)); test('enum alias - const - valid (alias)', () => expect( validateData('EnumAliasConst', 'TestEnumAlias_GAMMA') ).toBe(true)); test('enum alias - const - invalid', () => expect( validateData('EnumAliasConst', 'TestEnumAlias_ALPHA') ).toBe(false)); }); describe('defined_only', () => { test('enum alias - defined_only - valid', () => expect( validateData('EnumAliasDefined', 1) ).toBe(true)); test('enum alias - defined_only - invalid', () => expect( validateData('EnumAliasDefined', 0x7fffffff) ).toBe(false)); }); describe('in', () => { test('enum alias - in - valid', () => expect( validateData('EnumAliasIn', 'TestEnumAlias_A') ).toBe(true)); test('enum alias - in - valid (alias)', () => expect( validateData('EnumAliasIn', 'TestEnumAlias_ALPHA') ).toBe(true)); test('enum alias - in - invalid', () => expect( validateData('EnumAliasIn', 'TestEnumAlias_BETA') ).toBe(false)); }); describe('not in', () => { test('enum alias - not in - valid', () => expect( validateData('EnumAliasNotIn', 'TestEnumAlias_ALPHA') ).toBe(true)); test('enum alias - not in - invalid', () => expect( validateData('EnumAliasNotIn', 'TestEnumAlias_B') ).toBe(false)); test('enum alias - not in - invalid (alias)', () => expect( validateData('EnumAliasNotIn', 'TestEnumAlias_BETA') ).toBe(false)); });
Patrick-Luo-THR/libsbp
c/src/v4/string/null_terminated.c
<gh_stars>10-100 #include <stdint.h> #include <stdio.h> #include <string.h> #include <libsbp/internal/v4/string/null_terminated.h> #include <libsbp/internal/v4/string/sbp_string.h> #include <libsbp/internal/v4/string/sbp_strnlen.h> static const sbp_string_params_t params = { .valid = sbp_null_terminated_string_valid, .init = sbp_null_terminated_string_init, .default_output = "", // Just the NULL terminator .default_output_len = 1, .inject_missing_terminator = true, }; static void maybe_init(sbp_string_t *s, size_t maxlen) { if (!sbp_null_terminated_string_valid(s, maxlen) || s->encoded_len == 0) { sbp_null_terminated_string_init(s); } } void sbp_null_terminated_string_init(sbp_string_t *s) { memset(s, 0, sizeof(*s)); s->encoded_len = 1; } bool sbp_null_terminated_string_valid(const sbp_string_t *s, size_t maxlen) { if (s->encoded_len == 0) { return false; } size_t n = sbp_strnlen(s->data, sizeof(s->data)); if (n + 1 > maxlen) { return false; } if (n + 1 != s->encoded_len) { return false; } return s->data[n] == 0; } int sbp_null_terminated_string_strcmp(const sbp_string_t *a, const sbp_string_t *b, size_t maxlen) { return sbp_string_cmp(a, b, maxlen, &params); } size_t sbp_null_terminated_string_encoded_len(const sbp_string_t *s, size_t maxlen) { if (!sbp_null_terminated_string_valid(s, maxlen)) { return 1; } return s->encoded_len; } size_t sbp_null_terminated_string_strlen(const sbp_string_t *s, size_t maxlen) { return sbp_null_terminated_string_encoded_len(s, maxlen) - 1; } size_t sbp_null_terminated_string_space_remaining(const sbp_string_t *s, size_t maxlen) { return maxlen - sbp_null_terminated_string_encoded_len(s, maxlen); } bool sbp_null_terminated_string_set_raw(sbp_string_t *s, size_t maxlen, bool should_trunc, size_t *n_written, const char *new_buf, size_t new_buf_len) { size_t copied; size_t truncated_len = (maxlen - 1) > new_buf_len ? new_buf_len : (maxlen - 1); size_t len = should_trunc ? truncated_len : new_buf_len; if (!sbp_string_copy_to_buf(s->data, &copied, maxlen, new_buf, len)) { return false; } s->encoded_len = copied; if (n_written != NULL) { *n_written = s->encoded_len - 1; } return true; } bool sbp_null_terminated_string_set(sbp_string_t *s, size_t maxlen, bool should_trunc, size_t *n_written, const char *new_str) { return sbp_null_terminated_string_set_raw(s, maxlen, should_trunc, n_written, new_str, sbp_strnlen(new_str, maxlen)); } bool sbp_null_terminated_string_vprintf(sbp_string_t *s, size_t maxlen, bool should_trunc, size_t *n_written, const char *fmt, va_list ap) { size_t copied; if (!sbp_string_vprintf_to_buf(s->data, &copied, maxlen, should_trunc, fmt, ap)) { return false; } s->encoded_len = copied; if (n_written != NULL) { *n_written = copied - 1; } return true; } bool sbp_null_terminated_string_append(sbp_string_t *s, size_t maxlen, const char *new_str) { maybe_init(s, maxlen); size_t copied; if (!sbp_string_copy_to_buf(s->data + s->encoded_len - 1, &copied, maxlen - s->encoded_len + 1, new_str, sbp_strnlen(new_str, maxlen))) { return false; } s->encoded_len += copied - 1; return true; } bool sbp_null_terminated_string_append_vprintf(sbp_string_t *s, size_t maxlen, bool should_trunc, size_t *n_written, const char *fmt, va_list ap) { maybe_init(s, maxlen); size_t copied; if (!sbp_string_vprintf_to_buf(s->data + s->encoded_len - 1, &copied, maxlen - s->encoded_len + 1, should_trunc, fmt, ap)) { return false; } s->encoded_len += copied - 1; if (n_written != NULL) { *n_written = copied -1; } return true; } const char *sbp_null_terminated_string_get(const sbp_string_t *s, size_t maxlen) { if (!sbp_null_terminated_string_valid(s, maxlen)) { return NULL; } return s->data; } bool sbp_null_terminated_string_encode(const sbp_string_t *s, size_t maxlen, sbp_encode_ctx_t *ctx) { return sbp_string_encode(s, maxlen, ctx, &params); } bool sbp_null_terminated_string_decode(sbp_string_t *s, size_t maxlen, sbp_decode_ctx_t *ctx) { // Find out if we have a valid string. The valid unpack cases are // - A NULL is found up to maxlen into the incoming buffer // - The buffer contains less than maxlen bytes and there is a NULL // terminator in the final byte // - The buffer contains less than maxlen bytes and there is no NULL // terminator in the final byte size_t max_copy = maxlen; size_t max_buf_copy = ctx->buf_len - ctx->offset; if (max_copy > max_buf_copy) { max_copy = max_buf_copy; } size_t i; for (i = 0; i < max_copy; i++) { s->data[i] = (char)ctx->buf[ctx->offset + i]; if (s->data[i] == 0) { break; } } if (i == max_copy) { // No NULL terminator found if (i < max_buf_copy) { // the incoming buffer continues on with more data. We can't be certain we // have actually read a proper string so invalidate everything and return // an error s->data[0] = 0; s->encoded_len = 1; return false; } // Reached the end of the incoming buffer without finding a NULL. Make sure // we have a NULL in the unpacked string and call it success s->data[i] = 0; s->encoded_len = i + 1; // Append a NULL terminator ctx->offset += i; return true; } // Found a NULL terminator before the end of the incoming buffer. There must // be more data to follow so just take what we have and return success s->encoded_len = i + 1; ctx->offset += i + 1; return true; }
miathedev/BoostForArduino
src/boost_hana_fwd_remove.hpp
<reponame>miathedev/BoostForArduino #include <boost/hana/fwd/remove.hpp>
srcejon/libacars
libacars/asn1/FANSPDCrevision.h
<reponame>srcejon/libacars<gh_stars>10-100 /* * Generated by asn1c-0.9.28 (http://lionet.info/asn1c) * From ASN.1 module "FANSACTwoWayDataLinkCommunications" * found in "../../../libacars.asn1/fans-cpdlc.asn1" * `asn1c -fcompound-names -fincludes-quoted -gen-PER` */ #ifndef _FANSPDCrevision_H_ #define _FANSPDCrevision_H_ #include "asn_application.h" /* Including external dependencies */ #include "NativeInteger.h" #ifdef __cplusplus extern "C" { #endif /* FANSPDCrevision */ typedef long FANSPDCrevision_t; /* Implementation */ extern asn_TYPE_descriptor_t asn_DEF_FANSPDCrevision; asn_struct_free_f FANSPDCrevision_free; asn_struct_print_f FANSPDCrevision_print; asn_constr_check_f FANSPDCrevision_constraint; ber_type_decoder_f FANSPDCrevision_decode_ber; der_type_encoder_f FANSPDCrevision_encode_der; xer_type_decoder_f FANSPDCrevision_decode_xer; xer_type_encoder_f FANSPDCrevision_encode_xer; per_type_decoder_f FANSPDCrevision_decode_uper; per_type_encoder_f FANSPDCrevision_encode_uper; #ifdef __cplusplus } #endif #endif /* _FANSPDCrevision_H_ */ #include "asn_internal.h"
joequant/scms
NScrypt/db/migrate/20150416105111_create_reputations.rb
<reponame>joequant/scms class CreateReputations < ActiveRecord::Migration def change create_table :reputations do |t| t.belongs_to :user, index: true t.belongs_to :contract, index: true t.string :category t.string :subcategory t.string :item t.string :params t.string :status t.timestamps null: false end add_foreign_key :reputations, :users add_foreign_key :reputations, :contracts end end
matbentancur/pavlab6gr4
Guasap/include/MensajeFactory.h
<reponame>matbentancur/pavlab6gr4 #ifndef MENSAJEFACTORY_H_INCLUDED #define MENSAJEFACTORY_H_INCLUDED #include <iostream> #include "IMensajeController.h" #include "MensajeController.h" class MensajeFactory{ private: static MensajeFactory* instancia; MensajeFactory(); public: static MensajeFactory* getInstancia(); IMensajeController* getIMensajeController(); ~MensajeFactory(); }; #endif // MENSAJEFACTORY_H_INCLUDED
rbeucher/underworld2
underworld/libUnderworld/StgDomain/libStgDomain/src/Init.c
/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~* ** ** ** This file forms part of the Underworld geophysics modelling application. ** ** ** ** For full license and copyright information, please refer to the LICENSE.md file ** ** located at the project root, or contact the authors. ** ** ** **~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/ #include <mpi.h> #include <StGermain/libStGermain/src/StGermain.h> #include <StgDomain/Geometry/src/Geometry.h> #include <StgDomain/Shape/src/Shape.h> #include <StgDomain/Mesh/src/Mesh.h> #include <StgDomain/Utils/src/Utils.h> #include <StgDomain/Swarm/src/Swarm.h> #include "Init.h" #include <stdio.h> Bool StgDomain_Init( int* argc, char** argv[] ) { /* * This init function tells StGermain of all the component types, * etc this module contributes. Because it can be linked at compile * time or linked in by a toolbox at runtime, we need to make sure it isn't run twice * (compiled in and loaded through a toolbox. */ if( !ToolboxesManager_IsInitialised( stgToolboxesManager, "StgDomain" ) ) { int tmp; Stream_Flush( Journal_Register( InfoStream_Type, (Name)"Context" ) ); Stream_SetPrintingRank( Journal_Register( InfoStream_Type, (Name)"Context" ), tmp ); StgDomainGeometry_Init( argc, argv ); StgDomainShape_Init( argc, argv ); StgDomainMesh_Init( argc, argv ); StgDomainUtils_Init( argc, argv ); StgDomainSwarm_Init( argc, argv ); return True; } return False; }
Freeaqingme/ClueGetter
src/cluegetter/lua/lua.go
// ClueGetter - Does things with mail // // Copyright 2016 <NAME>, Freeaqingme. // // This Source Code Form is subject to the terms of the Apache License, Version 2.0. // For its contents, please refer to the LICENSE file. // package lua import ( "fmt" "io/ioutil" "strings" "cluegetter/core" "github.com/yuin/gopher-lua" ) const ModuleName = "lua" type module struct { *core.BaseModule modules map[string]*luaModule } func init() { core.ModuleRegister(&module{ BaseModule: core.NewBaseModule(nil), }) } func (m *module) Name() string { return ModuleName } func (m *module) Enable() bool { return true } func (m *module) Config() map[string]*core.ConfigLuaModule { return m.BaseModule.Config().LuaModule } func (m *module) Init() error { m.modules = make(map[string]*luaModule, 0) for name, conf := range m.Config() { if err := m.startModule(name, conf); err != nil { return err } } return nil } func (m *module) startModule(name string, conf *core.ConfigLuaModule) error { if conf.Script != "" && conf.ScriptContents != "" { panic("Cannot specify both Script as well as scriptContents in " + name) } else if conf.Script == "" && conf.ScriptContents == "" { panic("Either a Script or ScriptContents must be specified in " + name) } var scriptContents string if conf.Script != "" { scriptContentsBytes, err := ioutil.ReadFile(conf.Script) if err != nil { return fmt.Errorf("could not load LUA script: %s", err.Error()) } scriptContents = string(scriptContentsBytes) } else { scriptContents = conf.ScriptContents } if _, err := luaCanParse(string(scriptContents)); err != nil { return fmt.Errorf("could not parse LUA module '%s': %s", name, err.Error()) } m.Log().Infof("Registered LUA module " + name) module := &luaModule{ module: m, name: name, contents: string(scriptContents), } core.ModuleRegister(module) m.modules[name] = module return nil } type luaModule struct { *module name string contents string } func (m *luaModule) Enable() bool { return m.config().Enabled } func (m *luaModule) config() *core.ConfigLuaModule { return m.BaseModule.Config().LuaModule[m.name] } func (m *luaModule) Name() string { return "lua-" + m.name } func (m *luaModule) MessageCheck(msg *core.Message, done chan bool) *core.MessageCheckResult { L := luaGetState() if err := L.DoString(m.contents); err != nil { panic("Could not execute lua module " + m.name + ": " + err.Error()) } callback := L.GetField(L.Get(-1), "milterCheck") if callback == nil || callback.Type() == lua.LTNil { return nil } err := L.CallByParam(lua.P{ Fn: callback, NRet: 3, Protect: true, }, luaGetMessage(L, msg)) if err != nil { panic("Error in lua module '" + m.name + "': " + err.Error()) } resScore := L.Get(-1) L.Pop(1) resMsg := L.Get(-1) L.Pop(1) suggestedActionStr := L.Get(-1) L.Pop(1) var suggestedAction int32 var ok bool if suggestedAction, ok = core.Proto_Message_Verdict_value[suggestedActionStr.String()]; !ok { panic("Invalid suggested action from lua module '" + m.name + "': " + suggestedActionStr.String()) } return &core.MessageCheckResult{ Module: m.Name(), SuggestedAction: int(suggestedAction), Message: resMsg.String(), Score: float64(lua.LVAsNumber(resScore)), } } func (m *luaModule) SessionConfigure(sess *core.MilterSession) { L := luaGetState() if err := L.DoString(m.contents); err != nil { panic("Could not execute lua module " + m.name + ": " + err.Error()) } callback := L.GetField(L.Get(-1), "sessionConfigure") if callback == nil || callback.Type() == lua.LTNil { return } err := L.CallByParam(lua.P{ Fn: callback, NRet: 0, Protect: true, }, luaGetSession(L, sess)) if err != nil { panic("Error in lua module '" + m.name + "': " + err.Error()) } } func luaGetState() *lua.LState { L := lua.NewState(lua.Options{ IncludeGoStackTrace: true, }) defer L.Close() L.PreloadModule("crypto", CryptoLoader) L.PreloadModule("dns", DnsLoader) L.PreloadModule("spf", SpfLoader) luaSessionRegisterType(L) luaMessageRegisterType(L) luaMessageHeaderRegisterType(L) return L } func luaCanParse(script string) (bool, error) { L := lua.NewState() defer L.Close() _, err := L.LoadString(script) return err == nil, err } ////////////////////// ////// VM state ////// ////////////////////// /* Session */ func luaGetSession(L *lua.LState, sess *core.MilterSession) lua.LValue { ud := L.NewUserData() ud.Value = sess L.SetMetatable(ud, L.GetTypeMetatable("session")) L.Push(ud) return ud } func luaSessionRegisterType(L *lua.LState) { mt := L.NewTypeMetatable("session") L.SetGlobal("session", mt) L.SetField(mt, "__index", L.SetFuncs(L.NewTable(), luaSessionMethods)) } var luaSessionMethods = map[string]lua.LGFunction{ "config": luaSessionFuncGetSetSessionConfig, "getAS": luaSessionFuncAS, "getSaslUsername": luaSessionFuncSaslUsername, "getSaslMethod": luaSessionFuncSaslMethod, "getCertIssuer": luaSessionFuncCertIssuer, "getCertSubject": luaSessionFuncCertSubject, "getCipherBits": luaSessionFuncCipherBits, "getCipher": luaSessionFuncCipher, "getTlsVersion": luaSessionFuncTlsVersion, "getIp": luaSessionFuncIp, "getReverseDns": luaSessionFuncReverseDns, "getHostname": luaSessionFuncHostname, "getHelo": luaSessionFuncHelo, "getMtaHostName": luaSessionFuncMtaDaemonName, "getMtaDaemonName": luaSessionFuncMtaDaemonName, } func luaSessionGetFromVM(L *lua.LState) *core.MilterSession { ud := L.CheckUserData(1) if v, ok := ud.Value.(*core.MilterSession); ok { return v } L.ArgError(1, "Session expected") return nil } var sessionConfigSetters = map[string]func(*core.SessionConfig, *lua.LState){ "clamav.enabled": func(c *core.SessionConfig, L *lua.LState) { c.Clamav.Enabled = L.CheckBool(3) }, "dkim.sign": func(c *core.SessionConfig, L *lua.LState) { c.Dkim.Sign = L.CheckString(3) }, // Greylisting "greylisting.enabled": func(c *core.SessionConfig, L *lua.LState) { c.Greylisting.Enabled = L.CheckBool(3) }, "spamassassin.enabled": func(c *core.SessionConfig, L *lua.LState) { c.SpamAssassin.Enabled = L.CheckBool(3) }, } var sessionConfigGetters = map[string]func(*core.SessionConfig) lua.LValue{ "clamav.enabled": func(c *core.SessionConfig) lua.LValue { return lua.LBool(c.Clamav.Enabled) }, "dkim.sign": func(c *core.SessionConfig) lua.LValue { return lua.LString(c.Dkim.Sign) }, "greylisting.enabled": func(c *core.SessionConfig) lua.LValue { return lua.LBool(c.Greylisting.Enabled) }, "spamassassin.enabled": func(c *core.SessionConfig) lua.LValue { return lua.LBool(c.SpamAssassin.Enabled) }, } func luaSessionFuncGetSetSessionConfig(L *lua.LState) int { s := luaSessionGetFromVM(L) sconf := s.Config() key := strings.ToLower(L.CheckString(2)) setter, ok := sessionConfigSetters[key] getter, ok2 := sessionConfigGetters[key] if !ok || !ok2 { // ensure each getter also has a setter, and vice versa L.ArgError(1, "No value by name '"+key+"'") return 0 } if L.GetTop() == 3 { setter(sconf, L) return 0 } L.Push(getter(sconf)) return 1 } func luaSessionFuncAS(L *lua.LState) int { s := luaSessionGetFromVM(L) L.Push(lua.LString(s.GetIpInfo().ASN)) return 1 } func luaSessionFuncSaslUsername(L *lua.LState) int { s := luaSessionGetFromVM(L) L.Push(lua.LString(s.SaslUsername)) return 1 } func luaSessionFuncSaslMethod(L *lua.LState) int { s := luaSessionGetFromVM(L) L.Push(lua.LString(s.SaslMethod)) return 1 } func luaSessionFuncCertIssuer(L *lua.LState) int { s := luaSessionGetFromVM(L) L.Push(lua.LString(s.CertIssuer)) return 1 } func luaSessionFuncCertSubject(L *lua.LState) int { s := luaSessionGetFromVM(L) L.Push(lua.LString(s.CertSubject)) return 1 } func luaSessionFuncCipherBits(L *lua.LState) int { s := luaSessionGetFromVM(L) L.Push(lua.LString(s.CipherBits)) return 1 } func luaSessionFuncCipher(L *lua.LState) int { s := luaSessionGetFromVM(L) L.Push(lua.LString(s.Cipher)) return 1 } func luaSessionFuncTlsVersion(L *lua.LState) int { s := luaSessionGetFromVM(L) L.Push(lua.LString(s.TlsVersion)) return 1 } func luaSessionFuncIp(L *lua.LState) int { s := luaSessionGetFromVM(L) L.Push(lua.LString(s.Ip)) return 1 } func luaSessionFuncReverseDns(L *lua.LState) int { s := luaSessionGetFromVM(L) L.Push(lua.LString(s.ReverseDns)) return 1 } func luaSessionFuncHostname(L *lua.LState) int { s := luaSessionGetFromVM(L) L.Push(lua.LString(s.Hostname)) return 1 } func luaSessionFuncHelo(L *lua.LState) int { s := luaSessionGetFromVM(L) L.Push(lua.LString(s.Helo)) return 1 } func luaSessionFuncMtaHostName(L *lua.LState) int { s := luaSessionGetFromVM(L) L.Push(lua.LString(s.MtaHostName)) return 1 } func luaSessionFuncMtaDaemonName(L *lua.LState) int { s := luaSessionGetFromVM(L) L.Push(lua.LString(s.MtaDaemonName)) return 1 } /* Message */ func luaGetMessage(L *lua.LState, msg *core.Message) lua.LValue { ud := L.NewUserData() ud.Value = msg L.SetMetatable(ud, L.GetTypeMetatable("message")) L.Push(ud) return ud } func luaMessageRegisterType(L *lua.LState) { mt := L.NewTypeMetatable("message") L.SetGlobal("message", mt) L.SetField(mt, "__index", L.SetFuncs(L.NewTable(), luaMessageMethods)) } var luaMessageMethods = map[string]lua.LGFunction{ "getSession": luaMessageFuncSession, "getQueueId": luaMessageFuncQueueId, "getFrom": luaMessageFuncFrom, "getRcpt": luaMessageFuncRcpt, "getBody": luaMessageFuncBody, "getHeaders": luaMessageFuncHeaders, } func luaMessageGetFromVM(L *lua.LState) *core.Message { ud := L.CheckUserData(1) if v, ok := ud.Value.(*core.Message); ok { return v } L.ArgError(1, "Message expected") return nil } func luaMessageFuncSession(L *lua.LState) int { m := luaMessageGetFromVM(L) L.Push(luaGetSession(L, m.Session())) return 1 } func luaMessageFuncQueueId(L *lua.LState) int { p := luaMessageGetFromVM(L) L.Push(lua.LString(p.QueueId)) return 1 } func luaMessageFuncFrom(L *lua.LState) int { p := luaMessageGetFromVM(L) L.Push(lua.LString(p.From.String())) return 1 } func luaMessageFuncRcpt(L *lua.LState) int { p := luaMessageGetFromVM(L) t := L.NewTable() for _, v := range p.Rcpt { t.Append(lua.LString(v.String())) } L.Push(t) return 1 } func luaMessageFuncBody(L *lua.LState) int { p := luaMessageGetFromVM(L) L.Push(lua.LString(p.Body)) return 1 } func luaMessageFuncHeaders(L *lua.LState) int { p := luaMessageGetFromVM(L) t := L.NewTable() for k := range p.Headers { ud := L.NewUserData() ud.Value = &p.Headers[k] L.SetMetatable(ud, L.GetTypeMetatable("messageHeader")) t.Append(ud) } L.Push(t) return 1 } /* Message Header */ func luaMessageHeaderRegisterType(L *lua.LState) { mt := L.NewTypeMetatable("messageHeader") L.SetGlobal("messageHeader", mt) L.SetField(mt, "__index", L.SetFuncs(L.NewTable(), luaMessageHeaderMethods)) } var luaMessageHeaderMethods = map[string]lua.LGFunction{ "getKey": luaMessageHeaderFuncKey, "getValue": luaMessageHeaderFuncValue, } func luaMessageHeaderGetFromVM(L *lua.LState) *core.MessageHeader { ud := L.CheckUserData(1) if v, ok := ud.Value.(*core.MessageHeader); ok { return v } L.ArgError(1, "MessageHeader expected") return nil } func luaMessageHeaderFuncKey(L *lua.LState) int { p := luaMessageHeaderGetFromVM(L) L.Push(lua.LString(p.Key)) return 1 } func luaMessageHeaderFuncValue(L *lua.LState) int { p := luaMessageHeaderGetFromVM(L) L.Push(lua.LString(p.Value)) return 1 }
Ensembl/ensc-core
src/DataModel/TopLevelAssemblyMapper.h
/* * Copyright [1999-2017] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute * * 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 __TOPLEVELASSEMBLYMAPPER_H__ #define __TOPLEVELASSEMBLYMAPPER_H__ #include "BaseAssemblyMapper.h" #include "DataModelTypes.h" #include "EnsC.h" #include "Vector.h" #include "IDHash.h" #include "Mapper.h" #include "AdaptorTypes.h" #include "MapperRangeSet.h" #define MAXCHUNK 2000 BASEASSEMBLYMAPPERFUNC_TYPES(TopLevelAssemblyMapper) typedef struct TopLevelAssemblyMapperFuncsStruct { BASEASSEMBLYMAPPERFUNCS_DATA(TopLevelAssemblyMapper) } TopLevelAssemblyMapperFuncs; #define FUNCSTRUCTTYPE TopLevelAssemblyMapperFuncs struct TopLevelAssemblyMapperStruct { BASEASSEMBLYMAPPER_DATA Vector *coordSystems; CoordSystem *topLevelCs; CoordSystem *otherCs; }; #undef FUNCSTRUCTTYPE #define TopLevelAssemblyMapper_setAdaptor(tlam, ad) BaseAssemblyMapper_setAdaptor(tlam,ad) #define TopLevelAssemblyMapper_getAdaptor(tlam) BaseAssemblyMapper_getAdaptor(tlam) #define TopLevelAssemblyMapper_setTopLevelCoordSystem(tlam, tlcs) (tlam)->topLevelCs = tlcs #define TopLevelAssemblyMapper_getTopLevelCoordSystem(tlam) (tlam)->topLevelCs #define TopLevelAssemblyMapper_setOtherCoordSystem(tlam, ocs) (tlam)->otherCs = ocs #define TopLevelAssemblyMapper_getOtherCoordSystem(tlam) (tlam)->otherCs #define TopLevelAssemblyMapper_getCoordSystems(tlam) (tlam)->coordSystems #define TopLevelAssemblyMapper_getSeqRegionId(am, srName, cs) BaseAssemblyMapper_getSeqRegionId((BaseAssemblyMapper *)(am), (srName), (cs)) //IDType TopLevelAssemblyMapper_getSeqRegionId(TopLevelAssemblyMapper *tlam, char *seqRegionName, CoordSystem *cs); #define TopLevelAssemblyMapper_registerAll(am) BaseAssemblyMapper_registerAll((am)) #define TopLevelAssemblyMapper_flush(am) ((am)->funcs->flush((am))) #define TopLevelAssemblyMapper_free(am) ((am)->funcs->free((am))) #define TopLevelAssemblyMapper_map(am, fsrName, fStart, fEnd, fStrand, fCs, fFlag, slice) \ ((am)->funcs->map((am), (fsrName), (fStart), (fEnd), (fStrand), (fCs), (fFlag), (slice))) #define TopLevelAssemblyMapper_fastMap(am, fsrName, fStart, fEnd, fStrand, fCs, slice) \ ((am)->funcs->fastMap((am), (fsrName), (fStart), (fEnd), (fStrand), (fCs), (slice))) #define TopLevelAssemblyMapper_listIds(am, fsrName, fStart, fEnd, fCs) \ ((am)->funcs->listIds((am), (fsrName), (fStart), (fEnd), (fCs))) #define TopLevelAssemblyMapper_listSeqRegions(am, fsrName, fStart, fEnd, fCs) \ ((am)->funcs->listSeqRegions((am), (fsrName), (fStart), (fEnd), (fCs))) #define TopLevelAssemblyMapper_mapCoordinatesToAssembly(am, contigName, fStart, fEnd, fStrand) \ BaseAssemblyMapper_mapCoordinatesToAssembly((am), (contigName), (fStart), (fEnd), (fStrand)) #define TopLevelAssemblyMapper_fastToAssembly(am, contigName, fStart, fEnd, fStrand) \ BaseAssemblyMapper_fastToAssembly((am), (contigName), (fStart), (fEnd), (fStrand)) #define TopLevelAssemblyMapper_mapCoordinatesToRawContig(am, chrName, fStart, fEnd, fStrand) \ BaseAssemblyMapper_mapCoordinatesToRawContig((am), (chrName), (fStart), (fEnd), (fStrand)) #define TopLevelAssemblyMapper_listContigIds(am, chrName, fStart, fEnd, fStrand) \ BaseAssemblyMapper_listContigIds((am), (chrName), (fStart), (fEnd), (fStrand)) TopLevelAssemblyMapper *TopLevelAssemblyMapper_new(AssemblyMapperAdaptor *ama, CoordSystem *topLevelCs, CoordSystem *otherCs); MapperRangeSet *TopLevelAssemblyMapper_mapImpl(TopLevelAssemblyMapper *tlam, char *frmSeqRegionName, long frmStart, long frmEnd, int frmStrand, CoordSystem *frmCs, int fastMap, Slice *fakeSliceArg); void TopLevelAssemblyMapper_flushImpl(TopLevelAssemblyMapper *tlam); MapperRangeSet *TopLevelAssemblyMapper_fastMapImpl(TopLevelAssemblyMapper *tlam, char *frmSeqRegionName, long frmStart, long frmEnd, int frmStrand, CoordSystem *frmCs, Slice *fakeSliceArg); CoordSystem *TopLevelAssemblyMapper_assembledCoordSystem(TopLevelAssemblyMapper *tlam); CoordSystem *TopLevelAssemblyMapper_componentCoordSystem(TopLevelAssemblyMapper *tlam); Vector * TopLevelAssemblyMapper_list(TopLevelAssemblyMapper *tlam, char *frmSeqRegionName, long frmStart, long frmEnd, CoordSystem *frmCs, int SeqRegionsFlag); Vector *TopLevelAssemblyMapper_listSeqRegionsImpl(TopLevelAssemblyMapper *tlam, char *frmSeqRegionName, long frmStart, long frmEnd, CoordSystem *frmCs); Vector *TopLevelAssemblyMapper_listIdsImpl(TopLevelAssemblyMapper *tlam, char *frmSeqRegionName, long frmStart, long frmEnd, CoordSystem *frmCs); void TopLevelAssemblyMapper_freeImpl(TopLevelAssemblyMapper *tlam); void TopLevelAssemblyMapper_registerAllImpl(TopLevelAssemblyMapper *am); MapperRangeSet *TopLevelAssemblyMapper_mapCoordinatesToAssemblyImpl(TopLevelAssemblyMapper *am, char *contigName, long start, long end, int strand); MapperRangeSet *TopLevelAssemblyMapper_fastToAssemblyImpl(TopLevelAssemblyMapper *am, char *contigName, long start, long end, int strand); MapperRangeSet *TopLevelAssemblyMapper_mapCoordinatesToRawContigImpl(TopLevelAssemblyMapper *am, char *chrName, long start, long end, int strand); Vector *TopLevelAssemblyMapper_listContigIdsImpl(TopLevelAssemblyMapper *am, char *chrName, long start, long end, int strand); #ifdef __TOPLEVELASSEMBLYMAPPER_MAIN__ TopLevelAssemblyMapperFuncs topLevelAssemblyMapperFuncs = { TopLevelAssemblyMapper_freeImpl, // free NULL, // shallowCopy NULL, // deepCopy TopLevelAssemblyMapper_mapImpl, // map TopLevelAssemblyMapper_flushImpl, // flush TopLevelAssemblyMapper_fastMapImpl, //fastMap TopLevelAssemblyMapper_listSeqRegionsImpl, // listSeqRegions TopLevelAssemblyMapper_listIdsImpl, // listIds TopLevelAssemblyMapper_registerAllImpl, // registerAll TopLevelAssemblyMapper_mapCoordinatesToAssemblyImpl, // mapCoordinatesToAssembly TopLevelAssemblyMapper_fastToAssemblyImpl, // fastToAssembly TopLevelAssemblyMapper_mapCoordinatesToRawContigImpl, // mapCoordinatesToRawContig TopLevelAssemblyMapper_listContigIdsImpl // listContigIds }; #else extern TopLevelAssemblyMapperFuncs topLevelAssemblyMapperFuncs; #endif #endif
triffon/oop-2019-20
labs/5/Practice_13/solutions/Container.hpp
#pragma once template <typename U> class Container { public: Container() {} virtual void push(U) = 0; virtual U pop() = 0; virtual U top() = 0; virtual int size() = 0; virtual bool empty() = 0; };
skullbaselab/instructor_documents
Bootcamp-Prep-Online-master/scripts/8_assessment/w2d5/solution3/assessment.js
/****************************************************************************** ** Write a function #divisibleByFivePairSum(array), that takes an array of numbers. ** It should return an array of all the pairs of indices whose sum is a multiple of five. ** Example ** divisibleByFivePairSum([1, 5, 2, 0, 4]) => [ [ 0, 4 ], [ 1, 3 ] ] ** divisibleByFivePairSum([13, 22, 8, -3, 12]) => [[ 0, 1 ], [ 0, 3 ], [ 0, 4 ], [ 1, 2 ], [ 2, 3 ], [ 2, 4 ]] */ function divisibleByFivePairSum(array){ // your code here... var pairs = []; for (var i = 0; i < array.length; i++) { var num1 = array[i]; for (var j = i + 1; j < array.length; j++) { var num2 = array[j]; if((num1 + num2) % 5 === 0){ pairs.push([i, j]); } } } return pairs; } /****************************************************************************** ** Write a function #myIndexOf(array, ele) that takes an array and an element. ** Return the index of the element in the array, or -1 if it doesn't exist. Assume ** the `ele` will be a primitive data type (no arrays or objects) ** Example ** myIndexOf([1,2,3,4,5], 5) => 4 ** myIndexOf(["a", "b", "c"], "a") => 0 ** myIndexOf(["a", "b", "c"], "d") => -1 */ function myIndexOf(array, ele){ // your code here... for (var i = 0; i < array.length; i++) { if(array[i] === ele){ return i; } } return -1; } /****************************************************************************** ** Write a function #magicCipher(sentence, cipher) that takes in an string(sentence) ** and an object(cipher). Return a string where every character is replaced with its ** cooresponding value in the cipher. If the character doesn't exist in the ** cipher, use the character. ** Example ** magicCipher("add me on facebook" , { a : "c", d : "q"}) => "cqq me on fccebook" ** magicCipher("where are you?" , { v : "l", '?' : "!"}) => "where are you!" ** magicCipher("twmce" , { m : "n", t : "d", w : "a"}) => "dance" */ function magicCipher(sentence, cipher){ // your code here... var decoded = ""; for (var i = 0; i < sentence.length; i++) { var char = sentence[i]; var decodedChar = cipher[char] || char; decoded += decodedChar; } return decoded; } /****************************************************************************** ** Write a function `minMaxDifference(array)` that return the difference between the ** largest value and the smallest value in the array. Assume `array` is an array of ** numbers. Assume an array of at least two numbers. ** Example ** minMaxDifference([1,2,3,4,5]) => 4 ** minMaxDifference([5,4,3,2,1]) => 4 ** minMaxDifference([4,2,5,1,-5]) => 10 */ function minMaxDifference(array){ // your code here... var min = array[0]; var max = array[0]; for (var i = 0; i < array.length; i++) { var num = array[i]; if(min > num){ min = num; } else if(max < num){ max = num; } } return max - min; } /****************************************************************************** ** Write a function that #dynamicFizzBuzz(max, num1, num2) that returns an array ** of numbers up to the max. Each number should be either divisible by num1 or num2, ** BUT NOT BOTH. ** Example ** dynamicFizzBuzz(20, 5, 3) => [3, 5, 6, 9, 10, 12, 18] ** dynamicFizzBuzz(20, 4, 6) => [4, 6, 8, 16, 18] */ function dynamicFizzBuzz(max, num1, num2){ // your code here... var nums = []; for (var i = 0; i < max; i++) { if(i % num1 === 0 && i % num2 !== 0){ nums.push(i); } else if(i % num2 === 0 && i % num1 !== 0){ nums.push(i); } } return nums; } /**************DO NOT MODIFY ANYTHING UNDER THIS LINE*************************/ module.exports = { divisibleByFivePairSum : divisibleByFivePairSum, myIndexOf : myIndexOf, magicCipher : magicCipher, minMaxDifference : minMaxDifference, dynamicFizzBuzz : dynamicFizzBuzz };
pachecosamuel/Python-Exercises
beecrowd exercises/beecrowd-1115.py
<reponame>pachecosamuel/Python-Exercises while(1): par = [int(i) for i in input().split()] x = par[0] y = par[1] if x == 0 or y == 0: break if x > 0: if y > 0: print("primeiro") else: print("quarto") else: if y > 0: print("segundo") else: print("terceiro")
ejc123/geotrellis
benchmark/src/main/scala/geotrellis/benchmark/AverageResample.scala
package geotrellis.benchmark import geotrellis.raster.resample._ import com.google.caliper.Param object AverageResample extends BenchmarkRunner(classOf[AverageResample]) class AverageResample extends ResampleBenchmark { def resamp = Average }
tie/td
tg/tl_notify_peer_gen.go
// Code generated by gotdgen, DO NOT EDIT. package tg import ( "context" "errors" "fmt" "sort" "strings" "go.uber.org/multierr" "github.com/gotd/td/bin" "github.com/gotd/td/tdp" "github.com/gotd/td/tgerr" ) // No-op definition for keeping imports. var ( _ = bin.Buffer{} _ = context.Background() _ = fmt.Stringer(nil) _ = strings.Builder{} _ = errors.Is _ = multierr.AppendInto _ = sort.Ints _ = tdp.Format _ = tgerr.Error{} ) // NotifyPeer represents TL type `notifyPeer#9fd40bd8`. // Notifications generated by a certain user or group. // // See https://core.telegram.org/constructor/notifyPeer for reference. type NotifyPeer struct { // user or group Peer PeerClass } // NotifyPeerTypeID is TL type id of NotifyPeer. const NotifyPeerTypeID = 0x9fd40bd8 func (n *NotifyPeer) Zero() bool { if n == nil { return true } if !(n.Peer == nil) { return false } return true } // String implements fmt.Stringer. func (n *NotifyPeer) String() string { if n == nil { return "NotifyPeer(nil)" } type Alias NotifyPeer return fmt.Sprintf("NotifyPeer%+v", Alias(*n)) } // FillFrom fills NotifyPeer from given interface. func (n *NotifyPeer) FillFrom(from interface { GetPeer() (value PeerClass) }) { n.Peer = from.GetPeer() } // TypeID returns type id in TL schema. // // See https://core.telegram.org/mtproto/TL-tl#remarks. func (*NotifyPeer) TypeID() uint32 { return NotifyPeerTypeID } // TypeName returns name of type in TL schema. func (*NotifyPeer) TypeName() string { return "notifyPeer" } // TypeInfo returns info about TL type. func (n *NotifyPeer) TypeInfo() tdp.Type { typ := tdp.Type{ Name: "notifyPeer", ID: NotifyPeerTypeID, } if n == nil { typ.Null = true return typ } typ.Fields = []tdp.Field{ { Name: "Peer", SchemaName: "peer", }, } return typ } // Encode implements bin.Encoder. func (n *NotifyPeer) Encode(b *bin.Buffer) error { if n == nil { return fmt.Errorf("can't encode notifyPeer#9fd40bd8 as nil") } b.PutID(NotifyPeerTypeID) return n.EncodeBare(b) } // EncodeBare implements bin.BareEncoder. func (n *NotifyPeer) EncodeBare(b *bin.Buffer) error { if n == nil { return fmt.Errorf("can't encode notifyPeer#9fd40bd8 as nil") } if n.Peer == nil { return fmt.Errorf("unable to encode notifyPeer#9fd40bd8: field peer is nil") } if err := n.Peer.Encode(b); err != nil { return fmt.Errorf("unable to encode notifyPeer#9fd40bd8: field peer: %w", err) } return nil } // GetPeer returns value of Peer field. func (n *NotifyPeer) GetPeer() (value PeerClass) { return n.Peer } // Decode implements bin.Decoder. func (n *NotifyPeer) Decode(b *bin.Buffer) error { if n == nil { return fmt.Errorf("can't decode notifyPeer#9fd40bd8 to nil") } if err := b.ConsumeID(NotifyPeerTypeID); err != nil { return fmt.Errorf("unable to decode notifyPeer#9fd40bd8: %w", err) } return n.DecodeBare(b) } // DecodeBare implements bin.BareDecoder. func (n *NotifyPeer) DecodeBare(b *bin.Buffer) error { if n == nil { return fmt.Errorf("can't decode notifyPeer#9fd40bd8 to nil") } { value, err := DecodePeer(b) if err != nil { return fmt.Errorf("unable to decode notifyPeer#9fd40bd8: field peer: %w", err) } n.Peer = value } return nil } // construct implements constructor of NotifyPeerClass. func (n NotifyPeer) construct() NotifyPeerClass { return &n } // Ensuring interfaces in compile-time for NotifyPeer. var ( _ bin.Encoder = &NotifyPeer{} _ bin.Decoder = &NotifyPeer{} _ bin.BareEncoder = &NotifyPeer{} _ bin.BareDecoder = &NotifyPeer{} _ NotifyPeerClass = &NotifyPeer{} ) // NotifyUsers represents TL type `notifyUsers#b4c83b4c`. // Notifications generated by all users. // // See https://core.telegram.org/constructor/notifyUsers for reference. type NotifyUsers struct { } // NotifyUsersTypeID is TL type id of NotifyUsers. const NotifyUsersTypeID = 0xb4c83b4c func (n *NotifyUsers) Zero() bool { if n == nil { return true } return true } // String implements fmt.Stringer. func (n *NotifyUsers) String() string { if n == nil { return "NotifyUsers(nil)" } type Alias NotifyUsers return fmt.Sprintf("NotifyUsers%+v", Alias(*n)) } // TypeID returns type id in TL schema. // // See https://core.telegram.org/mtproto/TL-tl#remarks. func (*NotifyUsers) TypeID() uint32 { return NotifyUsersTypeID } // TypeName returns name of type in TL schema. func (*NotifyUsers) TypeName() string { return "notifyUsers" } // TypeInfo returns info about TL type. func (n *NotifyUsers) TypeInfo() tdp.Type { typ := tdp.Type{ Name: "notifyUsers", ID: NotifyUsersTypeID, } if n == nil { typ.Null = true return typ } typ.Fields = []tdp.Field{} return typ } // Encode implements bin.Encoder. func (n *NotifyUsers) Encode(b *bin.Buffer) error { if n == nil { return fmt.Errorf("can't encode notifyUsers#b4c83b4c as nil") } b.PutID(NotifyUsersTypeID) return n.EncodeBare(b) } // EncodeBare implements bin.BareEncoder. func (n *NotifyUsers) EncodeBare(b *bin.Buffer) error { if n == nil { return fmt.Errorf("can't encode notifyUsers#b4c83b4c as nil") } return nil } // Decode implements bin.Decoder. func (n *NotifyUsers) Decode(b *bin.Buffer) error { if n == nil { return fmt.Errorf("can't decode notifyUsers#b4c83b4c to nil") } if err := b.ConsumeID(NotifyUsersTypeID); err != nil { return fmt.Errorf("unable to decode notifyUsers#b4c83b4c: %w", err) } return n.DecodeBare(b) } // DecodeBare implements bin.BareDecoder. func (n *NotifyUsers) DecodeBare(b *bin.Buffer) error { if n == nil { return fmt.Errorf("can't decode notifyUsers#b4c83b4c to nil") } return nil } // construct implements constructor of NotifyPeerClass. func (n NotifyUsers) construct() NotifyPeerClass { return &n } // Ensuring interfaces in compile-time for NotifyUsers. var ( _ bin.Encoder = &NotifyUsers{} _ bin.Decoder = &NotifyUsers{} _ bin.BareEncoder = &NotifyUsers{} _ bin.BareDecoder = &NotifyUsers{} _ NotifyPeerClass = &NotifyUsers{} ) // NotifyChats represents TL type `notifyChats#c007cec3`. // Notifications generated by all groups. // // See https://core.telegram.org/constructor/notifyChats for reference. type NotifyChats struct { } // NotifyChatsTypeID is TL type id of NotifyChats. const NotifyChatsTypeID = 0xc007cec3 func (n *NotifyChats) Zero() bool { if n == nil { return true } return true } // String implements fmt.Stringer. func (n *NotifyChats) String() string { if n == nil { return "NotifyChats(nil)" } type Alias NotifyChats return fmt.Sprintf("NotifyChats%+v", Alias(*n)) } // TypeID returns type id in TL schema. // // See https://core.telegram.org/mtproto/TL-tl#remarks. func (*NotifyChats) TypeID() uint32 { return NotifyChatsTypeID } // TypeName returns name of type in TL schema. func (*NotifyChats) TypeName() string { return "notifyChats" } // TypeInfo returns info about TL type. func (n *NotifyChats) TypeInfo() tdp.Type { typ := tdp.Type{ Name: "notifyChats", ID: NotifyChatsTypeID, } if n == nil { typ.Null = true return typ } typ.Fields = []tdp.Field{} return typ } // Encode implements bin.Encoder. func (n *NotifyChats) Encode(b *bin.Buffer) error { if n == nil { return fmt.Errorf("can't encode notifyChats#c007cec3 as nil") } b.PutID(NotifyChatsTypeID) return n.EncodeBare(b) } // EncodeBare implements bin.BareEncoder. func (n *NotifyChats) EncodeBare(b *bin.Buffer) error { if n == nil { return fmt.Errorf("can't encode notifyChats#c007cec3 as nil") } return nil } // Decode implements bin.Decoder. func (n *NotifyChats) Decode(b *bin.Buffer) error { if n == nil { return fmt.Errorf("can't decode notifyChats#c007cec3 to nil") } if err := b.ConsumeID(NotifyChatsTypeID); err != nil { return fmt.Errorf("unable to decode notifyChats#c007cec3: %w", err) } return n.DecodeBare(b) } // DecodeBare implements bin.BareDecoder. func (n *NotifyChats) DecodeBare(b *bin.Buffer) error { if n == nil { return fmt.Errorf("can't decode notifyChats#c007cec3 to nil") } return nil } // construct implements constructor of NotifyPeerClass. func (n NotifyChats) construct() NotifyPeerClass { return &n } // Ensuring interfaces in compile-time for NotifyChats. var ( _ bin.Encoder = &NotifyChats{} _ bin.Decoder = &NotifyChats{} _ bin.BareEncoder = &NotifyChats{} _ bin.BareDecoder = &NotifyChats{} _ NotifyPeerClass = &NotifyChats{} ) // NotifyBroadcasts represents TL type `notifyBroadcasts#d612e8ef`. // Channel notification settings // // See https://core.telegram.org/constructor/notifyBroadcasts for reference. type NotifyBroadcasts struct { } // NotifyBroadcastsTypeID is TL type id of NotifyBroadcasts. const NotifyBroadcastsTypeID = 0xd612e8ef func (n *NotifyBroadcasts) Zero() bool { if n == nil { return true } return true } // String implements fmt.Stringer. func (n *NotifyBroadcasts) String() string { if n == nil { return "NotifyBroadcasts(nil)" } type Alias NotifyBroadcasts return fmt.Sprintf("NotifyBroadcasts%+v", Alias(*n)) } // TypeID returns type id in TL schema. // // See https://core.telegram.org/mtproto/TL-tl#remarks. func (*NotifyBroadcasts) TypeID() uint32 { return NotifyBroadcastsTypeID } // TypeName returns name of type in TL schema. func (*NotifyBroadcasts) TypeName() string { return "notifyBroadcasts" } // TypeInfo returns info about TL type. func (n *NotifyBroadcasts) TypeInfo() tdp.Type { typ := tdp.Type{ Name: "notifyBroadcasts", ID: NotifyBroadcastsTypeID, } if n == nil { typ.Null = true return typ } typ.Fields = []tdp.Field{} return typ } // Encode implements bin.Encoder. func (n *NotifyBroadcasts) Encode(b *bin.Buffer) error { if n == nil { return fmt.Errorf("can't encode notifyBroadcasts#d612e8ef as nil") } b.PutID(NotifyBroadcastsTypeID) return n.EncodeBare(b) } // EncodeBare implements bin.BareEncoder. func (n *NotifyBroadcasts) EncodeBare(b *bin.Buffer) error { if n == nil { return fmt.Errorf("can't encode notifyBroadcasts#d612e8ef as nil") } return nil } // Decode implements bin.Decoder. func (n *NotifyBroadcasts) Decode(b *bin.Buffer) error { if n == nil { return fmt.Errorf("can't decode notifyBroadcasts#d612e8ef to nil") } if err := b.ConsumeID(NotifyBroadcastsTypeID); err != nil { return fmt.Errorf("unable to decode notifyBroadcasts#d612e8ef: %w", err) } return n.DecodeBare(b) } // DecodeBare implements bin.BareDecoder. func (n *NotifyBroadcasts) DecodeBare(b *bin.Buffer) error { if n == nil { return fmt.Errorf("can't decode notifyBroadcasts#d612e8ef to nil") } return nil } // construct implements constructor of NotifyPeerClass. func (n NotifyBroadcasts) construct() NotifyPeerClass { return &n } // Ensuring interfaces in compile-time for NotifyBroadcasts. var ( _ bin.Encoder = &NotifyBroadcasts{} _ bin.Decoder = &NotifyBroadcasts{} _ bin.BareEncoder = &NotifyBroadcasts{} _ bin.BareDecoder = &NotifyBroadcasts{} _ NotifyPeerClass = &NotifyBroadcasts{} ) // NotifyPeerClass represents NotifyPeer generic type. // // See https://core.telegram.org/type/NotifyPeer for reference. // // Example: // g, err := tg.DecodeNotifyPeer(buf) // if err != nil { // panic(err) // } // switch v := g.(type) { // case *tg.NotifyPeer: // notifyPeer#9fd40bd8 // case *tg.NotifyUsers: // notifyUsers#b4c83b4c // case *tg.NotifyChats: // notifyChats#c007cec3 // case *tg.NotifyBroadcasts: // notifyBroadcasts#d612e8ef // default: panic(v) // } type NotifyPeerClass interface { bin.Encoder bin.Decoder bin.BareEncoder bin.BareDecoder construct() NotifyPeerClass // TypeID returns type id in TL schema. // // See https://core.telegram.org/mtproto/TL-tl#remarks. TypeID() uint32 // TypeName returns name of type in TL schema. TypeName() string // String implements fmt.Stringer. String() string // Zero returns true if current object has a zero value. Zero() bool } // DecodeNotifyPeer implements binary de-serialization for NotifyPeerClass. func DecodeNotifyPeer(buf *bin.Buffer) (NotifyPeerClass, error) { id, err := buf.PeekID() if err != nil { return nil, err } switch id { case NotifyPeerTypeID: // Decoding notifyPeer#9fd40bd8. v := NotifyPeer{} if err := v.Decode(buf); err != nil { return nil, fmt.Errorf("unable to decode NotifyPeerClass: %w", err) } return &v, nil case NotifyUsersTypeID: // Decoding notifyUsers#b4c83b4c. v := NotifyUsers{} if err := v.Decode(buf); err != nil { return nil, fmt.Errorf("unable to decode NotifyPeerClass: %w", err) } return &v, nil case NotifyChatsTypeID: // Decoding notifyChats#c007cec3. v := NotifyChats{} if err := v.Decode(buf); err != nil { return nil, fmt.Errorf("unable to decode NotifyPeerClass: %w", err) } return &v, nil case NotifyBroadcastsTypeID: // Decoding notifyBroadcasts#d612e8ef. v := NotifyBroadcasts{} if err := v.Decode(buf); err != nil { return nil, fmt.Errorf("unable to decode NotifyPeerClass: %w", err) } return &v, nil default: return nil, fmt.Errorf("unable to decode NotifyPeerClass: %w", bin.NewUnexpectedID(id)) } } // NotifyPeer boxes the NotifyPeerClass providing a helper. type NotifyPeerBox struct { NotifyPeer NotifyPeerClass } // Decode implements bin.Decoder for NotifyPeerBox. func (b *NotifyPeerBox) Decode(buf *bin.Buffer) error { if b == nil { return fmt.Errorf("unable to decode NotifyPeerBox to nil") } v, err := DecodeNotifyPeer(buf) if err != nil { return fmt.Errorf("unable to decode boxed value: %w", err) } b.NotifyPeer = v return nil } // Encode implements bin.Encode for NotifyPeerBox. func (b *NotifyPeerBox) Encode(buf *bin.Buffer) error { if b == nil || b.NotifyPeer == nil { return fmt.Errorf("unable to encode NotifyPeerClass as nil") } return b.NotifyPeer.Encode(buf) } // NotifyPeerClassArray is adapter for slice of NotifyPeerClass. type NotifyPeerClassArray []NotifyPeerClass // Sort sorts slice of NotifyPeerClass. func (s NotifyPeerClassArray) Sort(less func(a, b NotifyPeerClass) bool) NotifyPeerClassArray { sort.Slice(s, func(i, j int) bool { return less(s[i], s[j]) }) return s } // SortStable sorts slice of NotifyPeerClass. func (s NotifyPeerClassArray) SortStable(less func(a, b NotifyPeerClass) bool) NotifyPeerClassArray { sort.SliceStable(s, func(i, j int) bool { return less(s[i], s[j]) }) return s } // Retain filters in-place slice of NotifyPeerClass. func (s NotifyPeerClassArray) Retain(keep func(x NotifyPeerClass) bool) NotifyPeerClassArray { n := 0 for _, x := range s { if keep(x) { s[n] = x n++ } } s = s[:n] return s } // First returns first element of slice (if exists). func (s NotifyPeerClassArray) First() (v NotifyPeerClass, ok bool) { if len(s) < 1 { return } return s[0], true } // Last returns last element of slice (if exists). func (s NotifyPeerClassArray) Last() (v NotifyPeerClass, ok bool) { if len(s) < 1 { return } return s[len(s)-1], true } // PopFirst returns first element of slice (if exists) and deletes it. func (s *NotifyPeerClassArray) PopFirst() (v NotifyPeerClass, ok bool) { if s == nil || len(*s) < 1 { return } a := *s v = a[0] // Delete by index from SliceTricks. copy(a[0:], a[1:]) var zero NotifyPeerClass a[len(a)-1] = zero a = a[:len(a)-1] *s = a return v, true } // Pop returns last element of slice (if exists) and deletes it. func (s *NotifyPeerClassArray) Pop() (v NotifyPeerClass, ok bool) { if s == nil || len(*s) < 1 { return } a := *s v = a[len(a)-1] a = a[:len(a)-1] *s = a return v, true } // AsNotifyPeer returns copy with only NotifyPeer constructors. func (s NotifyPeerClassArray) AsNotifyPeer() (to NotifyPeerArray) { for _, elem := range s { value, ok := elem.(*NotifyPeer) if !ok { continue } to = append(to, *value) } return to } // NotifyPeerArray is adapter for slice of NotifyPeer. type NotifyPeerArray []NotifyPeer // Sort sorts slice of NotifyPeer. func (s NotifyPeerArray) Sort(less func(a, b NotifyPeer) bool) NotifyPeerArray { sort.Slice(s, func(i, j int) bool { return less(s[i], s[j]) }) return s } // SortStable sorts slice of NotifyPeer. func (s NotifyPeerArray) SortStable(less func(a, b NotifyPeer) bool) NotifyPeerArray { sort.SliceStable(s, func(i, j int) bool { return less(s[i], s[j]) }) return s } // Retain filters in-place slice of NotifyPeer. func (s NotifyPeerArray) Retain(keep func(x NotifyPeer) bool) NotifyPeerArray { n := 0 for _, x := range s { if keep(x) { s[n] = x n++ } } s = s[:n] return s } // First returns first element of slice (if exists). func (s NotifyPeerArray) First() (v NotifyPeer, ok bool) { if len(s) < 1 { return } return s[0], true } // Last returns last element of slice (if exists). func (s NotifyPeerArray) Last() (v NotifyPeer, ok bool) { if len(s) < 1 { return } return s[len(s)-1], true } // PopFirst returns first element of slice (if exists) and deletes it. func (s *NotifyPeerArray) PopFirst() (v NotifyPeer, ok bool) { if s == nil || len(*s) < 1 { return } a := *s v = a[0] // Delete by index from SliceTricks. copy(a[0:], a[1:]) var zero NotifyPeer a[len(a)-1] = zero a = a[:len(a)-1] *s = a return v, true } // Pop returns last element of slice (if exists) and deletes it. func (s *NotifyPeerArray) Pop() (v NotifyPeer, ok bool) { if s == nil || len(*s) < 1 { return } a := *s v = a[len(a)-1] a = a[:len(a)-1] *s = a return v, true }
arc03/30-DaysOfCode-March-2021
answers/VanshBaijal/Day 6/Question1.py
Candies = [int(x) for x in input("Enter the numbers with space: ").split()] extraCandies=int(input("Enter the number of extra candies: ")) Output=[ ] i=0 while(i<len(Candies)): if(Candies[i]+extraCandies>=max(Candies)): Output.append("True") else: Output.append("False") i+=1 print(Output)
ezherdeva/responsible-ai-toolbox
responsibleai/responsibleai/_tools/shared/__init__.py
# Copyright (c) Microsoft Corporation # Licensed under the MIT License. """ResponsibleAI package module."""
paulosalgado/cursos
clean-architecture-java-alura/src/test/java/tech/paulosalgado/escola/aplicacao/aluno/matricular/MatricularAlunoTest.java
package tech.paulosalgado.escola.aplicacao.aluno.matricular; import org.junit.jupiter.api.Test; import tech.paulosalgado.escola.dominio.aluno.CPF; import tech.paulosalgado.escola.infra.aluno.RepositorioDeAlunosEmMemoria; import static org.junit.jupiter.api.Assertions.assertEquals; class MatricularAlunoTest { @Test void alunoDeveriaSerPersistido() { var repositorio = new RepositorioDeAlunosEmMemoria(); var useCase = new MatricularAluno(repositorio); var alunoDTO = new MatricularAlunoDTO("Paulo", "123.456.789-00", "<EMAIL>"); useCase.executa(alunoDTO); var alunoEncontrado = repositorio.buscarPorCPF(new CPF("123.456.789-00")); assertEquals("Paulo", alunoEncontrado.getNome()); assertEquals("123.456.789-00", alunoEncontrado.getNumeroCpf()); assertEquals("<EMAIL>", alunoEncontrado.getEmail()); } }
channne/tp
src/main/java/seedu/address/model/student/Student.java
package seedu.address.model.student; import static seedu.address.commons.util.CollectionUtil.requireAllNonNull; import java.util.Collections; import java.util.HashSet; import java.util.Objects; import java.util.Set; import seedu.address.commons.core.index.Index; import seedu.address.model.lab.Lab; import seedu.address.model.lab.LabList; import seedu.address.model.tag.Tag; /** * Represents a Student in the address book. * Guarantees: details are present and not null, field values are validated, immutable. */ public class Student { // Identity fields private final Name name; private final Email email; private final GithubUsername githubUsername; private final Telegram telegram; private final StudentId studentId; private final LabList labs; // Data fields private final Set<Tag> tags = new HashSet<>(); /** * Every field must be present and not null. */ public Student(Name name, Email email, Set<Tag> tags, GithubUsername githubUsername, Telegram telegram, StudentId studentId) { requireAllNonNull(name, email, tags, githubUsername, studentId); this.name = name; this.email = email; this.tags.addAll(tags); this.githubUsername = githubUsername; this.telegram = telegram; this.studentId = studentId; this.labs = new LabList(); } public Name getName() { return name; } public Email getEmail() { return email; } public GithubUsername getGithubUsername() { return githubUsername; } public Telegram getTelegram() { return telegram; } public StudentId getStudentId() { return studentId; } public LabList getLabs() { return labs; } public void setLabs(LabList ll) { labs.setLabs(ll); } /** * Adds a Lab to the Student's {@code labs}. * The Lab must not already exist in the list. * * @param lab The Lab to add. */ public void addLab(Lab lab) { labs.add(lab); } /** * Removes the lab at the specified index from the Student's {@code labs}. * * @param index The index of the lab to be removed. */ public void removeLab(Index index) { labs.remove(index); } /** * Returns an immutable tag set, which throws {@code UnsupportedOperationException} * if modification is attempted. */ public Set<Tag> getTags() { return Collections.unmodifiableSet(tags); } /** * Returns true if both Students have the same student ID. * This defines a weaker notion of equality between two Students. */ public boolean isSameStudent(Student otherStudent) { if (otherStudent == this) { return true; } return otherStudent != null && otherStudent.getStudentId().equals(getStudentId()); } /** * Returns true if both Students have the same identity and data fields. * This defines a stronger notion of equality between two Students. */ @Override public boolean equals(Object other) { if (other == this) { return true; } if (!(other instanceof Student)) { return false; } Student otherStudent = (Student) other; return otherStudent.getName().equals(getName()) && otherStudent.getEmail().equals(getEmail()) && otherStudent.getTags().equals(getTags()) && otherStudent.getGithubUsername().equals(getGithubUsername()) && otherStudent.getTelegram().equals(getTelegram()) && otherStudent.getStudentId().equals(getStudentId()); } @Override public int hashCode() { // use this method for custom fields hashing instead of implementing your own return Objects.hash(name, email, tags, githubUsername, telegram, studentId); } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append(getName()) .append("; Email: ") .append(getEmail()) .append("; Github: ") .append(getGithubUsername()) .append("; Telegram: ") .append(getTelegram()) .append("; Student ID: ") .append(getStudentId()); Set<Tag> tags = getTags(); if (!tags.isEmpty()) { builder.append("; Tags: "); tags.forEach(builder::append); } return builder.toString(); } }
topxeq/qlang
lib/encoding/xml/xml.go
package xml import ( "encoding/xml" qlang "github.com/topxeq/qlang/spec" ) // Exports is the export table of this module. // var Exports = map[string]interface{}{ "_name": "encoding/xml", "Header": xml.Header, "HTMLAutoClose": xml.HTMLAutoClose, "HTMLEntity": xml.HTMLEntity, "escape": xml.Escape, "escapeText": xml.EscapeText, "marshal": xml.Marshal, "marshalIndent": xml.MarshalIndent, "unmarshal": xml.Unmarshal, "Escape": xml.Escape, "EscapeText": xml.EscapeText, "Marshal": xml.Marshal, "MarshalIndent": xml.MarshalIndent, "Unmarshal": xml.Unmarshal, "copyToken": xml.CopyToken, "CopyToken": xml.CopyToken, "Attr": qlang.StructOf((*xml.Attr)(nil)), "decoder": xml.NewDecoder, "newTokenDecoder": xml.NewTokenDecoder, "encoder": xml.NewEncoder, "NewDecoder": xml.NewDecoder, "NewTokenDecoder": xml.NewTokenDecoder, "NewEncoder": xml.NewEncoder, "EndElement": qlang.StructOf((*xml.EndElement)(nil)), "Name": qlang.StructOf((*xml.Name)(nil)), "ProcInst": qlang.StructOf((*xml.ProcInst)(nil)), "StartElement": qlang.StructOf((*xml.StartElement)(nil)), }
DiegoALRP/ASOR-UCM--2021-22
Examenes/Examen2019-ENE-Practico1/ejercicio3.c
<filename>Examenes/Examen2019-ENE-Practico1/ejercicio3.c #include <stdio.h> #include <string.h> #include <errno.h> //getaddrinfo #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> //getnameinfo #include <sys/socket.h> #include <netdb.h> //socket, bind, recv, send #include <sys/types.h> /* See NOTES */ #include <sys/socket.h> //time #include <time.h> //select #include <sys/time.h> #include <sys/types.h> #include <unistd.h> //read #include <unistd.h> int main(int argc, char *argv[]) { if (argc != 3) { printf("Introduce correctamente los parámetros\n"); printf("Uso: %s <dirección> <puerto>\n", argv[0]); return -1; } printf("argv[0]: %s, argv[1]: %s, argv[2]: %s\n", argv[0], argv[1], argv[2]); struct addrinfo hints; struct addrinfo *result; memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */ hints.ai_socktype = SOCK_DGRAM; /* Datagram socket */ hints.ai_flags = AI_PASSIVE; /* For wildcard IP address */ hints.ai_protocol = 0; /* Any protocol */ hints.ai_canonname = NULL; hints.ai_addr = NULL; hints.ai_next = NULL; if (getaddrinfo(argv[1], argv[2], &hints, &result) != 0) { printf("Error getaddrinfo() %d: %s\n", errno, strerror(errno)); return -1; } int socketfd = socket(result->ai_family, result->ai_socktype, result->ai_protocol); if (socketfd == -1) { printf("Error socket() %d: %s\n", errno, strerror(errno)); return -1; } if (bind(socketfd, result->ai_addr, result->ai_addrlen) == -1) { printf("Error bind() %d: %s\n", errno, strerror(errno)); close(socketfd); return -1; } freeaddrinfo(result); fd_set readfds; struct timeval tv; int retval; while (1) { FD_ZERO(&readfds); FD_SET(0, &readfds); FD_SET(socketfd, &readfds); tv.tv_sec = 10; tv.tv_usec = 0; retval = select(socketfd + 1, &readfds, NULL, NULL, &tv); if (retval == -1) { printf("Error select() %d: %s\n", errno, strerror(errno)); return -1; } else if (retval) { time_t tiempo; time(&tiempo); struct tm tiempolocal = *localtime(&tiempo); char buf_time[100]; int bytes_time = strftime(buf_time, 100, "%H:%M:%S\n", &tiempolocal); if (FD_ISSET(0, &readfds)) { printf("Lectura desde terminal\n"); char buf[100]; int bytes = read(0, buf, 100); if (bytes == -1) { printf("Error read() %d: %s\n", errno, strerror(errno)); return -1; } buf[bytes] = '\0'; printf("Se ha leido desde terminal: %s\n", buf); printf("Hora: %s\n", buf_time); } if (FD_ISSET(socketfd, &readfds)) { struct sockaddr_storage client; socklen_t client_len = sizeof(struct sockaddr_storage); char buf_rd[256]; int bytes_rd = recvfrom(socketfd, buf_rd, 256, 0, (struct sockaddr *) &client, &client_len); if (bytes_rd == -1) { printf("Error recvfrom() %d: %s\n", errno, strerror(errno)); close(socketfd); return -1; } buf_rd[bytes_rd] = '\0'; printf("El servidor ha leido: %s\n", buf_rd); char host[NI_MAXHOST]; char serv[NI_MAXSERV]; int nameInfo = getnameinfo((struct sockaddr *)&client, client_len, host, NI_MAXHOST, serv, NI_MAXSERV, NI_NUMERICHOST | NI_NUMERICSERV); if (nameInfo == -1) { printf("Error getnameinfo() %d: %s\n", errno, strerror(errno)); close(socketfd); return -1; } printf("Conexión desde Host: %s, Puerto: %s\n", host, serv); int bytes_sd = sendto(socketfd, buf_time, bytes_time, 0, (struct sockaddr *) &client, client_len); if (bytes_sd == -1) { printf("Error sendto() %d: %s\n", errno, strerror(errno)); close(socketfd); return -1; } printf("Servidor ha enviado: %s\n", buf_time); } } else { printf("Ningún dato leído en los últimos 10 segundos\n"); } } close(socketfd); return 0; }
Testiduk/gitlabhq
app/models/instance_metadata.rb
<reponame>Testiduk/gitlabhq<filename>app/models/instance_metadata.rb<gh_stars>1000+ # frozen_string_literal: true class InstanceMetadata attr_reader :version, :revision, :kas def initialize(version: Gitlab::VERSION, revision: Gitlab.revision) @version = version @revision = revision @kas = ::InstanceMetadata::Kas.new end end
Go-oG/TextureMusic
app/src/main/java/wzp/com/texturemusic/bean/ThemeBean.java
package wzp.com.texturemusic.bean; import android.os.Parcel; import android.os.Parcelable; /** * Created by Go_oG * Description:主题实体类 * on 2017/12/26. */ public class ThemeBean implements Parcelable { private Integer themeImgResId; private Integer themeIndex;//主题索引 private Integer showThemeImgResId; private Boolean isCheck; private String themeName; public Integer getThemeImgResId() { return themeImgResId; } public void setThemeImgResId(Integer themeImgResId) { this.themeImgResId = themeImgResId; } public Integer getThemeIndex() { return themeIndex; } public void setThemeIndex(Integer themeIndex) { this.themeIndex = themeIndex; } public Integer getShowThemeImgResId() { return showThemeImgResId; } public void setShowThemeImgResId(Integer showThemeImgResId) { this.showThemeImgResId = showThemeImgResId; } public Boolean getCheck() { return isCheck; } public void setCheck(Boolean check) { isCheck = check; } public String getThemeName() { return themeName; } public void setThemeName(String themeName) { this.themeName = themeName; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeValue(this.themeImgResId); dest.writeValue(this.themeIndex); dest.writeValue(this.showThemeImgResId); dest.writeValue(this.isCheck); dest.writeString(this.themeName); } public ThemeBean() { } protected ThemeBean(Parcel in) { this.themeImgResId = (Integer) in.readValue(Integer.class.getClassLoader()); this.themeIndex = (Integer) in.readValue(Integer.class.getClassLoader()); this.showThemeImgResId = (Integer) in.readValue(Integer.class.getClassLoader()); this.isCheck = (Boolean) in.readValue(Boolean.class.getClassLoader()); this.themeName = in.readString(); } public static final Parcelable.Creator<ThemeBean> CREATOR = new Parcelable.Creator<ThemeBean>() { @Override public ThemeBean createFromParcel(Parcel source) { return new ThemeBean(source); } @Override public ThemeBean[] newArray(int size) { return new ThemeBean[size]; } }; }
genomeannotation/GAG
src/cds.py
<reponame>genomeannotation/GAG #!/usr/bin/env python # coding=utf-8 import copy import src.translator as translate from src.gene_part import * class CDS(GenePart): def __init__(self, identifier=None, indices=None, score=None, phase=None, strand=None, parent_id=None, name=None): super(CDS, self).__init__(feature_type='CDS', identifier=identifier, indices=indices, score=score, strand=strand, parent_id=parent_id, name=name) self.phase = [] if phase is not None: self.phase.append(phase) def get_phase(self, i): """Returns phase for given segment of CDS.""" if i < 0: if self.phase and len(self.phase) > abs(i) - 1: return self.phase[i] else: return "." else: if self.phase and len(self.phase) > i: return self.phase[i] else: return "." def add_phase(self, ph): """Appends phase to CDS""" self.phase.append(ph) def get_start_indices(self, strand): """Returns coordinates of first and third base of CDS.""" if strand == '+': first_index = self.indices[0][0] return [first_index, first_index + 2] elif strand == '-': # Quick fix, applies get_stop_indices for - strand last_index_pair = self.indices[len(self.indices) - 1] last_index = last_index_pair[1] return [last_index - 2, last_index] def get_stop_indices(self, strand): """Returns coordinates of third-to-last and last base of CDS.""" if strand == '+': last_index_pair = self.indices[len(self.indices) - 1] last_index = last_index_pair[1] return [last_index - 2, last_index] elif strand == '-': # Quick fix, applies get_start_indices for - strand first_index = self.indices[0][0] return [first_index, first_index + 2] def sort_attributes(self): """Sorts indices, keeping identifiers and phases with their corresponding index pair. If CDS contains 'scores' they are kept sorted, too. """ sort_scores = False length = len(self.indices) if length != len(self.identifier) or length != len(self.phase): return if length == len(self.score): sort_scores = True # Build a list of lists where each entry is # composed of attributes all_attributes = [] for i in xrange(length): all_attributes.append([self.indices[i][0], self.indices[i][1], self.identifier[i], self.phase[i]]) if sort_scores: all_attributes[i].append(self.score[i]) # Sort that list (by first index in each index_pair) all_attributes.sort() # Repopulate the attributes for i in xrange(length): self.indices[i] = [all_attributes[i][0], all_attributes[i][1]] self.identifier[i] = all_attributes[i][2] self.phase[i] = all_attributes[i][3] if sort_scores: self.score[i] = all_attributes[i][4] def extract_sequence(self, seq_object, strand): """Returns nucleotide sequence corresponding to CDS. Args: seq_object: the actual Sequence containing the CDS. I know, I know. strand: either '+' or '-' Returns: a string of nucleotides (or an empty string if strand is invalid or CDS has no indices) """ seq = '' for i in xrange(len(self.indices)): index_pair = self.indices[i] subseq = seq_object.get_subseq(index_pair[0], index_pair[1]) if subseq: seq += subseq if strand == '-': seq = translate.reverse_complement(seq) return seq def to_tbl(self, has_start, has_stop): """Returns a string containing the .tbl-formatted entry for the CDS.""" indices = copy.deepcopy(self.indices) if self.strand == '+': phase = self.phase[0] else: phase = self.phase[-1] return write_tbl_entry(indices, self.strand, has_start, has_stop, "CDS", phase)
tiepvupsu/tabml
tabml/experiment_manager.py
import datetime import re import shutil from pathlib import Path from typing import Union from tabml.config_helpers import parse_pipeline_config class ExperimentManger: """Class managing folder structure of an experiment. For each experiment, there will be one run_dir under exp_root_dir that contains all related information about the run, e.g. run log, config file, submission csv file, trained model, and a model_analysis folder. Attributes: exp_root_dir: root directory of all experiments. run_prefix: prefix of the run name subfolder inside exp_root_dir. run_dir: run dir name (run_prefix + timestamp). """ log_filename = "run.log" config_filename = "config.yaml" _model_analysis_dir = "model_analysis" def __init__( self, path_to_config: str, should_create_new_run_dir: bool = True, exp_root_dir: Path = Path("./experiments"), custom_run_dir: Union[None, Path] = None, ): """ Args: path_to_config: path to pipeline config file. should_create_new_run_dir: create new experiment subfolder (True) or not (False). If not, set the experiment subfolder to the most recent run. run_prefix: prefix of the run name subfolder inside exp_root_dir run_dir: run dir name (exp_root_dir/run_prefix + timestamp) custom_run_dir: custom run dir that user can specify """ self._path_to_config = path_to_config self._config = parse_pipeline_config(self._path_to_config) self.exp_root_dir = exp_root_dir self.run_prefix = self._config.config_name + "_" self.custom_run_dir = custom_run_dir if not custom_run_dir or not custom_run_dir.name: self.run_dir = self._get_run_dir(should_create_new_run_dir) else: self.run_dir = custom_run_dir def _get_run_dir(self, should_create_new_run_dir): if not should_create_new_run_dir: return self.get_most_recent_run_dir() return self.exp_root_dir.joinpath(self.run_prefix + _get_time_stamp()) def create_new_run_dir(self): _make_dir_if_needed(self.run_dir) self._copy_config_file() def _copy_config_file(self): shutil.copyfile(self._path_to_config, self.get_config_path()) def get_log_path(self): return self._make_path_under_run_dir(self.log_filename) def get_config_path(self): return self._make_path_under_run_dir(self.config_filename) def get_model_analysis_dir(self): res = self._make_path_under_run_dir(self._model_analysis_dir) _make_dir_if_needed(res) return res def _make_path_under_run_dir(self, sub_path: str) -> str: return self.run_dir.joinpath(sub_path) def get_most_recent_run_dir(self): """Returns the run_dir corresponding to the most recent timestamp. Raises: IOError if there is no such folder """ if self.custom_run_dir: ValueError("get_most_recent_run_dir does not support custom run dir") subfolders = sorted( [ sub for sub in self.exp_root_dir.iterdir() if sub.is_dir() and sub.name.startswith(self.run_prefix) and bool(re.match("[0-9]{6}_[0-9]{6}", sub.name[-13:])) ], key=lambda x: x.name[-13:], # YYmmDD_HHMMSS ) if not subfolders: raise IOError( "Could not find any run directory starting with " f"{self.exp_root_dir.joinpath(self.run_prefix)}" ) return subfolders[-1] @classmethod def get_config_path_from_model_path(cls, model_path: str) -> str: run_dir = Path(model_path).parents[0] return str(run_dir / cls.config_filename) def _make_dir_if_needed(dir_path: str): if not Path(dir_path).exists(): Path(dir_path).mkdir(parents=True) def _get_time_stamp() -> str: """Returns a time stamp string in format 'YYmmdd_HHMMSS'. Example: 200907_123344. """ return datetime.datetime.now().strftime("%Y%m%d_%H%M%S")[2:]
benwerd/unlock
unlock-app/src/components/creator/lock/AppStore.js
<gh_stars>1-10 import PropTypes from 'prop-types' import React from 'react' import styled from 'styled-components' import UnlockPropTypes from '../../../propTypes' import Svg from '../../interface/svg' import Button from '../../interface/buttons/Button' const Integration = ({ name, icon, href }) => ( <App> <Button href={href} target={href ? '_blank' : null} size="40px" borderRadius="3px" label={name} > {icon} </Button> </App> ) Integration.propTypes = { name: PropTypes.string.isRequired, icon: PropTypes.element.isRequired, href: PropTypes.string, } Integration.defaultProps = { href: null, } export class AppStore extends React.Component { constructor(props, context) { super(props, context) this.integrations = { adfree: { name: 'Ad-Free Experience', icon: <Svg.Adfree />, href: 'https://docs.unlock-protocol.com/tutorials/ad-free-experience', }, tickets: { name: 'Tickets', icon: <Svg.Ticket />, href: 'https://docs.unlock-protocol.com/tutorials/selling-tickets-for-an-event', }, donations: { name: 'Donations', icon: <Svg.Heart />, href: 'https://docs.unlock-protocol.com/tutorials/receiving-donations-on-github', }, newsletter: { name: 'Newsletter', icon: <Svg.Newsletter />, href: 'https://docs.unlock-protocol.com/tutorials/using-unlock-newsletter', }, wordpress: { name: 'Wordpress', icon: <Svg.Wordpress />, href: 'https://wordpress.org/plugins/unlock-protocol/', }, } } render() { const { lock } = this.props return ( <Wrapper> <DetailTitle>Integrate</DetailTitle> <Apps> {Object.keys(this.integrations).map(index => { const integration = this.integrations[index] return ( <Integration key={index} name={integration.name} icon={integration.icon} href={integration.href} /> ) })} </Apps> <Details> <DetailTitle>Custom Integration</DetailTitle> <DetailBlock> <p> Easily integrate Unlock into your application flow with a few lines of code. We’ve structured it in a way to make it incredibly flexible yet light weight. </p> <ExtraLink> <Button backgroundColor="white" borderRadius="3px" size="64px" fillColor="var(--grey)" href="https://docs.unlock-protocol.com/" target="_blank" > <Svg.Documentation /> </Button> <Label>Documentation</Label> </ExtraLink> <ExtraLink> <Button href={`/demo?lock=${lock.address}`} target="_blank" backgroundColor="white" borderRadius="3px" size="64px" fillColor="var(--grey)" > <Svg.LiveDemo /> </Button> <Label>Live Demo</Label> </ExtraLink> </DetailBlock> </Details> </Wrapper> ) } } AppStore.propTypes = { lock: UnlockPropTypes.lock.isRequired, } export default AppStore const Wrapper = styled.section` padding-top: 20px; padding-left: 50px; padding-bottom: 50px; ` const Apps = styled.ul` display: flex; width: 100%; margin: 0px; margin-top: 8px; padding: 0px; height: 75px; ` const App = styled.li` display: inline-block; margin-right: 15px; font-size: 15px; font-weight: normal; ` const Details = styled.div` display: block; font-family: IBM Plex Sans; border-top: 1px solid var(--lightgrey); ` const DetailTitle = styled.h3` color: var(--blue); margin-bottom: 0px; margin-top: 8px; ` const DetailBlock = styled.div` display: flex; p { max-width: 400px; margin-right: 10px; margin-top: 8px; } ` const ExtraLink = styled.div` width: 96px; text-align: center; ` const Label = styled.div` font-family: IBM Plex Mono; font-weight: 100; font-size: 8px; line-height: 10px; text-transform: uppercase; letter-spacing: 1px; text-align: center; `
petewill/home-assistant
homeassistant/components/zha/core/channels/homeautomation.py
<gh_stars>1-10 """ Home automation channels module for Zigbee Home Automation. For more details about this component, please refer to the documentation at https://home-assistant.io/components/zha/ """ import logging import zigpy.zcl.clusters.homeautomation as homeautomation from homeassistant.helpers.dispatcher import async_dispatcher_send from . import AttributeListeningChannel, ZigbeeChannel from .. import registries from ..const import ( CHANNEL_ELECTRICAL_MEASUREMENT, REPORT_CONFIG_DEFAULT, SIGNAL_ATTR_UPDATED, ) _LOGGER = logging.getLogger(__name__) @registries.ZIGBEE_CHANNEL_REGISTRY.register( homeautomation.ApplianceEventAlerts.cluster_id ) class ApplianceEventAlerts(ZigbeeChannel): """Appliance Event Alerts channel.""" pass @registries.ZIGBEE_CHANNEL_REGISTRY.register( homeautomation.ApplianceIdentification.cluster_id ) class ApplianceIdentification(ZigbeeChannel): """Appliance Identification channel.""" pass @registries.ZIGBEE_CHANNEL_REGISTRY.register( homeautomation.ApplianceStatistics.cluster_id ) class ApplianceStatistics(ZigbeeChannel): """Appliance Statistics channel.""" pass @registries.ZIGBEE_CHANNEL_REGISTRY.register(homeautomation.Diagnostic.cluster_id) class Diagnostic(ZigbeeChannel): """Diagnostic channel.""" pass @registries.ZIGBEE_CHANNEL_REGISTRY.register( homeautomation.ElectricalMeasurement.cluster_id ) class ElectricalMeasurementChannel(AttributeListeningChannel): """Channel that polls active power level.""" CHANNEL_NAME = CHANNEL_ELECTRICAL_MEASUREMENT REPORT_CONFIG = ({"attr": "active_power", "config": REPORT_CONFIG_DEFAULT},) async def async_update(self): """Retrieve latest state.""" self.debug("async_update") # This is a polling channel. Don't allow cache. result = await self.get_attribute_value("active_power", from_cache=False) async_dispatcher_send( self._zha_device.hass, f"{self.unique_id}_{SIGNAL_ATTR_UPDATED}", result ) async def async_initialize(self, from_cache): """Initialize channel.""" await self.get_attribute_value("active_power", from_cache=from_cache) await super().async_initialize(from_cache) @registries.ZIGBEE_CHANNEL_REGISTRY.register( homeautomation.MeterIdentification.cluster_id ) class MeterIdentification(ZigbeeChannel): """Metering Identification channel.""" pass
JumpStartGeorgia/Georgian-Budget-API
app/view_models/csv_excel_converter.rb
class CsvExcelConverter def initialize end def convert_csv(csv_filepath, output_path) require 'spreadsheet' book = Spreadsheet::Workbook.new sheet1 = book.create_worksheet header_format = Spreadsheet::Format.new( :weight => :bold, :horizontal_align => :center, :locked => true ) sheet1.row(0).default_format = header_format require 'csv' CSV.open(csv_filepath, 'r') do |csv| csv.each_with_index do |row, i| sheet1.row(i).replace(row) end end book.write(output_path) return output_path end end
kingname/SourceCodeOfBook
第9章/program/generate_token.py
<gh_stars>100-1000 from selenium import webdriver import time service_args = ["--proxy=127.0.0.1:8080", '--ignore-ssl-errors=yes'] def run(): print('start to Token') driver = webdriver.PhantomJS(service_args=service_args) driver.get('http://xxxx') time.sleep(5) driver.close() if __name__ == '__main__': run()
ampcpmgp/anki-pan
src/components/parts/Modal/Settings.stories.js
import { withKnobs, text } from '@storybook/addon-knobs' import Settings from './Settings.svelte' export default { title: 'Modal/Settings', component: Settings, decorators: [withKnobs], } export const Main = () => ({ Component: Settings, props: { userId: text('userId', 'dummy-id'), }, on: { click: console.info, }, })
EvilMog99/MOGEngine
src/modComponents/GameEntity.java
package modComponents; import java.io.Serializable; import java.util.Random; import gameRunner.Dimension; import gameRunner.GameData; public class GameEntity implements Serializable { //for all entity types private int entitysModID; private int entityID_inMod; private int entityMatterValue = 0; private float fillValue = 0;//100% private int entity_textureNo; private int entity_variationNo; private int entity_animationNo; private String entityNickName; private int entitySpawnType; private float positionX; private float positionY; private float velocityX; private float velocityY; private boolean hasCollisions; private boolean isLiquid; private float entityCurrentHealth = 1f; private float entityMaxHealth = 1f; private Random rnd; //for creatures private int currentDimensionID; //for blocks // private int[] entityInventory_inputSlots; // private int[] entityInventory_outputSlots; // private int[] entityInventory_progressRightArrows; // private int[] entityInventory_energyBars; // private int[] entityInventory_dangerBars; public GameEntity(int entitysModID, int entityID_inMod, int entityMatterValue, int entity_textureNo, int entity_variationNo, int entity_animationNo, String entityNickName, float positionX, float positionY, float entityCurrentHealth, float entityMaxHealth, int currentDimensionID, Random rnd, boolean hasCollisions) { super(); this.entitysModID = entitysModID; this.entityID_inMod = entityID_inMod; this.entityMatterValue = entityMatterValue; this.entity_textureNo = entity_textureNo; this.entity_variationNo = entity_variationNo; this.entity_animationNo = entity_animationNo; this.entityNickName = entityNickName; this.positionX = positionX; this.positionY = positionY; this.entityCurrentHealth = entityCurrentHealth; this.entityMaxHealth = entityMaxHealth; this.currentDimensionID = currentDimensionID; this.rnd = rnd; entitySpawnType = SpawnType.NoSpawn; this.fillValue = 0; this.hasCollisions = hasCollisions; } public void setEntityID(int modIndex, Mod mod, Dimension wld, GameEntityData ged, int spawnType) { setEntityID(modIndex, ged.getEntityIndex(), mod, wld, ged.getMatterValue() , ged.getEntityMaxHealth(), ged.getUploadedTextures().length, ged.getEntityPriority(), spawnType); } public void setEntityID(int modID, int EntityID, Mod mod, Dimension wld , int matterValue, int entityMaxHealth , int maxTexturesLength, int entityPriority , int entitySpawnType) { wld.allFastActiveBlocks.remove(this); wld.allMediumActiveBlocks.remove(this); wld.allSlowActiveBlocks.remove(this); this.entitysModID = modID; this.entityID_inMod = EntityID; this.entityMatterValue = matterValue; this.entityMaxHealth = entityMaxHealth; this.entityCurrentHealth = entityMaxHealth; this.entitySpawnType = entitySpawnType; entity_animationNo = 0; entity_variationNo = 0; entity_textureNo = 0; if (entityID_inMod > -1) { entity_textureNo = rnd.nextInt(maxTexturesLength); } else { entity_textureNo = 0; } if (mod != null) { this.fillValue = GameData.calculateFillValue(mod.getAllEntityData()[entityID_inMod].getSpawnTypeID()); GameData.setEntityCollisions(this, mod.getAllEntityData()[entityID_inMod].getSpawnTypeID());//with natural mod based spawn type } else { this.fillValue = 0f; GameData.setEntityCollisions(this, entitySpawnType);//with its own set spawn type } if (entityID_inMod > -1 && entityPriority != 0)//if this block is important to process { switch (entityPriority) { case 3://fast wld.allFastActiveBlocks.add(this); break; case 2://medium wld.allMediumActiveBlocks.add(this); System.out.println("add medium"); break; case 1://slow wld.allSlowActiveBlocks.add(this); break; default: } } } public void addToEntityCurrentHealth(float add) { if (entityCurrentHealth + add > entityMaxHealth) { entityCurrentHealth = entityMaxHealth; } else { entityCurrentHealth += add; } } public void removeFromEntityCurrentHealth(float minus) { if (entityCurrentHealth - minus < 0) { entityCurrentHealth = 0; } else { entityCurrentHealth -= minus; } } //all getters and setters public int getEntitysModID() { return entitysModID; } public void setEntitysModID(int entitysModID) { this.entitysModID = entitysModID; } public int getEntityID_inMod() { return entityID_inMod; } public void setEntityID_inMod(int entityID_inMod) { this.entityID_inMod = entityID_inMod; } public int getEntityMatterValue() { return entityMatterValue; } public void setEntityMatterValue(int entityMatterValue) { this.entityMatterValue = entityMatterValue; } public int getEntity_textureNo() { return entity_textureNo; } public void setEntity_textureNo(int entity_textureNo) { this.entity_textureNo = entity_textureNo; } public int getEntity_variationNo() { return entity_variationNo; } public void setEntity_variationNo(int entity_variationNo) { this.entity_variationNo = entity_variationNo; } public int getEntity_animationNo() { return entity_animationNo; } public void setEntity_animationNo(int entity_animationNo) { this.entity_animationNo = entity_animationNo; } public String getEntityNickName() { return entityNickName; } public void setEntityNickName(String entityNickName) { this.entityNickName = entityNickName; } public float getPositionX() { return positionX; } public void setPositionX(float positionX) { this.positionX = positionX; } public float getPositionY() { return positionY; } public void setPositionY(float positionY) { this.positionY = positionY; } public float getVelocityX() { return velocityX; } public void setVelocityX(float velocityX) { this.velocityX = velocityX; } public float getVelocityY() { return velocityY; } public void setVelocityY(float velocityY) { this.velocityY = velocityY; } public void updateVelocityY(float gravity) { this.velocityY += gravity; if (this.velocityY < GameData.playerMaxFallSpeed_horizontal) { this.velocityY = GameData.playerMaxFallSpeed_horizontal; } //minusing minus values else if (this.velocityY > -GameData.playerMaxFallSpeed_horizontal) { this.velocityY = -GameData.playerMaxFallSpeed_horizontal; } } public void updateVelocityX(float force) { System.out.println("up0 X: " + this.velocityX + " force: " + force); this.velocityX += force; System.out.println("up1 X: " + this.velocityX); if (this.velocityX > GameData.playerMaxWalkSpeed_verticle) { this.velocityX = GameData.playerMaxWalkSpeed_verticle; System.out.println("up2 X: " + this.velocityX); } else if (this.velocityX < -GameData.playerMaxWalkSpeed_verticle) { this.velocityX = -GameData.playerMaxWalkSpeed_verticle; System.out.println("up3 X: " + this.velocityX); } } public int getCurrentDimensionID() { return currentDimensionID; } public void setCurrentDimensionID(int currentDimensionID) { this.currentDimensionID = currentDimensionID; } public float getEntityCurrentHealth() { return entityCurrentHealth; } public void setEntityCurrentHealth(float entityCurrentHealth) { this.entityCurrentHealth = entityCurrentHealth; } public float getEntityMaxHealth() { return entityMaxHealth; } public void setEntityMaxHealth(float entityMaxHealth) { this.entityMaxHealth = entityMaxHealth; } public int getEntitySpawnType() { return entitySpawnType; } public float getFillValue() { return fillValue; } public void setFillValue(float fillValue) { this.fillValue = fillValue; } public boolean isHasCollisions() { return hasCollisions; } public void setHasCollisions(boolean hasCollisions) { this.hasCollisions = hasCollisions; } public boolean isLiquid() { return isLiquid; } public void setLiquid(boolean isLiquid) { this.isLiquid = isLiquid; } }
swj0418/Java_Course_Project
Statistical_Analysis/GUISource/portfolioFramework/PortfolioManagerFrame_Mother.java
<filename>Statistical_Analysis/GUISource/portfolioFramework/PortfolioManagerFrame_Mother.java package portfolioFramework; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JInternalFrame; import gray.Global; public class PortfolioManagerFrame_Mother extends JInternalFrame{ PortfolioManagerPanel_Mother motherpanel; public PortfolioManagerFrame_Mother() { super("Portfolio Manager", true, true, true, true); renderFrame(); } public void renderFrame() { motherpanel = new PortfolioManagerPanel_Mother(); setSize(500, 500); setLocation(300, 300); add(motherpanel); validate(); repaint(); setVisible(true); } }
Fimbure/icebox-1
third_party/virtualbox/src/VBox/Additions/x11/x11include/xorg-server-1.14.0/xkbsrv.h
/************************************************************ Copyright (c) 1993 by Silicon Graphics Computer Systems, Inc. Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Silicon Graphics not be used in advertising or publicity pertaining to distribution of the software without specific prior written permission. Silicon Graphics makes no representation about the suitability of this software for any purpose. It is provided "as is" without any express or implied warranty. SILICON GRAPHICS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON GRAPHICS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ********************************************************/ #ifndef _XKBSRV_H_ #define _XKBSRV_H_ #define XkbAllocClientMap SrvXkbAllocClientMap #define XkbAllocServerMap SrvXkbAllocServerMap #define XkbChangeTypesOfKey SrvXkbChangeTypesOfKey #define XkbCopyKeyTypes SrvXkbCopyKeyTypes #define XkbFreeClientMap SrvXkbFreeClientMap #define XkbFreeServerMap SrvXkbFreeServerMap #define XkbKeyTypesForCoreSymbols SrvXkbKeyTypesForCoreSymbols #define XkbApplyCompatMapToKey SrvXkbApplyCompatMapToKey #define XkbResizeKeyActions SrvXkbResizeKeyActions #define XkbResizeKeySyms SrvXkbResizeKeySyms #define XkbResizeKeyType SrvXkbResizeKeyType #define XkbAllocCompatMap SrvXkbAllocCompatMap #define XkbAllocControls SrvXkbAllocControls #define XkbAllocIndicatorMaps SrvXkbAllocIndicatorMaps #define XkbAllocKeyboard SrvXkbAllocKeyboard #define XkbAllocNames SrvXkbAllocNames #define XkbFreeCompatMap SrvXkbFreeCompatMap #define XkbFreeKeyboard SrvXkbFreeKeyboard #define XkbFreeNames SrvXkbFreeNames #define XkbLatchModifiers SrvXkbLatchModifiers #define XkbLatchGroup SrvXkbLatchGroup #define XkbVirtualModsToReal SrvXkbVirtualModsToReal #define XkbChangeKeycodeRange SrvXkbChangeKeycodeRange #define XkbApplyVirtualModChanges SrvXkbApplyVirtualModChanges #include <X11/extensions/XKBproto.h> #include "xkbstr.h" #include "xkbrules.h" #include "inputstr.h" #include "events.h" typedef struct _XkbInterest { DeviceIntPtr dev; ClientPtr client; XID resource; struct _XkbInterest *next; CARD16 extDevNotifyMask; CARD16 stateNotifyMask; CARD16 namesNotifyMask; CARD32 ctrlsNotifyMask; CARD8 compatNotifyMask; BOOL bellNotifyMask; BOOL actionMessageMask; CARD16 accessXNotifyMask; CARD32 iStateNotifyMask; CARD32 iMapNotifyMask; CARD16 altSymsNotifyMask; CARD32 autoCtrls; CARD32 autoCtrlValues; } XkbInterestRec, *XkbInterestPtr; typedef struct _XkbRadioGroup { CARD8 flags; CARD8 nMembers; CARD8 dfltDown; CARD8 currentDown; CARD8 members[XkbRGMaxMembers]; } XkbRadioGroupRec, *XkbRadioGroupPtr; typedef struct _XkbEventCause { CARD8 kc; CARD8 event; CARD8 mjr; CARD8 mnr; ClientPtr client; } XkbEventCauseRec, *XkbEventCausePtr; #define XkbSetCauseKey(c,k,e) { (c)->kc= (k),(c)->event= (e),\ (c)->mjr= (c)->mnr= 0; \ (c)->client= NULL; } #define XkbSetCauseReq(c,j,n,cl) { (c)->kc= (c)->event= 0,\ (c)->mjr= (j),(c)->mnr= (n);\ (c)->client= (cl); } #define XkbSetCauseCoreReq(c,e,cl) XkbSetCauseReq(c,e,0,cl) #define XkbSetCauseXkbReq(c,e,cl) XkbSetCauseReq(c,XkbReqCode,e,cl) #define XkbSetCauseUnknown(c) XkbSetCauseKey(c,0,0) #define _OFF_TIMER 0 #define _KRG_WARN_TIMER 1 #define _KRG_TIMER 2 #define _SK_TIMEOUT_TIMER 3 #define _ALL_TIMEOUT_TIMER 4 #define _BEEP_NONE 0 #define _BEEP_FEATURE_ON 1 #define _BEEP_FEATURE_OFF 2 #define _BEEP_FEATURE_CHANGE 3 #define _BEEP_SLOW_WARN 4 #define _BEEP_SLOW_PRESS 5 #define _BEEP_SLOW_ACCEPT 6 #define _BEEP_SLOW_REJECT 7 #define _BEEP_SLOW_RELEASE 8 #define _BEEP_STICKY_LATCH 9 #define _BEEP_STICKY_LOCK 10 #define _BEEP_STICKY_UNLOCK 11 #define _BEEP_LED_ON 12 #define _BEEP_LED_OFF 13 #define _BEEP_LED_CHANGE 14 #define _BEEP_BOUNCE_REJECT 15 typedef struct _XkbFilter { CARD16 keycode; CARD8 what; CARD8 active; CARD8 filterOthers; CARD32 priv; XkbAction upAction; int (*filter) (struct _XkbSrvInfo * /* xkbi */ , struct _XkbFilter * /* filter */ , unsigned /* keycode */ , XkbAction * /* action */ ); struct _XkbFilter *next; } XkbFilterRec, *XkbFilterPtr; typedef struct _XkbSrvInfo { XkbStateRec prev_state; XkbStateRec state; XkbDescPtr desc; DeviceIntPtr device; KbdCtrlProcPtr kbdProc; XkbRadioGroupPtr radioGroups; CARD8 nRadioGroups; CARD8 clearMods; CARD8 setMods; INT16 groupChange; CARD16 dfltPtrDelta; double mouseKeysCurve; double mouseKeysCurveFactor; INT16 mouseKeysDX; INT16 mouseKeysDY; CARD8 mouseKeysFlags; Bool mouseKeysAccel; CARD8 mouseKeysCounter; CARD8 lockedPtrButtons; CARD8 shiftKeyCount; KeyCode mouseKey; KeyCode inactiveKey; KeyCode slowKey; KeyCode slowKeyEnableKey; KeyCode repeatKey; CARD8 krgTimerActive; CARD8 beepType; CARD8 beepCount; CARD32 flags; CARD32 lastPtrEventTime; CARD32 lastShiftEventTime; OsTimerPtr beepTimer; OsTimerPtr mouseKeyTimer; OsTimerPtr slowKeysTimer; OsTimerPtr bounceKeysTimer; OsTimerPtr repeatKeyTimer; OsTimerPtr krgTimer; int szFilters; XkbFilterPtr filters; } XkbSrvInfoRec, *XkbSrvInfoPtr; #define XkbSLI_IsDefault (1L<<0) #define XkbSLI_HasOwnState (1L<<1) typedef struct _XkbSrvLedInfo { CARD16 flags; CARD16 class; CARD16 id; union { KbdFeedbackPtr kf; LedFeedbackPtr lf; } fb; CARD32 physIndicators; CARD32 autoState; CARD32 explicitState; CARD32 effectiveState; CARD32 mapsPresent; CARD32 namesPresent; XkbIndicatorMapPtr maps; Atom *names; CARD32 usesBase; CARD32 usesLatched; CARD32 usesLocked; CARD32 usesEffective; CARD32 usesCompat; CARD32 usesControls; CARD32 usedComponents; } XkbSrvLedInfoRec, *XkbSrvLedInfoPtr; /* * Settings for xkbClientFlags field (used by DIX) * These flags _must_ not overlap with XkbPCF_* */ #define _XkbClientInitialized (1<<15) #define _XkbWantsDetectableAutoRepeat(c)\ ((c)->xkbClientFlags&XkbPCF_DetectableAutoRepeatMask) /* * Settings for flags field */ #define _XkbStateNotifyInProgress (1<<0) typedef struct { ProcessInputProc processInputProc; /* If processInputProc is set to something different than realInputProc, * UNWRAP and COND_WRAP will not touch processInputProc and update only * realInputProc. This ensures that * processInputProc == (frozen ? EnqueueEvent : realInputProc) * * WRAP_PROCESS_INPUT_PROC should only be called during initialization, * since it may destroy this invariant. */ ProcessInputProc realInputProc; DeviceUnwrapProc unwrapProc; } xkbDeviceInfoRec, *xkbDeviceInfoPtr; #define WRAP_PROCESS_INPUT_PROC(device, oldprocs, proc, unwrapproc) \ device->public.processInputProc = proc; \ oldprocs->processInputProc = \ oldprocs->realInputProc = device->public.realInputProc; \ device->public.realInputProc = proc; \ oldprocs->unwrapProc = device->unwrapProc; \ device->unwrapProc = unwrapproc; #define COND_WRAP_PROCESS_INPUT_PROC(device, oldprocs, proc, unwrapproc) \ if (device->public.processInputProc == device->public.realInputProc)\ device->public.processInputProc = proc; \ oldprocs->processInputProc = \ oldprocs->realInputProc = device->public.realInputProc; \ device->public.realInputProc = proc; \ oldprocs->unwrapProc = device->unwrapProc; \ device->unwrapProc = unwrapproc; #define UNWRAP_PROCESS_INPUT_PROC(device, oldprocs, backupproc) \ backupproc = device->public.realInputProc; \ if (device->public.processInputProc == device->public.realInputProc)\ device->public.processInputProc = oldprocs->realInputProc; \ device->public.realInputProc = oldprocs->realInputProc; \ device->unwrapProc = oldprocs->unwrapProc; extern _X_EXPORT DevPrivateKeyRec xkbDevicePrivateKeyRec; #define xkbDevicePrivateKey (&xkbDevicePrivateKeyRec) #define XKBDEVICEINFO(dev) ((xkbDeviceInfoPtr)dixLookupPrivate(&(dev)->devPrivates, xkbDevicePrivateKey)) extern void xkbUnwrapProc(DeviceIntPtr, DeviceHandleProc, pointer); /***====================================================================***/ /***====================================================================***/ #define XkbAX_KRGMask (XkbSlowKeysMask|XkbBounceKeysMask) #define XkbAllFilteredEventsMask \ (XkbAccessXKeysMask|XkbRepeatKeysMask|XkbMouseKeysAccelMask|XkbAX_KRGMask) /***====================================================================***/ extern _X_EXPORT int XkbReqCode; extern _X_EXPORT int XkbEventBase; extern _X_EXPORT int XkbKeyboardErrorCode; extern _X_EXPORT const char *XkbBaseDirectory; extern _X_EXPORT const char *XkbBinDirectory; extern _X_EXPORT CARD32 xkbDebugFlags; #define _XkbLibError(c,l,d) /* Epoch fail */ /* "a" is a "unique" numeric identifier that just defines which error * code statement it is. _XkbErrCode2(4, foo) means "this is the 4th error * statement in this function". lovely. */ #define _XkbErrCode2(a,b) ((XID)((((unsigned int)(a))<<24)|((b)&0xffffff))) #define _XkbErrCode3(a,b,c) _XkbErrCode2(a,(((unsigned int)(b))<<16)|(c)) #define _XkbErrCode4(a,b,c,d) _XkbErrCode3(a,b,((((unsigned int)(c))<<8)|(d))) #define Status int extern _X_EXPORT void XkbUseMsg(void ); extern _X_EXPORT int XkbProcessArguments(int /* argc */ , char ** /* argv */ , int /* i */ ); extern _X_EXPORT Bool XkbInitPrivates(void); extern _X_EXPORT void XkbSetExtension(DeviceIntPtr device, ProcessInputProc proc); extern _X_EXPORT void XkbFreeCompatMap(XkbDescPtr /* xkb */ , unsigned int /* which */ , Bool /* freeMap */ ); extern _X_EXPORT void XkbFreeNames(XkbDescPtr /* xkb */ , unsigned int /* which */ , Bool /* freeMap */ ); extern _X_EXPORT int _XkbLookupAnyDevice(DeviceIntPtr *pDev, int id, ClientPtr client, Mask access_mode, int *xkb_err); extern _X_EXPORT int _XkbLookupKeyboard(DeviceIntPtr *pDev, int id, ClientPtr client, Mask access_mode, int *xkb_err); extern _X_EXPORT int _XkbLookupBellDevice(DeviceIntPtr *pDev, int id, ClientPtr client, Mask access_mode, int *xkb_err); extern _X_EXPORT int _XkbLookupLedDevice(DeviceIntPtr *pDev, int id, ClientPtr client, Mask access_mode, int *xkb_err); extern _X_EXPORT int _XkbLookupButtonDevice(DeviceIntPtr *pDev, int id, ClientPtr client, Mask access_mode, int *xkb_err); extern _X_EXPORT XkbDescPtr XkbAllocKeyboard(void ); extern _X_EXPORT Status XkbAllocClientMap(XkbDescPtr /* xkb */ , unsigned int /* which */ , unsigned int /* nTypes */ ); extern _X_EXPORT Status XkbAllocServerMap(XkbDescPtr /* xkb */ , unsigned int /* which */ , unsigned int /* nNewActions */ ); extern _X_EXPORT void XkbFreeClientMap(XkbDescPtr /* xkb */ , unsigned int /* what */ , Bool /* freeMap */ ); extern _X_EXPORT void XkbFreeServerMap(XkbDescPtr /* xkb */ , unsigned int /* what */ , Bool /* freeMap */ ); extern _X_EXPORT Status XkbAllocIndicatorMaps(XkbDescPtr /* xkb */ ); extern _X_EXPORT Status XkbAllocCompatMap(XkbDescPtr /* xkb */ , unsigned int /* which */ , unsigned int /* nInterpret */ ); extern _X_EXPORT Status XkbAllocNames(XkbDescPtr /* xkb */ , unsigned int /* which */ , int /* nTotalRG */ , int /* nTotalAliases */ ); extern _X_EXPORT Status XkbAllocControls(XkbDescPtr /* xkb */ , unsigned int /* which */ ); extern _X_EXPORT Status XkbCopyKeyTypes(XkbKeyTypePtr /* from */ , XkbKeyTypePtr /* into */ , int /* num_types */ ); extern _X_EXPORT Status XkbResizeKeyType(XkbDescPtr /* xkb */ , int /* type_ndx */ , int /* map_count */ , Bool /* want_preserve */ , int /* new_num_lvls */ ); extern _X_EXPORT void XkbFreeKeyboard(XkbDescPtr /* xkb */ , unsigned int /* which */ , Bool /* freeDesc */ ); extern _X_EXPORT void XkbFreeComponentNames(XkbComponentNamesPtr /* names */ , Bool /* freeNames */ ); extern _X_EXPORT void XkbSetActionKeyMods(XkbDescPtr /* xkb */ , XkbAction * /* act */ , unsigned int /* mods */ ); extern _X_EXPORT unsigned int XkbMaskForVMask(XkbDescPtr /* xkb */ , unsigned int /* vmask */ ); extern _X_EXPORT Bool XkbVirtualModsToReal(XkbDescPtr /* xkb */ , unsigned int /* virtua_mask */ , unsigned int * /* mask_rtrn */ ); extern _X_EXPORT unsigned int XkbAdjustGroup(int /* group */ , XkbControlsPtr /* ctrls */ ); extern _X_EXPORT KeySym *XkbResizeKeySyms(XkbDescPtr /* xkb */ , int /* key */ , int /* needed */ ); extern _X_EXPORT XkbAction *XkbResizeKeyActions(XkbDescPtr /* xkb */ , int /* key */ , int /* needed */ ); extern _X_EXPORT void XkbUpdateKeyTypesFromCore(DeviceIntPtr /* pXDev */ , KeySymsPtr /* syms */ , KeyCode /* first */ , CARD8 /* num */ , XkbChangesPtr /* pChanges */ ); extern _X_EXPORT void XkbUpdateDescActions(XkbDescPtr /* xkb */ , KeyCode /* first */ , CARD8 /* num */ , XkbChangesPtr /* changes */ ); extern _X_EXPORT void XkbUpdateActions(DeviceIntPtr /* pXDev */ , KeyCode /* first */ , CARD8 /* num */ , XkbChangesPtr /* pChanges */ , unsigned int * /* needChecksRtrn */ , XkbEventCausePtr /* cause */ ); extern _X_EXPORT KeySymsPtr XkbGetCoreMap(DeviceIntPtr /* keybd */ ); extern _X_EXPORT void XkbApplyMappingChange(DeviceIntPtr /* pXDev */ , KeySymsPtr /* map */ , KeyCode /* firstKey */ , CARD8 /* num */ , CARD8 * /* modmap */ , ClientPtr /* client */ ); extern _X_EXPORT void XkbSetIndicators(DeviceIntPtr /* pXDev */ , CARD32 /* affect */ , CARD32 /* values */ , XkbEventCausePtr /* cause */ ); extern _X_EXPORT void XkbUpdateIndicators(DeviceIntPtr /* keybd */ , CARD32 /* changed */ , Bool /* check_edevs */ , XkbChangesPtr /* pChanges */ , XkbEventCausePtr /* cause */ ); extern _X_EXPORT XkbSrvLedInfoPtr XkbAllocSrvLedInfo(DeviceIntPtr /* dev */ , KbdFeedbackPtr /* kf */ , LedFeedbackPtr /* lf */ , unsigned int /* needed_parts */ ); extern _X_EXPORT XkbSrvLedInfoPtr XkbCopySrvLedInfo(DeviceIntPtr /* dev */ , XkbSrvLedInfoPtr /* src */ , KbdFeedbackPtr /* kf */ , LedFeedbackPtr /* lf */ ); extern _X_EXPORT XkbSrvLedInfoPtr XkbFindSrvLedInfo(DeviceIntPtr /* dev */ , unsigned int /* class */ , unsigned int /* id */ , unsigned int /* needed_parts */ ); extern _X_EXPORT void XkbApplyLedNameChanges(DeviceIntPtr /* dev */ , XkbSrvLedInfoPtr /* sli */ , unsigned int /* changed_names */ , xkbExtensionDeviceNotify * /* ed */ , XkbChangesPtr /* changes */ , XkbEventCausePtr /* cause */ ); extern _X_EXPORT void XkbApplyLedMapChanges(DeviceIntPtr /* dev */ , XkbSrvLedInfoPtr /* sli */ , unsigned int /* changed_maps */ , xkbExtensionDeviceNotify * /* ed */ , XkbChangesPtr /* changes */ , XkbEventCausePtr /* cause */ ); extern _X_EXPORT void XkbApplyLedStateChanges(DeviceIntPtr /* dev */ , XkbSrvLedInfoPtr /* sli */ , unsigned int /* changed_leds */ , xkbExtensionDeviceNotify * /* ed */ , XkbChangesPtr /* changes */ , XkbEventCausePtr /* cause */ ); extern _X_EXPORT void XkbFlushLedEvents(DeviceIntPtr /* dev */ , DeviceIntPtr /* kbd */ , XkbSrvLedInfoPtr /* sli */ , xkbExtensionDeviceNotify * /* ed */ , XkbChangesPtr /* changes */ , XkbEventCausePtr /* cause */ ); extern _X_EXPORT unsigned int XkbIndicatorsToUpdate(DeviceIntPtr /* dev */ , unsigned long /* state_changes */ , Bool /* enabled_ctrl_changes */ ); extern _X_EXPORT void XkbComputeDerivedState(XkbSrvInfoPtr /* xkbi */ ); extern _X_EXPORT void XkbCheckSecondaryEffects(XkbSrvInfoPtr /* xkbi */ , unsigned int /* which */ , XkbChangesPtr /* changes */ , XkbEventCausePtr /* cause */ ); extern _X_EXPORT void XkbCheckIndicatorMaps(DeviceIntPtr /* dev */ , XkbSrvLedInfoPtr /* sli */ , unsigned int /* which */ ); extern _X_EXPORT unsigned int XkbStateChangedFlags(XkbStatePtr /* old */ , XkbStatePtr /* new */ ); extern _X_EXPORT void XkbSendStateNotify(DeviceIntPtr /* kbd */ , xkbStateNotify * /* pSN */ ); extern _X_EXPORT void XkbSendMapNotify(DeviceIntPtr /* kbd */ , xkbMapNotify * /* ev */ ); extern _X_EXPORT int XkbComputeControlsNotify(DeviceIntPtr /* kbd */ , XkbControlsPtr /* old */ , XkbControlsPtr /* new */ , xkbControlsNotify * /* pCN */ , Bool /* forceCtrlProc */ ); extern _X_EXPORT void XkbSendControlsNotify(DeviceIntPtr /* kbd */ , xkbControlsNotify * /* ev */ ); extern _X_EXPORT void XkbSendCompatMapNotify(DeviceIntPtr /* kbd */ , xkbCompatMapNotify * /* ev */ ); extern _X_EXPORT void XkbHandleBell(BOOL /* force */ , BOOL /* eventOnly */ , DeviceIntPtr /* kbd */ , CARD8 /* percent */ , pointer /* ctrl */ , CARD8 /* class */ , Atom /* name */ , WindowPtr /* pWin */ , ClientPtr /* pClient */ ); extern _X_EXPORT void XkbSendAccessXNotify(DeviceIntPtr /* kbd */ , xkbAccessXNotify * /* pEv */ ); extern _X_EXPORT void XkbSendNamesNotify(DeviceIntPtr /* kbd */ , xkbNamesNotify * /* ev */ ); extern _X_EXPORT void XkbSendActionMessage(DeviceIntPtr /* kbd */ , xkbActionMessage * /* ev */ ); extern _X_EXPORT void XkbSendExtensionDeviceNotify(DeviceIntPtr /* kbd */ , ClientPtr /* client */ , xkbExtensionDeviceNotify * /* ev */ ); extern _X_EXPORT void XkbSendNotification(DeviceIntPtr /* kbd */ , XkbChangesPtr /* pChanges */ , XkbEventCausePtr /* cause */ ); extern _X_EXPORT void XkbProcessKeyboardEvent(DeviceEvent * /* event */ , DeviceIntPtr /* keybd */ ); extern _X_EXPORT void XkbHandleActions(DeviceIntPtr /* dev */ , DeviceIntPtr /* kbd */ , DeviceEvent * /* event */ ); extern _X_EXPORT Bool XkbEnableDisableControls(XkbSrvInfoPtr /* xkbi */ , unsigned long /* change */ , unsigned long /* newValues */ , XkbChangesPtr /* changes */ , XkbEventCausePtr /* cause */ ); extern _X_EXPORT void AccessXInit(DeviceIntPtr /* dev */ ); extern _X_EXPORT Bool AccessXFilterPressEvent(DeviceEvent * /* event */ , DeviceIntPtr /* keybd */ ); extern _X_EXPORT Bool AccessXFilterReleaseEvent(DeviceEvent * /* event */ , DeviceIntPtr /* keybd */ ); extern _X_EXPORT void AccessXCancelRepeatKey(XkbSrvInfoPtr /* xkbi */ , KeyCode /* key */ ); extern _X_EXPORT void AccessXComputeCurveFactor(XkbSrvInfoPtr /* xkbi */ , XkbControlsPtr /* ctrls */ ); extern _X_EXPORT XkbInterestPtr XkbFindClientResource(DevicePtr /* inDev */ , ClientPtr /* client */ ); extern _X_EXPORT XkbInterestPtr XkbAddClientResource(DevicePtr /* inDev */ , ClientPtr /* client */ , XID /* id */ ); extern _X_EXPORT int XkbRemoveResourceClient(DevicePtr /* inDev */ , XID /* id */ ); extern _X_EXPORT int XkbDDXAccessXBeep(DeviceIntPtr /* dev */ , unsigned int /* what */ , unsigned int /* which */ ); extern _X_EXPORT int XkbDDXUsesSoftRepeat(DeviceIntPtr /* dev */ ); extern _X_EXPORT void XkbDDXKeybdCtrlProc(DeviceIntPtr /* dev */ , KeybdCtrl * /* ctrl */ ); extern _X_EXPORT void XkbDDXChangeControls(DeviceIntPtr /* dev */ , XkbControlsPtr /* old */ , XkbControlsPtr /* new */ ); extern _X_EXPORT void XkbDDXUpdateDeviceIndicators(DeviceIntPtr /* dev */ , XkbSrvLedInfoPtr /* sli */ , CARD32 /* newState */ ); extern _X_EXPORT int XkbDDXTerminateServer(DeviceIntPtr /* dev */ , KeyCode /* key */ , XkbAction * /* act */ ); extern _X_EXPORT int XkbDDXSwitchScreen(DeviceIntPtr /* dev */ , KeyCode /* key */ , XkbAction * /* act */ ); extern _X_EXPORT int XkbDDXPrivate(DeviceIntPtr /* dev */ , KeyCode /* key */ , XkbAction * /* act */ ); extern _X_EXPORT void XkbDisableComputedAutoRepeats(DeviceIntPtr /* pXDev */ , unsigned int /* key */ ); extern _X_EXPORT void XkbSetRepeatKeys(DeviceIntPtr /* pXDev */ , int /* key */ , int /* onoff */ ); extern _X_EXPORT int XkbLatchModifiers(DeviceIntPtr /* pXDev */ , CARD8 /* mask */ , CARD8 /* latches */ ); extern _X_EXPORT int XkbLatchGroup(DeviceIntPtr /* pXDev */ , int /* group */ ); extern _X_EXPORT void XkbClearAllLatchesAndLocks(DeviceIntPtr /* dev */ , XkbSrvInfoPtr /* xkbi */ , Bool /* genEv */ , XkbEventCausePtr /* cause */ ); extern _X_EXPORT void XkbGetRulesDflts(XkbRMLVOSet * /* rmlvo */ ); extern _X_EXPORT void XkbFreeRMLVOSet(XkbRMLVOSet * /* rmlvo */ , Bool /* freeRMLVO */ ); extern _X_EXPORT void XkbSetRulesDflts(XkbRMLVOSet * /* rmlvo */ ); extern _X_EXPORT void XkbDeleteRulesDflts(void ); extern _X_EXPORT int SProcXkbDispatch(ClientPtr /* client */ ); extern _X_EXPORT XkbGeometryPtr XkbLookupNamedGeometry(DeviceIntPtr /* dev */ , Atom /* name */ , Bool * /* shouldFree */ ); extern _X_EXPORT void XkbConvertCase(KeySym /* sym */ , KeySym * /* lower */ , KeySym * /* upper */ ); extern _X_EXPORT Status XkbChangeKeycodeRange(XkbDescPtr /* xkb */ , int /* minKC */ , int /* maxKC */ , XkbChangesPtr /* changes */ ); extern _X_EXPORT void XkbFreeSrvLedInfo(XkbSrvLedInfoPtr /* sli */ ); extern _X_EXPORT void XkbFreeInfo(XkbSrvInfoPtr /* xkbi */ ); extern _X_EXPORT Status XkbChangeTypesOfKey(XkbDescPtr /* xkb */ , int /* key */ , int /* nGroups */ , unsigned int /* groups */ , int * /* newTypesIn */ , XkbMapChangesPtr /* changes */ ); extern _X_EXPORT int XkbKeyTypesForCoreSymbols(XkbDescPtr /* xkb */ , int /* map_width */ , KeySym * /* core_syms */ , unsigned int /* protected */ , int * /* types_inout */ , KeySym * /* xkb_syms_rtrn */ ); extern _X_EXPORT Bool XkbApplyCompatMapToKey(XkbDescPtr /* xkb */ , KeyCode /* key */ , XkbChangesPtr /* changes */ ); extern _X_EXPORT Bool XkbApplyVirtualModChanges(XkbDescPtr /* xkb */ , unsigned int /* changed */ , XkbChangesPtr /* changes */ ); extern _X_EXPORT void XkbSendNewKeyboardNotify(DeviceIntPtr /* kbd */ , xkbNewKeyboardNotify * /* pNKN */ ); extern Bool XkbCopyKeymap(XkbDescPtr /* dst */ , XkbDescPtr /* src */ ); extern _X_EXPORT Bool XkbCopyDeviceKeymap(DeviceIntPtr /* dst */ , DeviceIntPtr /* src */ ); extern void XkbFilterEvents(ClientPtr /* pClient */ , int /* nEvents */ , xEvent * /* xE */ ); extern int XkbGetEffectiveGroup(XkbSrvInfoPtr /* xkbi */ , XkbStatePtr /* xkbstate */ , CARD8 /* keycode */ ); extern void XkbMergeLockedPtrBtns(DeviceIntPtr /* master */ ); extern void XkbFakeDeviceButton(DeviceIntPtr /* dev */ , int /* press */ , int /* button */ ); #include "xkbfile.h" #include "xkbrules.h" #define _XkbListKeycodes 0 #define _XkbListTypes 1 #define _XkbListCompat 2 #define _XkbListSymbols 3 #define _XkbListGeometry 4 #define _XkbListNumComponents 5 extern _X_EXPORT unsigned int XkbDDXLoadKeymapByNames(DeviceIntPtr /* keybd */ , XkbComponentNamesPtr /* names */ , unsigned int /* want */ , unsigned int /* need */ , XkbDescPtr * /* finfoRtrn */ , char * /* keymapNameRtrn */ , int /* keymapNameRtrnLen */ ); extern _X_EXPORT Bool XkbDDXNamesFromRules(DeviceIntPtr /* keybd */ , char * /* rules */ , XkbRF_VarDefsPtr /* defs */ , XkbComponentNamesPtr /* names */ ); extern _X_EXPORT XkbDescPtr XkbCompileKeymap(DeviceIntPtr /* dev */ , XkbRMLVOSet * /* rmlvo */ ); #endif /* _XKBSRV_H_ */
coldenheart/123
python/level1_single_api/9_amct/amct_caffe/faster_rcnn/src/init_paths_for_amct.py
#!/usr/bin/python3 # -*- coding: UTF-8 -*- """ Copyright (C) 2019. Huawei Technologies Co., Ltd. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the Apache License Version 2.0.You may not use this file except in compliance with the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Apache License for more details at http://www.apache.org/licenses/LICENSE-2.0 AMCT_CAFFE sample of faster-rcnn model, init path env. """ import sys import os def add_path(path): """add path to sys""" if path not in sys.path: sys.path.insert(0, path) # Add caffe to path CAFFE_PATH = 'your_caffe_master_dir' caffe_path = os.path.realpath(CAFFE_PATH) # Add path of pycaffe add_path(os.path.join(caffe_path, 'python')) # Add lib to path LIB_PATH = './python_tools' lib_path = os.path.realpath(LIB_PATH) add_path(lib_path)