repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
Huawei-Ascend/modelzoo
built-in/TensorFlow/Research/cv/image_classification/Cars_for_TensorFlow/automl/vega/search_space/networks/tensorflow/customs/adelaide_nn/mobilenetv2_backbone.py
<reponame>Huawei-Ascend/modelzoo # -*- coding:utf-8 -*- # Copyright (C) 2020. 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 MIT 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 # MIT License for more details. """Backbone of mobilenet v2.""" import tensorflow as tf class MobileNetV2Backbone(object): """Backbone of mobilenet v2.""" def __init__(self, load_path=None, data_format='channels_first'): """Construct MobileNetV2 class. :param load_path: path for saved model """ self.data_format = data_format self.channel_axis = 1 if data_format == 'channels_first' else 3 self.load_path = load_path def block(self, x, input_filters, output_filters, expansion, stride, training): """Mobilenetv2 block.""" shortcut = x if expansion != 1: x = tf.layers.conv2d(x, input_filters * expansion, kernel_size=1, use_bias=False, padding='same', data_format=self.data_format) x = tf.layers.batch_normalization(x, axis=self.channel_axis, training=training) x = tf.nn.relu6(x) x = tf.keras.layers.DepthwiseConv2D( 3, strides=stride, padding='same', data_format=self.data_format, use_bias=False)(x) x = tf.layers.batch_normalization(x, axis=self.channel_axis, training=training) x = tf.nn.relu6(x) x = tf.layers.conv2d(x, output_filters, kernel_size=1, use_bias=False, padding='same', data_format=self.data_format) x = tf.layers.batch_normalization(x, axis=self.channel_axis, training=training) if stride == 1 and input_filters == output_filters: return shortcut + x else: return x def blocks(self, x, expansion, output_filters, repeat, stride, training): """Mobilenetv2 blocks.""" input_filters = int(x.get_shape()[self.channel_axis]) # first layer should take stride into account x = self.block(x, input_filters, output_filters, expansion, stride, training) for _ in range(1, repeat): input_filters = output_filters x = self.block(x, input_filters, output_filters, expansion, 1, training) return x def __call__(self, x, training): """Do an inference on MobileNetV2. :param x: input tensor :return: output tensor """ outs = [] x = tf.layers.conv2d(x, 32, 3, strides=2, use_bias=False, padding='same', data_format=self.data_format) x = tf.layers.batch_normalization(x, axis=self.channel_axis, training=training) x = tf.nn.relu6(x) expansion_list = [1] + [6] * 6 output_filter_list = [16, 24, 32, 64, 96, 160, 320] repeat_list = [1, 2, 3, 4, 3, 3, 1] stride_list = [1, 2, 2, 2, 1, 2, 1] for i in range(7): x = self.blocks(x, expansion_list[i], output_filter_list[i], repeat_list[i], stride_list[i], training) if i in [1, 2, 4, 6]: outs.append(x) return outs
ts-3156/CoinKarasu
app/src/main/java/com/coinkarasu/utils/CKStringUtils.java
<filename>app/src/main/java/com/coinkarasu/utils/CKStringUtils.java package com.coinkarasu.utils; import java.util.List; public class CKStringUtils { public static String join(String[] params, String delim) { return join(delim, (Object[]) params); } public static String join(String delim, Object... params) { StringBuilder builder = new StringBuilder(); for (Object obj : params) { if (builder.length() > 0) { builder.append(delim); } builder.append(obj); } return builder.toString(); } public static String join(String delim, List<String> list) { StringBuilder builder = new StringBuilder(); for (String str : list) { if (builder.length() > 0) { builder.append(delim); } builder.append(str); } return builder.toString(); } }
LeolichN/jdchain-core
ledger/ledger-database/src/main/java/com/jd/blockchain/ledger/core/EmptyLedgerDataSet.java
<gh_stars>1-10 package com.jd.blockchain.ledger.core; import com.jd.blockchain.crypto.HashDigest; import com.jd.blockchain.ledger.LedgerAdminSettings; import com.jd.blockchain.ledger.MerkleProof; import com.jd.blockchain.ledger.ParticipantNode; import utils.Bytes; import utils.EmptySkippingIterator; import utils.SkippingIterator; /** * 一个只读的空的账本数据集; * * @author huanghaiquan * */ public class EmptyLedgerDataSet implements LedgerDataSet { public static final LedgerDataSet INSTANCE = new EmptyLedgerDataSet(); private static final LedgerAdminDataSet EMPTY_ADMIN_DATA = new EmptyAdminData(); private static final UserAccountSet EMPTY_USER_ACCOUNTS = new EmptyUserAccountSet(); private static final DataAccountSet EMPTY_DATA_ACCOUNTS = new EmptyDataAccountSet(); private static final ContractAccountSet EMPTY_CONTRACT_ACCOUNTS = new EmptyContractAccountSet(); private static final ParticipantCollection EMPTY_PARTICIPANTS = new EmptyParticipantData(); private EmptyLedgerDataSet() { } @Override public LedgerAdminDataSet getAdminDataset() { return EMPTY_ADMIN_DATA; } @Override public UserAccountSet getUserAccountSet() { return EMPTY_USER_ACCOUNTS; } @Override public DataAccountSet getDataAccountSet() { return EMPTY_DATA_ACCOUNTS; } @Override public ContractAccountSet getContractAccountSet() { return EMPTY_CONTRACT_ACCOUNTS; } private static class EmptyAdminData implements LedgerAdminDataSet { @Override public LedgerAdminSettings getAdminSettings() { return null; } @Override public ParticipantCollection getParticipantDataset() { return EMPTY_PARTICIPANTS; } } private static class EmptyParticipantData implements ParticipantCollection { @Override public HashDigest getRootHash() { return null; } @Override public MerkleProof getProof(Bytes key) { return null; } @Override public long getParticipantCount() { return 0; } @Override public boolean contains(Bytes address) { return false; } @Override public ParticipantNode getParticipant(Bytes address) { return null; } @Override public ParticipantNode[] getParticipants() { return null; } @Override public SkippingIterator<ParticipantNode> getAllParticipants() { return EmptySkippingIterator.instance(); } } private static class EmptyUserAccountSet extends EmptyAccountSet<UserAccount> implements UserAccountSet { } private static class EmptyDataAccountSet extends EmptyAccountSet<DataAccount> implements DataAccountSet { } private static class EmptyContractAccountSet extends EmptyAccountSet<ContractAccount> implements ContractAccountSet { } }
CS2103JAN2018-W13-B4/main
src/main/java/seedu/organizer/storage/XmlAdaptedUser.java
package seedu.organizer.storage; import static java.util.Objects.requireNonNull; import static seedu.organizer.commons.util.CollectionUtil.requireAllNonNull; import javax.xml.bind.annotation.XmlElement; import seedu.organizer.commons.exceptions.IllegalValueException; import seedu.organizer.model.user.User; import seedu.organizer.model.user.UserWithQuestionAnswer; //@@author dominickenn /** * JAXB-friendly adapted version of the User. */ public class XmlAdaptedUser { @XmlElement(required = true) private String username; @XmlElement(required = true) private String password; @XmlElement private String question; @XmlElement private String answer; /** * Constructs an XmlAdaptedUser. * This is the no-arg constructor that is required by JAXB. */ public XmlAdaptedUser() {} /** * Constructs a {@code XmlAdaptedUser} with the given {@code username} and {@code password}. */ public XmlAdaptedUser(String username, String password) { requireAllNonNull(username, password); this.username = username; this.password = password; } /** * Constructs a {@code XmlAdaptedUser} with the given * {@code usernamename}, {@code password}, {@code question}, and {@code answer}. */ public XmlAdaptedUser(String username, String password, String question, String answer) { requireAllNonNull(username, password, question, answer); this.username = username; this.password = password; this.question = question; this.answer = answer; } /** * Converts a given User into this class for JAXB use. * * @param source future changes to this will not affect the created */ public XmlAdaptedUser(User source) { requireNonNull(source); username = source.username; password = source.password; } /** * Converts a given UserWithQuestionAnswer into this class for JAXB use. * * @param source future changes to this will not affect the created */ public XmlAdaptedUser(UserWithQuestionAnswer source) { requireNonNull(source); username = source.username; password = source.password; question = source.question; answer = source.answer; } public String getUsername() { return username; } public String getPassword() { return password; } /** * Converts this jaxb-friendly adapted user object into the model's User object * * @throws IllegalValueException if there were any data constraints violated in the adapted user */ public User toUserModelType() throws IllegalValueException { requireAllNonNull(username, password); if (!User.isValidUsername(username)) { throw new IllegalValueException(User.MESSAGE_USERNAME_CONSTRAINTS); } if (!User.isValidPassword(password)) { throw new IllegalValueException(User.MESSAGE_PASSWORD_CONSTRAINTS); } return new User(username, password); } /** * Converts this jaxb-friendly adapted user object into the model's UserWithQuestionAnswer object * * @throws IllegalValueException if there were any data constraints violated in the adapted user */ public UserWithQuestionAnswer toUserQuestionAnswerModelType() throws IllegalValueException { requireAllNonNull(username, password, question, answer); if (!User.isValidUsername(username)) { throw new IllegalValueException(User.MESSAGE_USERNAME_CONSTRAINTS); } if (!User.isValidPassword(password)) { throw new IllegalValueException(User.MESSAGE_PASSWORD_CONSTRAINTS); } if (!UserWithQuestionAnswer.isValidAnswer(answer)) { throw new IllegalValueException(UserWithQuestionAnswer.MESSAGE_ANSWER_CONSTRAINTS); } if (!UserWithQuestionAnswer.isValidQuestion(question)) { throw new IllegalValueException(UserWithQuestionAnswer.MESSAGE_QUESTION_CONSTRAINTS); } return new UserWithQuestionAnswer(username, password, question, answer); } public boolean isUserWithQuestionAnswer() { return !(question == null) && !(answer == null); } @Override public boolean equals(Object other) { if (other == this) { return true; } if (!(other instanceof XmlAdaptedUser)) { return false; } return username.equals(((XmlAdaptedUser) other).username) && password.equals(((XmlAdaptedUser) other).password); } }
angelopolotto/code-challenge
sorting/ctci-bubble-sort/__init__.py
import math import os import random import re import sys def countSwaps(a): swaps = 0 for i in range(len(a) - 1): for j in range(len(a) - 1): if a[j] > a[j + 1]: a[j], a[j + 1] = a[j + 1], a[j] swaps += 1 print('Array is sorted in %s swaps.' % swaps) print('First Element: %s' % a[0]) print('Last Element: %s' % a[-1]) if __name__ == '__main__': scr_dir = os.path.dirname(__file__) fp_in = open(os.path.join(scr_dir, './input/input03.txt'), 'r') n = int(fp_in.readline()) a = list(map(int, fp_in.readline().rstrip().split())) countSwaps(a)
microsoftgraph/msgraph-sdk-go
users/item/translateexchangeids/translate_exchange_ids_request_bodyable.go
package translateexchangeids import ( i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91 "github.com/microsoft/kiota-abstractions-go/serialization" iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242 "github.com/microsoftgraph/msgraph-sdk-go/models" ) // TranslateExchangeIdsRequestBodyable type TranslateExchangeIdsRequestBodyable interface { i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.AdditionalDataHolder i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable GetInputIds()([]string) GetSourceIdType()(*iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.ExchangeIdFormat) GetTargetIdType()(*iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.ExchangeIdFormat) SetInputIds(value []string)() SetSourceIdType(value *iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.ExchangeIdFormat)() SetTargetIdType(value *iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.ExchangeIdFormat)() }
AndrewBoyarsky/DPoSBlockchain
src/main/java/com/boyarsky/dapos/core/tx/type/handler/impl/PaymentTransactionHandler.java
<filename>src/main/java/com/boyarsky/dapos/core/tx/type/handler/impl/PaymentTransactionHandler.java<gh_stars>1-10 package com.boyarsky.dapos.core.tx.type.handler.impl; import com.boyarsky.dapos.core.service.account.AccountService; import com.boyarsky.dapos.core.service.account.Operation; import com.boyarsky.dapos.core.tx.Transaction; import com.boyarsky.dapos.core.tx.type.TxType; import com.boyarsky.dapos.core.tx.type.handler.TransactionTypeHandler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class PaymentTransactionHandler implements TransactionTypeHandler { private AccountService accountService; @Autowired public PaymentTransactionHandler(AccountService accountService) { this.accountService = accountService; } @Override public TxType type() { return TxType.PAYMENT; } @Override public void handle(Transaction tx) { if (tx.getAmount() > 0) { Operation op = new Operation(tx.getTxId(), tx.getHeight(), tx.getType().toString(), tx.getAmount()); accountService.transferMoney(tx.getSender(), tx.getRecipient(), op); } } }
IbexOmega/CrazyCanvas
Dependencies/NoesisGUI/Include/NsRender/Texture.h
//////////////////////////////////////////////////////////////////////////////////////////////////// // NoesisGUI - http://www.noesisengine.com // Copyright (c) 2013 Noesis Technologies S.L. All Rights Reserved. //////////////////////////////////////////////////////////////////////////////////////////////////// #ifndef __RENDER_TEXTURE_H__ #define __RENDER_TEXTURE_H__ #include <NsCore/Noesis.h> #include <NsCore/BaseComponent.h> #include <NsCore/Ptr.h> #include <NsCore/ReflectionDeclare.h> #include <NsRender/RenderDeviceApi.h> namespace Noesis { NS_WARNING_PUSH NS_MSVC_WARNING_DISABLE(4251) //////////////////////////////////////////////////////////////////////////////////////////////////// /// Base class for 2D textures. //////////////////////////////////////////////////////////////////////////////////////////////////// class NS_RENDER_RENDERDEVICE_API Texture: public BaseComponent { public: /// Returns the width of the texture virtual uint32_t GetWidth() const = 0; /// Returns the height of the texture virtual uint32_t GetHeight() const = 0; /// True if the texture has mipmaps virtual bool HasMipMaps() const = 0; /// True is the texture must be vertically inverted when mapped. This is true for render targets /// on platforms (OpenGL) where texture V coordinate is zero at the "bottom of the texture" virtual bool IsInverted() const = 0; /// Stores custom private data void SetPrivateData(BaseComponent* data); private: Ptr<BaseComponent> mData; NS_DECLARE_REFLECTION(Texture, BaseComponent) }; NS_WARNING_POP } #endif
I99900K/CNPM_G9
Code/FE/src/routers/ProtectedUserRoute.js
<gh_stars>10-100 import React from "react"; import { Route, Redirect } from "react-router-dom"; import PropTypes from "prop-types"; import { connect } from "react-redux"; const ProtectedUserRoute = ({ layout: Layout, component: Component, isAuthenticated, user, ...rest }) => ( <Route {...rest} render={(props) => isAuthenticated && user.role === "guest" ? ( <Layout history={props.history}> <Component {...props} /> </Layout> ) : ( <Redirect to={{ pathname: "/login", state: { from: props.location } }} /> ) } /> ); ProtectedUserRoute.propTypes = { isAuthenticated: PropTypes.bool, }; const mapStateToProps = (state) => ({ isAuthenticated: state.authState.isAuthenticated, user: state.authState.user, }); export default connect(mapStateToProps)(ProtectedUserRoute);
DaRetroCat/Primal-Magick-Archaic
src/main/java/com/verdantartifice/primalmagick/client/gui/grimoire/AttunementIndexPage.java
package com.verdantartifice.primalmagick.client.gui.grimoire; import com.mojang.blaze3d.matrix.MatrixStack; import com.verdantartifice.primalmagick.client.gui.GrimoireScreen; import com.verdantartifice.primalmagick.client.gui.widgets.grimoire.AttunementButton; import com.verdantartifice.primalmagick.common.sources.Source; import net.minecraft.client.Minecraft; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TranslationTextComponent; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; /** * Grimoire page showing the list of discovered attunements. * * @author Daedalus4096 */ @OnlyIn(Dist.CLIENT) public class AttunementIndexPage extends AbstractPage { public static final String TOPIC = "attunements"; protected boolean firstPage; public AttunementIndexPage() { this(false); } public AttunementIndexPage(boolean first) { this.firstPage = first; } @Override public void render(MatrixStack matrixStack, int side, int x, int y, int mouseX, int mouseY) { // Just render the title; buttons have already been added if (this.isFirstPage() && side == 0) { this.renderTitle(matrixStack, side, x, y, mouseX, mouseY, null); } } public boolean isFirstPage() { return this.firstPage; } @Override protected String getTitleTranslationKey() { return "primalmagick.grimoire.attunement_header"; } @Override public void initWidgets(GrimoireScreen screen, int side, int x, int y) { // Add a button to the screen for each discovered source Minecraft mc = Minecraft.getInstance(); for (Source source : Source.SORTED_SOURCES) { if (source.isDiscovered(mc.player)) { ITextComponent text = new TranslationTextComponent(source.getNameTranslationKey()); screen.addWidgetToScreen(new AttunementButton(x + 12 + (side * 140), y, text, screen, source)); y += 12; } } } }
TinyTanic/music-player
src/reducers/view.js
import { SONGS } from '../constants/views' import { CHANGE_VIEW } from '../constants/actions' const defaultState = SONGS export default (state = defaultState, action) => { switch (action.type) { case CHANGE_VIEW: return action.payload.view default: return state } }
gcbpay/radarj9
ripple-bouncycastle/src/main/java/org/ripple/bouncycastle/crypto/util/PrivateKeyInfoFactory.java
<reponame>gcbpay/radarj9<filename>ripple-bouncycastle/src/main/java/org/ripple/bouncycastle/crypto/util/PrivateKeyInfoFactory.java<gh_stars>10-100 package org.ripple.bouncycastle.crypto.util; import java.io.IOException; import org.ripple.bouncycastle.asn1.ASN1Integer; import org.ripple.bouncycastle.asn1.DERNull; import org.ripple.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.ripple.bouncycastle.asn1.pkcs.PrivateKeyInfo; import org.ripple.bouncycastle.asn1.pkcs.RSAPrivateKey; import org.ripple.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.ripple.bouncycastle.asn1.x509.DSAParameter; import org.ripple.bouncycastle.asn1.x9.X9ObjectIdentifiers; import org.ripple.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.ripple.bouncycastle.crypto.params.DSAParameters; import org.ripple.bouncycastle.crypto.params.DSAPrivateKeyParameters; import org.ripple.bouncycastle.crypto.params.RSAKeyParameters; import org.ripple.bouncycastle.crypto.params.RSAPrivateCrtKeyParameters; /** * Factory to create ASN.1 private key info objects from lightweight private keys. */ public class PrivateKeyInfoFactory { /** * Create a PrivateKeyInfo representation of a private key. * * @param privateKey the SubjectPublicKeyInfo encoding * @return the appropriate key parameter * @throws java.io.IOException on an error encoding the key */ public static PrivateKeyInfo createPrivateKeyInfo(AsymmetricKeyParameter privateKey) throws IOException { if (privateKey instanceof RSAKeyParameters) { RSAPrivateCrtKeyParameters priv = (RSAPrivateCrtKeyParameters)privateKey; return new PrivateKeyInfo(new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE), new RSAPrivateKey(priv.getModulus(), priv.getPublicExponent(), priv.getExponent(), priv.getP(), priv.getQ(), priv.getDP(), priv.getDQ(), priv.getQInv())); } else if (privateKey instanceof DSAPrivateKeyParameters) { DSAPrivateKeyParameters priv = (DSAPrivateKeyParameters)privateKey; DSAParameters params = priv.getParameters(); return new PrivateKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_dsa, new DSAParameter(params.getP(), params.getQ(), params.getG())), new ASN1Integer(priv.getX())); } else { throw new IOException("key parameters not recognised."); } } }
codenote/chromium-test
components/autofill/browser/webdata/autofill_webdata_service.cc
<reponame>codenote/chromium-test // Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/autofill/browser/webdata/autofill_webdata_service.h" #include "base/logging.h" #include "base/stl_util.h" #include "components/autofill/browser/autofill_country.h" #include "components/autofill/browser/autofill_profile.h" #include "components/autofill/browser/credit_card.h" #include "components/autofill/browser/webdata/autofill_change.h" #include "components/autofill/browser/webdata/autofill_entry.h" #include "components/autofill/browser/webdata/autofill_table.h" #include "components/autofill/browser/webdata/autofill_webdata_service_observer.h" #include "components/autofill/common/form_field_data.h" #include "components/webdata/common/web_database_service.h" using base::Bind; using base::Time; using content::BrowserThread; // static void AutofillWebDataService::NotifyOfMultipleAutofillChanges( AutofillWebDataService* web_data_service) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB)); if (!web_data_service) return; BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, Bind(&AutofillWebDataService::NotifyAutofillMultipleChangedOnUIThread, make_scoped_refptr(web_data_service))); } AutofillWebDataService::AutofillWebDataService( scoped_refptr<WebDatabaseService> wdbs, const ProfileErrorCallback& callback) : WebDataServiceBase(wdbs, callback) { } AutofillWebDataService::AutofillWebDataService() : WebDataServiceBase(NULL, WebDataServiceBase::ProfileErrorCallback()) { } void AutofillWebDataService::AddFormFields( const std::vector<FormFieldData>& fields) { wdbs_->ScheduleDBTask(FROM_HERE, Bind(&AutofillWebDataService::AddFormElementsImpl, this, fields)); } WebDataServiceBase::Handle AutofillWebDataService::GetFormValuesForElementName( const base::string16& name, const base::string16& prefix, int limit, WebDataServiceConsumer* consumer) { return wdbs_->ScheduleDBTaskWithResult(FROM_HERE, Bind(&AutofillWebDataService::GetFormValuesForElementNameImpl, this, name, prefix, limit), consumer); } void AutofillWebDataService::RemoveFormElementsAddedBetween( const Time& delete_begin, const Time& delete_end) { wdbs_->ScheduleDBTask(FROM_HERE, Bind(&AutofillWebDataService::RemoveFormElementsAddedBetweenImpl, this, delete_begin, delete_end)); } void AutofillWebDataService::RemoveExpiredFormElements() { wdbs_->ScheduleDBTask(FROM_HERE, Bind(&AutofillWebDataService::RemoveExpiredFormElementsImpl, this)); } void AutofillWebDataService::RemoveFormValueForElementName( const base::string16& name, const base::string16& value) { wdbs_->ScheduleDBTask(FROM_HERE, Bind(&AutofillWebDataService::RemoveFormValueForElementNameImpl, this, name, value)); } void AutofillWebDataService::AddAutofillProfile( const AutofillProfile& profile) { wdbs_->ScheduleDBTask(FROM_HERE, Bind(&AutofillWebDataService::AddAutofillProfileImpl, this, profile)); } void AutofillWebDataService::UpdateAutofillProfile( const AutofillProfile& profile) { wdbs_->ScheduleDBTask(FROM_HERE, Bind(&AutofillWebDataService::UpdateAutofillProfileImpl, this, profile)); } void AutofillWebDataService::RemoveAutofillProfile( const std::string& guid) { wdbs_->ScheduleDBTask(FROM_HERE, Bind(&AutofillWebDataService::RemoveAutofillProfileImpl, this, guid)); } WebDataServiceBase::Handle AutofillWebDataService::GetAutofillProfiles( WebDataServiceConsumer* consumer) { return wdbs_->ScheduleDBTaskWithResult(FROM_HERE, Bind(&AutofillWebDataService::GetAutofillProfilesImpl, this), consumer); } void AutofillWebDataService::AddCreditCard(const CreditCard& credit_card) { wdbs_->ScheduleDBTask( FROM_HERE, Bind(&AutofillWebDataService::AddCreditCardImpl, this, credit_card)); } void AutofillWebDataService::UpdateCreditCard( const CreditCard& credit_card) { wdbs_->ScheduleDBTask( FROM_HERE, Bind(&AutofillWebDataService::UpdateCreditCardImpl, this, credit_card)); } void AutofillWebDataService::RemoveCreditCard(const std::string& guid) { wdbs_->ScheduleDBTask( FROM_HERE, Bind(&AutofillWebDataService::RemoveCreditCardImpl, this, guid)); } WebDataServiceBase::Handle AutofillWebDataService::GetCreditCards( WebDataServiceConsumer* consumer) { return wdbs_->ScheduleDBTaskWithResult(FROM_HERE, Bind(&AutofillWebDataService::GetCreditCardsImpl, this), consumer); } void AutofillWebDataService::RemoveAutofillDataModifiedBetween( const Time& delete_begin, const Time& delete_end) { wdbs_->ScheduleDBTask( FROM_HERE, Bind(&AutofillWebDataService::RemoveAutofillDataModifiedBetweenImpl, this, delete_begin, delete_end)); } void AutofillWebDataService::AddObserver( AutofillWebDataServiceObserverOnDBThread* observer) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB)); db_observer_list_.AddObserver(observer); } void AutofillWebDataService::RemoveObserver( AutofillWebDataServiceObserverOnDBThread* observer) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB)); db_observer_list_.RemoveObserver(observer); } void AutofillWebDataService::AddObserver( AutofillWebDataServiceObserverOnUIThread* observer) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); ui_observer_list_.AddObserver(observer); } void AutofillWebDataService::RemoveObserver( AutofillWebDataServiceObserverOnUIThread* observer) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); ui_observer_list_.RemoveObserver(observer); } AutofillWebDataService::~AutofillWebDataService() {} void AutofillWebDataService::NotifyDatabaseLoadedOnUIThread() { // Notify that the database has been initialized. FOR_EACH_OBSERVER(AutofillWebDataServiceObserverOnUIThread, ui_observer_list_, WebDatabaseLoaded()); } //////////////////////////////////////////////////////////////////////////////// // // Autofill implementation. // //////////////////////////////////////////////////////////////////////////////// WebDatabase::State AutofillWebDataService::AddFormElementsImpl( const std::vector<FormFieldData>& fields, WebDatabase* db) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB)); AutofillChangeList changes; if (!AutofillTable::FromWebDatabase(db)->AddFormFieldValues( fields, &changes)) { NOTREACHED(); return WebDatabase::COMMIT_NOT_NEEDED; } // Post the notifications including the list of affected keys. // This is sent here so that work resulting from this notification will be // done on the DB thread, and not the UI thread. FOR_EACH_OBSERVER(AutofillWebDataServiceObserverOnDBThread, db_observer_list_, AutofillEntriesChanged(changes)); return WebDatabase::COMMIT_NEEDED; } scoped_ptr<WDTypedResult> AutofillWebDataService::GetFormValuesForElementNameImpl( const base::string16& name, const base::string16& prefix, int limit, WebDatabase* db) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB)); std::vector<base::string16> values; AutofillTable::FromWebDatabase(db)->GetFormValuesForElementName( name, prefix, &values, limit); return scoped_ptr<WDTypedResult>( new WDResult<std::vector<base::string16> >(AUTOFILL_VALUE_RESULT, values)); } WebDatabase::State AutofillWebDataService::RemoveFormElementsAddedBetweenImpl( const base::Time& delete_begin, const base::Time& delete_end, WebDatabase* db) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB)); AutofillChangeList changes; if (AutofillTable::FromWebDatabase(db)->RemoveFormElementsAddedBetween( delete_begin, delete_end, &changes)) { if (!changes.empty()) { // Post the notifications including the list of affected keys. // This is sent here so that work resulting from this notification // will be done on the DB thread, and not the UI thread. FOR_EACH_OBSERVER(AutofillWebDataServiceObserverOnDBThread, db_observer_list_, AutofillEntriesChanged(changes)); } return WebDatabase::COMMIT_NEEDED; } return WebDatabase::COMMIT_NOT_NEEDED; } WebDatabase::State AutofillWebDataService::RemoveExpiredFormElementsImpl( WebDatabase* db) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB)); AutofillChangeList changes; if (AutofillTable::FromWebDatabase(db)->RemoveExpiredFormElements(&changes)) { if (!changes.empty()) { // Post the notifications including the list of affected keys. // This is sent here so that work resulting from this notification // will be done on the DB thread, and not the UI thread. FOR_EACH_OBSERVER(AutofillWebDataServiceObserverOnDBThread, db_observer_list_, AutofillEntriesChanged(changes)); } return WebDatabase::COMMIT_NEEDED; } return WebDatabase::COMMIT_NOT_NEEDED; } WebDatabase::State AutofillWebDataService::RemoveFormValueForElementNameImpl( const base::string16& name, const base::string16& value, WebDatabase* db) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB)); if (AutofillTable::FromWebDatabase(db)->RemoveFormElement(name, value)) { AutofillChangeList changes; changes.push_back( AutofillChange(AutofillChange::REMOVE, AutofillKey(name, value))); // Post the notifications including the list of affected keys. FOR_EACH_OBSERVER(AutofillWebDataServiceObserverOnDBThread, db_observer_list_, AutofillEntriesChanged(changes)); return WebDatabase::COMMIT_NEEDED; } return WebDatabase::COMMIT_NOT_NEEDED; } WebDatabase::State AutofillWebDataService::AddAutofillProfileImpl( const AutofillProfile& profile, WebDatabase* db) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB)); if (!AutofillTable::FromWebDatabase(db)->AddAutofillProfile(profile)) { NOTREACHED(); return WebDatabase::COMMIT_NOT_NEEDED; } // Send GUID-based notification. AutofillProfileChange change( AutofillProfileChange::ADD, profile.guid(), &profile); FOR_EACH_OBSERVER(AutofillWebDataServiceObserverOnDBThread, db_observer_list_, AutofillProfileChanged(change)); return WebDatabase::COMMIT_NEEDED; } WebDatabase::State AutofillWebDataService::UpdateAutofillProfileImpl( const AutofillProfile& profile, WebDatabase* db) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB)); // Only perform the update if the profile exists. It is currently // valid to try to update a missing profile. We simply drop the write and // the caller will detect this on the next refresh. AutofillProfile* original_profile = NULL; if (!AutofillTable::FromWebDatabase(db)->GetAutofillProfile(profile.guid(), &original_profile)) { return WebDatabase::COMMIT_NOT_NEEDED; } scoped_ptr<AutofillProfile> scoped_profile(original_profile); if (!AutofillTable::FromWebDatabase(db)->UpdateAutofillProfileMulti( profile)) { NOTREACHED(); return WebDatabase::COMMIT_NEEDED; } // Send GUID-based notification. AutofillProfileChange change( AutofillProfileChange::UPDATE, profile.guid(), &profile); FOR_EACH_OBSERVER(AutofillWebDataServiceObserverOnDBThread, db_observer_list_, AutofillProfileChanged(change)); return WebDatabase::COMMIT_NEEDED; } WebDatabase::State AutofillWebDataService::RemoveAutofillProfileImpl( const std::string& guid, WebDatabase* db) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB)); AutofillProfile* profile = NULL; if (!AutofillTable::FromWebDatabase(db)->GetAutofillProfile(guid, &profile)) { NOTREACHED(); return WebDatabase::COMMIT_NOT_NEEDED; } scoped_ptr<AutofillProfile> scoped_profile(profile); if (!AutofillTable::FromWebDatabase(db)->RemoveAutofillProfile(guid)) { NOTREACHED(); return WebDatabase::COMMIT_NOT_NEEDED; } // Send GUID-based notification. AutofillProfileChange change(AutofillProfileChange::REMOVE, guid, NULL); FOR_EACH_OBSERVER(AutofillWebDataServiceObserverOnDBThread, db_observer_list_, AutofillProfileChanged(change)); return WebDatabase::COMMIT_NEEDED; } scoped_ptr<WDTypedResult> AutofillWebDataService::GetAutofillProfilesImpl( WebDatabase* db) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB)); std::vector<AutofillProfile*> profiles; AutofillTable::FromWebDatabase(db)->GetAutofillProfiles(&profiles); return scoped_ptr<WDTypedResult>( new WDDestroyableResult<std::vector<AutofillProfile*> >( AUTOFILL_PROFILES_RESULT, profiles, base::Bind(&AutofillWebDataService::DestroyAutofillProfileResult, base::Unretained(this)))); } WebDatabase::State AutofillWebDataService::AddCreditCardImpl( const CreditCard& credit_card, WebDatabase* db) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB)); if (!AutofillTable::FromWebDatabase(db)->AddCreditCard(credit_card)) { NOTREACHED(); return WebDatabase::COMMIT_NOT_NEEDED; } return WebDatabase::COMMIT_NEEDED; } WebDatabase::State AutofillWebDataService::UpdateCreditCardImpl( const CreditCard& credit_card, WebDatabase* db) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB)); // It is currently valid to try to update a missing profile. We simply drop // the write and the caller will detect this on the next refresh. CreditCard* original_credit_card = NULL; if (!AutofillTable::FromWebDatabase(db)->GetCreditCard(credit_card.guid(), &original_credit_card)) { return WebDatabase::COMMIT_NOT_NEEDED; } scoped_ptr<CreditCard> scoped_credit_card(original_credit_card); if (!AutofillTable::FromWebDatabase(db)->UpdateCreditCard(credit_card)) { NOTREACHED(); return WebDatabase::COMMIT_NOT_NEEDED; } return WebDatabase::COMMIT_NEEDED; } WebDatabase::State AutofillWebDataService::RemoveCreditCardImpl( const std::string& guid, WebDatabase* db) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB)); if (!AutofillTable::FromWebDatabase(db)->RemoveCreditCard(guid)) { NOTREACHED(); return WebDatabase::COMMIT_NOT_NEEDED; } return WebDatabase::COMMIT_NEEDED; } scoped_ptr<WDTypedResult> AutofillWebDataService::GetCreditCardsImpl( WebDatabase* db) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB)); std::vector<CreditCard*> credit_cards; AutofillTable::FromWebDatabase(db)->GetCreditCards(&credit_cards); return scoped_ptr<WDTypedResult>( new WDDestroyableResult<std::vector<CreditCard*> >( AUTOFILL_CREDITCARDS_RESULT, credit_cards, base::Bind(&AutofillWebDataService::DestroyAutofillCreditCardResult, base::Unretained(this)))); } WebDatabase::State AutofillWebDataService::RemoveAutofillDataModifiedBetweenImpl( const base::Time& delete_begin, const base::Time& delete_end, WebDatabase* db) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB)); std::vector<std::string> profile_guids; std::vector<std::string> credit_card_guids; if (AutofillTable::FromWebDatabase(db)->RemoveAutofillDataModifiedBetween( delete_begin, delete_end, &profile_guids, &credit_card_guids)) { for (std::vector<std::string>::iterator iter = profile_guids.begin(); iter != profile_guids.end(); ++iter) { AutofillProfileChange change(AutofillProfileChange::REMOVE, *iter, NULL); FOR_EACH_OBSERVER(AutofillWebDataServiceObserverOnDBThread, db_observer_list_, AutofillProfileChanged(change)); } // Note: It is the caller's responsibility to post notifications for any // changes, e.g. by calling the Refresh() method of PersonalDataManager. return WebDatabase::COMMIT_NEEDED; } return WebDatabase::COMMIT_NOT_NEEDED; } void AutofillWebDataService::DestroyAutofillProfileResult( const WDTypedResult* result) { DCHECK(result->GetType() == AUTOFILL_PROFILES_RESULT); const WDResult<std::vector<AutofillProfile*> >* r = static_cast<const WDResult<std::vector<AutofillProfile*> >*>(result); std::vector<AutofillProfile*> profiles = r->GetValue(); STLDeleteElements(&profiles); } void AutofillWebDataService::DestroyAutofillCreditCardResult( const WDTypedResult* result) { DCHECK(result->GetType() == AUTOFILL_CREDITCARDS_RESULT); const WDResult<std::vector<CreditCard*> >* r = static_cast<const WDResult<std::vector<CreditCard*> >*>(result); std::vector<CreditCard*> credit_cards = r->GetValue(); STLDeleteElements(&credit_cards); } void AutofillWebDataService::NotifyAutofillMultipleChangedOnUIThread() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); FOR_EACH_OBSERVER(AutofillWebDataServiceObserverOnUIThread, ui_observer_list_, AutofillMultipleChanged()); }
ScalablyTyped/SlinkyTyped
g/googleapis/src/main/scala/typingsSlinky/googleapis/v1b3Mod/dataflowV1b3/ResourceProjectsJobs.scala
package typingsSlinky.googleapis.v1b3Mod.dataflowV1b3 import typingsSlinky.gaxios.commonMod.GaxiosPromise import typingsSlinky.googleapisCommon.apiMod.APIRequestContext import typingsSlinky.googleapisCommon.apiMod.BodyResponseCallback import typingsSlinky.googleapisCommon.apiMod.MethodOptions import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} @JSImport("googleapis/build/src/apis/dataflow/v1b3", "dataflow_v1b3.Resource$Projects$Jobs") @js.native class ResourceProjectsJobs protected () extends StObject { def this(context: APIRequestContext) = this() /** * dataflow.projects.jobs.aggregated * @desc List the jobs of a project across all regions. * @alias dataflow.projects.jobs.aggregated * @memberOf! () * * @param {object} params Parameters for request * @param {string=} params.filter The kind of filter to use. * @param {string=} params.location The [regional endpoint] (https://cloud.google.com/dataflow/docs/concepts/regional-endpoints) that contains this job. * @param {integer=} params.pageSize If there are many jobs, limit response to at most this many. The actual number of jobs returned will be the lesser of max_responses and an unspecified server-defined limit. * @param {string=} params.pageToken Set this to the 'next_page_token' field of a previous response to request additional results in a long list. * @param {string} params.projectId The project which owns the jobs. * @param {string=} params.view Level of information requested in response. Default is `JOB_VIEW_SUMMARY`. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ def aggregated(): GaxiosPromise[SchemaListJobsResponse] = js.native def aggregated(callback: BodyResponseCallback[SchemaListJobsResponse]): Unit = js.native def aggregated(params: js.UndefOr[scala.Nothing], options: MethodOptions): GaxiosPromise[SchemaListJobsResponse] = js.native def aggregated(params: ParamsResourceProjectsJobsAggregated): GaxiosPromise[SchemaListJobsResponse] = js.native def aggregated( params: ParamsResourceProjectsJobsAggregated, callback: BodyResponseCallback[SchemaListJobsResponse] ): Unit = js.native def aggregated( params: ParamsResourceProjectsJobsAggregated, options: BodyResponseCallback[SchemaListJobsResponse], callback: BodyResponseCallback[SchemaListJobsResponse] ): Unit = js.native def aggregated(params: ParamsResourceProjectsJobsAggregated, options: MethodOptions): GaxiosPromise[SchemaListJobsResponse] = js.native def aggregated( params: ParamsResourceProjectsJobsAggregated, options: MethodOptions, callback: BodyResponseCallback[SchemaListJobsResponse] ): Unit = js.native var context: APIRequestContext = js.native /** * dataflow.projects.jobs.create * @desc Creates a Cloud Dataflow job. To create a job, we recommend using * `projects.locations.jobs.create` with a [regional endpoint] * (https://cloud.google.com/dataflow/docs/concepts/regional-endpoints). * Using `projects.jobs.create` is not recommended, as your job will always * start in `us-central1`. * @alias dataflow.projects.jobs.create * @memberOf! () * * @param {object} params Parameters for request * @param {string=} params.location The [regional endpoint] (https://cloud.google.com/dataflow/docs/concepts/regional-endpoints) that contains this job. * @param {string} params.projectId The ID of the Cloud Platform project that the job belongs to. * @param {string=} params.replaceJobId Deprecated. This field is now in the Job message. * @param {string=} params.view The level of information requested in response. * @param {().Job} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ def create(): GaxiosPromise[SchemaJob] = js.native def create(callback: BodyResponseCallback[SchemaJob]): Unit = js.native def create(params: js.UndefOr[scala.Nothing], options: MethodOptions): GaxiosPromise[SchemaJob] = js.native def create(params: ParamsResourceProjectsJobsCreate): GaxiosPromise[SchemaJob] = js.native def create(params: ParamsResourceProjectsJobsCreate, callback: BodyResponseCallback[SchemaJob]): Unit = js.native def create( params: ParamsResourceProjectsJobsCreate, options: BodyResponseCallback[SchemaJob], callback: BodyResponseCallback[SchemaJob] ): Unit = js.native def create(params: ParamsResourceProjectsJobsCreate, options: MethodOptions): GaxiosPromise[SchemaJob] = js.native def create( params: ParamsResourceProjectsJobsCreate, options: MethodOptions, callback: BodyResponseCallback[SchemaJob] ): Unit = js.native var debug: ResourceProjectsJobsDebug = js.native /** * dataflow.projects.jobs.get * @desc Gets the state of the specified Cloud Dataflow job. To get the * state of a job, we recommend using `projects.locations.jobs.get` with a * [regional endpoint] * (https://cloud.google.com/dataflow/docs/concepts/regional-endpoints). * Using `projects.jobs.get` is not recommended, as you can only get the * state of jobs that are running in `us-central1`. * @alias dataflow.projects.jobs.get * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.jobId The job ID. * @param {string=} params.location The [regional endpoint] (https://cloud.google.com/dataflow/docs/concepts/regional-endpoints) that contains this job. * @param {string} params.projectId The ID of the Cloud Platform project that the job belongs to. * @param {string=} params.view The level of information requested in response. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ def get(): GaxiosPromise[SchemaJob] = js.native def get(callback: BodyResponseCallback[SchemaJob]): Unit = js.native def get(params: js.UndefOr[scala.Nothing], options: MethodOptions): GaxiosPromise[SchemaJob] = js.native def get(params: ParamsResourceProjectsJobsGet): GaxiosPromise[SchemaJob] = js.native def get(params: ParamsResourceProjectsJobsGet, callback: BodyResponseCallback[SchemaJob]): Unit = js.native def get( params: ParamsResourceProjectsJobsGet, options: BodyResponseCallback[SchemaJob], callback: BodyResponseCallback[SchemaJob] ): Unit = js.native def get(params: ParamsResourceProjectsJobsGet, options: MethodOptions): GaxiosPromise[SchemaJob] = js.native def get( params: ParamsResourceProjectsJobsGet, options: MethodOptions, callback: BodyResponseCallback[SchemaJob] ): Unit = js.native /** * dataflow.projects.jobs.getMetrics * @desc Request the job status. To request the status of a job, we * recommend using `projects.locations.jobs.getMetrics` with a [regional * endpoint] * (https://cloud.google.com/dataflow/docs/concepts/regional-endpoints). * Using `projects.jobs.getMetrics` is not recommended, as you can only * request the status of jobs that are running in `us-central1`. * @alias dataflow.projects.jobs.getMetrics * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.jobId The job to get messages for. * @param {string=} params.location The [regional endpoint] (https://cloud.google.com/dataflow/docs/concepts/regional-endpoints) that contains the job specified by job_id. * @param {string} params.projectId A project id. * @param {string=} params.startTime Return only metric data that has changed since this time. Default is to return all information about all metrics for the job. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ def getMetrics(): GaxiosPromise[SchemaJobMetrics] = js.native def getMetrics(callback: BodyResponseCallback[SchemaJobMetrics]): Unit = js.native def getMetrics(params: js.UndefOr[scala.Nothing], options: MethodOptions): GaxiosPromise[SchemaJobMetrics] = js.native def getMetrics(params: ParamsResourceProjectsJobsGetmetrics): GaxiosPromise[SchemaJobMetrics] = js.native def getMetrics(params: ParamsResourceProjectsJobsGetmetrics, callback: BodyResponseCallback[SchemaJobMetrics]): Unit = js.native def getMetrics( params: ParamsResourceProjectsJobsGetmetrics, options: BodyResponseCallback[SchemaJobMetrics], callback: BodyResponseCallback[SchemaJobMetrics] ): Unit = js.native def getMetrics(params: ParamsResourceProjectsJobsGetmetrics, options: MethodOptions): GaxiosPromise[SchemaJobMetrics] = js.native def getMetrics( params: ParamsResourceProjectsJobsGetmetrics, options: MethodOptions, callback: BodyResponseCallback[SchemaJobMetrics] ): Unit = js.native /** * dataflow.projects.jobs.list * @desc List the jobs of a project. To list the jobs of a project in a * region, we recommend using `projects.locations.jobs.get` with a [regional * endpoint] * (https://cloud.google.com/dataflow/docs/concepts/regional-endpoints). To * list the all jobs across all regions, use `projects.jobs.aggregated`. * Using `projects.jobs.list` is not recommended, as you can only get the * list of jobs that are running in `us-central1`. * @alias dataflow.projects.jobs.list * @memberOf! () * * @param {object} params Parameters for request * @param {string=} params.filter The kind of filter to use. * @param {string=} params.location The [regional endpoint] (https://cloud.google.com/dataflow/docs/concepts/regional-endpoints) that contains this job. * @param {integer=} params.pageSize If there are many jobs, limit response to at most this many. The actual number of jobs returned will be the lesser of max_responses and an unspecified server-defined limit. * @param {string=} params.pageToken Set this to the 'next_page_token' field of a previous response to request additional results in a long list. * @param {string} params.projectId The project which owns the jobs. * @param {string=} params.view Level of information requested in response. Default is `JOB_VIEW_SUMMARY`. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ def list(): GaxiosPromise[SchemaListJobsResponse] = js.native def list(callback: BodyResponseCallback[SchemaListJobsResponse]): Unit = js.native def list(params: js.UndefOr[scala.Nothing], options: MethodOptions): GaxiosPromise[SchemaListJobsResponse] = js.native def list(params: ParamsResourceProjectsJobsList): GaxiosPromise[SchemaListJobsResponse] = js.native def list(params: ParamsResourceProjectsJobsList, callback: BodyResponseCallback[SchemaListJobsResponse]): Unit = js.native def list( params: ParamsResourceProjectsJobsList, options: BodyResponseCallback[SchemaListJobsResponse], callback: BodyResponseCallback[SchemaListJobsResponse] ): Unit = js.native def list(params: ParamsResourceProjectsJobsList, options: MethodOptions): GaxiosPromise[SchemaListJobsResponse] = js.native def list( params: ParamsResourceProjectsJobsList, options: MethodOptions, callback: BodyResponseCallback[SchemaListJobsResponse] ): Unit = js.native var messages: ResourceProjectsJobsMessages = js.native /** * dataflow.projects.jobs.snapshot * @desc Snapshot the state of a streaming job. * @alias dataflow.projects.jobs.snapshot * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.jobId The job to be snapshotted. * @param {string} params.projectId The project which owns the job to be snapshotted. * @param {().SnapshotJobRequest} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ def snapshot(): GaxiosPromise[SchemaSnapshot] = js.native def snapshot(callback: BodyResponseCallback[SchemaSnapshot]): Unit = js.native def snapshot(params: js.UndefOr[scala.Nothing], options: MethodOptions): GaxiosPromise[SchemaSnapshot] = js.native def snapshot(params: ParamsResourceProjectsJobsSnapshot): GaxiosPromise[SchemaSnapshot] = js.native def snapshot(params: ParamsResourceProjectsJobsSnapshot, callback: BodyResponseCallback[SchemaSnapshot]): Unit = js.native def snapshot( params: ParamsResourceProjectsJobsSnapshot, options: BodyResponseCallback[SchemaSnapshot], callback: BodyResponseCallback[SchemaSnapshot] ): Unit = js.native def snapshot(params: ParamsResourceProjectsJobsSnapshot, options: MethodOptions): GaxiosPromise[SchemaSnapshot] = js.native def snapshot( params: ParamsResourceProjectsJobsSnapshot, options: MethodOptions, callback: BodyResponseCallback[SchemaSnapshot] ): Unit = js.native /** * dataflow.projects.jobs.update * @desc Updates the state of an existing Cloud Dataflow job. To update the * state of an existing job, we recommend using * `projects.locations.jobs.update` with a [regional endpoint] * (https://cloud.google.com/dataflow/docs/concepts/regional-endpoints). * Using `projects.jobs.update` is not recommended, as you can only update * the state of jobs that are running in `us-central1`. * @alias dataflow.projects.jobs.update * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.jobId The job ID. * @param {string=} params.location The [regional endpoint] (https://cloud.google.com/dataflow/docs/concepts/regional-endpoints) that contains this job. * @param {string} params.projectId The ID of the Cloud Platform project that the job belongs to. * @param {().Job} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ def update(): GaxiosPromise[SchemaJob] = js.native def update(callback: BodyResponseCallback[SchemaJob]): Unit = js.native def update(params: js.UndefOr[scala.Nothing], options: MethodOptions): GaxiosPromise[SchemaJob] = js.native def update(params: ParamsResourceProjectsJobsUpdate): GaxiosPromise[SchemaJob] = js.native def update(params: ParamsResourceProjectsJobsUpdate, callback: BodyResponseCallback[SchemaJob]): Unit = js.native def update( params: ParamsResourceProjectsJobsUpdate, options: BodyResponseCallback[SchemaJob], callback: BodyResponseCallback[SchemaJob] ): Unit = js.native def update(params: ParamsResourceProjectsJobsUpdate, options: MethodOptions): GaxiosPromise[SchemaJob] = js.native def update( params: ParamsResourceProjectsJobsUpdate, options: MethodOptions, callback: BodyResponseCallback[SchemaJob] ): Unit = js.native var workItems: ResourceProjectsJobsWorkitems = js.native }
byspigotapi/CloudNet
cloudnet-cord/cloudnet-cloudflare/src/main/java/de/dytanic/cloudnet/cloudflare/util/DNSRecord.java
/* * Copyright (c) <NAME> 2017 */ package de.dytanic.cloudnet.cloudflare.util; import com.google.gson.JsonObject; import lombok.AllArgsConstructor; import lombok.Getter; /** * General container for storing a DNS record. */ @Getter @AllArgsConstructor public class DNSRecord { /** * The type of this record. */ private String type; /** * Name of this record like in a zone file */ private String name; /** * The content of this record like in a zone file */ private String content; /** * The "Time-to-live" for this record */ private int ttl; /** * Whether the record should be proxied by CLoudFlare */ private boolean proxied; /** * Additional data about this record for SRV records */ private JsonObject data; }
knokko/Custom-Races
Races/src/nl/knokko/races/event/response/RaceBreakBlockResponse.java
<reponame>knokko/Custom-Races package nl.knokko.races.event.response; import nl.knokko.races.event.RaceBreakBlockEvent; public interface RaceBreakBlockResponse { void execute(RaceBreakBlockEvent event); }
fee1in/hms-flutter-plugin
flutter-hms-ads/android/src/main/java/com/huawei/hms/flutter/ads/utils/constants/AdGravity.java
/* Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.huawei.hms.flutter.ads.utils.constants; import android.view.Gravity; public enum AdGravity { bottom(Gravity.BOTTOM), center(Gravity.CENTER_VERTICAL), top(Gravity.TOP); private final int value; AdGravity(final int value) { this.value = value; } public int getValue() { return value; } }
tkobayas/drools-wb
drools-wb-screens/drools-wb-guided-dtable-editor/drools-wb-guided-dtable-editor-client/src/main/java/org/drools/workbench/screens/guided/dtable/client/widget/table/events/cdi/DecisionTableSelectedEvent.java
/* * Copyright 2011 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.drools.workbench.screens.guided.dtable.client.widget.table.events.cdi; import java.util.Optional; import org.drools.workbench.screens.guided.dtable.client.widget.table.GuidedDecisionTableView; import org.kie.soup.commons.validation.PortablePreconditions; public class DecisionTableSelectedEvent { private final Optional<GuidedDecisionTableView.Presenter> dtPresenter; private final boolean isLockRequired; public DecisionTableSelectedEvent(final GuidedDecisionTableView.Presenter dtPresenter) { this(dtPresenter, true); } public DecisionTableSelectedEvent(final GuidedDecisionTableView.Presenter dtPresenter, final boolean isLockRequired) { this.dtPresenter = Optional.of(PortablePreconditions.checkNotNull("dtPresenter", dtPresenter)); this.isLockRequired = isLockRequired; } public static final DecisionTableSelectedEvent NONE = new DecisionTableSelectedEvent(); private DecisionTableSelectedEvent() { dtPresenter = Optional.empty(); isLockRequired = false; } public Optional<GuidedDecisionTableView.Presenter> getPresenter() { return dtPresenter; } public boolean isLockRequired() { return isLockRequired; } }
cmcfarlen/trafficserver
plugins/experimental/stek_share/state_manager.h
<reponame>cmcfarlen/trafficserver /************************************************************************ Copyright 2017-2019 eBay Inc. Author/Developer(s): <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 https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. **************************************************************************/ // This file is based on the example code from https://github.com/eBay/NuRaft/tree/master/examples #pragma once #include <libnuraft/nuraft.hxx> #include "log_store.h" class STEKShareSMGR : public nuraft::state_mgr { public: STEKShareSMGR(int srv_id, const std::string &endpoint, std::map<int, std::string> server_list) : my_id_(srv_id), my_endpoint_(endpoint), cur_log_store_(nuraft::cs_new<STEKShareLogStore>()) { my_srv_config_ = nuraft::cs_new<nuraft::srv_config>(srv_id, endpoint); // Initial cluster config, read from the list loaded from the configuration file. saved_config_ = nuraft::cs_new<nuraft::cluster_config>(); for (auto const &s : server_list) { int server_id = s.first; std::string endpoint = s.second; nuraft::ptr<nuraft::srv_config> new_server = nuraft::cs_new<nuraft::srv_config>(server_id, endpoint); saved_config_->get_servers().push_back(new_server); } } ~STEKShareSMGR() {} nuraft::ptr<nuraft::cluster_config> load_config() { return saved_config_; } void save_config(const nuraft::cluster_config &config) { nuraft::ptr<nuraft::buffer> buf = config.serialize(); saved_config_ = nuraft::cluster_config::deserialize(*buf); } void save_state(const nuraft::srv_state &state) { nuraft::ptr<nuraft::buffer> buf = state.serialize(); saved_state_ = nuraft::srv_state::deserialize(*buf); } nuraft::ptr<nuraft::srv_state> read_state() { return saved_state_; } nuraft::ptr<nuraft::log_store> load_log_store() { return cur_log_store_; } int32_t server_id() { return my_id_; } void system_exit(const int exit_code) { } nuraft::ptr<nuraft::srv_config> get_srv_config() const { return my_srv_config_; } private: int my_id_; std::string my_endpoint_; nuraft::ptr<STEKShareLogStore> cur_log_store_; nuraft::ptr<nuraft::srv_config> my_srv_config_; nuraft::ptr<nuraft::cluster_config> saved_config_; nuraft::ptr<nuraft::srv_state> saved_state_; };
persequor-com/ran
core/src/main/java/io/ran/ObjectMapColumnizer.java
/* Copyright (C) Persequor ApS - All Rights Reserved * Unauthorized copying of this file, via any medium is strictly prohibited * Proprietary and confidential * Written by Persequor Development Team <<EMAIL>>, */ package io.ran; import io.ran.token.Token; import java.math.BigDecimal; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZonedDateTime; import java.util.Collection; import java.util.UUID; public interface ObjectMapColumnizer { void set(Token key, String value); void set(Token key, Character value); void set(Token key, ZonedDateTime value); void set(Token key, LocalDateTime value); void set(Token key, Instant value); void set(Token key, LocalDate value); void set(Token key, Integer value); void set(Token key, Short value); void set(Token key, Long value); void set(Token key, UUID value); void set(Token key, Double value); void set(Token key, BigDecimal value); void set(Token key, Float value); void set(Token key, Boolean value); void set(Token key, Byte value); void set(Token key, byte[] value); void set(Token key, Enum<?> value); void set(Token key, Collection<?> value); }
michel-pi/xenforo-documentation
docs/2-1-0/df/d7e/class_x_f_1_1_session_1_1_null_storage.js
var class_x_f_1_1_session_1_1_null_storage = [ [ "deleteExpiredSessions", "df/d7e/class_x_f_1_1_session_1_1_null_storage.html#a1fdd8ae7c7c4a7f9aca80581a31a01e5", null ], [ "deleteSession", "df/d7e/class_x_f_1_1_session_1_1_null_storage.html#a70648a90a8af44589ba119abfd2417f2", null ], [ "getSession", "df/d7e/class_x_f_1_1_session_1_1_null_storage.html#a28a6c013ae88afcdfcce96084a16dae6", null ], [ "writeSession", "df/d7e/class_x_f_1_1_session_1_1_null_storage.html#a1ad977b6f1a60dc064187908bf87551b", null ] ];
anupamdev/Spring
pet-sitter/15-ps-ws-rest-practice/src/main/java/com/ps/config/WebConfig.java
<reponame>anupamdev/Spring<gh_stars>10-100 package com.ps.config; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.servlet.config.annotation.*; import org.springframework.web.servlet.view.InternalResourceViewResolver; import java.util.List; @Configuration @EnableWebMvc @ComponentScan(basePackages = {"com.ps.web", "com.ps.exs"}) public class WebConfig extends WebMvcConfigurerAdapter { //Declare our static resources. I added cache to the java config but it?s not required. @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/images/**").addResourceLocations("/images/").setCachePeriod(31556926); } // <=> <mvc:default-servlet-handler/> @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); } @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("welcome"); } @Bean InternalResourceViewResolver getViewResolver(){ InternalResourceViewResolver resolver = new InternalResourceViewResolver(); resolver.setPrefix("/WEB-INF/"); resolver.setSuffix(".jsp" ); return resolver; } /** * Setting the MappingJackson2HttpMessageConverter and configuring it * @return */ @Bean public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() { MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter(); mappingJackson2HttpMessageConverter.setObjectMapper(objectMapper()); return mappingJackson2HttpMessageConverter; } @Bean public ObjectMapper objectMapper() { ObjectMapper objMapper = new ObjectMapper(); objMapper.enable(SerializationFeature.INDENT_OUTPUT); objMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); return objMapper; } @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { super.configureMessageConverters(converters); converters.add(mappingJackson2HttpMessageConverter()); } }
arvisingh098/stake
public/aragon-ui/esm/IconConnection.js
<reponame>arvisingh098/stake<gh_stars>1-10 import './slicedToArray-4e274c67.js'; import './unsupportedIterableToArray-137e449b.js'; import React from 'react'; import './_commonjsHelpers-97e6d7b1.js'; import './index-097535f1.js'; import './defineProperty-a0480c32.js'; import 'styled-components'; import './miscellaneous.js'; import './environment.js'; import './font.js'; import './constants.js'; import './breakpoints.js'; import './springs.js'; import './text-styles.js'; import { _ as _extends } from './extends-db4f0c26.js'; import { _ as _objectWithoutProperties } from './objectWithoutProperties-234758e1.js'; import './index-422d37c0.js'; import { u as useIconSize, I as IconPropTypes } from './IconPropTypes-aab7337d.js'; function IconConnection(_ref) { var size = _ref.size, props = _objectWithoutProperties(_ref, ["size"]); var sizeValue = useIconSize(size); return /*#__PURE__*/React.createElement("svg", _extends({ width: sizeValue, height: sizeValue, fill: "none", viewBox: "0 0 24 24" }, props), /*#__PURE__*/React.createElement("path", { fill: "currentColor", d: "M12 9.388a2.385 2.385 0 00-2.382 2.382A2.385 2.385 0 0012 14.152a2.385 2.385 0 002.382-2.382A2.385 2.385 0 0012 9.388zm0 3.31a.929.929 0 010-1.856.929.929 0 010 1.855zm4.022-4.951a.727.727 0 10-1.027 1.029 4.242 4.242 0 01.003 5.992l-.004.004a.727.727 0 001.029 1.028l.004-.004a5.698 5.698 0 00-.005-8.05zm-7.017 7.017a4.21 4.21 0 01-1.242-2.996 4.21 4.21 0 011.243-3 .727.727 0 00-1.029-1.029l-.004.004a5.698 5.698 0 00.005 8.05.725.725 0 001.028 0 .727.727 0 000-1.03z" }), /*#__PURE__*/React.createElement("path", { fill: "currentColor", d: "M18.364 5.405a.727.727 0 00-1.028 1.029c2.941 2.942 2.941 7.73 0 10.672a.727.727 0 101.028 1.028A8.943 8.943 0 0021 11.77a8.943 8.943 0 00-2.636-6.365zm-11.7 1.029a.727.727 0 00-1.028-1.029A8.943 8.943 0 003 11.77a8.94 8.94 0 002.636 6.364.724.724 0 001.028 0 .727.727 0 000-1.028c-2.941-2.943-2.941-7.73 0-10.672z" })); } IconConnection.propTypes = IconPropTypes; export default IconConnection; //# sourceMappingURL=IconConnection.js.map
LeyliG/ds4se
benchmarking/traceability/datasets/italian/smos/[smos-raw-src]/ServletInitialize.java
package smos.application; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import smos.utility.Utility; /** * Servlet utilizzata per inizializzare i parametri del sistema. * * @author <NAME>, <NAME>. * */ public class ServletInitialize extends HttpServlet { private static final long serialVersionUID = -2542143445249797492L; @SuppressWarnings("unused") private ServletConfig config; /** * Inizializza i parametri */ public void init(ServletConfig config) throws ServletException { this.config = config; //Setto il server smtp specificato nel file di configurazione xml Utility.setServerSmtp(config.getInitParameter("serverSmtp")); //Setto i parametri necessari alla connessione al Database Utility.setDriverMySql(config.getInitParameter("driverMySql")); Utility.setFullPathDatabase(config.getInitParameter("fullPathDatabase")); Utility.setUserName(config.getInitParameter("userName")); Utility.setPassword(config.getInitParameter("password")); Utility.setMaxPoolSize(Integer.valueOf(config.getInitParameter("maxPoolSize"))); Utility.setWaitTimeout(Integer.valueOf(config.getInitParameter("waitTimeout"))); Utility.setActiveTimeout(Integer.valueOf(config.getInitParameter("activeTimeout"))); Utility.setPoolTimeout(Integer.valueOf(config.getInitParameter("poolTimeout"))); Utility.setTextFooter(config.getInitParameter("textFooter")); } }
silvinobrigido/P2B-Prob2-G
src/br/furb/programcaoii/problema2/factory/ControllerFactory.java
<reponame>silvinobrigido/P2B-Prob2-G package br.furb.programcaoii.problema2.factory; import br.furb.programcaoii.problema2.controller.Controller; import java.lang.reflect.Constructor; import java.util.HashMap; import java.util.Map; /** * * @author ariel */ public class ControllerFactory<C extends Controller> { private static final Map<String, Controller> map = new HashMap<>(); private static <C extends Controller> String getNome(Class<C> clazz) { return clazz.getName(); } public static <C extends Controller> C getController(Class<C> clazz) { String nomeClasse = getNome(clazz); C controller = (C) map.get(nomeClasse); if (null == controller) { controller = instanciarController(clazz); map.put(nomeClasse, controller); } return controller; } private static <C extends Controller> C instanciarController(Class<C> clazz) { Constructor<?>[] construtores = clazz.getConstructors(); for (Constructor<?> construtor : construtores) { if (0 == construtor.getParameterCount()) { try { return (C) construtor.newInstance(new Object[] {}); } catch (Exception e) { return null; } } } return null; } }
oryxsolutions/frappe
cypress/integration/file_uploader.js
<reponame>oryxsolutions/frappe context('FileUploader', () => { before(() => { cy.login(); cy.visit('/app'); }); function open_upload_dialog() { cy.window().its('frappe').then(frappe => { new frappe.ui.FileUploader(); }); } it('upload dialog api works', () => { open_upload_dialog(); cy.get_open_dialog().should('contain', 'Drag and drop files'); cy.hide_dialog(); }); it('should accept dropped files', () => { open_upload_dialog(); cy.get_open_dialog().find('.file-upload-area').attachFile('example.json', { subjectType: 'drag-n-drop', }); cy.get_open_dialog().find('.file-name').should('contain', 'example.json'); cy.intercept('POST', '/api/method/upload_file').as('upload_file'); cy.get_open_dialog().findByRole('button', {name: 'Upload'}).click(); cy.wait('@upload_file').its('response.statusCode').should('eq', 200); cy.get('.modal:visible').should('not.exist'); }); it('should accept uploaded files', () => { open_upload_dialog(); cy.get_open_dialog().findByRole('button', {name: 'Library'}).click(); cy.findByPlaceholderText('Search by filename or extension').type('example.json'); cy.get_open_dialog().findAllByText('example.json').first().click(); cy.intercept('POST', '/api/method/upload_file').as('upload_file'); cy.get_open_dialog().findByRole('button', {name: 'Upload'}).click(); cy.wait('@upload_file').its('response.body.message') .should('have.property', 'file_name', 'example.json'); cy.get('.modal:visible').should('not.exist'); }); it('should accept web links', () => { open_upload_dialog(); cy.get_open_dialog().findByRole('button', {name: 'Link'}).click(); cy.get_open_dialog() .findByPlaceholderText('Attach a web link') .type('https://github.com', { delay: 100, force: true }); cy.intercept('POST', '/api/method/upload_file').as('upload_file'); cy.get_open_dialog().findByRole('button', {name: 'Upload'}).click(); cy.wait('@upload_file').its('response.body.message') .should('have.property', 'file_url', 'https://github.com'); cy.get('.modal:visible').should('not.exist'); }); it('should allow cropping and optimization for valid images', () => { open_upload_dialog(); cy.get_open_dialog().find('.file-upload-area').attachFile('sample_image.jpg', { subjectType: 'drag-n-drop', }); cy.get_open_dialog().findAllByText('sample_image.jpg').should('exist'); cy.get_open_dialog().find('.btn-crop').first().click(); cy.get_open_dialog().findByRole('button', {name: 'Crop'}).click(); cy.get_open_dialog().findAllByRole('checkbox', {name: 'Optimize'}).should('exist'); cy.get_open_dialog().findAllByLabelText('Optimize').first().click(); cy.intercept('POST', '/api/method/upload_file').as('upload_file'); cy.get_open_dialog().findByRole('button', {name: 'Upload'}).click(); cy.wait('@upload_file').its('response.statusCode').should('eq', 200); cy.get('.modal:visible').should('not.exist'); }); });
neharkarvishal/Data-Structures-and-Algorithms-with-Object-Oriented-Design-Patterns-in-C-
pgm10_15.cpp
<filename>pgm10_15.cpp // // This file contains the C++ code from Program 10.15 of // "Data Structures and Algorithms // with Object-Oriented Design Patterns in C++" // by <NAME>. // // Copyright (c) 1998 by <NAME>, P.Eng. All rights reserved. // // http://www.pads.uwaterloo.ca/Bruno.Preiss/books/opus4/programs/pgm10_15.cpp // Object& MWayTree::Find (Object const& object) const { if (IsEmpty ()) return NullObject::Instance (); unsigned int i = numberOfKeys; while (i > 0) { int const diff = object.Compare (*key [i]); if (diff == 0) return *key [i]; if (diff > 0) break; --i; } return subtree [i]->Find (object); }
iabernikhin/VK-GL-CTS
modules/internal/ditSRGB8ConversionTest.cpp
<reponame>iabernikhin/VK-GL-CTS /*------------------------------------------------------------------------- * drawElements Internal Test Module * --------------------------------- * * Copyright 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *//*! * \file * \brief 8-bit sRGB conversion test. *//*--------------------------------------------------------------------*/ #include "ditSRGB8ConversionTest.hpp" #include "tcuFloat.hpp" #include "tcuTestLog.hpp" #include "tcuTextureUtil.hpp" #include "tcuVectorUtil.hpp" namespace dit { namespace { deUint32 calculateDiscreteFloatDistance (float a, float b) { const deUint32 au = tcu::Float32(a).bits(); const deUint32 bu = tcu::Float32(b).bits(); const bool asign = (au & (0x1u << 31u)) != 0u; const bool bsign = (bu & (0x1u << 31u)) != 0u; const deUint32 avalue = (au & ((0x1u << 31u) - 1u)); const deUint32 bvalue = (bu & ((0x1u << 31u) - 1u)); if (asign != bsign) return avalue + bvalue + 1u; else if (avalue < bvalue) return bvalue - avalue; else return avalue - bvalue; } const tcu::UVec4 calculateDiscreteFloatDistance (const tcu::Vec4& ref, const tcu::Vec4& res) { return tcu::UVec4(calculateDiscreteFloatDistance(ref[0], res[0]), calculateDiscreteFloatDistance(ref[1], res[1]), calculateDiscreteFloatDistance(ref[2], res[2]), calculateDiscreteFloatDistance(ref[3], res[3])); } class SRGB8ConversionTest : public tcu::TestCase { public: SRGB8ConversionTest (tcu::TestContext& context) : tcu::TestCase (context, "srgb8", "SRGB8 conversion test") { } IterateResult iterate (void) { bool isOk = true; tcu::TestLog& log = m_testCtx.getLog(); for (int i = 0; i < 256; i++) { const tcu::UVec4 src (i); const tcu::Vec4 res (tcu::sRGBA8ToLinear(src)); const tcu::Vec4 ref (tcu::sRGBToLinear(src.cast<float>() / tcu::Vec4(255.0f))); const tcu::Vec4 diff (res - ref); const tcu::UVec4 discreteFloatDiff (calculateDiscreteFloatDistance(ref, res)); if (tcu::anyNotEqual(res, ref)) log << tcu::TestLog::Message << i << ", Res: " << res << ", Ref: " << ref << ", Diff: " << diff << ", Discrete float diff: " << discreteFloatDiff << tcu::TestLog::EndMessage; if (tcu::boolAny(tcu::greaterThan(discreteFloatDiff, tcu::UVec4(1u)))) isOk = false; } if (isOk) m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass"); else m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Got ulp diffs greater than one."); return STOP; } }; } // anonymous tcu::TestCase* createSRGB8ConversionTest (tcu::TestContext& context) { return new SRGB8ConversionTest(context); } } // dit
zachhaitz/kochiku
lib/github_request.rb
<filename>lib/github_request.rb require 'uri' require 'net/http' class GithubRequest class ResponseError < RuntimeError attr_accessor :response end def self.get(url, oauth_token) uri = URI(url) request = Net::HTTP::Get.new(uri.request_uri) request["Authorization"] = "token #{oauth_token}" request["Accept"] = "application/vnd.github.v3+json" make_request(uri, request) end def self.post(url, data, oauth_token) uri = URI(url) request = Net::HTTP::Post.new(uri.request_uri) request.body = data.to_json request["Authorization"] = "token #{oauth_token}" request["Accept"] = "application/vnd.github.v3+json" request["Content-Type"] = "application/json; charset=utf-8" make_request(uri, request) end def self.patch(url, data, oauth_token) uri = URI(url) request = Net::HTTP::Patch.new(uri.request_uri) request.body = data.to_json request["Authorization"] = "token #{oauth_token}" request["Accept"] = "application/vnd.github.v3+json" request["Content-Type"] = "application/json; charset=utf-8" make_request(uri, request) end def self.make_request(uri, request_object) Rails.logger.info("Github request: #{request_object.method}, #{uri}") body = nil Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http| response = http.request(request_object) body = response.body Rails.logger.info("Github response: #{response.inspect}") Rails.logger.info("Github response body: #{body.inspect}") unless response.is_a? Net::HTTPSuccess response_error = ResponseError.new("response: #{response.class} body: #{body}") response_error.response = response raise response_error end end body end private_class_method :make_request end
ariella/DeployTool
HandsOn/Aula02/Cookbook/Blueprints/grupos.py
<reponame>ariella/DeployTool #!/usr/bin/python from flask import Blueprint,jsonify grupos = Blueprint("grupos",__name__) @grupos.route("/grupos/") def list_grupos(): data = {"message":"Aqui serao listados todos os grupos"} return jsonify(data) @grupos.route("/grupos/",methods=["POST"]) def inserir_grupos(): data = {"message":"Aqui serao cadastrados os novos grupos"} return jsonify(data) @grupos.route("/grupos/<int:id>/",methods=["GET"]) def select_grupos(id): data = {"message":"Mostrando grupo cujo o ID e igual a %s"%id} return jsonify(data) @grupos.route("/grupos/<int:id>/",methods=["PUT"]) def update_grupos(id): data = {"message":"Atualizando o grupo cujo o ID e igual a %s"%id} return jsonify(data) @grupos.route("/grupos/<int:id>/",methods=["DELETE"]) def delete_grupos(id): data = {"message":"Deletando grupo cujo o ID e igual a %s"%id} return jsonify(data)
roboterclubaachen/xpcc-doc
docs/api/group__ui.js
<filename>docs/api/group__ui.js var group__ui = [ [ "Button", "classxpcc_1_1_button.html", null ], [ "ButtonGroup", "classxpcc_1_1_button_group.html", [ [ "Identifier", "classxpcc_1_1_button_group.html#a5ab6ab92cc1bbb34ee431ec5e85b4443", [ [ "NONE", "classxpcc_1_1_button_group.html#a5ab6ab92cc1bbb34ee431ec5e85b4443a2139cda31544d0b80da8f588d3d0a79c", null ], [ "BUTTON0", "classxpcc_1_1_button_group.html#a5ab6ab92cc1bbb34ee431ec5e85b4443ad08910ad36221c826164908220c33a48", null ], [ "BUTTON1", "classxpcc_1_1_button_group.html#a5ab6ab92cc1bbb34ee431ec5e85b4443a0dc3a3d66507ed667d89a1d33e533156", null ], [ "BUTTON2", "classxpcc_1_1_button_group.html#a5ab6ab92cc1bbb34ee431ec5e85b4443afc1b8badc7f2ade3f038c83c0d09be3c", null ], [ "BUTTON3", "classxpcc_1_1_button_group.html#a5ab6ab92cc1bbb34ee431ec5e85b4443a33513b77d3f86bf7635367737f00ad23", null ], [ "BUTTON4", "classxpcc_1_1_button_group.html#a5ab6ab92cc1bbb34ee431ec5e85b4443a479e3e7ce77a1c1c6423881d8eac795a", null ], [ "BUTTON5", "classxpcc_1_1_button_group.html#a5ab6ab92cc1bbb34ee431ec5e85b4443a220077f6136cc38fbf86f82568da5480", null ], [ "BUTTON6", "classxpcc_1_1_button_group.html#a5ab6ab92cc1bbb34ee431ec5e85b4443ad79aa7626e66943e85f6faa141c75b75", null ], [ "BUTTON7", "classxpcc_1_1_button_group.html#a5ab6ab92cc1bbb34ee431ec5e85b4443adb42beb7d50000bab9e158cafa46e9d0", null ], [ "ALL", "classxpcc_1_1_button_group.html#a5ab6ab92cc1bbb34ee431ec5e85b4443a413bc4f5e448b2bf02a57e138518dd08", null ] ] ], [ "ButtonGroup", "classxpcc_1_1_button_group.html#ae444915a84bf4d45abaa915450273703", null ], [ "getState", "classxpcc_1_1_button_group.html#aa3cef6ff7d391454d8dfb628a0ef58fa", null ], [ "isReleased", "classxpcc_1_1_button_group.html#a543afb9661099587cbd62104958d5a1d", null ], [ "isPressed", "classxpcc_1_1_button_group.html#a650056c1955240d1785c3581176444e9", null ], [ "isRepeated", "classxpcc_1_1_button_group.html#a43f5b54a271461e2329755a8d2b9aeeb", null ], [ "isPressedShort", "classxpcc_1_1_button_group.html#a47643a4d831e193be47b4bd52280a72e", null ], [ "isPressedLong", "classxpcc_1_1_button_group.html#ac627e9ed0df16256bca2bacff57146ef", null ], [ "update", "classxpcc_1_1_button_group.html#ab5442ca6572d259525ce9f7de31f7ac1", null ], [ "timeout", "classxpcc_1_1_button_group.html#af2d47cca97ecbb0d40b463fa405631f6", null ], [ "interval", "classxpcc_1_1_button_group.html#adafb23682a9fa77ece5adf1200bf8cdf", null ], [ "repeatMask", "classxpcc_1_1_button_group.html#a8e1bbec435f7ccc245382533302255a5", null ], [ "repeatCounter", "classxpcc_1_1_button_group.html#a4df673cfc086c4d149ab57f867e8b52d", null ], [ "state", "classxpcc_1_1_button_group.html#a7d37e81e07826d5b112eb3f1a5cd70e1", null ], [ "pressState", "classxpcc_1_1_button_group.html#aa9b8544d7314ad738386a4772876b48f", null ], [ "releaseState", "classxpcc_1_1_button_group.html#a8522cd5724ac3a84ed3d601c64ae3f57", null ], [ "repeatState", "classxpcc_1_1_button_group.html#a26e6f526b30888d92e8c0584916bae18", null ] ] ], [ "UnixTime", "classxpcc_1_1_unix_time.html", [ [ "UnixTime", "classxpcc_1_1_unix_time.html#aa4fdc5faff748e7c20515fb9ead9f17c", null ], [ "operator uint32_t", "classxpcc_1_1_unix_time.html#ab0b513855a7c3cf02c59e7481eec45fe", null ], [ "toDate", "classxpcc_1_1_unix_time.html#a77b77725d8cf9d86af36f1cfd2933e45", null ] ] ], [ "Date", "classxpcc_1_1_date.html", [ [ "toUnixTimestamp", "classxpcc_1_1_date.html#af7b4cfdc4534fbd9b69843b7d63d193f", null ], [ "second", "classxpcc_1_1_date.html#a7a5cf60c1964ed80db860fb31de0d228", null ], [ "minute", "classxpcc_1_1_date.html#ab7fe455ab93917a403b6ae6b9cbd6804", null ], [ "hour", "classxpcc_1_1_date.html#a4b39cc587f72a772b8aa03a269783d1d", null ], [ "day", "classxpcc_1_1_date.html#aea31871fca3acd678fd9c49ad4a6039f", null ], [ "month", "classxpcc_1_1_date.html#aa8e96e3a7eb20fb3f572fbd1279a5d62", null ], [ "year", "classxpcc_1_1_date.html#a4386667477b13897edae5cb498f3a084", null ], [ "dayOfTheWeek", "classxpcc_1_1_date.html#ad936b70a10c10e94b7444f35acd3f31a", null ], [ "dayOfTheYear", "classxpcc_1_1_date.html#a3e8fd18760f0f34f4dd79b0582477fd0", null ] ] ], [ "Animators", "group__animation.html", "group__animation" ], [ "Graphics", "group__graphics.html", "group__graphics" ], [ "Graphical User Interface", "group__gui.html", "group__gui" ], [ "LED Indicators", "group__led.html", "group__led" ], [ "Display Menu", "group__display__menu.html", "group__display__menu" ] ];
edorosh/kangal
pkg/kubernetes/apis/loadtest/v1/loadtest_test.go
<filename>pkg/kubernetes/apis/loadtest/v1/loadtest_test.go package v1 import ( "testing" "github.com/stretchr/testify/assert" metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) func TestHash(t *testing.T) { assert.Equal(t, "da39a3ee5e6b4b0d3255bfef95601890afd80709", getHashFromString("")) } func TestBuildLoadTestObject(t *testing.T) { ltType := LoadTestTypeJMeter expectedDP := int32(2) spec := LoadTestSpec{ Type: ltType, DistributedPods: &expectedDP, TestFile: "load-test file\n", TestData: "test data 1\ntest data 2\n", EnvVars: "envVar1,value1\nenvVar2,value2\n", } expectedLt := LoadTest{ TypeMeta: metaV1.TypeMeta{}, ObjectMeta: metaV1.ObjectMeta{}, Spec: spec, Status: LoadTestStatus{ Phase: LoadTestCreating, }, } lt, err := BuildLoadTestObject(spec) assert.NoError(t, err) assert.Equal(t, expectedLt.Spec, lt.Spec) assert.Equal(t, expectedLt.Status.Phase, lt.Status.Phase) }
margostino/amplifix
toolkit/src/main/java/org/gaussian/amplifix/toolkit/processor/ConversionProcessor.java
package org.gaussian.amplifix.toolkit.processor; import io.micrometer.core.instrument.Meter; import io.micrometer.core.instrument.Tag; import io.vertx.core.json.JsonObject; import lombok.extern.slf4j.Slf4j; import org.gaussian.amplifix.toolkit.annotation.ConversionRegister; import org.gaussian.amplifix.toolkit.datagrid.DataGridNode; import org.gaussian.amplifix.toolkit.model.Event; import java.util.ArrayList; import java.util.List; import java.util.Optional; import static io.micrometer.core.instrument.Metrics.counter; import static java.util.Arrays.asList; @Slf4j public class ConversionProcessor extends EventProcessor { public DataGridNode dataGridNode; public ConversionProcessor(DataGridNode dataGridNode) { super(ConversionRegister.class); this.dataGridNode = dataGridNode; } protected List<Meter> getData(Event event) { List<Meter> meters = new ArrayList<>(); List<Tag> tags = new ArrayList<>(); JsonObject metadata = null;//event.metadata.control; JsonObject data = event.data; // TODO: evaluate decode in a class JsonObject control = metadata.getJsonObject("control"); String key = metadata.getString("key"); String metricName = decorateMetricName(DEFAULT_PREFIX, "conversion"); Optional<String> fieldName = control.fieldNames() .stream() .findFirst(); if (fieldName.isPresent()) { String value = control.getString(fieldName.get()); String valueToControl = data.getString(fieldName.get()); if (valueToControl.equalsIgnoreCase(value)) { dataGridNode.remove(key); } meters = asList(counter(metricName, tags)); } return meters; } }
markosbg/debug
rabix-engine/src/main/java/org/rabix/engine/processor/dispatcher/impl/AsyncEventDispatcher.java
package org.rabix.engine.processor.dispatcher.impl; import org.rabix.engine.event.Event; import org.rabix.engine.processor.EventProcessor; import org.rabix.engine.processor.dispatcher.EventDispatcher; import com.google.inject.Inject; public class AsyncEventDispatcher implements EventDispatcher { private final EventProcessor engine; @Inject public AsyncEventDispatcher(EventProcessor engine) { this.engine = engine; } @Override public void send(Event event) { engine.addToQueue(event); } @Override public Type getType() { return Type.ASYNC; } }
rmurphey/mulberry
app/toura/components/PinCaption.js
<gh_stars>1-10 dojo.provide('toura.components.PinCaption'); dojo.require('toura.components.BodyText'); dojo.declare('toura.components.PinCaption', toura.components.BodyText, { "class" : 'pin-caption', _getBodyText : function() { return this.caption || this.inherited(arguments); } });
marinisz/Projeto01-Lab.Desenvolvimento
implementacao/project3-final/View/View.java
package View; import Utils.Data; import Utils.Pessoa; import java.util.Calendar; import java.util.Date; import java.util.Scanner; public class View { protected static final Scanner teclado = new Scanner(System.in); private static View instance; private View() { } public static View getInstance() { if (instance == null) { return instance = new View(); } else return instance; } public static Pessoa pessoaForm() throws Exception { System.out.print("Digite um nome: \n"); String nome = teclado.nextLine(); System.out.print("Digite uma senha: \n"); String senha = teclado.nextLine(); System.out.print("Informe a data de nascimento (dia-mes-ano): \n"); String dataNascimento = Data.validarData(teclado.nextLine()); return new Pessoa(nome, senha, dataNascimento); } public static String nomeForm(String message) throws Exception { System.out.print(message); String nome = teclado.nextLine(); return nome; } public static Date dateForm(String message) throws Exception { Calendar date = Calendar.getInstance(); System.out.print(message + " - dia-mes-ano (01-03-1900): \n"); String dateString = teclado.nextLine(); String[] dateArr = dateString.split("-"); date.set(Integer.parseInt(dateArr[2]), Integer.parseInt(dateArr[1]) - 1, Integer.parseInt(dateArr[0])); return date.getTime(); } public static int intForm(String message) throws Exception { System.out.print(message); String numero = teclado.nextLine(); return Integer.parseInt(numero); } public static Double doubleForm(String message) throws Exception { System.out.print(message); String numero = teclado.nextLine(); return Double.parseDouble(numero); } public static String tipoForm() throws Exception { System.out.println("Tipo de usuario:"); System.out.println("1 - Aluno"); System.out.println("2 - Professor"); return teclado.nextLine(); } protected static int tratarOpcao() { int opcao = 0; try { opcao = teclado.nextInt(); } catch (Exception exception) { System.out.println("Favor inserir valor válido!"); opcao = tratarOpcao(); } teclado.nextLine(); return opcao; } public int renderHome() { System.out.println("____________Home____________"); System.out.println("1 - Logar"); System.out.println("2 - Listar usuarios"); System.out.println("3 - Cadastrar Secretaria"); System.out.println("0 - Sair"); System.out.print("Opção: "); return View.tratarOpcao(); } public int renderUsuario() { System.out.println("____________Menu Usuario____________"); System.out.println("1 - Cadastrar Usuario"); System.out.println("2 - Listar usuarios"); System.out.println("3 - Remover Usuario"); System.out.println("0 - Voltar"); System.out.print("Opção: "); return View.tratarOpcao(); } public int renderAluno() { System.out.println("____________Menu Aluno____________"); System.out.println("1 - Matricular disciplina"); System.out.println("2 - Cancelar disciplina"); System.out.println("0 - Logout"); System.out.print("Opção: "); return View.tratarOpcao(); } public int renderProfessor() { System.out.println("____________Menu Professor____________"); System.out.println("1 - Imprimir alunos na disciplina"); System.out.println("0 - Logout"); System.out.print("Opção: "); return View.tratarOpcao(); } public int renderSecretaria() { System.out.println("____________Menu Secretaria____________"); System.out.println("1 - Menu Usuario"); System.out.println("2 - Menu curso"); System.out.println("3 - Menu Curriculo"); System.out.println("0 - Logout"); System.out.print("Opção: "); return View.tratarOpcao(); } public int renderLogin() { System.out.println("____________Menu Autenticacao____________"); System.out.println("0 - Voltar"); System.out.print("Opção: "); return View.tratarOpcao(); } public int renderCurso() { System.out.println("____________Menu Curso____________"); System.out.println("1 - Cadastrar"); System.out.println("2 - Listar"); System.out.println("3 - Remover"); System.out.println("0 - Voltar"); System.out.print("Opção: "); return View.tratarOpcao(); } public int renderCurriculo() { System.out.println("____________Menu Curriculo____________"); System.out.println("1 - Gerar curriculo"); System.out.println("2 - Adicionar disciplina"); System.out.println("3 - Remover disciplina curso"); System.out.println("0 - Voltar"); System.out.print("Opção: "); return View.tratarOpcao(); } }
AllaMaevskaya/AliRoot
EMCAL/EMCALTriggerBase/AliEMCALTriggerAlgorithm.cxx
/** * @file AliEMCALTriggerAlgorithm.cxx * @date Oct. 23, 2015 * @author <NAME> <<EMAIL>>, Lawrence Berkeley National Laboratory */ /************************************************************************** * Copyright(c) 1998-2013, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ #include "AliEMCALTriggerDataGrid.h" #include "AliEMCALTriggerAlgorithm.h" #include <algorithm> /// \cond CLASSIMP templateClassImp(AliEMCALTriggerAlgorithm) /// \endcond template<typename T> AliEMCALTriggerAlgorithm<T>::AliEMCALTriggerAlgorithm(): TObject(), fRowMin(0), fRowMax(0), fPatchSize(0), fSubregionSize(1), fBitMask(0), fThreshold(0), fOfflineThreshold(0) { } template<typename T> AliEMCALTriggerAlgorithm<T>::AliEMCALTriggerAlgorithm(Int_t rowmin, Int_t rowmax, UInt_t bitmask): TObject(), fRowMin(rowmin), fRowMax(rowmax), fPatchSize(0), fSubregionSize(1), fBitMask(bitmask), fThreshold(0), fOfflineThreshold(0) { } template<typename T> AliEMCALTriggerAlgorithm<T>::~AliEMCALTriggerAlgorithm() { } template<typename T> std::vector<AliEMCALTriggerRawPatch> AliEMCALTriggerAlgorithm<T>::FindPatches(const AliEMCALTriggerDataGrid<T> &adc, const AliEMCALTriggerDataGrid<T> &offlineAdc) const { std::vector<AliEMCALTriggerRawPatch> result; T sumadc(0); T sumofflineAdc(0); int rowStartMax = fRowMax - (fPatchSize-1); int colStartMax = adc.GetNumberOfCols() - fPatchSize; for(int irow = fRowMin; irow <= rowStartMax; irow += fSubregionSize){ for(int icol = 0; icol <= colStartMax; icol += fSubregionSize){ sumadc = 0; sumofflineAdc = 0; for(int jrow = irow; jrow < irow + fPatchSize; jrow++){ for(int jcol = icol; jcol < icol + fPatchSize; jcol++){ try{ sumadc += adc(jcol, jrow); sumofflineAdc += offlineAdc(jcol, jrow); } catch (typename AliEMCALTriggerDataGrid<T>::OutOfBoundsException &e){ } } } if(sumadc > fThreshold || sumofflineAdc > fOfflineThreshold){ AliEMCALTriggerRawPatch recpatch(icol, irow, fPatchSize, sumadc, sumofflineAdc); recpatch.SetBitmask(fBitMask); result.push_back(recpatch); } } } std::sort(result.begin(), result.end()); return result; } template class AliEMCALTriggerAlgorithm<int>; template class AliEMCALTriggerAlgorithm<double>; template class AliEMCALTriggerAlgorithm<float>;
code81192/micro-boot
micro-common/micro-common-log/micro-common-log-starter/src/main/java/pers/lbf/microboot/common/log/domain/params/CreateOperationLogParams.java
<filename>micro-common/micro-common-log/micro-common-log-starter/src/main/java/pers/lbf/microboot/common/log/domain/params/CreateOperationLogParams.java /* * Copyright 2020 赖柄沣 <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 pers.lbf.microboot.common.log.domain.params; import lombok.Data; import lombok.EqualsAndHashCode; import pers.lbf.microboot.common.core.domain.params.AbstractCreateParams; import pers.lbf.microboot.common.log.domain.entity.LogInfoEntity; import java.time.LocalDateTime; /** * 创建操作日志参数 * * @author 赖柄沣 <EMAIL> * @version 1.0 * @date 2021/10/5 22:47 */ @EqualsAndHashCode(callSuper = true) @Data public class CreateOperationLogParams extends AbstractCreateParams implements LogInfoEntity { private LocalDateTime operationTime; private String method; private String businessType; private String operatorAccount; private String ip; private String requestParamsJson; private String responseParamsJson; private String operationState; private String executeTime; private String location; }
chuan-He/learning-spring
demo/src/main/java/com/example/demo/_6_8_1/DefaultAdvisorAppConfig.java
<gh_stars>1-10 package com.example.demo._6_8_1; import org.aopalliance.aop.Advice; import org.springframework.aop.Advisor; import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator; import org.springframework.aop.support.DefaultPointcutAdvisor; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.example.demo._6_8_1.auto.proxy.AutoProxyService1; import com.example.demo._6_8_1.auto.proxy.AutoProxyService2; import com.example.demo._6_8_1.auto.proxy.Service; @Configuration public class DefaultAdvisorAppConfig { @Bean public static Advice advice() { return new TestAdvice(); } @Bean public static DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() { return new DefaultAdvisorAutoProxyCreator(); } @Bean public static Advisor advisor() { DefaultPointcutAdvisor defaultPointcutAdvisor = new DefaultPointcutAdvisor(); defaultPointcutAdvisor.setAdvice(advice()); return defaultPointcutAdvisor; } public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.register(DefaultAdvisorAppConfig.class, AutoProxyService1.class, AutoProxyService2.class, Service.class); context.refresh(); AutoProxyService1 service1 = context.getBean("autoProxyService1", AutoProxyService1.class); service1.test("hh"); AutoProxyService2 service2 = context.getBean(AutoProxyService2.class); service2.test("mm"); Service service = context.getBean(Service.class); service.test("nn"); } }
nembrotorg/nembrot-api
app/models/google_books_request.rb
<gh_stars>1-10 # encoding: utf-8 class GoogleBooksRequest include HTTParty base_uri NB.google_books_domain attr_accessor :metadata def initialize(isbn) params = { 'country' => 'GB', 'q' => "ISBN:#{ isbn }", 'maxResults' => 1 } response = self.class.get(NB.google_books_path, query: params) populate(response, isbn) if response && response['items'].first['volumeInfo'] rescue SYNC_LOG.error I18n.t('books.sync.failed.logger', provider: 'GoogleBooks', isbn: isbn) end def populate(response, isbn) response = response['items'].first volume_info = response['volumeInfo'] metadata = {} # GoogleBooks does not return nil when a book is not found so we need to verify that the data returned is # relevant if volume_info['industryIdentifiers'].map { |id| id['identifier'] }.include? isbn metadata['google_books_id'] = response.try { |r| r['id'] } metadata['google_books_embeddable'] = response.try { |r| r['accessInfo']['embeddable'] } metadata['title'] = volume_info.try { |v| v['title'].titlecase } metadata['author'] = volume_info.try { |v| Array(v['authors']).flatten.join(', ') } metadata['lang'] = volume_info.try { |v| v['language'] } metadata['published_date'] = volume_info.try { |v| v['publishedDate'] } metadata['page_count'] = volume_info.try { |v| v['pageCount'] } end self.metadata = metadata unless metadata.empty? end end
yunus-ceyhan/kivyx
kivyx/chip.py
<filename>kivyx/chip.py """ <MainApp>: bg_color: root.bgr_color XChip: right_icon: "check" left_icon: "android" text: "hello" pos_hint: {"center_x":.5,"center_y":.5} type: "outlined" bg_color: root.red_color #text_color: root.opposite_color """ from kivy.lang import Builder from kivyx.theming import Theming from kivy.properties import ColorProperty, OptionProperty, StringProperty from kivy.lang import Builder from kivyx.boxlayout import XBoxLayout from kivyx.theming import Theming Builder.load_string(""" <XChip>: size_hint: None, None height: dp(32) padding: [dp(16),0,dp(16),0] if not root.right_icon and not root.left_icon else [dp(4),0,dp(16),0]\ if not root.right_icon else [dp(16),0,dp(4),0]\ if not root.left_icon else [dp(4),0,dp(4), 0] width: max(dp(24) + ic.width + icr.width + lb.texture_size[0], dp(32)) #spacing: dp(8) if root.icon else 0 bg_color: self.bg_color if root.type == "filled" else [0,0,0,0] radius: [dp(8),] canvas.after: Color: rgba: root.txt_color if root.type != "filled" else root.trans_color Line: width: dp(1) rounded_rectangle: (self.x, self.y, self.width, self.height,dp(8)) XIcon: id: ic icon: root.left_icon font_size: "17dp" size_hint: None,None size: dp(32) if root.left_icon else 0, dp(32) color: root.icon_color XLabel: id: lb text: root.text aligned: False pos_hint: {"center_y":.5} color: root.text_color font_size: "13sp" XIcon: id: icr icon: root.right_icon font_size: "17dp" size_hint: None,None size: dp(32) if root.right_icon else 0, dp(32) color: root.icon_color """) class XChip(Theming, XBoxLayout): type = OptionProperty("outlined", options=["filled", "outlined"]) left_icon = StringProperty() right_icon = StringProperty() text = StringProperty() text_color = ColorProperty() icon_color = ColorProperty() def __init__(self, **kwargs): super().__init__(**kwargs) self.text_color = self.txt_color self.icon_color = self.txt_color
Dbevan/SunderingShadows
d/undead/rooms/forest/room72.c
<filename>d/undead/rooms/forest/room72.c #include "../../undead.h" inherit INH+"forest_one.c"; void create() { ::create(); set_exits(([ "north" :PATH+"room65", "northeast" :PATH+"room66", "east" :PATH+"room73", "south" :PATH+"room77", "west" :PATH+"room71" ])); }
careylam/vivaldi
ui/vivaldi_app_window_client_views_win.cc
<reponame>careylam/vivaldi // Copyright (c) 2017 Vivaldi Technologies AS. All rights reserved. // // Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/vivaldi_app_window_client.h" #include "ui/vivaldi_native_app_window_views_win.h" // static extensions::NativeAppWindow* VivaldiAppWindowClient::CreateNativeAppWindowImpl( VivaldiBrowserWindow* app_window, const extensions::AppWindow::CreateParams& params) { VivaldiNativeAppWindowViewsWin* window = new VivaldiNativeAppWindowViewsWin; window->Init(app_window, params); return window; }
datenstrudel/bulbs-core
src/main/java/net/datenstrudel/bulbs/core/web/filter/RequestEncodingAndCacheCtrlFilter.java
<filename>src/main/java/net/datenstrudel/bulbs/core/web/filter/RequestEncodingAndCacheCtrlFilter.java package net.datenstrudel.bulbs.core.web.filter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; /** * This filter obeys two requirements: * <ul> * <li>Set character encoding to the one configured in <code>web.xml</code></li> * <li>Set immediate cache expiration to all files served, that match the pattern * <code>*.nocache.*</code></li> * </ul> * @author <NAME> */ public class RequestEncodingAndCacheCtrlFilter implements Filter { private static final Logger log = LoggerFactory.getLogger(RequestEncodingAndCacheCtrlFilter.class); //~ (Bean) Members ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ private String encoding = "utf-8"; private FilterConfig filterConfig = null; private Set<String> nocacheUris = new HashSet<>(); //~ (Bean) Setter(s), Getter(s) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~ Constructor(s) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~ Method(s) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @Override public void init(FilterConfig filterConfig) { // log.info("1------------------------"); this.filterConfig = filterConfig; if (filterConfig != null) { String encodingParam = filterConfig .getInitParameter("encoding"); if (encodingParam != null) { this.encoding = encodingParam; } String noCacheUris = filterConfig.getInitParameter("noCache"); StringTokenizer nocUrisTk = new StringTokenizer(noCacheUris, ";"); String tmpUri; while(nocUrisTk.hasMoreTokens()){ tmpUri = nocUrisTk.nextToken(); if(!tmpUri.isEmpty())this.nocacheUris.add(tmpUri); } } } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)throws IOException, ServletException{ HttpServletResponse resp; HttpServletRequest req = (HttpServletRequest)request; //~ Set correct Character Encoding request.setCharacterEncoding(encoding); response.setCharacterEncoding(encoding); //~ Set caching policy if( reqUriMatchesNocacheUri(req.getRequestURI()) ){ resp = (HttpServletResponse) response; resp.setDateHeader("Expires", 0); resp.setHeader("Pragma", "no-cache"); resp.setHeader("Cache-control", "no-cache, no-store, must-revalidate"); } try{ chain.doFilter(request, response); }catch(IOException | ServletException ex){ log.error("Exception raised to filter; Apply propper handling!!!!",ex); throw ex; } } private boolean reqUriMatchesNocacheUri(String uri){ for (String el : nocacheUris) { if(uri.contains(el))return true; } return false; } /** * Destroy method for this filter */ @Override public void destroy() { this.filterConfig = null; } }
globocom/cloudstack
plugins/network-elements/globonetwork/src/com/globo/globonetwork/cloudstack/api/ListGloboNetworkVipsCmd.java
<filename>plugins/network-elements/globonetwork/src/com/globo/globonetwork/cloudstack/api/ListGloboNetworkVipsCmd.java<gh_stars>10-100 // 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 com.globo.globonetwork.cloudstack.api; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.api.response.ProjectResponse; import org.apache.cloudstack.context.CallContext; import org.apache.log4j.Logger; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.utils.exception.CloudRuntimeException; import com.globo.globonetwork.cloudstack.manager.GloboNetworkService; import com.globo.globonetwork.cloudstack.response.GloboNetworkVipExternalResponse; import com.globo.globonetwork.cloudstack.response.GloboNetworkVipResponse; @APICommand(name = "listGloboNetworkVips", responseObject = GloboNetworkVipExternalResponse.class, description = "Lists GloboNetwork Vips") public class ListGloboNetworkVipsCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(ListGloboNetworkVipsCmd.class); private static final String s_name = "listglobonetworkvipsresponse"; @Inject GloboNetworkService _globoNetworkService; @Parameter(name = ApiConstants.PROJECT_ID, type = CommandType.UUID, entityType = ProjectResponse.class, description = "the project id") private Long projectId; /* Implementation */ @Override public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException { try { s_logger.debug("listGloboNetworkVipsCmd command with projectId=" + projectId); List<GloboNetworkVipResponse> globoNetworkVips = _globoNetworkService.listGloboNetworkVips(this.projectId); List<GloboNetworkVipExternalResponse> responseList = new ArrayList<GloboNetworkVipExternalResponse>(); for (GloboNetworkVipResponse globoNetworkVip : globoNetworkVips) { GloboNetworkVipExternalResponse vipResponse = new GloboNetworkVipExternalResponse(); vipResponse.setId(globoNetworkVip.getId()); vipResponse.setName(globoNetworkVip.getName()); vipResponse.setIp(globoNetworkVip.getIp()); vipResponse.setCache(globoNetworkVip.getCache()); vipResponse.setMethod(globoNetworkVip.getMethod()); vipResponse.setPersistence(globoNetworkVip.getPersistence()); vipResponse.setHealthchecktype(globoNetworkVip.getHealthcheckType()); vipResponse.setHealthcheck(globoNetworkVip.getHealthcheck()); vipResponse.setMaxconn(globoNetworkVip.getMaxConn()); vipResponse.setPorts(globoNetworkVip.getPorts()); vipResponse.setNetworkids(globoNetworkVip.getNetworkIds()); vipResponse.setObjectName("globonetworkvip"); responseList.add(vipResponse); } ListResponse<GloboNetworkVipExternalResponse> response = new ListResponse<GloboNetworkVipExternalResponse>(); response.setResponses(responseList); response.setResponseName(getCommandName()); this.setResponseObject(response); } catch (InvalidParameterValueException invalidParamExcp) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage()); } catch (CloudRuntimeException runtimeExcp) { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage(), runtimeExcp); } } @Override public String getCommandName() { return s_name; } @Override public long getEntityOwnerId() { return CallContext.current().getCallingAccountId(); } }
DeltaML/data-owner
data_owner/services/user_login_service.py
from google.auth.transport import requests from google.oauth2 import id_token import logging class UserLoginService: """ Use: https://developers.google.com/identity/sign-in/web/backend-auth """ CLIENT_ID = "472467752298-t4oph39ih14iaro5rn0n0qsnqbsdev8e.apps.googleusercontent.com" @staticmethod def validate(idinfo): return idinfo['iss'] in ['accounts.google.com', 'https://accounts.google.com'] @staticmethod def get_user_info(token): idinfo = id_token.verify_oauth2_token(token, requests.Request(), UserLoginService.CLIENT_ID) logging.info(idinfo) return idinfo
jprescott/TrickHLA
source/TrickHLA/Int64Interval.cpp
/*! @file TrickHLA/Int64Interval.cpp @ingroup TrickHLA @brief This class represents the HLA Interval time. @copyright Copyright 2019 United States Government as represented by the Administrator of the National Aeronautics and Space Administration. No copyright is claimed in the United States under Title 17, U.S. Code. All Other Rights Reserved. \par<b>Responsible Organization</b> Simulation and Graphics Branch, Mail Code ER7\n Software, Robotics & Simulation Division\n NASA, Johnson Space Center\n 2101 NASA Parkway, Houston, TX 77058 @tldh @trick_link_dependency{Int64Time.cpp} @trick_link_dependency{Int64Interval.cpp} @trick_link_dependency{Types.cpp} @revs_title @revs_begin @rev_entry{<NAME>, Titan Corp., DIS, October 2004, --, Initial implementation for ISS HTV Sim} @rev_entry{<NAME>, NASA ER7, TrickHLA, March 2019, --, Version 2 origin.} @rev_entry{<NAME>, NASA ER7, TrickHLA, March 2019, --, Version 3 rewrite.} @rev_entry{<NAME>, NASA ER6, TrickHLA, July 2020, --, Changed function names to match TrickHLA coding style.} @revs_end */ // System include files. #include <cmath> #include <limits> #include <sstream> #include <stdint.h> #include <stdio.h> // TrickHLA include files. #include "TrickHLA/Int64Interval.hh" #include "TrickHLA/Types.hh" namespace TrickHLA { extern const int64_t MICROS_MULTIPLIER = 1000000; extern const int64_t MAX_VALUE_IN_MICROS = std::numeric_limits< int64_t >::max(); extern const double MAX_LOGICAL_TIME_SECONDS = ( (double)MAX_VALUE_IN_MICROS / (double)MICROS_MULTIPLIER ); } // namespace TrickHLA using namespace std; using namespace TrickHLA; /*! * @job_class{initialization} */ Int64Interval::Int64Interval( int64_t value ) { set( value ); } /*! * @job_class{initialization} */ Int64Interval::Int64Interval( double value ) { set( value ); } /*! * @job_class{initialization} */ Int64Interval::Int64Interval( RTI1516_NAMESPACE::LogicalTimeInterval const &value ) { set( value ); } /*! * @job_class{initialization} */ Int64Interval::Int64Interval( RTI1516_NAMESPACE::HLAinteger64Interval const &value ) : hla_interval( value ) { return; } /*! * @job_class{initialization} */ Int64Interval::Int64Interval( Int64Interval const &value ) : hla_interval( value.get_time_in_micros() ) { return; } /*! * @job_class{shutdown} */ Int64Interval::~Int64Interval() { return; } int64_t Int64Interval::get_seconds() const { return ( (int64_t)( hla_interval.getInterval() / MICROS_MULTIPLIER ) ); } int32_t Int64Interval::get_micros() const { return ( (int32_t)( hla_interval.getInterval() % MICROS_MULTIPLIER ) ); } int64_t Int64Interval::get_time_in_micros() const { return ( hla_interval.getInterval() ); } double Int64Interval::get_time_in_seconds() const { double seconds = (double)get_seconds(); double micros = (double)get_micros() / (double)MICROS_MULTIPLIER; return ( seconds + micros ); } wstring Int64Interval::to_wstring() const { ostringstream msg; msg << "Int64Interval<" << get_time_in_seconds() << ">"; wstring wstr; wstr.assign( msg.str().begin(), msg.str().end() ); return wstr; } void Int64Interval::set( const int64_t value ) { hla_interval = value; } void Int64Interval::set( const double value ) { hla_interval = to_microseconds( value ); } void Int64Interval::set( RTI1516_NAMESPACE::LogicalTimeInterval const &value ) { const RTI1516_NAMESPACE::HLAinteger64Interval &p = dynamic_cast< const RTI1516_NAMESPACE::HLAinteger64Interval & >( value ); hla_interval = p.getInterval(); } int64_t Int64Interval::to_microseconds( const double value ) { // Do a range check on the double value in seconds. if ( value > MAX_LOGICAL_TIME_SECONDS ) { return MAX_VALUE_IN_MICROS; } else if ( value < -MAX_LOGICAL_TIME_SECONDS ) { return -MAX_VALUE_IN_MICROS; } int64_t seconds = (int64_t)trunc( value ); int64_t micros = ( seconds >= 0 ) ? (int64_t)( fmod( value * MICROS_MULTIPLIER, MICROS_MULTIPLIER ) + 0.5 ) : (int64_t)( fmod( value * MICROS_MULTIPLIER, MICROS_MULTIPLIER ) - 0.5 ); return ( ( seconds * MICROS_MULTIPLIER ) + micros ); } double Int64Interval::to_seconds( const int64_t usec ) { double seconds = (double)( usec / (int64_t)MICROS_MULTIPLIER ); double micros = (double)( usec % (int64_t)MICROS_MULTIPLIER ) / (double)MICROS_MULTIPLIER; return ( seconds + micros ); }
android-xiao-jun/android-chat
uikit/src/main/java/cn/wildfire/chat/kit/widget/LinkClickListener.java
/* * Copyright (c) 2020 WildFireChat. All rights reserved. */ package cn.wildfire.chat.kit.widget; public interface LinkClickListener { boolean onLinkClick(String link); }
coldnew/leetcode-solutions
src/0682/0682-Baseball-Game.cpp
<filename>src/0682/0682-Baseball-Game.cpp #include <numeric> #include <vector> #include "leetcode_utils.h" using namespace std; class Solution1 { public: int calPoints(vector<string>& ops) { std::vector<int> records; for (const auto& op : ops) { if (op == "+") records.emplace_back(records[records.size() - 2] + records.back()); else if (op == "D") records.emplace_back(2 * records.back()); else if (op == "C") records.pop_back(); else records.emplace_back(stoi(op)); } return std::accumulate(records.begin(), records.end(), 0); } };
mnishiguchi/react-native-redux-practice
src/shared/SideBar/ProjectsPane.js
<filename>src/shared/SideBar/ProjectsPane.js import React from 'react'; import * as NB from 'native-base'; const ProjectsPane = ({ projects, navigation }) => ( <NB.Content padder> <NB.H1>Projcts Pane</NB.H1> <NB.Text> Summis appellat qui domesticarum, quae non mandaremus te eu cupidatat eruditionem si officia irure enim do quorum, aut enim quid nulla consequat quo noster ea probant ab malis iis ad quem singulis exquisitaque ea se deserunt nam admodum. Fabulas ita minim si si culpa irure labore probant ita proident quid nam cupidatat adipisicing, se qui minim fabulas, esse officia ne amet tempor ut ex export cupidatat commodo, aut fugiat nostrud, noster iis ullamco. Ut ne noster appellat iis nescius ne legam laborum. Ea irure appellat concursionibus, arbitror non nisi incididunt, constias de amet quibusdam, officia export esse de ipsum hic ex do sint eram minim, enim ex a dolor mentitum eu velit domesticarum cupidatat veniam singulis eu litteris minim ex pariatur concursionibus.O sint officia aliquip. Senserit ex proident aut est aut sempiternum, appellat exercitation aut vidisse e iis ex cillum illum summis, te litteris de cupidatat, quem non ullamco nam se magna non aute a ubi nulla ingeniis quibusdam. Senserit de export eu id sint graviterque. </NB.Text> </NB.Content> ); export default ProjectsPane;
rleber/bun
lib/bun/file/blocked.rb
#!/usr/bin/env ruby # -*- encoding: us-ascii -*- module Bun class File < ::File class Blocked < Bun::File::Unpacked include CacheableMethods attr_accessor :status attr_accessor :strict attr_reader :good_blocks attr_reader :llink_count def initialize(options={}, &blk) super @strict = options[:strict] @llink_count = nil # descriptor.register_fields(:blocks, :good_blocks, :status) end def words=(words) super if @words.nil? @deblocked_content = nil end words end def reblock @deblocked_content = nil end def content deblocked_content end def file_content data.file_content end BLOCK_SIZE = 0500 # words def blocks (size - content_offset).div(BLOCK_SIZE) end # TODO Build a capability in Slicr to do things like this def deblocked_content deblocked_content = [] offset = 0 block_number = 1 self.status = :readable @good_blocks = 0 link_number = 1 llink_number = 1 loop do # Process a link break if offset >= words.size bcw = words.at(offset) break if bcw.to_i == 0 # debug "link: offset: #{offset}(0#{'%o' % offset}): #{'%013o' % words.at(offset)}" # debug "preamble: offset: #{offset+1}(0#{'%o' % (offset+1)}): #{'%013o' % words.at(offset+1)}" link_sequence_number = bcw.half_word[0].to_i raise BadBlockError, "Link out of sequence at #{offset}(0#{'%o'%offset}): Found #{link_sequence_number}, expected #{link_number}. BCW #{'%013o' % bcw.to_i}" \ unless link_sequence_number == link_number next_link = bcw.half_word[1].to_i + offset + 1 # debug "next link: #{'%013o' % next_link}" preamble_length = words.at(offset+1).half_word[1].to_i offset += preamble_length loop do # debug "llink: offset: #{offset}(0#{'%o' % offset}): #{'%013o' % words.at(offset)}" break if offset >= words.size || offset >= next_link break if words.at(offset) == 0 block_size = words.at(offset).byte(3) unless words.at(offset).half_word[0] == block_number # stop "Bad block_number at #{'%013o' % (offset+content_offset)}: #{'%013o' % words.at(offset)}, block_number: #{block_number}" if strict raise "Llink out of sequence in #{location} at #{'%#o' % (offset+content_offset)}: expected #{'%07o' % block_number}; got #{file_content[offset].half_word[0]}" else error "Truncated before block #{block_number} at #{'%#o' % (offset+content_offset)}" if block_number == 1 self.status = :unreadable else self.status = :truncated end break end end deblocked_content += words[offset+1..(offset+block_size)].to_a offset += BLOCK_SIZE block_number += 1 @good_blocks += 1 end offset = next_link link_number += 1 end @llink_count = link_number Bun::Words.new(deblocked_content) end cache :deblocked_content def llink_count unless @llink_count _ = deblocked_content descriptor.merge!(llink_count: @llink_count) end @llink_count end end end end
danekja/discussment
discussment-core/src/main/java/org/danekja/discussment/core/service/imp/DefaultPostReputationService.java
package org.danekja.discussment.core.service.imp; import org.danekja.discussment.core.accesscontrol.domain.IDiscussionUser; import org.danekja.discussment.core.accesscontrol.service.DiscussionUserService; import org.danekja.discussment.core.dao.PostDao; import org.danekja.discussment.core.dao.UserPostReputationDao; import org.danekja.discussment.core.domain.Post; import org.danekja.discussment.core.domain.UserPostReputation; import org.danekja.discussment.core.event.PostReputationChangedEvent; import org.danekja.discussment.core.event.UserPostReputationChangedEvent; import org.danekja.discussment.core.service.PostReputationService; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisherAware; import org.springframework.transaction.annotation.Transactional; /** * Implementation of the PostReputationService interface. * * Date: 17.2.18 * * @author <NAME> */ @Transactional public class DefaultPostReputationService implements PostReputationService, ApplicationEventPublisherAware { private final UserPostReputationDao userPostReputationDao; private final PostDao postDao; private final DiscussionUserService userService; private ApplicationEventPublisher applicationEventPublisher; public DefaultPostReputationService(UserPostReputationDao userPostReputationDao, PostDao postDao, DiscussionUserService userService){ this.userPostReputationDao = userPostReputationDao; this.postDao = postDao; this.userService = userService; } @Override public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { this.applicationEventPublisher = applicationEventPublisher; } @Override public void addLike(Post post){ IDiscussionUser user = userService.getCurrentlyLoggedUser(); UserPostReputation upr = getVote(user, post); if (upr == null) { post.getPostReputation().addLike(); UserPostReputation savedUpr = userPostReputationDao.save(new UserPostReputation(user.getDiscussionUserId(), post, true)); Post savedPost = postDao.save(post); publishEvent(new UserPostReputationChangedEvent(savedUpr)); publishEvent(new PostReputationChangedEvent(savedPost)); } else if (upr.getLiked()){ changeVote(user, post); } } @Override public void addDislike(Post post){ IDiscussionUser user = userService.getCurrentlyLoggedUser(); UserPostReputation upr = getVote(user, post); if (upr == null) { post.getPostReputation().addDislike(); UserPostReputation savedUpr = userPostReputationDao.save(new UserPostReputation(user.getDiscussionUserId(), post, false)); Post savedPost = postDao.save(post); publishEvent(new UserPostReputationChangedEvent(savedUpr)); publishEvent(new PostReputationChangedEvent(savedPost)); } else if(!upr.getLiked()){ changeVote(user, post); } } @Override public void changeVote(IDiscussionUser user, Post post){ if (userVotedOn(user, post)) { UserPostReputation upr = getVote(user, post); if (upr.getLiked()) { post.getPostReputation().removeLike(); post.getPostReputation().addDislike(); upr.changeLiked(); } else { post.getPostReputation().addLike(); post.getPostReputation().removeDislike(); upr.changeLiked(); } UserPostReputation savedUpr = userPostReputationDao.save(upr); Post savedPost = postDao.save(post); publishEvent(new UserPostReputationChangedEvent(savedUpr)); publishEvent(new PostReputationChangedEvent(savedPost)); } } @Override public void removeVote(IDiscussionUser user, Post post) { if (userVotedOn(user, post)) { UserPostReputation upr = getVote(user, post); if (upr.getLiked()) { post.getPostReputation().removeLike(); } else { post.getPostReputation().removeDislike(); } userPostReputationDao.remove(upr); Post savedPost = postDao.save(post); publishEvent(new PostReputationChangedEvent(savedPost)); } } @Override public UserPostReputation getVote(IDiscussionUser user, Post post){ if (user == null) { return null; } else { return userPostReputationDao.getForUser(user, post); } } @Override public boolean userVotedOn(IDiscussionUser user, Post post){ return getVote(user, post) != null; } /** * Publishes event if {@link #applicationEventPublisher} is not null. * @param event Event to be published. */ private void publishEvent(Object event) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent(event); } } }
mlooz/networkit-general-polylog
networkit/cpp/community/ParallelAgglomerativeClusterer.cpp
<reponame>mlooz/networkit-general-polylog<filename>networkit/cpp/community/ParallelAgglomerativeClusterer.cpp /* * ParallelAgglomerativeClusterer.cpp * * Created on: 30.10.2012 * Author: <NAME> (<EMAIL>), * <NAME> (<EMAIL>) */ #include "ParallelAgglomerativeClusterer.h" #include "../scoring/ModularityScoring.h" #include "../matching/PathGrowingMatcher.h" #include "../coarsening/MatchingCoarsening.h" #include "../coarsening/ClusteringProjector.h" namespace NetworKit { ParallelAgglomerativeClusterer::ParallelAgglomerativeClusterer(const Graph& G) : CommunityDetectionAlgorithm(G) {}; void ParallelAgglomerativeClusterer::run() { count MIN_NUM_COMMUNITIES = 2; double REL_REPEAT_THRSH = 5e-3; ///< threshold for minimum number of matching edges relative to number of vertices to proceed agglomeration // copy graph because we make changes due to merges Graph Gcopy(G.numberOfNodes(), true); // make weighted copy G.forEdges([&](node u, node v, edgeweight w){ Gcopy.addEdge(u, v, w); }); std::vector<std::vector<node> > mapHierarchy; bool repeat = true; do { // prepare attributes for scoring // FIXME: update to new edge attribute system //int attrId = Gcopy.addEdgeAttribute_double(0.0); int attrId = 0; // perform scoring TRACE("before scoring graph of size " , Gcopy.numberOfNodes()); ModularityScoring<double> modScoring(Gcopy); modScoring.scoreEdges(attrId); // FIXME: so far only sequential // compute matching PathGrowingMatcher parMatcher(Gcopy); parMatcher.run(); Matching M = parMatcher.getMatching(); // contract graph according to matching, TODO: (and star-like structures) MatchingCoarsening matchingContracter(Gcopy, M); matchingContracter.run(); Graph Gcombined = matchingContracter.getCoarseGraph(); // determine if it makes sense to proceed count n = Gcopy.numberOfNodes(); count cn = Gcombined.numberOfNodes(); count diff = n - cn; repeat = ((diff > 0) && (cn >= MIN_NUM_COMMUNITIES) && ((double) diff / (double) n > REL_REPEAT_THRSH) ); // TODO: last condition: no community becomes too big // prepare next iteration if there is one if (repeat) { Gcopy = Gcombined; mapHierarchy.push_back(matchingContracter.getFineToCoarseNodeMapping()); TRACE("Repeat agglomeration with graph of size " , Gcopy.numberOfNodes()); } } while (repeat); // vertices of coarsest graph are the clusters count cn = Gcopy.numberOfNodes(); Partition zetaCoarse(cn); zetaCoarse.allToSingletons(); // project clustering back to finest graph ClusteringProjector projector; Partition zeta = projector.projectBackToFinest(zetaCoarse, mapHierarchy, G); result = std::move(zeta); hasRun = true; } std::string ParallelAgglomerativeClusterer::toString() const { std::stringstream strm; strm << "ParallelAgglomerativeClusterer"; return strm.str(); } } /* namespace NetworKit */
webdevhub42/Lambda
0-notes/my-notes/REACT/REPOS/react-docgen-master/src/__tests__/fixtures/component_14.js
type Props = $ReadOnly<{| color?: ?string, |}>; const ColoredView = React.forwardRef((props: Props, ref) => ( <View style={{ backgroundColor: props.color }} /> )); ColoredView.displayName = 'UncoloredView'; module.exports = ColoredView;
JamesGlover/lighthouse
tests/requests/test_samples_declarations.py
import json from http import HTTPStatus TIMESTAMP = "2013-04-04T10:29:13" class CheckNumInstancesChangeBy: def __init__(self, app, model_name, num): with app.app_context(): self.__num = num self.__model_name = model_name self.__model = app.data.driver.db[model_name] self.__app = app def __enter__(self): with self.__app.app_context(): self.__size = self.__model.count() def __exit__(self, type, value, tb): with self.__app.app_context(): assert self.__model.count() == self.__size + self.__num def assert_has_error(record, key, error_message): assert record["_status"] == "ERR" assert record["_issues"][key] == error_message def test_get_empty_samples_declarations(client): response = client.get("/samples_declarations") assert response.status_code == HTTPStatus.OK assert response.json["_items"] == [] def test_get_samples_declarations_with_content(client, samples_declarations): response = client.get("/samples_declarations") assert response.status_code == HTTPStatus.OK assert len(response.json["_items"]) == 4 def test_post_new_sample_declaration_for_existing_samples_unauthorized( app, client, samples_declarations ): with CheckNumInstancesChangeBy(app, "samples_declarations", 0): response = client.post( "/samples_declarations", data=json.dumps( [ { "root_sample_id": "MCM001", "value_in_sequencing": "Yes", "declared_at": TIMESTAMP, }, { "root_sample_id": "MCM003", "value_in_sequencing": "Yes", "declared_at": TIMESTAMP, }, ], ), content_type="application/json", headers={"x-lighthouse-client": "wronk key!!!"}, ) assert response.status_code == HTTPStatus.UNAUTHORIZED, response.json def post_authorized_create_samples_declaration(client, payload): return client.post( "/samples_declarations", data=json.dumps(payload), content_type="application/json", headers={"x-lighthouse-client": "develop"}, ) def test_post_new_single_sample_declaration_for_existing_sample( app, client, samples, empty_data_when_finish ): with CheckNumInstancesChangeBy(app, "samples_declarations", 1): items = { "root_sample_id": "MCM001", "value_in_sequencing": "Yes", "declared_at": TIMESTAMP, } response = post_authorized_create_samples_declaration(client, items) assert response.status_code == HTTPStatus.CREATED, response.json assert response.json["_status"] == "OK" def test_post_new_sample_declaration_for_existing_samples( app, client, samples, empty_data_when_finish ): with CheckNumInstancesChangeBy(app, "samples_declarations", 2): items = [ { "root_sample_id": "MCM001", "value_in_sequencing": "Yes", "declared_at": TIMESTAMP, }, { "root_sample_id": "MCM003", "value_in_sequencing": "Yes", "declared_at": TIMESTAMP, }, ] response = post_authorized_create_samples_declaration(client, items) assert response.status_code == HTTPStatus.CREATED, response.json assert response.json["_status"] == "OK" assert len(response.json["_items"]) == 2 assert response.json["_items"][0]["_status"] == "OK" assert response.json["_items"][1]["_status"] == "OK" def test_create_lots_of_samples_declarations( app, client, lots_of_samples, lots_of_samples_declarations_payload, empty_data_when_finish ): with CheckNumInstancesChangeBy( app, "samples_declarations", len(lots_of_samples_declarations_payload) ): response = post_authorized_create_samples_declaration( client, lots_of_samples_declarations_payload ) assert len(response.json["_items"]) == len(lots_of_samples_declarations_payload) assert response.json["_status"] == "OK" for item in response.json["_items"]: assert item["_status"] == "OK" def test_inserts_new_declarations_even_when_other_declarations_are_wrong( app, client, samples, empty_data_when_finish ): with CheckNumInstancesChangeBy(app, "samples_declarations", 1): stamp = "2013-04-10T09:00:00" post_authorized_create_samples_declaration( client, [ { "root_sample_id": "MCM001", "value_in_sequencing": "wrong answer!!", "declared_at": stamp, }, {"root_sample_id": "MCM002", "value_in_sequencing": "Yes", "declared_at": stamp}, ], ) with app.app_context(): li = [ x for x in app.data.driver.db.samples_declarations.find({"root_sample_id": "MCM002"}) ] assert len(li) == 1 def test_wrong_value_for_value_in_sequencing( app, client, samples, samples_declarations, empty_data_when_finish ): with CheckNumInstancesChangeBy(app, "samples_declarations", 1): response = post_authorized_create_samples_declaration( client, [ { "root_sample_id": "MCM001", "value_in_sequencing": "wrong answer!!", "declared_at": TIMESTAMP, }, { "root_sample_id": "MCM003", "value_in_sequencing": "Yes", "declared_at": TIMESTAMP, }, ], ) assert response.status_code == HTTPStatus.UNPROCESSABLE_ENTITY, response.json assert len(response.json["_items"]) == 2 assert response.json["_status"] == "ERR" assert_has_error( response.json["_items"][0], "value_in_sequencing", "unallowed value wrong answer!!" ) assert response.json["_items"][1]["_status"] == "OK" def test_wrong_value_for_declared_at( app, client, samples, samples_declarations, empty_data_when_finish ): with CheckNumInstancesChangeBy(app, "samples_declarations", 1): response = post_authorized_create_samples_declaration( client, [ { "root_sample_id": "MCM001", "value_in_sequencing": "Unknown", "declared_at": TIMESTAMP, }, { "root_sample_id": "MCM003", "value_in_sequencing": "Yes", "declared_at": "wrong time mate!!", }, ], ) assert response.status_code == HTTPStatus.UNPROCESSABLE_ENTITY, response.json assert len(response.json["_items"]) == 2 assert response.json["_status"] == "ERR" assert response.json["_items"][0]["_status"] == "OK" assert_has_error(response.json["_items"][1], "declared_at", "must be of datetime type") def test_wrong_value_for_root_sample_id( app, client, samples, samples_declarations, empty_data_when_finish ): with CheckNumInstancesChangeBy(app, "samples_declarations", 1): response = post_authorized_create_samples_declaration( client, [ { "root_sample_id": True, "value_in_sequencing": "Unknown", "declared_at": TIMESTAMP, }, { "root_sample_id": "MCM003", "value_in_sequencing": "Yes", "declared_at": TIMESTAMP, }, ], ) assert response.status_code == HTTPStatus.UNPROCESSABLE_ENTITY, response.json assert len(response.json["_items"]) == 2 assert response.json["_status"] == "ERR" assert_has_error(response.json["_items"][0], "root_sample_id", "must be of string type") assert response.json["_items"][1]["_status"] == "OK" def test_unknown_sample_for_root_sample_id( app, client, samples, samples_declarations, empty_data_when_finish ): with CheckNumInstancesChangeBy(app, "samples_declarations", 0): response = post_authorized_create_samples_declaration( client, { "root_sample_id": "nonsense", "value_in_sequencing": "Yes", "declared_at": TIMESTAMP, }, ) assert response.status_code == HTTPStatus.UNPROCESSABLE_ENTITY, response.json assert response.json["_status"] == "ERR" assert_has_error( response.json, "root_sample_id", "Sample does not exist in database: nonsense" ) def test_missing_value_for_root_sample_id_multiple( app, client, samples, samples_declarations, empty_data_when_finish ): with CheckNumInstancesChangeBy(app, "samples_declarations", 1): response = post_authorized_create_samples_declaration( client, [ { "value_in_sequencing": "Yes", "declared_at": TIMESTAMP, }, { "root_sample_id": "MCM003", "value_in_sequencing": "Yes", "declared_at": TIMESTAMP, }, ], ) assert response.status_code == HTTPStatus.UNPROCESSABLE_ENTITY, response.json assert len(response.json["_items"]) == 2 assert response.json["_status"] == "ERR" assert_has_error(response.json["_items"][0], "root_sample_id", "required field") assert response.json["_items"][1]["_status"] == "OK" def test_missing_value_for_root_sample_id_single( app, client, samples, samples_declarations, empty_data_when_finish ): with CheckNumInstancesChangeBy(app, "samples_declarations", 0): response = post_authorized_create_samples_declaration( client, { "value_in_sequencing": "Yes", "declared_at": TIMESTAMP, }, ) assert response.status_code == HTTPStatus.UNPROCESSABLE_ENTITY, response.json assert response.json["_status"] == "ERR" assert_has_error(response.json, "root_sample_id", "required field") def test_validate_sample_exist_in_samples_table( app, client, samples, samples_declarations, empty_data_when_finish ): with CheckNumInstancesChangeBy(app, "samples_declarations", 1): response = post_authorized_create_samples_declaration( client, [ { "root_sample_id": "MCM001", "value_in_sequencing": "Unknown", "declared_at": TIMESTAMP, }, { "root_sample_id": "MCM_WRONG_VALUE", "value_in_sequencing": "Yes", "declared_at": TIMESTAMP, }, ], ) assert response.status_code == HTTPStatus.UNPROCESSABLE_ENTITY, response.json assert response.json["_status"] == "ERR" assert len(response.json["_items"]) == 2 assert response.json["_items"][0]["_status"] == "OK" assert_has_error( response.json["_items"][1], "root_sample_id", "Sample does not exist in database: MCM_WRONG_VALUE", ) def test_validate_samples_are_defined_twice_v1( app, client, samples, samples_declarations, empty_data_when_finish ): with CheckNumInstancesChangeBy(app, "samples_declarations", 0): response = post_authorized_create_samples_declaration( client, [ { "root_sample_id": "MCM001", "value_in_sequencing": "Unknown", "declared_at": TIMESTAMP, }, { "root_sample_id": "MCM001", "value_in_sequencing": "Yes", "declared_at": TIMESTAMP, }, ], ) assert response.status_code == HTTPStatus.UNPROCESSABLE_ENTITY, response.json assert len(response.json["_items"]) == 2 assert response.json["_status"] == "ERR" assert_has_error( response.json["_items"][0], "root_sample_id", "Sample is a duplicate: MCM001" ) assert_has_error( response.json["_items"][1], "root_sample_id", "Sample is a duplicate: MCM001" ) def test_validate_samples_are_defined_twice_v2( app, client, samples, samples_declarations, empty_data_when_finish ): with CheckNumInstancesChangeBy(app, "samples_declarations", 1): response = post_authorized_create_samples_declaration( client, [ { "root_sample_id": "MCM001", "value_in_sequencing": "Unknown", "declared_at": "2013-04-04T10:29:13", }, { "root_sample_id": "MCM002", "value_in_sequencing": "Unknown", "declared_at": "2013-04-04T10:29:13", }, { "root_sample_id": "MCM001", "value_in_sequencing": "Unknown", "declared_at": "2013-04-04T10:29:13", }, { "root_sample_id": "MCM003", "value_in_sequencing": "Unknown", "declared_at": "2013-04-04T10:29:13", }, { "root_sample_id": "MCM003", "value_in_sequencing": "Unknown", "declared_at": "2013-04-04T10:29:13", }, ], ) assert response.status_code == HTTPStatus.UNPROCESSABLE_ENTITY, response.json assert len(response.json["_items"]) == 5 assert response.json["_status"] == "ERR" assert_has_error( response.json["_items"][0], "root_sample_id", "Sample is a duplicate: MCM001" ) assert response.json["_items"][1]["_status"] == "OK" assert_has_error( response.json["_items"][2], "root_sample_id", "Sample is a duplicate: MCM001" ) assert_has_error( response.json["_items"][3], "root_sample_id", "Sample is a duplicate: MCM003" ) assert_has_error( response.json["_items"][4], "root_sample_id", "Sample is a duplicate: MCM003" ) def test_multiple_errors_on_samples_declaration( app, client, multiple_errors_samples_declarations_payload ): with CheckNumInstancesChangeBy(app, "samples_declarations", 0): response = post_authorized_create_samples_declaration( client, multiple_errors_samples_declarations_payload ) assert response.status_code == HTTPStatus.UNPROCESSABLE_ENTITY, response.json assert len(response.json["_items"]) == 8 assert response.json["_status"] == "ERR" assert_has_error( response.json["_items"][0], "root_sample_id", "Sample does not exist in database: YOR10020466", ) assert_has_error(response.json["_items"][1], "root_sample_id", "required field") assert_has_error( response.json["_items"][2], "root_sample_id", [ "Sample does not exist in database: YOR10020379", "Sample is a duplicate: YOR10020379", ], ) assert_has_error(response.json["_items"][2], "declared_at", "must be of datetime type") assert_has_error( response.json["_items"][3], "root_sample_id", "Sample does not exist in database: YOR10020240", ) assert_has_error( response.json["_items"][4], "root_sample_id", [ "Sample does not exist in database: YOR10020379", "Sample is a duplicate: YOR10020379", ], ) assert_has_error( response.json["_items"][5], "root_sample_id", "Sample does not exist in database: YOR10020224", ) assert_has_error( response.json["_items"][6], "root_sample_id", "Sample does not exist in database: YOR10020217", ) assert_has_error(response.json["_items"][6], "value_in_sequencing", "required field") assert_has_error( response.json["_items"][7], "value_in_sequencing", "unallowed value maybelater" ) def test_filter_by_root_sample_id(client, samples_declarations): response = client.get( '/samples_declarations?where={"root_sample_id":"MCM001"}', content_type="application/json", ) assert response.status_code == HTTPStatus.OK, response.json assert len(response.json["_items"]) == 1, response.json assert response.json["_items"][0]["value_in_sequencing"] == "Yes", response.json def test_get_last_samples_declaration_for_a_root_sample_id(client, samples_declarations): response = client.get( '/samples_declarations?where={"root_sample_id":"MCM003"}&sort=-declared_at&max_results=1', content_type="application/json", ) assert response.status_code == HTTPStatus.OK, response.json assert len(response.json["_items"]) == 1, response.json assert response.json["_items"][0]["value_in_sequencing"] == "Yes", response.json assert response.json["_items"][0]["declared_at"] == "2013-04-06T10:29:13", response.json
YuriSpiridonov/LeetCode
Easy/258.AddDigits.py
<reponame>YuriSpiridonov/LeetCode<filename>Easy/258.AddDigits.py ''' Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. Example: Input: 38 Output: 2 Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. Follow up: Could you do it without any loop/recursion in O(1) runtime? ''' #Difficulty: Easy #1101 / 1101 test cases passed. #Runtime: 36 ms #Memory Usage: 14.2 MB #Runtime: 36 ms, faster than 28.26% of Python3 online submissions for Add Digits. #Memory Usage: 14.2 MB, less than 51.11% of Python3 online submissions for Add Digits. class Solution: def addDigits(self, num: int) -> int: while num > 9: num = num//10 + num%10 return num
eugeneilyin/mdi-norm
src/SharpPictureInPictureAlt.js
<gh_stars>1-10 import React from 'react' import { Icon } from './Icon' export const SharpPictureInPictureAlt = /*#__PURE__*/ props => <Icon {...props}> <path d="M19 11h-8v6h8zm4 10V3H1v18zm-2-1.98H3V4.97h18z"/> </Icon>
tangentspace/telegraf-cloudwatch-plugin
plugins/system/cpu.go
<reponame>tangentspace/telegraf-cloudwatch-plugin package system import ( "fmt" "github.com/influxdb/telegraf/plugins" "github.com/shirou/gopsutil/cpu" ) type CPUStats struct { ps PS lastStats []cpu.CPUTimesStat PerCPU bool `toml:"percpu"` TotalCPU bool `toml:"totalcpu"` } func NewCPUStats(ps PS) *CPUStats { return &CPUStats{ ps: ps, } } func (_ *CPUStats) Description() string { return "Read metrics about cpu usage" } var sampleConfig = ` # Whether to report per-cpu stats or not percpu = true # Whether to report total system cpu stats or not totalcpu = true # Comment this line if you want the raw CPU time metrics drop = ["cpu_time"] ` func (_ *CPUStats) SampleConfig() string { return sampleConfig } func (s *CPUStats) Gather(acc plugins.Accumulator) error { times, err := s.ps.CPUTimes(s.PerCPU, s.TotalCPU) if err != nil { return fmt.Errorf("error getting CPU info: %s", err) } for i, cts := range times { tags := map[string]string{ "cpu": cts.CPU, } total := totalCpuTime(cts) // Add total cpu numbers add(acc, "time_user", cts.User, tags) add(acc, "time_system", cts.System, tags) add(acc, "time_idle", cts.Idle, tags) add(acc, "time_nice", cts.Nice, tags) add(acc, "time_iowait", cts.Iowait, tags) add(acc, "time_irq", cts.Irq, tags) add(acc, "time_softirq", cts.Softirq, tags) add(acc, "time_steal", cts.Steal, tags) add(acc, "time_guest", cts.Guest, tags) add(acc, "time_guest_nice", cts.GuestNice, tags) // Add in percentage if len(s.lastStats) == 0 { // If it's the 1st gather, can't get CPU stats yet continue } lastCts := s.lastStats[i] lastTotal := totalCpuTime(lastCts) totalDelta := total - lastTotal if totalDelta < 0 { return fmt.Errorf("Error: current total CPU time is less than previous total CPU time") } if totalDelta == 0 { continue } add(acc, "usage_user", 100*(cts.User-lastCts.User)/totalDelta, tags) add(acc, "usage_system", 100*(cts.System-lastCts.System)/totalDelta, tags) add(acc, "usage_idle", 100*(cts.Idle-lastCts.Idle)/totalDelta, tags) add(acc, "usage_nice", 100*(cts.Nice-lastCts.Nice)/totalDelta, tags) add(acc, "usage_iowait", 100*(cts.Iowait-lastCts.Iowait)/totalDelta, tags) add(acc, "usage_irq", 100*(cts.Irq-lastCts.Irq)/totalDelta, tags) add(acc, "usage_softirq", 100*(cts.Softirq-lastCts.Softirq)/totalDelta, tags) add(acc, "usage_steal", 100*(cts.Steal-lastCts.Steal)/totalDelta, tags) add(acc, "usage_guest", 100*(cts.Guest-lastCts.Guest)/totalDelta, tags) add(acc, "usage_guest_nice", 100*(cts.GuestNice-lastCts.GuestNice)/totalDelta, tags) } s.lastStats = times return nil } func totalCpuTime(t cpu.CPUTimesStat) float64 { total := t.User + t.System + t.Nice + t.Iowait + t.Irq + t.Softirq + t.Steal + t.Guest + t.GuestNice + t.Idle return total } func init() { plugins.Add("cpu", func() plugins.Plugin { return &CPUStats{ps: &systemPS{}} }) }
hjc851/Dataset2-HowToDetectAdvancedSourceCodePlagiarism
Variant Programs/1-5/29/show/ManufacturerCase.java
package show; import euphonious.ThingCatch; import operator.Exporter; public class ManufacturerCase extends show.ExtravaganzaDisc implements java.lang.Comparable<ManufacturerCase> { public operator.Exporter boss; public static final java.lang.String MayBegin = "CAN_START"; public static final java.lang.String LetCompletedPurpose = "WILL_FINISH_OBJECT"; static final double minutes = 0.41848485011854175; public ManufacturerCase(double meter, String news, Exporter entrepreneur) { this.now = (meter); this.nicky = (news); this.boss = (entrepreneur); } public synchronized int compareTo(ManufacturerCase remember) { double apexRestrictions; apexRestrictions = (0.7289571125269692); if (this.now < remember.now) return 1; else if (this.now == remember.now) return 0; else return -1; } public synchronized void litigateVenue() { int matter; matter = (943652983); euphonious.ThingCatch.rigidAmount(this.now); this.boss.cycleNowPurpose(); } public synchronized String toString() { String minus; minus = ("4sNOfWLVVZj"); return ("owner: " + boss + " info: " + nicky + " chrono: " + now); } }
JesperTerkelsen/aws-price-api
modules/api/src/test/java/dk/deck/aws/price/api/RdsPriceListTest.java
<reponame>JesperTerkelsen/aws-price-api /* * Copyright 2013 <NAME>. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. * */ package dk.deck.aws.price.api; import dk.deck.aws.price.api.model.Price; import java.io.IOException; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; /** * * @author <NAME> */ public class RdsPriceListTest { public RdsPriceListTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } private RdsPriceList instance; @Before public void setUp() { instance = new RdsPriceList(); } @After public void tearDown() { } /** * Test of getRdsHourRate method, of class RdsPriceList. */ @Test public void testGetRdsHourRate() throws Exception { System.out.println("getRdsHourRate"); getRdsHourRate("eu-west-1", "mysql", "db.t1.micro", false); getRdsHourRate("eu-west-1", "mysql", "db.t1.micro", true); getRdsHourRate("eu-west-1", "mysql", "db.m1.small", false); getRdsHourRate("eu-west-1", "mysql", "db.m1.small", true); getRdsHourRate("eu-west-1", "mysql", "db.m1.medium", false); getRdsHourRate("eu-west-1", "mysql", "db.m1.medium", true); getRdsHourRate("eu-west-1", "mysql", "db.m1.large", false); getRdsHourRate("eu-west-1", "mysql", "db.m1.large", true); getRdsHourRate("eu-west-1", "mysql", "db.m1.xlarge", false); getRdsHourRate("eu-west-1", "mysql", "db.m1.xlarge", true); getRdsHourRate("eu-west-1", "mysql", "db.m2.xlarge", false); getRdsHourRate("eu-west-1", "mysql", "db.m2.xlarge", true); getRdsHourRate("eu-west-1", "mysql", "db.m2.2xlarge", false); getRdsHourRate("eu-west-1", "mysql", "db.m2.2xlarge", true); getRdsHourRate("eu-west-1", "mysql", "db.m2.4xlarge", false); getRdsHourRate("eu-west-1", "mysql", "db.m2.4xlarge", true); } private Price getRdsHourRate(String regionName, String dbEngine, String instanceTypeClass, boolean multiAz) throws IOException{ Price result = instance.getRdsHourRate(regionName, dbEngine, instanceTypeClass, multiAz); System.out.println(regionName + " " + dbEngine + " " + instanceTypeClass + " " + multiAz + ": " + result); return result; } }
Jarkob/pacr
webapp_backend/src/test/java/pacr/webapp_backend/result_management/services/BenchmarkManagerTest.java
<gh_stars>1-10 package pacr.webapp_backend.result_management.services; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import pacr.webapp_backend.SpringBootTestWithoutShell; import pacr.webapp_backend.database.BenchmarkDB; import pacr.webapp_backend.database.BenchmarkGroupDB; import pacr.webapp_backend.shared.ResultInterpretation; import java.util.Collection; import java.util.NoSuchElementException; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.atMostOnce; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class BenchmarkManagerTest extends SpringBootTestWithoutShell { private final BenchmarkDB benchmarkDB; private final BenchmarkGroupDB groupDB; private BenchmarkManager benchmarkManager; private static final String BENCHMARK_NAME = "benchmark"; private static final String BENCHMARK_NAME_TWO = "benchmark2"; private static final String BENCHMARK_DESCRIPTION = "desc"; private static final String GROUP_NAME = "group"; private static final String GROUP_NAME_TWO = "groupTwo"; private static final String PROPERTY_NAME = "property"; private static final String PROPERTY_NAME_TWO = "propertyTwo"; private static final String UNIT = "unit"; private static final int EXPECTED_NUM_OF_PROPERTIES = 2; private static final int EXPECTED_NUM_OF_GROUPS = 3; private static final int EXPECTED_SINGLE = 1; private static final int NO_ID = 0; private Benchmark benchmark; private BenchmarkGroup group; @Autowired public BenchmarkManagerTest(final BenchmarkDB benchmarkDB, final BenchmarkGroupDB groupDB) { this.benchmarkDB = benchmarkDB; this.groupDB = groupDB; this.benchmarkManager = new BenchmarkManager(benchmarkDB, groupDB); } @BeforeEach public void setUp() { group = new BenchmarkGroup(GROUP_NAME); benchmark = new Benchmark(BENCHMARK_NAME); final BenchmarkProperty property = new BenchmarkProperty(PROPERTY_NAME, UNIT, ResultInterpretation.LESS_IS_BETTER); benchmark.addProperty(property); benchmark.setGroup(group); groupDB.saveBenchmarkGroup(group); } @AfterEach public void cleanUp() { benchmarkDB.deleteAll(); groupDB.deleteAll(); this.benchmarkManager = new BenchmarkManager(benchmarkDB, groupDB); } /** * Tests whether a benchmark saved with createOrUpdateBenchmark can be retrieved. */ @Test public void createOrUpdateBenchmark_benchmarkNotYetSaved_shouldSaveBenchmark() { final Benchmark benchmark = new Benchmark(BENCHMARK_NAME_TWO); benchmarkManager.createOrUpdateBenchmark(benchmark); final Benchmark savedBenchmark = benchmarkDB.getBenchmark(benchmark.getId()); assertEquals(BENCHMARK_NAME_TWO, savedBenchmark.getOriginalName()); assertEquals(benchmark.getId(), savedBenchmark.getId()); } /** * Tests whether createOrUpdateBenchmark also updates the list of associated properties. */ @Test public void createOrUpdateBenchmark_addedProperty_shouldAlsoReturnAddedProperty() { benchmarkDB.saveBenchmark(benchmark); final BenchmarkProperty newProperty = new BenchmarkProperty(PROPERTY_NAME_TWO, UNIT, ResultInterpretation.LESS_IS_BETTER); benchmark.addProperty(newProperty); benchmarkManager.createOrUpdateBenchmark(benchmark); final Benchmark savedBenchmark = benchmarkDB.getBenchmark(benchmark.getId()); assertEquals(EXPECTED_NUM_OF_PROPERTIES, savedBenchmark.getProperties().size()); } /** * Tests whether createOrUpdateBenchmark can create a benchmark and then add a property to it. Also tests if the id * of the property gets set. */ @Test public void createOrUpdateBenchmark_createAndAddProperty_shouldAlsoReturnAddedProperty() { benchmarkManager.createOrUpdateBenchmark(benchmark); final BenchmarkProperty newProperty = new BenchmarkProperty(PROPERTY_NAME_TWO, UNIT, ResultInterpretation.LESS_IS_BETTER); benchmark.addProperty(newProperty); benchmarkManager.createOrUpdateBenchmark(benchmark); final Benchmark savedBenchmark = benchmarkDB.getBenchmark(benchmark.getId()); assertEquals(EXPECTED_NUM_OF_PROPERTIES, savedBenchmark.getProperties().size()); assertNotEquals(NO_ID, newProperty.getId()); } /** * Tests whether updateBenchmark changes the custom name of a benchmark in the database (and nothing else). */ @Test public void updateBenchmark_newName_shouldOnlyChangeName() { benchmarkDB.saveBenchmark(benchmark); benchmarkManager.updateBenchmark(benchmark.getId(), BENCHMARK_NAME_TWO, BENCHMARK_DESCRIPTION, group.getId()); final Benchmark savedBenchmark = benchmarkDB.getBenchmark(benchmark.getId()); assertEquals(BENCHMARK_NAME_TWO, savedBenchmark.getCustomName()); assertEquals(BENCHMARK_NAME, savedBenchmark.getOriginalName()); assertEquals(BENCHMARK_DESCRIPTION, savedBenchmark.getDescription()); assertEquals(group.getId(), savedBenchmark.getGroup().getId()); } /** * Tests whether updateBenchmark changes the group of a benchmark in the database (and nothing else). */ @Test public void updateBenchmark_newGroup_shouldOnlyChangeGroup() { benchmarkDB.saveBenchmark(benchmark); final BenchmarkGroup groupTwo = new BenchmarkGroup(GROUP_NAME_TWO); groupDB.saveBenchmarkGroup(groupTwo); benchmarkManager.updateBenchmark(benchmark.getId(), BENCHMARK_NAME, BENCHMARK_DESCRIPTION, groupTwo.getId()); final Benchmark savedBenchmark = benchmarkDB.getBenchmark(benchmark.getId()); assertEquals(groupTwo.getId(), savedBenchmark.getGroup().getId()); assertEquals(BENCHMARK_NAME, savedBenchmark.getCustomName()); assertEquals(BENCHMARK_NAME, savedBenchmark.getOriginalName()); assertEquals(BENCHMARK_DESCRIPTION, savedBenchmark.getDescription()); } /** * Tests whether a benchmark can be removed from a group with updateBenchmark by passing the standard group id. */ @Test public void updateBenchmark_groupIdStandard_shouldMakeGroupStandard() { benchmarkDB.saveBenchmark(benchmark); benchmarkManager.updateBenchmark(benchmark.getId(), BENCHMARK_NAME, BENCHMARK_DESCRIPTION, BenchmarkManager.getStandardGroupId()); final Benchmark savedBenchmark = benchmarkDB.getBenchmark(benchmark.getId()); assertEquals(BenchmarkManager.getStandardGroupId(), savedBenchmark.getGroup().getId()); } @Test void updateBenchmark_noBenchmarkWithGivenIdSaved_shouldNotUpdate() { IBenchmarkAccess benchmarkAccessSpy = Mockito.mock(IBenchmarkAccess.class); when(benchmarkAccessSpy.getBenchmark(benchmark.getId())).thenReturn(null); BenchmarkManager managerWithSpy = new BenchmarkManager(benchmarkAccessSpy, groupDB); managerWithSpy.updateBenchmark(benchmark.getId(), benchmark.getCustomName(), benchmark.getDescription(), group.getId()); verify(benchmarkAccessSpy, never()).saveBenchmark(any()); } @Test void updateBenchmark_noGroupWithGivenIdSaved_shouldNotUpdateBenchmark() { benchmarkDB.saveBenchmark(benchmark); benchmarkManager.updateBenchmark(benchmark.getId(), BENCHMARK_NAME_TWO, benchmark.getDescription(), group.getId() + 1); Benchmark newBenchmark = benchmarkDB.getBenchmark(benchmark.getId()); assertEquals(group.getId(), newBenchmark.getGroup().getId()); assertEquals(BENCHMARK_NAME, newBenchmark.getCustomName()); } @Test void updateBenchmark_emptyName_shouldThrowException() { benchmarkDB.saveBenchmark(benchmark); assertThrows(IllegalArgumentException.class, () -> benchmarkManager.updateBenchmark(benchmark.getId(), "", benchmark.getDescription(), group.getId())); } /** * Tests whether group that was added with addGroup can be retrieved. */ @Test public void addGroup_shouldSaveGroup() { benchmarkManager.addGroup(GROUP_NAME_TWO); assertEquals(EXPECTED_NUM_OF_GROUPS, benchmarkManager.getAllGroups().size()); } @Test void addGroup_emptyName_shouldThrowException() { assertThrows(IllegalArgumentException.class, () -> benchmarkManager.addGroup("")); } /** * Tests whether updateGroup updates contents of group. */ @Test public void updateGroup_newName_shouldChangeName() { benchmarkManager.updateGroup(group.getId(), GROUP_NAME_TWO); final BenchmarkGroup savedGroup = groupDB.getBenchmarkGroup(group.getId()); assertEquals(GROUP_NAME_TWO, savedGroup.getName()); } @Test void updateGroup_emptyName_shouldThrowException() { assertThrows(IllegalArgumentException.class, () -> benchmarkManager.updateGroup(group.getId(), "")); } @Test void updateGroup_noGroupWithGivenIdSaved_shouldNotUpdate() { IBenchmarkGroupAccess groupAccessSpy = Mockito.mock(IBenchmarkGroupAccess.class); BenchmarkManager managerWithSpy = new BenchmarkManager(benchmarkDB, groupAccessSpy); when(groupAccessSpy.getBenchmarkGroup(group.getId())).thenReturn(null); managerWithSpy.updateGroup(group.getId(), GROUP_NAME_TWO); verify(groupAccessSpy, atMostOnce()).saveBenchmarkGroup(any()); } /** * Tests whether deleteGroup removes the group from the database. */ @Test public void deleteGroup_shouldRemoveGroupFromDatabase() throws IllegalAccessException { benchmarkManager.deleteGroup(group.getId()); assertEquals(EXPECTED_SINGLE, groupDB.count()); } /** * Tests whether deleteGroup also removes the group from an associated benchmark. */ @Test public void deleteGroup_benchmarkHasGroup_shouldRemoveGroupFromBenchmark() throws IllegalAccessException { benchmarkDB.saveBenchmark(benchmark); benchmarkManager.deleteGroup(group.getId()); final Benchmark savedBenchmark = benchmarkDB.getBenchmark(benchmark.getId()); assertEquals(BenchmarkManager.getStandardGroupId(), savedBenchmark.getGroup().getId()); } @Test void deleteGroup_attemptToDeleteStandardGroup_shouldThrowException() { final BenchmarkGroup standardGroup = groupDB.getStandardGroup(); assertThrows(IllegalAccessException.class, () -> benchmarkManager.deleteGroup(standardGroup.getId())); } @Test void deleteGroup_noGroupWithGivenIdSaved_shouldThrowException() { final BenchmarkGroup standardGroup = groupDB.getStandardGroup(); assertThrows(NoSuchElementException.class, () -> benchmarkManager.deleteGroup(standardGroup.getId() + group.getId())); } @Test void getBenchmarksByGroup_twoBenchmarksDifferentGroups_shouldOnlyReturnBenchmarkOfGroup() { final BenchmarkGroup groupTwo = new BenchmarkGroup(GROUP_NAME_TWO); final Benchmark benchmarkTwo = new Benchmark(BENCHMARK_NAME_TWO); benchmarkTwo.setGroup(groupTwo); groupDB.saveBenchmarkGroup(groupTwo); benchmarkDB.saveBenchmark(benchmarkTwo); final Collection<Benchmark> benchmarks = benchmarkManager.getBenchmarksByGroup(groupTwo.getId()); assertEquals(EXPECTED_SINGLE, benchmarks.size()); assertEquals(benchmarkTwo, benchmarks.iterator().next()); } }
samuelfac/portalunico.siscomex.gov.br
src/main/java/br/gov/siscomex/portalunico/talpco/model/TemplateLpco.java
<filename>src/main/java/br/gov/siscomex/portalunico/talpco/model/TemplateLpco.java package br.gov.siscomex.portalunico.talpco.model; import java.util.ArrayList; import java.util.List; import javax.validation.Valid; import javax.validation.constraints.NotNull; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "TemplateLpco", propOrder = { "modelo", "listaCamposFormulario", "listaCamposNcm" }) @XmlRootElement(name="TemplateLpco") /** * Template que especifica a estrutura de um formulário de um LPCO **/ @ApiModel(description="Template que especifica a estrutura de um formulário de um LPCO") public class TemplateLpco { @XmlElement(name="modelo", required = true) @ApiModelProperty(required = true, value = "") @Valid private ModeloLpcoCompleto modelo = null; @XmlElement(name="listaCamposFormulario", required = true) @ApiModelProperty(required = true, value = "Lista de definições de campos do formulário.") @Valid /** * Lista de definições de campos do formulário. **/ private List<CampoFormulario> listaCamposFormulario = new ArrayList<>(); @XmlElement(name="listaCamposNcm", required = true) @ApiModelProperty(required = true, value = "Lista de definições de campos a serem preenchidos para cada NCM informada no LPCO") @Valid /** * Lista de definições de campos a serem preenchidos para cada NCM informada no LPCO **/ private List<CampoFormulario> listaCamposNcm = new ArrayList<>(); /** * Get modelo * @return modelo **/ @JsonProperty("modelo") @NotNull public ModeloLpcoCompleto getModelo() { return modelo; } public void setModelo(ModeloLpcoCompleto modelo) { this.modelo = modelo; } public TemplateLpco modelo(ModeloLpcoCompleto modelo) { this.modelo = modelo; return this; } /** * Lista de definições de campos do formulário. * @return listaCamposFormulario **/ @JsonProperty("listaCamposFormulario") @NotNull public List<CampoFormulario> getListaCamposFormulario() { return listaCamposFormulario; } public void setListaCamposFormulario(List<CampoFormulario> listaCamposFormulario) { this.listaCamposFormulario = listaCamposFormulario; } public TemplateLpco listaCamposFormulario(List<CampoFormulario> listaCamposFormulario) { this.listaCamposFormulario = listaCamposFormulario; return this; } public TemplateLpco addListaCamposFormularioItem(CampoFormulario listaCamposFormularioItem) { this.listaCamposFormulario.add(listaCamposFormularioItem); return this; } /** * Lista de definições de campos a serem preenchidos para cada NCM informada no LPCO * @return listaCamposNcm **/ @JsonProperty("listaCamposNcm") @NotNull public List<CampoFormulario> getListaCamposNcm() { return listaCamposNcm; } public void setListaCamposNcm(List<CampoFormulario> listaCamposNcm) { this.listaCamposNcm = listaCamposNcm; } public TemplateLpco listaCamposNcm(List<CampoFormulario> listaCamposNcm) { this.listaCamposNcm = listaCamposNcm; return this; } public TemplateLpco addListaCamposNcmItem(CampoFormulario listaCamposNcmItem) { this.listaCamposNcm.add(listaCamposNcmItem); return this; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class TemplateLpco {\n"); sb.append(" modelo: ").append(toIndentedString(modelo)).append("\n"); sb.append(" listaCamposFormulario: ").append(toIndentedString(listaCamposFormulario)).append("\n"); sb.append(" listaCamposNcm: ").append(toIndentedString(listaCamposNcm)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private static String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
StefanLB/JS-Advanced-September-2019
Lectures-And-Exercises/06.JS-Advanced-DOM-Manipulations-Exercise/06. Time-Converter/solution.js
<reponame>StefanLB/JS-Advanced-September-2019 function attachEventsListeners() { let days = document.querySelector('#days'); let hours = document.querySelector('#hours'); let minutes = document.querySelector('#minutes'); let seconds = document.querySelector('#seconds'); document .querySelector('#daysBtn') .addEventListener('click',() => { hours.value = days.value*24; minutes.value = days.value*60*24; seconds.value = days.value*60*60*24; }); document .querySelector('#hoursBtn') .addEventListener('click',() => { days.value = hours.value/24; minutes.value = hours.value*60; seconds.value = hours.value*60*60; }); document .querySelector('#minutesBtn') .addEventListener('click',() => { days.value = minutes.value/60/24; hours.value = minutes.value/60; seconds.value = minutes.value*60; }); document .querySelector('#secondsBtn') .addEventListener('click',() => { days.value = seconds.value/60/60/24; hours.value = seconds.value/60/60; minutes.value = seconds.value/60; }); }
elanthia-online/cartograph
maps/gsiv/string_procs/wayto/5871_5880.rb
move 'southeast' if checkpaths == ['se','nw'] move 'southeast' move 'northeast' move 'northeast' move 'northeast' move 'north' move 'north' end
sskbskdrin/ssk-libs
ssk-http/src/main/java/cn/sskbskdrin/http/IResponse.java
package cn.sskbskdrin.http; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Map; /** * Created by keayuan on 2020/4/7. * * @author keayuan */ public interface IResponse extends Closeable { /** * 返回byte数据 * * @return 数据数组 * @throws IOException 可能抛出异常 */ byte[] bytes() throws IOException; /** * 返回数据转字符串 * * @return 返回的字符串 * @throws IOException 可能抛出异常 */ String string() throws IOException; int code(); String message(); Throwable throwable(); boolean isSuccess(); InputStream byteStream(); Map<String, List<String>> getHeaders(); long getContentLength(); Object getRawResponse(); }
natnat-mc/jjvm
src/com/github/natnatMc/jjvm/intermediate/JMethod.java
<reponame>natnat-mc/jjvm package com.github.natnatMc.jjvm.intermediate; import java.util.*; import com.github.natnatMc.jjvm.classFile.ClassAttribute; import com.github.natnatMc.jjvm.classFile.ClassMethod; import com.github.natnatMc.jjvm.classFile.ConstantPool; import com.github.natnatMc.jjvm.exceptions.MalformedClassException; import com.github.natnatMc.jjvm.struct.CONSTANT_Class_info; import com.github.natnatMc.jjvm.struct.CONSTANT_Utf8_info; import com.github.natnatMc.jjvm.struct.IntHolder; public class JMethod { protected int flags; protected JCode code; protected String[] exceptions=new String[0]; protected String name; protected String[] parameterTypes; protected String returnType; protected boolean ro; void read(ClassMethod method, ConstantPool pool) throws MalformedClassException { //set method name name=method.name; //set flags flags=method.flags; //read method parameters and return types ArrayList<String> params=new ArrayList<String>(); String desc=method.descriptor; IntHolder pos=new IntHolder(); pos.value=1; while(desc.charAt(pos.value)!=')') { params.add(readType(pos, desc)); } pos.value++; if(desc.charAt(pos.value)=='V') returnType="void"; else returnType=readType(pos, desc); parameterTypes=params.toArray(new String[0]); //read attributes for(ClassAttribute attr:method.attributes) { if(attr.name.equals("Code")) { code=new JCode(); code.read(attr, pool); } else if(attr.name.equals("Exceptions")) { attr.data.position(0); int no=attr.data.getChar(); exceptions=new String[no]; for(int i=0; i<no; i++) { int p=attr.data.getChar(); CONSTANT_Class_info info=(CONSTANT_Class_info) pool.get(p); CONSTANT_Utf8_info utf8=(CONSTANT_Utf8_info) pool.get(info.pos); exceptions[i]=utf8.value.replaceAll("/", "."); } } } ro=true; } public String getName() { return name; } public String getType() { return returnType; } public List<String> getParameters() { return Collections.unmodifiableList(Arrays.asList(parameterTypes)); } public List<String> getExceptions() { return Collections.unmodifiableList(Arrays.asList(exceptions)); } public int getFlags() { return flags; } public JCode getCode() { return code.clone(); } public void setName(String name) { if(ro) throw new IllegalStateException("Cannot modify ro class"); this.name=name; } public void setType(String type) { if(ro) throw new IllegalStateException("Cannot modify ro class"); this.returnType=type; } public void setParameters(List<String> params) { if(ro) throw new IllegalStateException("Cannot modify ro class"); this.parameterTypes=params.toArray(new String[0]); } public void setExceptions(List<String> exceptions) { if(ro) throw new IllegalStateException("Cannot modify ro class"); this.exceptions=exceptions.toArray(new String[0]); } public void setFlags(int flags) { if(ro) throw new IllegalStateException("Cannot modify ro class"); this.flags=flags; } public void setCode(JCode code) { if(ro) throw new IllegalStateException("Cannot modify ro class"); this.code=code; } public static String readType(IntHolder pos, String desc) throws MalformedClassException { char c=desc.charAt(pos.value++); switch(c) { case 'B': return "byte"; case 'C': return "char"; case 'D': return "double"; case 'F': return "float"; case 'I': return "int"; case 'J': return "long"; case 'S': return "short"; case 'Z': return "boolean"; case '[': return readType(pos, desc)+"[]"; } if(c=='L') { String name=""; while(pos.value<desc.length()) { c=desc.charAt(pos.value++); if(c==';') break; if(c=='/') name+='.'; else name+=c; } return name; } else { throw new MalformedClassException("unknown descriptor found :"+c); } } }
nebulastream/nebulastream-query-generator
operator_generator_strategies/distinct_operator_strategies/distinct_projection_strategy.py
<reponame>nebulastream/nebulastream-query-generator<gh_stars>1-10 from typing import List import random from operator_generator_strategies.base_generator_strategy import BaseGeneratorStrategy from operators.project_operator import ProjectOperator from utils.contracts import Schema, Operator from utils.utils import random_int_between, random_name class DistinctProjectionGeneratorStrategy(BaseGeneratorStrategy): def __init__(self, max_number_of_predicates: int = 1): super().__init__() self._max_number_of_predicates = max_number_of_predicates def generate(self, schema: Schema) -> List[Operator]: numericalFields = schema.get_numerical_fields() noOfFieldsToProject = 1 if len(numericalFields) > 1: noOfFieldsToProject = random_int_between(2, len(numericalFields)) fields = [] for i in range(noOfFieldsToProject): fields.append(numericalFields[i]) newFiledNames = [] if bool(random.getrandbits(1)): fieldMapping = {} for i in range(len(fields)): newFieldName = random_name() fieldMapping[newFieldName] = fields[i] newFiledNames.append(newFieldName) schema = Schema(name=schema.name, int_fields=newFiledNames, double_fields=schema.double_fields, string_fields=schema.string_fields, timestamp_fields=schema.timestamp_fields, fieldNameMapping=fieldMapping) else: schema = Schema(name=schema.name, int_fields=fields, double_fields=schema.double_fields, string_fields=schema.string_fields, timestamp_fields=schema.timestamp_fields, fieldNameMapping=schema.get_field_name_mapping()) project = ProjectOperator(fieldsToProject=fields, newFieldNames=newFiledNames, schema=schema) return [project]
SRAhub/MinimaxSimulator
src/test/java/de/uni_hannover/sra/minimax_simulator/model/machine/PartNameTest.java
package de.uni_hannover.sra.minimax_simulator.model.machine; import java.lang.reflect.Field; import org.junit.Test; import de.uni_hannover.sra.minimax_simulator.model.machine.minimax.Parts; import static org.junit.Assert.*; /** * Tests the access to the part names listed in {@link Parts}. * * @author <NAME>uml;ck */ public class PartNameTest { /** * Checks the names provided by {@code Parts}. * * @throws IllegalAccessException * thrown if a field could not be accessed */ @Test public void checkNames() throws IllegalAccessException { for (Field field : Parts.class.getDeclaredFields()) { if (field.isSynthetic()) { // e.g. JaCoCo coverage analysis continue; } assertEquals(field.getName(), field.get(null)); } } }
syniavskyi/intranet_dev
backend/src/main/java/com/btech/repositories/UserEngagRepository.java
package com.btech.repositories; import com.btech.model.UserEngag; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.List; import java.util.Optional; @Repository public interface UserEngagRepository extends JpaRepository<UserEngag, Long> { List<UserEngag> findByUserId(Long id); Optional<UserEngag> findById(Long id); }
passcod/rollup
test/form/samples/comment-start-inside-comment/main.js
<filename>test/form/samples/comment-start-inside-comment/main.js // /* import foo from './foo.js'; const bar = 'unused'; /*/ this comment is not closed yet */ console.log(foo());
longgangfan/underworld2
underworld/libUnderworld/StGermain/Base/Foundation/src/NamedObject_Register.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 "types.h" #include "forwardDecl.h" #include "Memory.h" #include "Class.h" #include "Object.h" #include "ObjectAdaptor.h" #include "ObjectList.h" #include "NamedObject_Register.h" #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <string.h> /* Stg_Class Administration members ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ const Type NamedObject_Register_Type = "NamedObject_Register"; NamedObject_Register* NamedObject_Register_New( void ) { /* Variables set in this function */ SizeT _sizeOfSelf = sizeof(NamedObject_Register); Type type = NamedObject_Register_Type; Stg_Class_DeleteFunction* _delete = _NamedObject_Register_Delete; Stg_Class_PrintFunction* _print = _NamedObject_Register_Print; Stg_Class_CopyFunction* _copy = _NamedObject_Register_Copy; return _NamedObject_Register_New( NAMEDOBJECT_REGISTER_PASSARGS ); } NamedObject_Register* _NamedObject_Register_New( NAMEDOBJECT_REGISTER_DEFARGS ) { NamedObject_Register* self; /* Allocate memory/General info */ assert(_sizeOfSelf >= sizeof(NamedObject_Register)); self = (NamedObject_Register*)_Stg_Class_New( STG_CLASS_PASSARGS ); /* Virtual info */ /* Stg_Class info */ _NamedObject_Register_Init( self ); return self; } void _NamedObject_Register_Init( NamedObject_Register* self ) { self->objects = Stg_ObjectList_New(); } void _NamedObject_Register_Delete( void* namedObjectRegister ) { NamedObject_Register* self = (NamedObject_Register*)namedObjectRegister; Journal_DPrintf( Journal_Register( Debug_Type, NamedObject_Register_Type ), "In: %s()\n", __func__ ); Stg_Class_Delete( self->objects ); /* Stg_Class_Delete parent */ _Stg_Class_Delete( self ); } void NamedObject_Register_DeleteAll( void* reg ) { /* * Deletes all elements from register and then * deletes the register. */ NamedObject_Register* self = (NamedObject_Register*)reg; Stg_ObjectList_DeleteAllObjects( self->objects ); /* Stg_Class_Delete parent */ Stg_Class_Delete( self ); } void _NamedObject_Register_Print( void* namedObjectRegister, struct Stream* stream ) { NamedObject_Register* self = (NamedObject_Register*)namedObjectRegister; /* General info */ Journal_Printf( stream, "NamedObject_Register (ptr): %p\n", self); Stream_Indent( stream ); /* Use parent print */ _Stg_Class_Print( self, stream ); /* Print the list of registered objects */ Stg_Class_Print( self->objects, stream ); Stream_UnIndent( stream ); } void* _NamedObject_Register_Copy( void* namedObjectRegister, void* dest, Bool deep, Name nameExt, struct PtrMap* ptrMap ) { NamedObject_Register* self = (NamedObject_Register*)namedObjectRegister; NamedObject_Register* newNamedObjectRegister; newNamedObjectRegister = (NamedObject_Register*)_Stg_Class_Copy( self, dest, deep, nameExt, ptrMap ); Journal_Firewall( deep, Journal_Register( Error_Type, NamedObject_Register_Type ), "Shallow copy not yet implemented\n" ); if( deep ) { newNamedObjectRegister->objects = (Stg_ObjectList*)Stg_Class_Copy( self->objects, NULL, deep, nameExt, ptrMap ); } return newNamedObjectRegister; } /* Public member functions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ /* Private member functions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
sunboy0523/gatk
src/main/java/org/broadinstitute/hellbender/tools/copynumber/formats/records/annotation/AnnotationKey.java
package org.broadinstitute.hellbender.tools.copynumber.formats.records.annotation; import org.broadinstitute.hellbender.utils.Utils; import java.util.function.Function; /** * Represents a key for a named, typed annotation. * * @author <NAME> &lt;<EMAIL>&gt; */ public final class AnnotationKey<T> { private final String name; private final Class<T> clazz; private final Function<T, Boolean> validateValue; public AnnotationKey(final String name, final Class<T> clazz, final Function<T, Boolean> validateValue) { this.name = Utils.nonEmpty(name); this.clazz = Utils.nonNull(clazz); this.validateValue = Utils.nonNull(validateValue); } public String getName() { return name; } public Class<T> getType() { return clazz; } public T validate(final T value) { Utils.validateArg(validateValue.apply(value), String.format("Invalid value %s for annotation %s.", value, name)); return value; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final AnnotationKey<?> that = (AnnotationKey<?>) o; return name.equals(that.name) && clazz.equals(that.clazz); } @Override public int hashCode() { int result = name.hashCode(); result = 31 * result + clazz.hashCode(); return result; } @Override public String toString() { return "AnnotationKey{" + "name='" + name + '\'' + ", class=" + clazz + '}'; } }
peter50216/pwntools-ruby
test/shellcraft/memcpy_test.rb
# encoding: ASCII-8BIT # frozen_string_literal: true require 'test_helper' require 'pwnlib/context' require 'pwnlib/shellcraft/shellcraft' class MemcpyTest < MiniTest::Test include ::Pwnlib::Context def setup @shellcraft = ::Pwnlib::Shellcraft::Shellcraft.instance end def test_amd64 context.local(arch: 'amd64') do assert_equal(<<-'EOS', @shellcraft.memcpy('rdi', 'rbx', 255)) /* memcpy("rdi", "rbx", 0xff) */ cld mov rsi, rbx xor ecx, ecx mov cl, 0xff rep movsb EOS assert_equal(<<-'EOS', @shellcraft.memcpy('rdi', 0x602020, 10)) /* memcpy("rdi", 0x602020, 0xa) */ cld mov esi, 0x1010101 xor esi, 0x1612121 /* 0x602020 == 0x1010101 ^ 0x1612121 */ push 9 /* mov ecx, '\n' */ pop rcx inc ecx rep movsb EOS end end def test_i386 context.local(arch: :i386) do assert_equal(<<-'EOS', @shellcraft.memcpy('eax', 'ebx', 'ecx')) /* memcpy("eax", "ebx", "ecx") */ cld mov edi, eax mov esi, ebx rep movsb EOS end end end
randolphwong/mcsema
boost/libs/spirit/example/karma/num_list2.cpp
<filename>boost/libs/spirit/example/karma/num_list2.cpp /*============================================================================= Copyright (c) 2002-2010 <NAME> Copyright (c) 2002-2010 <NAME> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ /////////////////////////////////////////////////////////////////////////////// // // This sample demonstrates a generator for a comma separated list of numbers. // No actions. It is based on the example qi/num_lists.cpp for reading in // some numbers to generate. // /////////////////////////////////////////////////////////////////////////////// #include <boost/config/warning_disable.hpp> #include <boost/spirit/include/qi.hpp> #include <boost/spirit/include/karma.hpp> #include <iostream> #include <string> #include <vector> namespace client { /////////////////////////////////////////////////////////////////////////// // Our number list parser, please see the example qi/numlist1.cpp for // more information /////////////////////////////////////////////////////////////////////////// template <typename Iterator> bool parse_numbers(Iterator first, Iterator last, std::vector<double>& v) { using boost::spirit::qi::double_; using boost::spirit::qi::phrase_parse; using boost::spirit::ascii::space; bool r = phrase_parse(first, last, double_ % ',', space, v); if (first != last) return false; return r; } /////////////////////////////////////////////////////////////////////////// // Our number list generator /////////////////////////////////////////////////////////////////////////// //[tutorial_karma_numlist2 template <typename OutputIterator, typename Container> bool generate_numbers(OutputIterator& sink, Container const& v) { using boost::spirit::karma::double_; using boost::spirit::karma::generate_delimited; using boost::spirit::ascii::space; bool r = generate_delimited( sink, // destination: output iterator double_ % ',', // the generator space, // the delimiter-generator v // the data to output ); return r; } //] } //////////////////////////////////////////////////////////////////////////// // Main program //////////////////////////////////////////////////////////////////////////// int main() { std::cout << "/////////////////////////////////////////////////////////\n\n"; std::cout << "\t\tA comma separated list generator for Spirit...\n\n"; std::cout << "/////////////////////////////////////////////////////////\n\n"; std::cout << "Give me a comma separated list of numbers.\n"; std::cout << "Type [q or Q] to quit\n\n"; std::string str; while (getline(std::cin, str)) { if (str.empty() || str[0] == 'q' || str[0] == 'Q') break; std::vector<double> v; // here we put the data to generate if (client::parse_numbers(str.begin(), str.end(), v)) { // ok, we got some numbers, now print them back out std::cout << "-------------------------\n"; std::string generated; std::back_insert_iterator<std::string> sink(generated); if (!client::generate_numbers(sink, v)) { std::cout << "-------------------------\n"; std::cout << "Generating failed\n"; std::cout << "-------------------------\n"; } else { std::cout << "-------------------------\n"; std::cout << "Generated: " << generated << "\n"; std::cout << "-------------------------\n"; } } else { std::cout << "-------------------------\n"; std::cout << "Parsing failed\n"; std::cout << "-------------------------\n"; } } std::cout << "Bye... :-) \n\n"; return 0; }
morses/essentialmath
docs/html/_iv_hermite_8cpp.js
<reponame>morses/essentialmath<filename>docs/html/_iv_hermite_8cpp.js var _iv_hermite_8cpp = [ [ "operator<<", "_iv_hermite_8cpp.html#a21520106c9c3b1dc59c0b58ac07f5909", null ] ];
rmartinsanta/mork
core/src/main/java/es/urjc/etsii/grafo/solver/algorithms/multistart/MultiStartAlgorithmBuilder.java
<filename>core/src/main/java/es/urjc/etsii/grafo/solver/algorithms/multistart/MultiStartAlgorithmBuilder.java package es.urjc.etsii.grafo.solver.algorithms.multistart; import es.urjc.etsii.grafo.io.Instance; import es.urjc.etsii.grafo.solution.Solution; import es.urjc.etsii.grafo.solver.algorithms.Algorithm; import java.util.concurrent.TimeUnit; /** * Mutistart algorithm builder based on Java Builder Pattern * * @param <S> type of the solution of the problem * @param <I> type of the instance of the problem */ public class MultiStartAlgorithmBuilder<S extends Solution<S, I>, I extends Instance> { /** * Name of the algorithm */ private String name = ""; /** * Maximum number of iterations, set by default to 1073741823 */ private int maxIterations = Integer.MAX_VALUE / 2; /** * Minimum number of iterations, set by default to one */ private int minIterations = 1; /** * Maximum number of iterations without improving, set by default to 1073741823 */ private int maxIterationsWithoutImproving = Integer.MAX_VALUE / 2; /** * Cut off time of the algorithm. In this case is set to 1 year. */ private int units = 365; private TimeUnit timeUnit = TimeUnit.DAYS; /** * Use MultiStartAlgorithmBuilder::builder static method instead */ protected MultiStartAlgorithmBuilder() { } /** * <p>withAlgorithmName.</p> * * @param name name of the algorithm * @return MultiStartAlgorithmBuilder */ public MultiStartAlgorithmBuilder<S, I> withAlgorithmName(String name) { this.name = name; return this; } /** * <p>withMaxIterations.</p> * * @param maxIterations maximum number of iteration of the algorithm * @return MultiStartAlgorithmBuilder */ public MultiStartAlgorithmBuilder<S, I> withMaxIterations(int maxIterations) { this.maxIterations = maxIterations; return this; } /** * <p>withMinIterations.</p> * * @param minIterations minimum number of iterations of the algorithm * @return MultiStartAlgorithmBuilder */ public MultiStartAlgorithmBuilder<S, I> withMinIterations(int minIterations) { this.minIterations = minIterations; return this; } /** * <p>withMaxIterationsWithoutImproving.</p> * * @param maxIterationsWithoutImproving maximum number of iterations without improving * @return MultiStartAlgorithmBuilder */ public MultiStartAlgorithmBuilder<S, I> withMaxIterationsWithoutImproving(int maxIterationsWithoutImproving) { this.maxIterationsWithoutImproving = maxIterationsWithoutImproving; return this; } /** * <p>withTime.</p> * * @param time number of a spcefic time unit measure * @param timeUnit time unit measure: SECOND, DAY, etc. * @return MultiStartAlgorithmBuilder */ public MultiStartAlgorithmBuilder<S, I> withTime(int time, TimeUnit timeUnit) { this.units = time; this.timeUnit = timeUnit; return this; } /** * Method to build a Multistart Algorithm * * @param algorithm algorithm * @return the multistart algorithm */ public MultiStartAlgorithm<S, I> build(Algorithm<S, I> algorithm) { return new MultiStartAlgorithm<>(name, algorithm, maxIterations, minIterations, maxIterationsWithoutImproving, units, timeUnit); } }
bfcoder/vt-ht-tracker
db/schema.rb
<gh_stars>0 # encoding: UTF-8 # This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your # database schema. If you need to create the application database on another # system, you should be using db:schema:load, not running all the migrations # from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 20151205161225) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" create_table "districts", force: :cascade do |t| t.string "name", limit: 255 t.datetime "created_at" t.datetime "updated_at" end add_index "districts", ["name"], name: "index_districts_on_name", unique: true, using: :btree create_table "histories", force: :cascade do |t| t.datetime "month" t.string "status" t.string "notes" t.integer "visit_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "histories", ["visit_id"], name: "index_histories_on_visit_id", using: :btree create_table "households", force: :cascade do |t| t.integer "district_id" t.string "name" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.string "teachers" t.boolean "status", default: true end add_index "households", ["district_id"], name: "index_households_on_district_id", using: :btree add_index "households", ["status"], name: "index_households_on_status", using: :btree create_table "settings", force: :cascade do |t| t.string "mode" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.string "presidency_message", limit: 10000 end create_table "sisters", force: :cascade do |t| t.integer "district_id", null: false t.datetime "created_at" t.datetime "updated_at" t.string "first_name", limit: 255 t.string "last_name", limit: 255 t.string "teachers" t.boolean "status", default: true end add_index "sisters", ["district_id"], name: "index_sisters_on_district_id", using: :btree add_index "sisters", ["status"], name: "index_sisters_on_status", using: :btree create_table "users", force: :cascade do |t| t.string "email", limit: 255, default: "", null: false t.string "encrypted_password", limit: 255, default: "", null: false t.string "reset_password_token", limit: 255 t.datetime "reset_password_sent_at" t.datetime "remember_created_at" t.integer "sign_in_count", default: 0, null: false t.datetime "current_sign_in_at" t.datetime "last_sign_in_at" t.inet "current_sign_in_ip" t.inet "last_sign_in_ip" t.datetime "created_at" t.datetime "updated_at" t.integer "roles_mask" t.string "username", limit: 255 end add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree add_index "users", ["username"], name: "index_users_on_username", unique: true, using: :btree create_table "visits", force: :cascade do |t| t.date "month" t.string "status", limit: 255 t.integer "sister_id" t.datetime "created_at" t.datetime "updated_at" t.string "notes" t.integer "household_id" end add_index "visits", ["household_id"], name: "index_visits_on_household_id", using: :btree add_index "visits", ["month"], name: "index_visits_on_month", using: :btree add_index "visits", ["sister_id"], name: "index_visits_on_sister_id", using: :btree add_index "visits", ["status"], name: "index_visits_on_status", using: :btree end
nakamotoo/lifelong_rl
experiment_configs/configs/mpc/loop_config.py
<reponame>nakamotoo/lifelong_rl<gh_stars>10-100 import torch from lifelong_rl.models.dynamics_models.probabilistic_ensemble import ProbabilisticEnsemble from lifelong_rl.policies.models.gaussian_policy import TanhGaussianPolicy from lifelong_rl.policies.mpc.mpc import MPCPolicy from lifelong_rl.models.networks import FlattenMlp from lifelong_rl.trainers.mbrl.mbrl import MBRLTrainer from lifelong_rl.trainers.mpc.mpc_trainer import MPPITrainer from lifelong_rl.trainers.multi_trainer import MultiTrainer from lifelong_rl.trainers.q_learning.sac import SACTrainer import lifelong_rl.util.pythonplusplus as ppp def value_func(obs, critic_policy=None, qf1=None, qf2=None): actions, *_ = critic_policy(obs) sa = torch.cat([obs, actions], dim=-1) q1, q2 = qf1(sa), qf2(sa) min_q = torch.min(q1, q2) return min_q def get_config( variant, expl_env, eval_env, obs_dim, action_dim, replay_buffer, ): """ Set up terminal value function """ M = variant['policy_kwargs']['layer_size'] critic_policy = TanhGaussianPolicy( obs_dim=obs_dim, action_dim=action_dim, hidden_sizes=[M, M], ) qf1, qf2, target_qf1, target_qf2 = ppp.group_init( 4, FlattenMlp, input_size=obs_dim + action_dim, output_size=1, hidden_sizes=[M, M], ) critic_policy_trainer = SACTrainer( env=expl_env, policy=critic_policy, qf1=qf1, qf2=qf2, target_qf1=target_qf1, target_qf2=target_qf2, **variant['policy_trainer_kwargs'], ) """ Set up dynamics model """ M = variant['mbrl_kwargs']['layer_size'] dynamics_model = ProbabilisticEnsemble( ensemble_size=variant['mbrl_kwargs']['ensemble_size'], obs_dim=obs_dim, action_dim=action_dim, hidden_sizes=[M, M, M, M], ) model_trainer = MBRLTrainer( ensemble=dynamics_model, **variant['mbrl_kwargs'], ) """ Set up MPC """ policy = MPCPolicy( env=expl_env, dynamics_model=dynamics_model, plan_dim=action_dim, value_func=value_func, value_func_kwargs=dict( critic_policy=critic_policy, qf1=qf1, qf2=qf2, ), **variant['mpc_kwargs'], ) trainer = MPPITrainer( policy=policy, ) trainer = MultiTrainer( trainers=[trainer, critic_policy_trainer], trainer_steps=[1, 1], trainer_names=['mpc_trainer', 'sac_trainer'], ) config = dict() config.update(dict( trainer=trainer, model_trainer=model_trainer, exploration_policy=policy, evaluation_policy=critic_policy, exploration_env=expl_env, evaluation_env=eval_env, replay_buffer=replay_buffer, dynamics_model=dynamics_model, )) config['algorithm_kwargs'] = variant.get('algorithm_kwargs', dict()) return config
loooon/fitnesse
src/test/java/com/qa/CITest.java
<reponame>loooon/fitnesse<gh_stars>0 package com.qa; import com.qa.http.Get; import com.qa.http.Http; import fitnesse.fixtures.SystemExitTableConfiguration; import org.testng.annotations.Test; import java.io.IOException; import java.util.HashMap; import java.util.Map; import static com.qa.Store.GLOBAL_HEADERS_KEY; /** * IAT @wkzf * Created by yu on 2017/7/13. */ public class CITest { // @Ignore // @Test public void st() throws Exception { new Store(GLOBAL_HEADERS_KEY, "{authorization:\"e7701df281864c28a58319fa6afce73f\""); ConnectServer cs = new ConnectServer("http://cw.lieluobo.testing/api/bd/list/developing"); cs.setParam("id", "1"); cs.setBody(" var out={\n" + " staffId: \"204632\",\n" + " // teamId: 1,\n" + " page: 1,\n" + " size: 10\n" + "}\n" + "out.bb=\"SS\"", "js"); cs.post(); assert cs.jsonContain("\t{name:\t\"客户公司-自动化测试预埋数据\",orgBdName:\t\"员工4-HRBD-自动化测试预埋数据\"}\t"); // cs.delete(); } // // @Test // public void sss() throws UnirestException { // Unirest.get("http://www.baidu.com") // .queryString("name", "Mark") // .asString(); // // // Get get = Http.get("http://yahoo.com"); // System.out.println(get.text()); // } // @Test public void ssls() { // for(int i=0;i<100;i++){ // long stime=System.currentTimeMillis(); // // Get get = Http.get("https://baidu.com"); // get.text(); // long etime=System.currentTimeMillis(); // // System.out.println(etime-stime); // } ConnectServer cs = new ConnectServer("http://cw.lieluobo.testing/api/bd/list/developing"); cs.setParam("id", "1"); cs.setParam("id2", "3"); cs.get(); } @Test public void baiduTest() { new Store("headers","{auther:\"abc\"}"); ConnectServer cs = new ConnectServer("http://baidu.com"); cs.setParam("id", "1"); cs.setParam("id2", "3"); cs.get(); } //@Test public void sk22(){ ConnectServer cs = new ConnectServer("http://cw.lieluobo.testing/api/bd/org/101707/visit"); cs.setHeader("author", "haolie"); cs.setHeader("authorization", "<KEY>"); cs.setHeader("channel","crmhr"); cs.get(); } //@Test public void ss(){ try { fitnesse.slim.SlimService.main(new String[]{"1"}); } catch (IOException e) { e.printStackTrace(); } new SystemExitTableConfiguration(); } @Test public void memoutTest(){ //内存溢出测试 Map map=new HashMap(); for(int i=0;i<1000000000;i++){ map.put(i,i); } } }
marient/PelePhysics
Support/Fuego/Pythia/pythia-0.4/packages/fuego/tests/mechanisms/mechanism.py
<filename>Support/Fuego/Pythia/pythia-0.4/packages/fuego/tests/mechanisms/mechanism.py #!/usr/bin/env python # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # <NAME> # (C) 1998-2001 All Rights Reserved # # <LicenseText> # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # import pyre # convenient definitions for interactive use from pyre.handbook.units.SI import meter, second, mole, kelvin from pyre.handbook.units.length import cm from pyre.handbook.units.energy import cal, kcal from pyre.handbook.units.pressure import atm T = 1000.0 * kelvin R = pyre.handbook.constants.fundamental.gas_constant timer = pyre.timers.timer("meshanism") def test(options): mechanism = load(options) mixture = prepareMixture(mechanism) calc = calculator(mixture, mechanism) T = 1000.0 * kelvin progressRate(calc, T) nasty = mismatches(calc) for reaction in nasty: reactionDetails(reaction) validateThermo(mixture, T) validateRates(calc) return mechanism, calc def progressRate(calc, T): print " --- computing the rate of progress at T = %s" % str(T), timer.reset() timer.start() i = 0 for reaction in calc.reaction(): i += 1 reaction.update(T) timer.stop() print "... done in %g sec" % timer.read() #print return def reactionDetails(reaction): header = "Reaction %d: " % reaction.id() + str(reaction) line = "-"*len(header) print print header print line print print "phase space dimension:", reaction.equlibrium.dimPhaseSpace print "equilibrium constant:", reaction.equlibrium(T) print f = reaction.forwardRate print "forward:" print " rate calculator:", f print " rate type:", f.rateCalculator print print " progress rate:", f() print print " enhancement:", f.enhancement print " phase factor:", f.phaseSpace print " reaction rate:", f.rate #print " Preduced:", f.rateCalculator.P_red print r = reaction.reverseRate print "reverse:" print " rate calculator:", r print " rate type:", r.rateCalculator print print " progress rate:", r() print print " enhancement:", r.enhancement print " phase factor:", r.phaseSpace print " equilibrium constant:", reaction.equlibrium(T) print " reaction rate:", r.rate print q = f() - r() from chemkin_rates import chemkin_rates n = reaction.id() cq, cK_c = chemkin_rates[n-1] cK_c *= (cm**3 / mole) cq *= (mole/cm**3)/second print "chemkin:" print " K_c = %s" % cK_c print " q = %s" % cq print " ratio = %g, error = %g" % (q/cq, abs(1.0 - q/cq)) return def validateRates(calc): width = 14 precision = width - 7 header1 = "".center(4) \ + ' ' + "".center(40) \ + ' ' + 'progress rate'.center(width+2) \ + ' ' + 'chemkin value'.center(width+2) header2 = "Id".center(4) \ + ' | ' + "Reaction".center(40) \ + ('|' + 'mole/cm^3/s'.center(width+2))*2 \ + '|' + 'relative error'.center(width+2) line = "-----+-" + "-"*40 + ("+" + "-"*(width+2))*3 print header1 print header2 print line i = 0 format = "%4d : %-40s" + ("| %%%d.%de " % (width, precision))*3 #format = "%4d : %-40s" + "| %s "*2 from chemkin_rates import chemkin_rates for reaction in calc.reaction(): i += 1 q_f, q_r = reaction.progressRate() if q_f.derivation != (mole/meter**3/second).derivation: pyre.debug.Firewall.hit("bad units in forward progress rate for reaction %d" % i) if q_r.derivation != (mole/meter**3/second).derivation: pyre.debug.Firewall.hit("bad units in reverse progress rate for reaction %d" % i) progress = 1e-6 * (q_f - q_r).value chemkin, k_c = chemkin_rates[i-1] err = abs((progress-chemkin)/chemkin) print format % (i, str(reaction), progress, chemkin, err) return def mismatches(calc): from chemkin_rates import chemkin_rates candidates = [] for reaction in calc.reaction(): i = reaction.id() q_f, q_r = reaction.progressRate() if q_f.derivation != (mole/meter**3/second).derivation: pyre.debug.Firewall.hit("bad units in forward progress rate for reaction %d" % i) if q_r.derivation != (mole/meter**3/second).derivation: pyre.debug.Firewall.hit("bad units in reverse progress rate for reaction %d" % i) progress = 1e-6 * (q_f - q_r).value chemkin, k_c = chemkin_rates[i-1] err = abs((progress-chemkin)/chemkin) if err > 1e-2: print " ### reaction %d: mismatch = %g" % (i, err) candidates.append(reaction) return candidates def prepareMixture(mechanism): print " --- preparing a mixture", timer.reset() timer.start() mix = pyre.chemistry.mixture(mechanism) from pyre.handbook.units.SI import * c = mole / (centi*meter)**3 for species in mix.find(): species.updateConcentration(c) mix.find("<mixture>").updateConcentration((mix.size() - 1) * c) #mix.find("O").updateConcentration(c) #mix.find("CO").updateConcentration(c) #mix.find("<mixture>").updateConcentration(2*c) timer.stop() print "... done in %g sec" % timer.read() print " +++ mixture: concentration", mix.find("<mixture>").concentration() #print return mix def calculator(mix, mechanism): print " --- coverting mechanism to a rate calculator", timer.reset() timer.start() calc = pyre.chemistry.mechanism(mix, mechanism) timer.stop() print "... done in %g sec" % timer.read() return calc def validateThermo(mixture, T): msg = "Thermal properties at T=%s" % T print msg print "-" * len(msg) print "Tabulating thermal properties" table = [] timer.reset() timer.start() for species in mixture.find(): symbol = species.symbol() if symbol == "<mixture>": continue cp_R = species.cp_R(T) h_RT = species.h_RT(T) s_R = species.s_R(T) g_RT = species.g_RT(T) table.append((symbol, cp_R, h_RT, s_R, g_RT)) timer.stop() print "Tabulation done in %g sec" % timer.read() print width = 18 precision = width - 7 header = "Species".center(12) \ + '|' + "cp_R".center(width+2) \ + '|' + "h_RT".center(width+2) \ + '|' + "s_R".center(width+2) \ + '|' + "g_RT".center(width+2) line = "-"*12 + ("+" + "-"*(width+2))*4 print header print line format = " %-10s" + ("| %%%d.%df " % (width, precision))*4 for symbol, cp_R, h_RT, s_R, g_RT in table: print format % (symbol, cp_R, h_RT, s_R, g_RT) print print "Verifying against cantera data" print print header print line from cantera_thermo import cantera format = " %-10s" + ("| %%%d.%de " % (width, precision))*4 for symbol, mcp_R, mh_RT, ms_R, mg_RT in table: ccp_R, ch_RT, cs_R, cg_RT = cantera[symbol] dcp_R = abs((mcp_R - ccp_R)/mcp_R) dh_RT = abs((mh_RT - ch_RT)/mh_RT) ds_R = abs((ms_R - cs_R)/ms_R) dg_RT = abs((mg_RT - cg_RT)/mg_RT) print format % (symbol, dcp_R, dh_RT, ds_R, dg_RT) print return def load(options): file = options["--file"] format = options["--format"] print " --- loading mechanism '%s'" % file, timer.start() mechanism = pyre.chemistry.serialization.load(file, format) timer.stop() print "... done in %g sec" % timer.read() #mechanism.printStatistics() return mechanism # usage def usage(program): print "Usage: %s [options ...]" % program print "Options: (default values in brackets)" print " --file=<mechanism filename> [%s]" % defaults["--file"] print " --format=<chemkin|ckml> [%s]" % defaults["--file"] print return defaults = { "--file": "GRIMech-3.0.ck2", "--format": "chemkin" } # main if __name__ == "__main__": # pyre.support.debug.activate("pyre.chemistry.serialization") # pyre.support.debug.activate("pyre.chemistry.chemkin-scanner") # pyre.support.debug.activate("pyre.chemistry.chemkin-parser") # pyre.support.debug.activate("pyre.chemistry.chemkin-tokenizer") import pyre options = pyre.applications.main(defaults, usage) mechanism, calc = test(options) # version __id__ = "$Id$" # # End of file
cping/LGame
Java/Loon-Neo/src/loon/component/layout/Margin.java
<filename>Java/Loon-Neo/src/loon/component/layout/Margin.java /** * Copyright 2008 - 2019 The Loon Game Engine Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. * * @project loon * @author cping * @email:<EMAIL> * @version 0.5 */ package loon.component.layout; import loon.action.ActionBind; import loon.component.LToolTip; import loon.geom.PointF; import loon.geom.Vector2f; import loon.utils.MathUtils; import loon.utils.TArray; /** * 动作对象布局用类,可以根据左右高低参数布置一组ActionBind的显示位置 */ public class Margin { private TArray<ActionBind> _childrens; private Vector2f _offset; private float _marginTop; private float _marginRight; private float _marginBottom; private float _marginLeft; private float _size; private boolean _isSnap; private boolean _isVertical; public Margin(float size, boolean vertical) { this(size, vertical, true); } public Margin(float size, boolean vertical, boolean snap) { this._size = size; this._isVertical = vertical; this._offset = new Vector2f(); this._childrens = new TArray<ActionBind>(); this._isSnap = snap; this._marginTop = 0; this._marginRight = 0; this._marginBottom = 0; this._marginLeft = 0; } public Margin addChild(ActionBind bind) { if (bind == null) { return this; } if (!_childrens.contains(bind)) { _childrens.add(bind); } return this; } public boolean removeChild(ActionBind bind) { if (bind == null) { return false; } return _childrens.remove(bind); } public Margin clear() { _childrens.clear(); return this; } public Margin reverse() { _childrens.reverse(); return this; } public Margin layout() { ActionBind bind; PointF size; float cols = 0; float rows = 0; float largest = 0; float dx; float dy; float w; float h; TArray<ActionBind> temp = new TArray<ActionBind>(_childrens); for (int i = 0; i < temp.size; i++) { bind = _childrens.get(i); if (bind == null || bind instanceof LToolTip) { continue; } size = (bind.getWidth() > 1 && bind.getHeight() > 1) ? new PointF(bind.getWidth(), bind.getHeight()) : new PointF(bind.getX(), bind.getY()); w = size.x + this._marginLeft + this._marginRight; h = size.y + this._marginTop + this._marginBottom; if (!this._isVertical) { cols += w; if (cols > this._size) { rows += (largest == 0) ? rows : largest; largest = 0; cols = w; } if (h > largest) { largest = h; } dx = cols - size.x - this._marginRight; dy = rows + this._marginTop; } else { rows += h; if (rows > this._size) { cols += (largest == 0) ? cols : largest; largest = 0; rows = h; } if (w > largest) { largest = w; } dx = cols + this._marginLeft; dy = rows - size.y - this._marginBottom; } this.pos(bind, dx, dy); } temp.clear(); return this; } protected void pos(ActionBind o, float dx, float dy) { o.setLocation((this._isSnap ? MathUtils.round(dx) : dx) + _offset.x, (this._isSnap ? MathUtils.round(dy) : dy) + _offset.y); } public Margin setSize(float size) { this._size = size; return this; } public float getSize() { return this._size; } public Margin setVertical(boolean v) { this._isVertical = v; return this; } public boolean isVertical() { return this._isVertical; } public Margin setMargin(float left, float top, float right, float bottom) { setMarginLeft(left); setMarginTop(top); setMarginRight(right); setMarginBottom(bottom); return this; } public float getMarginTop() { return _marginTop; } public Margin setMarginTop(float marginTop) { this._marginTop = marginTop; return this; } public float getMarginRight() { return _marginRight; } public Margin setMarginRight(float marginRight) { this._marginRight = marginRight; return this; } public float getMarginBottom() { return _marginBottom; } public Margin setMarginBottom(float marginBottom) { this._marginBottom = marginBottom; return this; } public float getMarginLeft() { return _marginLeft; } public Margin setMarginLeft(float marginLeft) { this._marginLeft = marginLeft; return this; } public Vector2f getOffset() { return _offset; } public Margin setOffset(float x, float y) { this._offset.set(x, y); return this; } public Margin setOffset(Vector2f offset) { this._offset.set(offset); return this; } }
knokko/Old-Platformer
Platformer/src/entities/monsters/Catapult.java
<reponame>knokko/Old-Platformer<filename>Platformer/src/entities/monsters/Catapult.java package entities.monsters; import java.awt.Graphics; import java.awt.Point; import java.awt.geom.Point2D; import java.awt.geom.Point2D.Double; import render.Model; import entities.Entity; import entities.Shape; import entities.ai.EntityAIRangedAttack; import entities.projectiles.Stone; import main.Game; import world.World; import static java.lang.Math.*; public class Catapult extends Monster { private static short[][][] directionTable; public double goalRotation = 255; public Catapult(Game game, World world, Double position) { super(game, world, position); models.add(new Model("sprites/entities/enemies/catapult/catapult.png", new Point(0, 60), new Point(90, 75), this)); models.add(new Model("sprites/entities/enemies/catapult/thrower.png", new Point(151, -30), new Point(14, 110), this).setParent(base())); ai.add(new EntityAIRangedAttack(this, game.player, 10000, 300)); width = 180; height = 150; } @Override public void update(){ super.update(); if(goalRotation != 255 && stoneThrower().rotation != goalRotation){ stoneThrower().rotation += 5; if(stoneThrower().rotation > 360) stoneThrower().rotation -= 360; if(Math.abs(stoneThrower().rotation - goalRotation) < 5){ stoneThrower().rotation = goalRotation; goalRotation = 255; if(goalRotation < 0) goalRotation += 360; } } else if(stoneThrower().rotation != goalRotation){ stoneThrower().rotation -= 2; if(stoneThrower().rotation < 0) stoneThrower().rotation += 360; if(Math.abs(stoneThrower().rotation - goalRotation) < 2){ stoneThrower().rotation = goalRotation; } } } public Stone projectile(Entity target){ Point2D.Double t = target.position; double distanceX = t.x - position.x; double distanceY = t.y - position.y; Stone stone = new Stone(this, t); double direction = getTable((int)(distanceX), (int) (distanceY)); System.out.println("direction = " + direction); double startForce = stone.getSpeed(); double dir = toRadians(direction); double startForceX = cos(dir) * startForce; double ticks = distanceX / stone.ntopt(startForceX); Stone test = new Stone(this, new Point2D.Double(position.x + cos(dir) * (distanceX >= 0 ? 10 : -10), position.y + sin(dir) * 10)){ private boolean test; @Override public int getPower() { test = true; return 0; } @Override public boolean test(){ return test; } }; int i = 0; while(i < Math.abs(ticks) + 50){ test.update(); ++i; } if(!test.test()){ direction = getTable((int)(distanceX), (int) (distanceY), 1); if(direction == 0) direction = getTable((int)distanceX, (int)distanceY); dir = toRadians(direction); startForceX = cos(dir) * startForce; ticks = distanceX / stone.ntopt(startForceX); } if(direction != 0) goalRotation = 360 - direction - base().rotation; if(goalRotation < 0) goalRotation += 360; System.out.println("direction = " + direction + " and goalRotation = " + goalRotation); return new Stone(this, new Point2D.Double(position.x + cos(dir) * (distanceX >= 0 ? 10 : -10), position.y + sin(dir) * 10)); } @Override public void paint(Graphics gr){ if(facingLeft) stoneThrower().rotation *= -1; super.paint(gr); if(facingLeft) stoneThrower().rotation *= -1; } @Override public Model gravityModel(){ return base(); } @Override public Shape getCollidingShape(){ return Shape.BOX; } @Override public double getUpdateRange(){ return 12000; } public static void updateDirectionTable(Game game, World world){ directionTable = new short[1000][400][2]; double rotation = 270; Stone stone = new Stone(new Catapult(game, world, new Point2D.Double()), new Point2D.Double()); double gravityForce = stone.getWeight() * world.gravity; double startForce = stone.getSpeed(); while(rotation <= 360 && rotation >= 270 || rotation >= 0 && rotation < 90){ int x = 0; while(x < 10000){ double startForceY = sin(toRadians(rotation)) * startForce; double startForceX = cos(toRadians(rotation)) * startForce; double ticks = x / stone.ntopt(startForceX); int y = (int) (stone.ntopt(startForceY) * ticks - 0.5 * stone.ntopt(gravityForce) * ticks * ticks); if(y > -600 && y < 3400) setTable(x, y, rotation); x += 10; } rotation += 0.01; if(rotation >= 360) rotation = 0; } } private static void setTable(int x, int y, double direction){ byte b = 0; if(direction > 45 && direction < 270) b = 1; if(direction >= 270) direction -= 180; else direction = -direction; directionTable[x / 10][y / 10 + 60][b] = (short) (direction * 100); } private static double getTable(int x, int y, int index3){ try { if(x < 0) x = -x; double table = directionTable[x / 10][y / 10 + 60][index3]; if(index3 == 1 && table == 0){ table = directionTable[(x + 10)/ 10][y / 10 + 60][index3]; if(table == 0) table = directionTable[(x - 10)/ 10][y / 10 + 60][index3]; if(table == 0) table = directionTable[(x + 20)/ 10][y / 10 + 60][index3]; if(table == 0) table = directionTable[(x - 20)/ 10][y / 10 + 60][index3]; if(table == 0) table = directionTable[x / 10][y / 10 + 61][index3]; if(table == 0) table = directionTable[x / 10][y / 10 + 59][index3]; if(table == 0) table = directionTable[x / 10][y / 10 + 62][index3]; if(table == 0) table = directionTable[x / 10][y / 10 + 58][index3]; } table /= 100; if(table >= 90) table += 180; else table = -table; return table; } catch(Exception ex){ return 0; } } private static double getTable(int x, int y){ return getTable(x, y, 0); } public Model base(){ return models.get(0); } public Model stoneThrower(){ return models.get(1); } }
OakCityLabs/ios_system
libinfo/lookup.subproj/si_data.c
/* * Copyright (c) 2008-2015 Apple Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ #include <assert.h> #include <errno.h> #include <stdlib.h> #include <libkern/OSAtomic.h> #include "si_data.h" #include "si_module.h" si_list_t * si_list_add(si_list_t *l, si_item_t *e) { size_t size; if (e == NULL) return l; if (l == NULL) { l = (si_list_t *)calloc(1, sizeof(si_list_t)); if (l != NULL) l->refcount = 1; } if (l != NULL) { size = (l->count + 1) * sizeof(si_item_t *); l->entry = (si_item_t **)reallocf(l->entry, size); if (l->entry != NULL) l->entry[l->count++] = si_item_retain(e); } if ((l == NULL) || (l->entry == NULL)) { free(l); l = NULL; errno = ENOMEM; } return l; } si_list_t * si_list_concat(si_list_t *l, si_list_t *x) { si_item_t *item; size_t newcount; size_t size; int i; if ((x == NULL) || (x->count == 0)) return l; if (l == NULL) { l = (si_list_t *)calloc(1, sizeof(si_list_t)); l->refcount = 1; } if (l != NULL) { newcount = (size_t)l->count + (size_t)x->count; size = newcount * sizeof(si_item_t *); l->entry = (si_item_t **)reallocf(l->entry, size); if (l->entry) { for (i = 0; i < x->count; ++i) { item = x->entry[i]; si_item_retain(item); l->entry[l->count + i] = item; } l->count += x->count; } else { l->count = 0; free(l); l = NULL; } } if (l == NULL) errno = ENOMEM; return l; } si_item_t * si_list_next(si_list_t *list) { if (list == NULL) return NULL; if (list->curr >= list->count) return NULL; return list->entry[list->curr++]; } void si_list_reset(si_list_t *list) { if (list != NULL) list->curr = 0; } si_list_t * si_list_retain(si_list_t *list) { int32_t rc; if (list == NULL) return NULL; rc = OSAtomicIncrement32Barrier(&list->refcount); assert(rc >= 1); return list; } void si_list_release(si_list_t *list) { int32_t rc, i; if (list == NULL) return; rc = OSAtomicDecrement32Barrier(&list->refcount); assert(rc >= 0); if (rc == 0) { for (i = 0; i < list->count; i++) { si_item_release(list->entry[i]); } free(list->entry); free(list); } } si_item_t * si_item_retain(si_item_t *item) { int32_t rc; if (item == NULL) return NULL; rc = OSAtomicIncrement32Barrier(&item->refcount); assert(rc >= 1); return item; } void si_item_release(si_item_t *item) { int32_t rc; if (item == NULL) return; rc = OSAtomicDecrement32Barrier(&item->refcount); assert(rc >= 0); if (rc == 0) free(item); }
teddywest32/intellij-community
python/src/com/jetbrains/python/console/PydevDocumentationProvider.java
<reponame>teddywest32/intellij-community<filename>python/src/com/jetbrains/python/console/PydevDocumentationProvider.java /* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jetbrains.python.console; import com.intellij.lang.documentation.AbstractDocumentationProvider; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiManager; import com.intellij.psi.util.PsiTreeUtil; import com.jetbrains.python.console.completion.PydevConsoleElement; import com.jetbrains.python.console.pydev.ConsoleCommunication; import com.jetbrains.python.psi.PyExpression; import org.jetbrains.annotations.Nullable; /** * @author oleg */ public class PydevDocumentationProvider extends AbstractDocumentationProvider { @Override public PsiElement getDocumentationElementForLookupItem(final PsiManager psiManager, final Object object, final PsiElement element) { if (object instanceof PydevConsoleElement){ return (PydevConsoleElement) object; } return super.getDocumentationElementForLookupItem(psiManager, object, element); } @Override public String generateDoc(final PsiElement element, @Nullable final PsiElement originalElement) { // Process PydevConsoleElement case if (element instanceof PydevConsoleElement){ return PydevConsoleElement.generateDoc((PydevConsoleElement)element); } return null; } @Nullable public static String createDoc(final PsiElement element, final PsiElement originalElement) { final PyExpression expression = PsiTreeUtil.getParentOfType(originalElement, PyExpression.class); // Indicates that we are inside console, not a lookup element! if (expression == null){ return null; } final ConsoleCommunication communication = PydevConsoleRunner.getConsoleCommunication(originalElement); if (communication == null){ return null; } try { final String description = communication.getDescription(expression.getText()); return StringUtil.isEmptyOrSpaces(description) ? null : description; } catch (Exception e) { return null; } } }
ramcn/flappie-darwin-arm
src/stimuli_gen/tracker.cpp
<filename>src/stimuli_gen/tracker.cpp #include <iostream> #include <string> #include <vector> #include <map> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> //#include <opencv2/mat.hpp> #include "../ref_model/fast.h" #include "../ref_model/fast_constants.h" #include "../stimuli_gen/utils.h" //#define ASSERT(cond, str) if(!(cond)) {std::cout << str << std::endl; abort(0);} #define SSC_MARK(mark_value) \ {__asm mov ebx, mark_value} \ {__asm mov ebx, ebx} \ {__asm _emit 0x64} \ {__asm _emit 0x67} \ {__asm _emit 0x90} //#define SSC_MARK(value) \ // __asm__("mov %ebx 0xaa\n" \ // "mov %ebx %ebx\n" \ // "_emit 0x64\n" \ // "_emit 0x67\n" \ // "_emit 0x90") struct feature { /* feature(int x, int y, const uint8_t * im, int stride) : dx(0), dy(0) { for(int py = 0; py < full_patch_width; ++py) { for(int px = 0; px < full_patch_width; ++px) { patch[py * full_patch_width + px] = im[(int)x + px - half_patch_width + ((int)y + py - half_patch_width) * stride]; } } } */ uint8_t patch[full_patch_width*full_patch_width]; struct Point { float x, y; }; Point pred[3]; float dx, dy; }; struct Fast_Score { uint32_t y : 11; uint32_t x : 11; uint32_t score : 10; }; extern int g_ncc_compute; int g_ncc_compute = 0; int main (int argc, char *argv[]) { if(argc <= 1) { printf("Usage: <exe> <tracker dir> [<dump dir>]\n"); exit(1); } string dir = argv[1]; string instr_dir = argc > 2 ? argv[2] : "."; string img_file = dir + "/image.bmp"; string conf_file = dir + "/conf.txt"; int num_feat; #define READ_FILE(n, str, ...) assert(n == fscanf(fp, str, __VA_ARGS__)) // Read feature points and prediction FILE *fp = fopen(conf_file.c_str(), "r"); assert(fp); READ_FILE(1, "Num Prediction:%d", &num_feat); std::map<uint64_t, feature> feature_map; for(int fid = 0; fid < num_feat; fid++) { string patch_file = dir + "/patch_" + to_string(fid) + ".bmp"; cv::Mat patch_img = cv::imread(patch_file.c_str(), CV_LOAD_IMAGE_GRAYSCALE); assert(patch_img.elemSize() == 1); assert(patch_img.cols == full_patch_width); assert(patch_img.rows == full_patch_width); assert(patch_img.step == full_patch_width); feature &f = feature_map[fid]; memcpy(f.patch, patch_img.data, sizeof(f.patch)); for(int i=0; i < 3; i++) { READ_FILE(2, "%f %f", &f.pred[i].x, &f.pred[i].y); } } #undef READ_FILE // Read image cv::Mat img = cv::imread(img_file.c_str(), CV_LOAD_IMAGE_GRAYSCALE); assert(img.data); assert(img.elemSize() == 1); unsigned char *img_data = (unsigned char*)img.data; #if INSTRUMENT // Stimulus for RTL system((string("mkdir -p ") + instr_dir).c_str()); dump_mem2d((instr_dir + "Image.txt").c_str(), img_data, img.cols, img.rows, img.step); FILE *fp_patch = fopen((instr_dir + "FPPatches.txt").c_str(), "w+"); assert(fp_patch); vector<Fast_Score> list; for(int fid = 0; fid < num_feat; fid++) { feature &f = feature_map[fid]; for(int i = 0; i < 3; i++) { Fast_Score pred; pred.x = (f.pred[i].x + 0.5); pred.y = (f.pred[i].y + 0.5); list.push_back(pred); dump_mem_fp(fp_patch, f.patch, (full_patch_width * full_patch_width)); // float to fixed point precision f.pred[i].x = pred.x; f.pred[i].y = pred.y; } } dump_mem((instr_dir + "FPList.txt").c_str(), (uint8_t*)list.data(), list.size() * sizeof(Fast_Score)); fclose(fp_patch); FILE *fp_config = fopen((instr_dir + "Config.txt").c_str(), "w+"); assert(fp_patch); fprintf(fp_config, "%08x // Width:%d\n", img.cols, img.cols); fprintf(fp_config, "%08x // Height:%d\n", img.rows, img.rows); fprintf(fp_config, "%08x // Threshold:%d\n", (uint32_t)fast_track_threshold, (uint32_t)fast_track_threshold); fprintf(fp_config, "%08x // FPListLen:%d\n", list.size(), list.size()); fclose(fp_config); #endif// STIMULUS GENERATION fast_detector_9 fast; fast.init(img.cols, img.rows, img.step, full_patch_width, half_patch_width); vector<xy> out; out.resize(num_feat * 3); int out_id = 0; #ifdef LIT_MARKER // Start Marker __SSC_MARK(0xaa); #endif for(int fid = 0; fid < num_feat; fid++) { feature &f = feature_map[fid]; out[out_id++] = fast.track(f.patch, img_data, half_patch_width, half_patch_width, f.pred[0].x, f.pred[0].y, fast_track_radius, fast_track_threshold, fast_min_match); out[out_id++] = fast.track(f.patch, img_data, half_patch_width, half_patch_width, f.pred[1].x, f.pred[1].y, fast_track_radius, fast_track_threshold, fast_min_match); out[out_id++] = fast.track(f.patch, img_data, half_patch_width, half_patch_width, f.pred[2].x, f.pred[2].y, fast_track_radius, fast_track_threshold, fast_min_match); } #ifdef LIT_MARKER // End Marker __SSC_MARK(0xbb); #endif /* printf("%s %d %d\n", dir.c_str(), num_feat, g_ncc_compute); for(int i = 0; i < out.size(); i += 3) { printf("X:%0.8f, Y:%0.8f, Score:%0.8f\n", out[i].x, out[i].y, out[i].score); } */ #if INSTRUMENT vector<Fast_Score> score; score.resize(out_id); for(int i = 0; i < out_id; i++) { score[i].x = out[i].x; score[i].y = out[i].y; score[i].score = (uint32_t)(out[i].score * 1024); } dump_mem((instr_dir + "Result.txt").c_str(), (uint8_t*)score.data(), score.size() * sizeof(Fast_Score), 4); #endif fclose(fp); return 0; } /* for(int i = 0; i < 7; i++) { for(int j = 7; j--; ) { printf("%2x", f.patch[7*i+j]); } printf("\n"); } */
dtk/dtk-server
application/model/module/module/dsl/adapters/v4/object_model_form/action_def/parameters.rb
# # Copyright (C) 2010-2016 dtk contributors # # This file is part of the dtk project. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # module DTK; class ModuleDSL; class V4::ObjectModelForm class ActionDef class Parameters < self def self.create?(parent, input_hash, opts = {}) ret = nil unless parameters = Constant.matches?(input_hash, :Parameters) return ret end ParsingError.raise_error_if_not(parameters, Hash) ret = parameters.inject(OutputHash.new) do |h, (attr_name, attr_info)| if attr_info.is_a?(Hash) h.merge(attr_name => attribute_fields(attr_name, attr_info)) else fail ParsingError.new('Ill-formed parameter section for action (?1): ?2', action_print_name(parent, opts), 'parameters' => parameters) end end ret.empty? ? nil : ret end private def self.action_print_name(parent, opts = {}) cmp_print_form = parent.cmp_print_form if action_name = opts[:action_name] "#{cmp_print_form}.#{action_name}" else "action on component #{cmp_print_form}" end end end end end; end; end
dschachinger/colibri
colibri-bacnet4j/src/main/java/com/serotonin/bacnet4j/type/enumerated/PropertyIdentifier.java
<reponame>dschachinger/colibri /* * ============================================================================ * GNU General Public License * ============================================================================ * * Copyright (C) 2006-2011 Serotonin Software Technologies Inc. http://serotoninsoftware.com * @author <NAME> * * 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 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.serotonin.bacnet4j.type.enumerated; import com.serotonin.bacnet4j.type.primitive.Enumerated; import com.serotonin.util.queue.ByteQueue; public class PropertyIdentifier extends Enumerated { private static final long serialVersionUID = 7289026444729646422L; public static final PropertyIdentifier ackedTransitions = new PropertyIdentifier(0); public static final PropertyIdentifier ackRequired = new PropertyIdentifier(1); public static final PropertyIdentifier action = new PropertyIdentifier(2); public static final PropertyIdentifier actionText = new PropertyIdentifier(3); public static final PropertyIdentifier activeText = new PropertyIdentifier(4); public static final PropertyIdentifier activeVtSessions = new PropertyIdentifier(5); public static final PropertyIdentifier alarmValue = new PropertyIdentifier(6); public static final PropertyIdentifier alarmValues = new PropertyIdentifier(7); public static final PropertyIdentifier all = new PropertyIdentifier(8); public static final PropertyIdentifier allWritesSuccessful = new PropertyIdentifier(9); public static final PropertyIdentifier apduSegmentTimeout = new PropertyIdentifier(10); public static final PropertyIdentifier apduTimeout = new PropertyIdentifier(11); public static final PropertyIdentifier applicationSoftwareVersion = new PropertyIdentifier(12); public static final PropertyIdentifier archive = new PropertyIdentifier(13); public static final PropertyIdentifier bias = new PropertyIdentifier(14); public static final PropertyIdentifier changeOfStateCount = new PropertyIdentifier(15); public static final PropertyIdentifier changeOfStateTime = new PropertyIdentifier(16); public static final PropertyIdentifier notificationClass = new PropertyIdentifier(17); public static final PropertyIdentifier controlledVariableReference = new PropertyIdentifier(19); public static final PropertyIdentifier controlledVariableUnits = new PropertyIdentifier(20); public static final PropertyIdentifier controlledVariableValue = new PropertyIdentifier(21); public static final PropertyIdentifier covIncrement = new PropertyIdentifier(22); public static final PropertyIdentifier dateList = new PropertyIdentifier(23); public static final PropertyIdentifier daylightSavingsStatus = new PropertyIdentifier(24); public static final PropertyIdentifier deadband = new PropertyIdentifier(25); public static final PropertyIdentifier derivativeConstant = new PropertyIdentifier(26); public static final PropertyIdentifier derivativeConstantUnits = new PropertyIdentifier(27); public static final PropertyIdentifier description = new PropertyIdentifier(28); public static final PropertyIdentifier descriptionOfHalt = new PropertyIdentifier(29); public static final PropertyIdentifier deviceAddressBinding = new PropertyIdentifier(30); public static final PropertyIdentifier deviceType = new PropertyIdentifier(31); public static final PropertyIdentifier effectivePeriod = new PropertyIdentifier(32); public static final PropertyIdentifier elapsedActiveTime = new PropertyIdentifier(33); public static final PropertyIdentifier errorLimit = new PropertyIdentifier(34); public static final PropertyIdentifier eventEnable = new PropertyIdentifier(35); public static final PropertyIdentifier eventState = new PropertyIdentifier(36); public static final PropertyIdentifier eventType = new PropertyIdentifier(37); public static final PropertyIdentifier exceptionSchedule = new PropertyIdentifier(38); public static final PropertyIdentifier faultValues = new PropertyIdentifier(39); public static final PropertyIdentifier feedbackValue = new PropertyIdentifier(40); public static final PropertyIdentifier fileAccessMethod = new PropertyIdentifier(41); public static final PropertyIdentifier fileSize = new PropertyIdentifier(42); public static final PropertyIdentifier fileType = new PropertyIdentifier(43); public static final PropertyIdentifier firmwareRevision = new PropertyIdentifier(44); public static final PropertyIdentifier highLimit = new PropertyIdentifier(45); public static final PropertyIdentifier inactiveText = new PropertyIdentifier(46); public static final PropertyIdentifier inProcess = new PropertyIdentifier(47); public static final PropertyIdentifier instanceOf = new PropertyIdentifier(48); public static final PropertyIdentifier integralConstant = new PropertyIdentifier(49); public static final PropertyIdentifier integralConstantUnits = new PropertyIdentifier(50); public static final PropertyIdentifier limitEnable = new PropertyIdentifier(52); public static final PropertyIdentifier listOfGroupMembers = new PropertyIdentifier(53); public static final PropertyIdentifier listOfObjectPropertyReferences = new PropertyIdentifier(54); public static final PropertyIdentifier listOfSessionKeys = new PropertyIdentifier(55); public static final PropertyIdentifier localDate = new PropertyIdentifier(56); public static final PropertyIdentifier localTime = new PropertyIdentifier(57); public static final PropertyIdentifier location = new PropertyIdentifier(58); public static final PropertyIdentifier lowLimit = new PropertyIdentifier(59); public static final PropertyIdentifier manipulatedVariableReference = new PropertyIdentifier(60); public static final PropertyIdentifier maximumOutput = new PropertyIdentifier(61); public static final PropertyIdentifier maxApduLengthAccepted = new PropertyIdentifier(62); public static final PropertyIdentifier maxInfoFrames = new PropertyIdentifier(63); public static final PropertyIdentifier maxMaster = new PropertyIdentifier(64); public static final PropertyIdentifier maxPresValue = new PropertyIdentifier(65); public static final PropertyIdentifier minimumOffTime = new PropertyIdentifier(66); public static final PropertyIdentifier minimumOnTime = new PropertyIdentifier(67); public static final PropertyIdentifier minimumOutput = new PropertyIdentifier(68); public static final PropertyIdentifier minPresValue = new PropertyIdentifier(69); public static final PropertyIdentifier modelName = new PropertyIdentifier(70); public static final PropertyIdentifier modificationDate = new PropertyIdentifier(71); public static final PropertyIdentifier notifyType = new PropertyIdentifier(72); public static final PropertyIdentifier numberOfApduRetries = new PropertyIdentifier(73); public static final PropertyIdentifier numberOfStates = new PropertyIdentifier(74); public static final PropertyIdentifier objectIdentifier = new PropertyIdentifier(75); public static final PropertyIdentifier objectList = new PropertyIdentifier(76); public static final PropertyIdentifier objectName = new PropertyIdentifier(77); public static final PropertyIdentifier objectPropertyReference = new PropertyIdentifier(78); public static final PropertyIdentifier objectType = new PropertyIdentifier(79); public static final PropertyIdentifier optional = new PropertyIdentifier(80); public static final PropertyIdentifier outOfService = new PropertyIdentifier(81); public static final PropertyIdentifier outputUnits = new PropertyIdentifier(82); public static final PropertyIdentifier eventParameters = new PropertyIdentifier(83); public static final PropertyIdentifier polarity = new PropertyIdentifier(84); public static final PropertyIdentifier presentValue = new PropertyIdentifier(85); public static final PropertyIdentifier priority = new PropertyIdentifier(86); public static final PropertyIdentifier priorityArray = new PropertyIdentifier(87); public static final PropertyIdentifier priorityForWriting = new PropertyIdentifier(88); public static final PropertyIdentifier processIdentifier = new PropertyIdentifier(89); public static final PropertyIdentifier programChange = new PropertyIdentifier(90); public static final PropertyIdentifier programLocation = new PropertyIdentifier(91); public static final PropertyIdentifier programState = new PropertyIdentifier(92); public static final PropertyIdentifier proportionalConstant = new PropertyIdentifier(93); public static final PropertyIdentifier proportionalConstantUnits = new PropertyIdentifier(94); public static final PropertyIdentifier protocolObjectTypesSupported = new PropertyIdentifier(96); public static final PropertyIdentifier protocolServicesSupported = new PropertyIdentifier(97); public static final PropertyIdentifier protocolVersion = new PropertyIdentifier(98); public static final PropertyIdentifier readOnly = new PropertyIdentifier(99); public static final PropertyIdentifier reasonForHalt = new PropertyIdentifier(100); public static final PropertyIdentifier recipientList = new PropertyIdentifier(102); public static final PropertyIdentifier reliability = new PropertyIdentifier(103); public static final PropertyIdentifier relinquishDefault = new PropertyIdentifier(104); public static final PropertyIdentifier required = new PropertyIdentifier(105); public static final PropertyIdentifier resolution = new PropertyIdentifier(106); public static final PropertyIdentifier segmentationSupported = new PropertyIdentifier(107); public static final PropertyIdentifier setpoint = new PropertyIdentifier(108); public static final PropertyIdentifier setpointReference = new PropertyIdentifier(109); public static final PropertyIdentifier stateText = new PropertyIdentifier(110); public static final PropertyIdentifier statusFlags = new PropertyIdentifier(111); public static final PropertyIdentifier systemStatus = new PropertyIdentifier(112); public static final PropertyIdentifier timeDelay = new PropertyIdentifier(113); public static final PropertyIdentifier timeOfActiveTimeReset = new PropertyIdentifier(114); public static final PropertyIdentifier timeOfStateCountReset = new PropertyIdentifier(115); public static final PropertyIdentifier timeSynchronizationRecipients = new PropertyIdentifier(116); public static final PropertyIdentifier units = new PropertyIdentifier(117); public static final PropertyIdentifier updateInterval = new PropertyIdentifier(118); public static final PropertyIdentifier utcOffset = new PropertyIdentifier(119); public static final PropertyIdentifier vendorIdentifier = new PropertyIdentifier(120); public static final PropertyIdentifier vendorName = new PropertyIdentifier(121); public static final PropertyIdentifier vtClassesSupported = new PropertyIdentifier(122); public static final PropertyIdentifier weeklySchedule = new PropertyIdentifier(123); public static final PropertyIdentifier attemptedSamples = new PropertyIdentifier(124); public static final PropertyIdentifier averageValue = new PropertyIdentifier(125); public static final PropertyIdentifier bufferSize = new PropertyIdentifier(126); public static final PropertyIdentifier clientCovIncrement = new PropertyIdentifier(127); public static final PropertyIdentifier covResubscriptionInterval = new PropertyIdentifier(128); public static final PropertyIdentifier eventTimeStamps = new PropertyIdentifier(130); public static final PropertyIdentifier logBuffer = new PropertyIdentifier(131); public static final PropertyIdentifier logDeviceObjectProperty = new PropertyIdentifier(132); public static final PropertyIdentifier enable = new PropertyIdentifier(133); public static final PropertyIdentifier logInterval = new PropertyIdentifier(134); public static final PropertyIdentifier maximumValue = new PropertyIdentifier(135); public static final PropertyIdentifier minimumValue = new PropertyIdentifier(136); public static final PropertyIdentifier notificationThreshold = new PropertyIdentifier(137); public static final PropertyIdentifier protocolRevision = new PropertyIdentifier(139); public static final PropertyIdentifier recordsSinceNotification = new PropertyIdentifier(140); public static final PropertyIdentifier recordCount = new PropertyIdentifier(141); public static final PropertyIdentifier startTime = new PropertyIdentifier(142); public static final PropertyIdentifier stopTime = new PropertyIdentifier(143); public static final PropertyIdentifier stopWhenFull = new PropertyIdentifier(144); public static final PropertyIdentifier totalRecordCount = new PropertyIdentifier(145); public static final PropertyIdentifier validSamples = new PropertyIdentifier(146); public static final PropertyIdentifier windowInterval = new PropertyIdentifier(147); public static final PropertyIdentifier windowSamples = new PropertyIdentifier(148); public static final PropertyIdentifier maximumValueTimestamp = new PropertyIdentifier(149); public static final PropertyIdentifier minimumValueTimestamp = new PropertyIdentifier(150); public static final PropertyIdentifier varianceValue = new PropertyIdentifier(151); public static final PropertyIdentifier activeCovSubscriptions = new PropertyIdentifier(152); public static final PropertyIdentifier backupFailureTimeout = new PropertyIdentifier(153); public static final PropertyIdentifier configurationFiles = new PropertyIdentifier(154); public static final PropertyIdentifier databaseRevision = new PropertyIdentifier(155); public static final PropertyIdentifier directReading = new PropertyIdentifier(156); public static final PropertyIdentifier lastRestoreTime = new PropertyIdentifier(157); public static final PropertyIdentifier maintenanceRequired = new PropertyIdentifier(158); public static final PropertyIdentifier memberOf = new PropertyIdentifier(159); public static final PropertyIdentifier mode = new PropertyIdentifier(160); public static final PropertyIdentifier operationExpected = new PropertyIdentifier(161); public static final PropertyIdentifier setting = new PropertyIdentifier(162); public static final PropertyIdentifier silenced = new PropertyIdentifier(163); public static final PropertyIdentifier trackingValue = new PropertyIdentifier(164); public static final PropertyIdentifier zoneMembers = new PropertyIdentifier(165); public static final PropertyIdentifier lifeSafetyAlarmValues = new PropertyIdentifier(166); public static final PropertyIdentifier maxSegmentsAccepted = new PropertyIdentifier(167); public static final PropertyIdentifier profileName = new PropertyIdentifier(168); public static final PropertyIdentifier autoSlaveDiscovery = new PropertyIdentifier(169); public static final PropertyIdentifier manualSlaveAddressBinding = new PropertyIdentifier(170); public static final PropertyIdentifier slaveAddressBinding = new PropertyIdentifier(171); public static final PropertyIdentifier slaveProxyEnable = new PropertyIdentifier(172); public static final PropertyIdentifier lastNotifyRecord = new PropertyIdentifier(173); public static final PropertyIdentifier scheduleDefault = new PropertyIdentifier(174); public static final PropertyIdentifier acceptedModes = new PropertyIdentifier(175); public static final PropertyIdentifier adjustValue = new PropertyIdentifier(176); public static final PropertyIdentifier count = new PropertyIdentifier(177); public static final PropertyIdentifier countBeforeChange = new PropertyIdentifier(178); public static final PropertyIdentifier countChangeTime = new PropertyIdentifier(179); public static final PropertyIdentifier covPeriod = new PropertyIdentifier(180); public static final PropertyIdentifier inputReference = new PropertyIdentifier(181); public static final PropertyIdentifier limitMonitoringInterval = new PropertyIdentifier(182); public static final PropertyIdentifier loggingObject = new PropertyIdentifier(183); public static final PropertyIdentifier loggingRecord = new PropertyIdentifier(184); public static final PropertyIdentifier prescale = new PropertyIdentifier(185); public static final PropertyIdentifier pulseRate = new PropertyIdentifier(186); public static final PropertyIdentifier scale = new PropertyIdentifier(187); public static final PropertyIdentifier scaleFactor = new PropertyIdentifier(188); public static final PropertyIdentifier updateTime = new PropertyIdentifier(189); public static final PropertyIdentifier valueBeforeChange = new PropertyIdentifier(190); public static final PropertyIdentifier valueSet = new PropertyIdentifier(191); public static final PropertyIdentifier valueChangeTime = new PropertyIdentifier(192); public static final PropertyIdentifier alignIntervals = new PropertyIdentifier(193); public static final PropertyIdentifier intervalOffset = new PropertyIdentifier(195); public static final PropertyIdentifier lastRestartReason = new PropertyIdentifier(196); public static final PropertyIdentifier loggingType = new PropertyIdentifier(197); public static final PropertyIdentifier restartNotificationRecipients = new PropertyIdentifier(202); public static final PropertyIdentifier timeOfDeviceRestart = new PropertyIdentifier(203); public static final PropertyIdentifier timeSynchronizationInterval = new PropertyIdentifier(204); public static final PropertyIdentifier trigger = new PropertyIdentifier(205); public static final PropertyIdentifier utcTimeSynchronizationRecipients = new PropertyIdentifier(206); public static final PropertyIdentifier nodeSubtype = new PropertyIdentifier(207); public static final PropertyIdentifier nodeType = new PropertyIdentifier(208); public static final PropertyIdentifier structuredObjectList = new PropertyIdentifier(209); public static final PropertyIdentifier subordinateAnnotations = new PropertyIdentifier(210); public static final PropertyIdentifier subordinateList = new PropertyIdentifier(211); public static final PropertyIdentifier actualShedLevel = new PropertyIdentifier(212); public static final PropertyIdentifier dutyWindow = new PropertyIdentifier(213); public static final PropertyIdentifier expectedShedLevel = new PropertyIdentifier(214); public static final PropertyIdentifier fullDutyBaseline = new PropertyIdentifier(215); public static final PropertyIdentifier requestedShedLevel = new PropertyIdentifier(218); public static final PropertyIdentifier shedDuration = new PropertyIdentifier(219); public static final PropertyIdentifier shedLevelDescriptions = new PropertyIdentifier(220); public static final PropertyIdentifier shedLevels = new PropertyIdentifier(221); public static final PropertyIdentifier stateDescription = new PropertyIdentifier(221); public static final PropertyIdentifier doorAlarmState = new PropertyIdentifier(226); public static final PropertyIdentifier doorExtendedPulseTime = new PropertyIdentifier(227); public static final PropertyIdentifier doorMembers = new PropertyIdentifier(228); public static final PropertyIdentifier doorOpenTooLongTime = new PropertyIdentifier(229); public static final PropertyIdentifier doorPulseTime = new PropertyIdentifier(230); public static final PropertyIdentifier doorStatus = new PropertyIdentifier(231); public static final PropertyIdentifier doorUnlockDelayTime = new PropertyIdentifier(232); public static final PropertyIdentifier lockStatus = new PropertyIdentifier(233); public static final PropertyIdentifier maskedAlarmValues = new PropertyIdentifier(234); public static final PropertyIdentifier securedStatus = new PropertyIdentifier(235); public static final PropertyIdentifier backupAndRestoreState = new PropertyIdentifier(338); public static final PropertyIdentifier backupPreparationTime = new PropertyIdentifier(339); public static final PropertyIdentifier restoreCompletionTime = new PropertyIdentifier(340); public static final PropertyIdentifier restorePreparationTime = new PropertyIdentifier(341); public PropertyIdentifier(int value) { super(value); } public PropertyIdentifier(ByteQueue queue) { super(queue); } @Override public String toString() { int type = intValue(); if (type == ackedTransitions.intValue()) return "Acked transitions"; if (type == ackRequired.intValue()) return "Ack required"; if (type == action.intValue()) return "Action"; if (type == actionText.intValue()) return "Action text"; if (type == activeText.intValue()) return "Active text"; if (type == activeVtSessions.intValue()) return "Active VT sessions"; if (type == alarmValue.intValue()) return "Alarm value"; if (type == alarmValues.intValue()) return "Alarm values"; if (type == all.intValue()) return "All"; if (type == allWritesSuccessful.intValue()) return "All writes successful"; if (type == apduSegmentTimeout.intValue()) return "APDU segment timeout"; if (type == apduTimeout.intValue()) return "APDU timeout"; if (type == applicationSoftwareVersion.intValue()) return "Application software version"; if (type == archive.intValue()) return "Archive"; if (type == bias.intValue()) return "Bias"; if (type == changeOfStateCount.intValue()) return "Change of state count"; if (type == changeOfStateTime.intValue()) return "Change of state time"; if (type == notificationClass.intValue()) return "Notification class"; if (type == controlledVariableReference.intValue()) return "Controlled variable reference"; if (type == controlledVariableUnits.intValue()) return "Controlled variable units"; if (type == controlledVariableValue.intValue()) return "Controlled variable value"; if (type == covIncrement.intValue()) return "COV increment"; if (type == dateList.intValue()) return "Date list"; if (type == daylightSavingsStatus.intValue()) return "Daylight savings status"; if (type == deadband.intValue()) return "Deadband"; if (type == derivativeConstant.intValue()) return "Derivative constant"; if (type == derivativeConstantUnits.intValue()) return "Derivative constant units"; if (type == description.intValue()) return "Description"; if (type == descriptionOfHalt.intValue()) return "Description of halt"; if (type == deviceAddressBinding.intValue()) return "Device address binding"; if (type == deviceType.intValue()) return "Device type"; if (type == effectivePeriod.intValue()) return "Effective period"; if (type == elapsedActiveTime.intValue()) return "Elapsed active time"; if (type == errorLimit.intValue()) return "Error limit"; if (type == eventEnable.intValue()) return "Event enable"; if (type == eventState.intValue()) return "Event state"; if (type == eventType.intValue()) return "Event type"; if (type == exceptionSchedule.intValue()) return "Exception schedule"; if (type == faultValues.intValue()) return "Fault values"; if (type == feedbackValue.intValue()) return "Feedback value"; if (type == fileAccessMethod.intValue()) return "File access method"; if (type == fileSize.intValue()) return "File size"; if (type == fileType.intValue()) return "File type"; if (type == firmwareRevision.intValue()) return "Firmware revision"; if (type == highLimit.intValue()) return "High limit"; if (type == inactiveText.intValue()) return "Inactive text"; if (type == inProcess.intValue()) return "In process"; if (type == instanceOf.intValue()) return "Instance of"; if (type == integralConstant.intValue()) return "Integral constant"; if (type == integralConstantUnits.intValue()) return "Integral constant units"; if (type == limitEnable.intValue()) return "Limit enable"; if (type == listOfGroupMembers.intValue()) return "List of group members"; if (type == listOfObjectPropertyReferences.intValue()) return "List of object property references"; if (type == listOfSessionKeys.intValue()) return "List of session keys"; if (type == localDate.intValue()) return "Local date"; if (type == localTime.intValue()) return "Local time"; if (type == location.intValue()) return "Location"; if (type == lowLimit.intValue()) return "Low limit"; if (type == manipulatedVariableReference.intValue()) return "Manipulated variable reference"; if (type == maximumOutput.intValue()) return "Maximum output"; if (type == maxApduLengthAccepted.intValue()) return "Max APDU length accepted"; if (type == maxInfoFrames.intValue()) return "Max info frames"; if (type == maxMaster.intValue()) return "Max master"; if (type == maxPresValue.intValue()) return "Max pres value"; if (type == minimumOffTime.intValue()) return "Minimum off time"; if (type == minimumOnTime.intValue()) return "Minimum on time"; if (type == minimumOutput.intValue()) return "Minimum output"; if (type == minPresValue.intValue()) return "Min pres value"; if (type == modelName.intValue()) return "Model name"; if (type == modificationDate.intValue()) return "Modification date"; if (type == notifyType.intValue()) return "Notify type"; if (type == numberOfApduRetries.intValue()) return "Number of APDU retries"; if (type == numberOfStates.intValue()) return "Number of states"; if (type == objectIdentifier.intValue()) return "Object identifier"; if (type == objectList.intValue()) return "Object list"; if (type == objectName.intValue()) return "Object name"; if (type == objectPropertyReference.intValue()) return "Object property reference"; if (type == objectType.intValue()) return "Object type"; if (type == optional.intValue()) return "Optional"; if (type == outOfService.intValue()) return "Out of service"; if (type == outputUnits.intValue()) return "Output units"; if (type == eventParameters.intValue()) return "Event parameters"; if (type == polarity.intValue()) return "Polarity"; if (type == presentValue.intValue()) return "Present value"; if (type == priority.intValue()) return "Priority"; if (type == priorityArray.intValue()) return "Priority array"; if (type == priorityForWriting.intValue()) return "Priority for writing"; if (type == processIdentifier.intValue()) return "Process identifier"; if (type == programChange.intValue()) return "Program change"; if (type == programLocation.intValue()) return "Program location"; if (type == programState.intValue()) return "Program state"; if (type == proportionalConstant.intValue()) return "Proportional constant"; if (type == proportionalConstantUnits.intValue()) return "Proportional constant units"; if (type == protocolObjectTypesSupported.intValue()) return "Protocol object types supported"; if (type == protocolServicesSupported.intValue()) return "Protocol services supported"; if (type == protocolVersion.intValue()) return "Protocol version"; if (type == readOnly.intValue()) return "Read only"; if (type == reasonForHalt.intValue()) return "Reason for halt"; if (type == recipientList.intValue()) return "Recipient list"; if (type == reliability.intValue()) return "Reliability"; if (type == relinquishDefault.intValue()) return "Relinquish default"; if (type == required.intValue()) return "Required"; if (type == resolution.intValue()) return "Resolution"; if (type == segmentationSupported.intValue()) return "Segmentation supported"; if (type == setpoint.intValue()) return "Setpoint"; if (type == setpointReference.intValue()) return "Setpoint reference"; if (type == stateText.intValue()) return "State text"; if (type == statusFlags.intValue()) return "Status flags"; if (type == systemStatus.intValue()) return "System status"; if (type == timeDelay.intValue()) return "Time delay"; if (type == timeOfActiveTimeReset.intValue()) return "Time of active time reset"; if (type == timeOfStateCountReset.intValue()) return "Time of state count reset"; if (type == timeSynchronizationRecipients.intValue()) return "Time synchronization recipients"; if (type == units.intValue()) return "Units"; if (type == updateInterval.intValue()) return "Update interval"; if (type == utcOffset.intValue()) return "UTC offset"; if (type == vendorIdentifier.intValue()) return "Vendor identifier"; if (type == vendorName.intValue()) return "Vendor name"; if (type == vtClassesSupported.intValue()) return "VT classes supported"; if (type == weeklySchedule.intValue()) return "Weekly schedule"; if (type == attemptedSamples.intValue()) return "Attempted samples"; if (type == averageValue.intValue()) return "Average value"; if (type == bufferSize.intValue()) return "Buffer size"; if (type == clientCovIncrement.intValue()) return "Client COV increment"; if (type == covResubscriptionInterval.intValue()) return "COV resubscription interval"; if (type == eventTimeStamps.intValue()) return "Event time stamps"; if (type == logBuffer.intValue()) return "Log buffer"; if (type == logDeviceObjectProperty.intValue()) return "Log device object property"; if (type == enable.intValue()) return "enable"; if (type == logInterval.intValue()) return "Log interval"; if (type == maximumValue.intValue()) return "Maximum value"; if (type == minimumValue.intValue()) return "Minimum value"; if (type == notificationThreshold.intValue()) return "Notification threshold"; if (type == protocolRevision.intValue()) return "Protocol revision"; if (type == recordsSinceNotification.intValue()) return "Records since notification"; if (type == recordCount.intValue()) return "Record count"; if (type == startTime.intValue()) return "Start time"; if (type == stopTime.intValue()) return "Stop time"; if (type == stopWhenFull.intValue()) return "Stop when full"; if (type == totalRecordCount.intValue()) return "Total record count"; if (type == validSamples.intValue()) return "Valid samples"; if (type == windowInterval.intValue()) return "Window interval"; if (type == windowSamples.intValue()) return "Window samples"; if (type == maximumValueTimestamp.intValue()) return "Maximum value timestamp"; if (type == minimumValueTimestamp.intValue()) return "Minimum value timestamp"; if (type == varianceValue.intValue()) return "Variance value"; if (type == activeCovSubscriptions.intValue()) return "Active COV subscriptions"; if (type == backupFailureTimeout.intValue()) return "Backup failure timeout"; if (type == configurationFiles.intValue()) return "Configuration files"; if (type == databaseRevision.intValue()) return "Database revision"; if (type == directReading.intValue()) return "Direct reading"; if (type == lastRestoreTime.intValue()) return "Last restore time"; if (type == maintenanceRequired.intValue()) return "Maintenance required"; if (type == memberOf.intValue()) return "Member of"; if (type == mode.intValue()) return "Mode"; if (type == operationExpected.intValue()) return "Operation expected"; if (type == setting.intValue()) return "Setting"; if (type == silenced.intValue()) return "Silenced"; if (type == trackingValue.intValue()) return "Tracking value"; if (type == zoneMembers.intValue()) return "Zone members"; if (type == lifeSafetyAlarmValues.intValue()) return "Life safety alarm values"; if (type == maxSegmentsAccepted.intValue()) return "Max segments accepted"; if (type == profileName.intValue()) return "Profile name"; if (type == autoSlaveDiscovery.intValue()) return "Auto slave discovery"; if (type == manualSlaveAddressBinding.intValue()) return "Manual slave address binding"; if (type == slaveAddressBinding.intValue()) return "Slave address binding"; if (type == slaveProxyEnable.intValue()) return "Slave proxy enable"; if (type == lastNotifyRecord.intValue()) return "Last notify record"; if (type == scheduleDefault.intValue()) return "Schedule default"; if (type == acceptedModes.intValue()) return "Accepted modes"; if (type == adjustValue.intValue()) return "Adjust value"; if (type == count.intValue()) return "Count"; if (type == countBeforeChange.intValue()) return "Count before change"; if (type == countChangeTime.intValue()) return "Count change time"; if (type == covPeriod.intValue()) return "COV period"; if (type == inputReference.intValue()) return "Input reference"; if (type == limitMonitoringInterval.intValue()) return "Limit monitoring interval"; if (type == loggingObject.intValue()) return "Logging object"; if (type == loggingRecord.intValue()) return "Logging record"; if (type == prescale.intValue()) return "Prescale"; if (type == pulseRate.intValue()) return "Pulse rate"; if (type == scale.intValue()) return "Scale"; if (type == scaleFactor.intValue()) return "Scale factor"; if (type == updateTime.intValue()) return "Update time"; if (type == valueBeforeChange.intValue()) return "Value before change"; if (type == valueSet.intValue()) return "Value set"; if (type == valueChangeTime.intValue()) return "Value change time"; if (type == alignIntervals.intValue()) return "Align Intervals"; if (type == intervalOffset.intValue()) return "Interval Offset"; if (type == lastRestartReason.intValue()) return "Last Restart Reason"; if (type == loggingType.intValue()) return "Logging Type"; if (type == restartNotificationRecipients.intValue()) return "Restart Notification Recipients"; if (type == timeOfDeviceRestart.intValue()) return "Time Of Device Restart"; if (type == timeSynchronizationInterval.intValue()) return "Time Synchronization Interval"; if (type == trigger.intValue()) return "Trigger"; if (type == utcTimeSynchronizationRecipients.intValue()) return "UTC Time Synchronization Recipients"; if (type == nodeSubtype.intValue()) return "Node Subtype"; if (type == nodeType.intValue()) return "Node Type"; if (type == structuredObjectList.intValue()) return "Structured Object List"; if (type == subordinateAnnotations.intValue()) return "Subordinate Annotations"; if (type == subordinateList.intValue()) return "Subordinate List"; if (type == actualShedLevel.intValue()) return "Actual Shed Level"; if (type == dutyWindow.intValue()) return "Duty Window"; if (type == expectedShedLevel.intValue()) return "Expected Shed Level"; if (type == fullDutyBaseline.intValue()) return "Full Duty Baseline"; if (type == requestedShedLevel.intValue()) return "Requested Shed Level"; if (type == shedDuration.intValue()) return "Shed Duration"; if (type == shedLevelDescriptions.intValue()) return "Shed Level Descriptions"; if (type == shedLevels.intValue()) return "Shed Levels"; if (type == stateDescription.intValue()) return "State Description"; if (type == doorAlarmState.intValue()) return "Door Alarm State"; if (type == doorExtendedPulseTime.intValue()) return "Door Extended Pulse Time"; if (type == doorMembers.intValue()) return "Door Members"; if (type == doorOpenTooLongTime.intValue()) return "Door Open Too Long Time"; if (type == doorPulseTime.intValue()) return "Door Pulse Time"; if (type == doorStatus.intValue()) return "Door Status"; if (type == doorUnlockDelayTime.intValue()) return "Door Unlock Delay Time"; if (type == lockStatus.intValue()) return "Lock Status"; if (type == maskedAlarmValues.intValue()) return "Masked Alarm Values"; if (type == securedStatus.intValue()) return "Secured Status"; if (type == backupAndRestoreState.intValue()) return "Backup And Restore State"; if (type == backupPreparationTime.intValue()) return "Backup Preparation Time"; if (type == restoreCompletionTime.intValue()) return "Restore Completion Time"; if (type == restorePreparationTime.intValue()) return "Restore Preparation Time"; return "Unknown: " + type; } }
GTBitsOfGood/hope-sustains-life
src/actions/Subscriber.js
import urls from "../../utils/urls"; import appRequest from "../../utils/requests"; export const getSubscribers = async () => { return await appRequest({ url: urls.baseUrl + urls.api.subscribers, method: "GET", isSecure: true, }); }; export const addSubscriber = async (email) => { return await appRequest({ url: urls.baseUrl + urls.api.subscribers, method: "POST", body: { email, }, isSecure: false, }); }; export const deleteSubscriber = async (id) => { return await appRequest({ url: urls.baseUrl + urls.api.subscribers + `/${id}`, method: "DELETE", isSecure: true, }); };
sgholamian/log-aware-clone-detection
LACCPlus/Camel/2589_1.java
<filename>LACCPlus/Camel/2589_1.java //,temp,IAM2Producer.java,556,594,temp,SecretsManagerProducer.java,337,372 //,3 public class xxx { private void removeUserFromGroup(IamClient iamClient, Exchange exchange) throws InvalidPayloadException { if (getConfiguration().isPojoRequest()) { Object payload = exchange.getIn().getMandatoryBody(); if (payload instanceof RemoveUserFromGroupRequest) { RemoveUserFromGroupResponse result; try { result = iamClient.removeUserFromGroup((RemoveUserFromGroupRequest) payload); } catch (AwsServiceException ase) { LOG.trace("Remove User From Group command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; } Message message = getMessageForResponse(exchange); message.setBody(result); } } else { RemoveUserFromGroupRequest.Builder builder = RemoveUserFromGroupRequest.builder(); if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(IAM2Constants.GROUP_NAME))) { String groupName = exchange.getIn().getHeader(IAM2Constants.GROUP_NAME, String.class); builder.groupName(groupName); } else { throw new IllegalArgumentException("Group Name must be specified"); } if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(IAM2Constants.USERNAME))) { String userName = exchange.getIn().getHeader(IAM2Constants.USERNAME, String.class); builder.userName(userName); } else { throw new IllegalArgumentException("User Name must be specified"); } RemoveUserFromGroupResponse result; try { result = iamClient.removeUserFromGroup(builder.build()); } catch (AwsServiceException ase) { LOG.trace("Remove User From Group command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; } Message message = getMessageForResponse(exchange); message.setBody(result); } } };
AlexLanzano/SeamOS
libraries/queue.c
<filename>libraries/queue.c<gh_stars>1-10 #include <stdint.h> #include <stdbool.h> #include <config.h> #include <libraries/queue.h> #include <libraries/error.h> #include <libraries/string.h> #ifndef CONFIG_QUEUE_COUNT #define CONFIG_QUEUE_COUNT 1 #endif typedef struct queue { bool is_initialized; uint32_t capacity; uint32_t length; uint32_t item_size; void *buffer_start; void *buffer_end; uint8_t *head; uint8_t *tail; } queue_t; queue_t g_queues[CONFIG_QUEUE_COUNT] = {0}; static error_t queue_find_free_queue(queue_handle_t *handle) { if (!handle) { return ERROR_INVALID; } queue_handle_t queue_handle; for (queue_handle = 0; queue_handle < CONFIG_QUEUE_COUNT; queue_handle++) { if (!g_queues[queue_handle].is_initialized) { *handle = queue_handle; return SUCCESS; } } return ERROR_NO_MEMORY; } static error_t queue_invalid_handle(queue_handle_t handle) { return (handle >= CONFIG_QUEUE_COUNT || !g_queues[handle].is_initialized); } error_t queue_init(uint32_t queue_capacity, uint32_t queue_item_size, void *queue_buffer, queue_handle_t *handle) { error_t error; error = queue_find_free_queue(handle); if (error) { return error; } queue_t *queue = &g_queues[*handle]; queue->is_initialized = true; queue->capacity = queue_capacity; queue->length = 0; queue->item_size = queue_item_size; queue->buffer_start = queue_buffer; queue->buffer_end = queue_buffer + ((queue_capacity - 1) * queue_item_size); queue->head = queue->buffer_end; queue->tail = queue->buffer_start; return SUCCESS; } error_t queue_deinit(queue_handle_t handle) { if (queue_invalid_handle(handle)) { return ERROR_INVALID; } g_queues[handle].is_initialized = false; return SUCCESS; } error_t queue_push(queue_handle_t handle, void *item) { if (queue_invalid_handle(handle) || !item) { return ERROR_INVALID; } queue_t *queue = &g_queues[handle]; if (queue->length >= queue->capacity) { return ERROR_NO_MEMORY; } if (queue->tail > (uint8_t *)queue->buffer_end) { queue->tail = queue->buffer_start; } memcpy(queue->tail, item, queue->item_size); queue->tail += queue->item_size; queue->length += 1; return SUCCESS; } error_t queue_pop(queue_handle_t handle, void *item) { if (queue_invalid_handle(handle) || !item) { return ERROR_INVALID; } queue_t *queue = &g_queues[handle]; if (queue->length == 0) { return ERROR_NO_MEMORY; } queue->head += queue->item_size; if (queue->head > (uint8_t *)queue->buffer_end) { queue->head = queue->buffer_start; } memcpy(item, queue->head, queue->item_size); queue->length -= 1; return SUCCESS; } uint32_t queue_length(queue_handle_t handle) { if (queue_invalid_handle(handle)) { return 0; } return g_queues[handle].length; }
Zakeshu/Brain_Academy_Java
src/com/brainacad/module_2/LabWork_2_8/Lab_Work_2_8_1.java
package com.brainacad.module_2.LabWork_2_8; /** * Created by a.zemlyanskiy on 05.09.2016. * Open project MyShapes. (from 2.7 labs) * Rewrite the class “Shape” to make it abstract and change calcArea() method declaration to make it abstract too. * Execute program */ public class Lab_Work_2_8_1 { }
zachaway/cloudinsight-agent
common/log/log_test.go
package log import ( "bytes" "testing" "github.com/stretchr/testify/assert" ) func TestFileLineLogging(t *testing.T) { var buf bytes.Buffer SetOutput(&buf) // The default logging level should be "info". Debug("This debug-level line should not show up in the output.") Infof("This %s-level line should show up in the output.", "info") re := `^time=".*" level=info msg="This info-level line should show up in the output." source="log_test.go:16" \n$` assert.Regexp(t, re, buf.String()) } func TestSetLevel(t *testing.T) { var buf bytes.Buffer for _, c := range []struct { in string want error count int re string }{ {"error", nil, 1, `^time=".*" level=error msg="This error-level line should show up in the output." source=".*" $`}, {"warn", nil, 2, `^time=".*" level=warning msg="This warn-level line should show up in the output." source=".*" $`}, {"info", nil, 3, `^time=".*" level=info msg="This info-level line should show up in the output." source=".*" $`}, {"debug", nil, 4, `^time=".*" level=debug msg="This debug-level line should show up in the output." source=".*" $`}, } { SetOutput(&buf) out := SetLevel(c.in) if out != c.want { t.Fatalf("SetLevel(%q) == %q, want %q", c.in, out, c.want) } for _, logger := range []logFunc{logging, loggingWithFormat, loggingWithNewLine} { logger() lineSep := []byte{'\n'} lines := bytes.Split(buf.Bytes(), lineSep) length := len(lines) - 1 assert.Equal(t, length, c.count) assert.Regexp(t, c.re, string(lines[length-1])) buf.Reset() } } } type logFunc func() func logging() { Error("This error-level line should show up in the output.") Warn("This warn-level line should show up in the output.") Info("This info-level line should show up in the output.") Debug("This debug-level line should show up in the output.") } func loggingWithFormat() { Errorf("This %s-level line should show up in the output.", "error") Warnf("This %s-level line should show up in the output.", "warn") Infof("This %s-level line should show up in the output.", "info") Debugf("This %s-level line should show up in the output.", "debug") } func loggingWithNewLine() { Errorln("This error-level line should show up in the output.") Warnln("This warn-level line should show up in the output.") Infoln("This info-level line should show up in the output.") Debugln("This debug-level line should show up in the output.") }
codingyen/CodeAlone
Python/0253_meeting_room_ii.py
<gh_stars>1-10 """ Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei) find the minimum number of conference rooms required Time: O(nlogn) because of the sort Space: O(n) space to store the start and end times """ class Interval(object): def __init__(self, s = 0, e = 0): self.start = s self.end = e class Solution(object): def minMeetingRooms(self, intervals): """ :type intervals: List[Interval] :rtype: int """ starts = [] ends = [] for i in intervals: starts.append(i.start) ends.append(i.end) starts.sort() ends.sort() # Create two pointers to indicate the specific start and end s, e = 0, 0 minRoom, usedRoom = 0, 0 while s < len(starts): if starts[s] < ends[e]: usedRoom += 1 minRoom = max(minRoom, usedRoom) s += 1 else: usedRoom -= 1 e += 1 return minRoom if __name__ == "__main__": print("Start the test!") first = [Interval() for _ in range(3)] first[0].start = 0 first[0].end = 30 first[1].start = 5 first[1].end = 10 first[2].start = 15 first[2].end = 20 second = [Interval() for _ in range(2)] second[0].start = 7 second[0].end = 10 second[1].start = 2 second[1].end = 4 s = Solution() print(s.minMeetingRooms(first)) print(s.minMeetingRooms(second))
codegraph-team/codegraph-index
codegraph-java/src/main/java/co/degraph/index/java/internal/javaparser/MethodsCollector.java
<gh_stars>0 package co.degraph.index.java.internal.javaparser; import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; import com.github.javaparser.ast.body.EnumDeclaration; import com.github.javaparser.ast.body.MethodDeclaration; import com.github.javaparser.ast.body.TypeDeclaration; import com.github.javaparser.ast.visitor.VoidVisitorAdapter; import java.util.ArrayList; import java.util.List; public class MethodsCollector { public List<MethodDeclaration> collect(TypeDeclaration typeDeclaration) { List<MethodDeclaration> methodDeclarations = new ArrayList<>(); VoidVisitorAdapter visitor = new VoidVisitorAdapter<List<MethodDeclaration>>() { @Override public void visit(MethodDeclaration n, List<MethodDeclaration> arg) { arg.add(n); } }; if (typeDeclaration instanceof ClassOrInterfaceDeclaration) { visitor.visit((ClassOrInterfaceDeclaration) typeDeclaration, methodDeclarations); } if (typeDeclaration instanceof EnumDeclaration) { visitor.visit((EnumDeclaration) typeDeclaration, methodDeclarations); } return methodDeclarations; } }
AaronFriel/pulumi-aws-native
sdk/go/aws/gamelift/build.go
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** package gamelift import ( "context" "reflect" "github.com/pulumi/pulumi/sdk/v3/go/pulumi" ) // Resource Type definition for AWS::GameLift::Build // // Deprecated: Build is not yet supported by AWS Native, so its creation will currently fail. Please use the classic AWS provider, if possible. type Build struct { pulumi.CustomResourceState Name pulumi.StringPtrOutput `pulumi:"name"` OperatingSystem pulumi.StringPtrOutput `pulumi:"operatingSystem"` StorageLocation BuildS3LocationPtrOutput `pulumi:"storageLocation"` Version pulumi.StringPtrOutput `pulumi:"version"` } // NewBuild registers a new resource with the given unique name, arguments, and options. func NewBuild(ctx *pulumi.Context, name string, args *BuildArgs, opts ...pulumi.ResourceOption) (*Build, error) { if args == nil { args = &BuildArgs{} } var resource Build err := ctx.RegisterResource("aws-native:gamelift:Build", name, args, &resource, opts...) if err != nil { return nil, err } return &resource, nil } // GetBuild gets an existing Build resource's state with the given name, ID, and optional // state properties that are used to uniquely qualify the lookup (nil if not required). func GetBuild(ctx *pulumi.Context, name string, id pulumi.IDInput, state *BuildState, opts ...pulumi.ResourceOption) (*Build, error) { var resource Build err := ctx.ReadResource("aws-native:gamelift:Build", name, id, state, &resource, opts...) if err != nil { return nil, err } return &resource, nil } // Input properties used for looking up and filtering Build resources. type buildState struct { } type BuildState struct { } func (BuildState) ElementType() reflect.Type { return reflect.TypeOf((*buildState)(nil)).Elem() } type buildArgs struct { Name *string `pulumi:"name"` OperatingSystem *string `pulumi:"operatingSystem"` StorageLocation *BuildS3Location `pulumi:"storageLocation"` Version *string `pulumi:"version"` } // The set of arguments for constructing a Build resource. type BuildArgs struct { Name pulumi.StringPtrInput OperatingSystem pulumi.StringPtrInput StorageLocation BuildS3LocationPtrInput Version pulumi.StringPtrInput } func (BuildArgs) ElementType() reflect.Type { return reflect.TypeOf((*buildArgs)(nil)).Elem() } type BuildInput interface { pulumi.Input ToBuildOutput() BuildOutput ToBuildOutputWithContext(ctx context.Context) BuildOutput } func (*Build) ElementType() reflect.Type { return reflect.TypeOf((*Build)(nil)) } func (i *Build) ToBuildOutput() BuildOutput { return i.ToBuildOutputWithContext(context.Background()) } func (i *Build) ToBuildOutputWithContext(ctx context.Context) BuildOutput { return pulumi.ToOutputWithContext(ctx, i).(BuildOutput) } type BuildOutput struct{ *pulumi.OutputState } func (BuildOutput) ElementType() reflect.Type { return reflect.TypeOf((*Build)(nil)) } func (o BuildOutput) ToBuildOutput() BuildOutput { return o } func (o BuildOutput) ToBuildOutputWithContext(ctx context.Context) BuildOutput { return o } func init() { pulumi.RegisterInputType(reflect.TypeOf((*BuildInput)(nil)).Elem(), &Build{}) pulumi.RegisterOutputType(BuildOutput{}) }
Skight/wndspy
Source/HsCommon/UxThemeFuncs.h
<filename>Source/HsCommon/UxThemeFuncs.h #if _MSC_VER > 1000 #pragma once #endif #ifndef HS_INC_HEADER_UXTHEMEFUNCS #define HS_INC_HEADER_UXTHEMEFUNCS ////////////////////////////////////////////////////////////////////////// #ifndef _UXTHEME_H_ #define ETDT_DISABLE 0x00000001 #define ETDT_ENABLE 0x00000002 #define ETDT_USETABTEXTURE 0x00000004 #define ETDT_ENABLETAB (ETDT_ENABLE | ETDT_USETABTEXTURE) #ifndef THEMEAPI #if !defined(_UXTHEME_) #define THEMEAPI EXTERN_C DECLSPEC_IMPORT HRESULT STDAPICALLTYPE #define THEMEAPI_(type) EXTERN_C DECLSPEC_IMPORT type STDAPICALLTYPE #else #define THEMEAPI STDAPI #define THEMEAPI_(type) STDAPI_(type) #endif #endif typedef HANDLE HTHEME; typedef enum THEMESIZE { TS_MIN, // minimum size TS_TRUE, // size without stretching TS_DRAW, // size that theme mgr will use to draw part }; #endif //end if not def_UXTHEME_H_ ////////////////////////////////////////////////////////////////////////// // #define _HS_GETTHEMEPARTSIZE ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// #define InitUxThemeLibrary(_h_uxtheme_dll) _h_uxtheme_dll=LoadLibrary(TEXT("UXTHEME.DLL")) ////////////////////////////////////////////////////////////////////////// #define UnInitUxThemeLibrary(_h_uxtheme_dll) DoFreeLibrary(_h_uxtheme_dll) ////////////////////////////////////////////////////////////////////////// //Macro: OnInit_EnableThemeDialogTexture(1)... #define OnInit_EnableThemeDialogTexture(_h_uxtheme_dll) \ hslib_lpfEnableThemeDialogTexture = \ (HSLIB_LPENABLETHEMEDIALOGTEXTURE) \ GetProcAddress(_h_uxtheme_dll, "EnableThemeDialogTexture") //MacroEnd: OnInit_EnableThemeDialogTexture(1)... #ifdef EnableThemeDialogTexture #undef EnableThemeDialogTexture #endif //Macro: EnableThemeDialogTexture(1, 2)... #define EnableThemeDialogTexture(_hwnd, _dwFlag) \ if(hslib_lpfEnableThemeDialogTexture) \ hslib_lpfEnableThemeDialogTexture(_hwnd, _dwFlag) //MacroEnd: EnableThemeDialogTexture(1, 2)... ////////////////////////////////////////////////////////////////////////// #define _HS_SBP_SIZEBOX 10 #define _HS_SZB_RIGHTALIGN 1 #define _HS_GRIP_SIZE 17 //Macro: IsThemeFuncsLoaded(1,2,3, [#ifdef _HS_GETTHEMEPARTSIZE: 4])... #ifdef _HS_GETTHEMEPARTSIZE #define IsThemeFuncsLoaded \ (hslib_lpfOpenThemeData && \ hslib_lpfCloseThemeData && \ hslib_lpfGetThemePartSize && \ hslib_lpfDrawThemeBackground) #else #define IsThemeFuncsLoaded \ (hslib_lpfOpenThemeData && \ hslib_lpfCloseThemeData && \ hslib_lpfDrawThemeBackground) #endif //MacroEnd: IsThemeFuncsLoaded()... ////////////////////////////////////////////////////////////////////////// typedef HTHEME (WINAPI *HSLIB_LPFOPENTHEMEDATA)(HWND, LPCWSTR); typedef HRESULT (WINAPI *HSLIB_LPFCLOSETHEMEDATA)(HTHEME); typedef HRESULT (WINAPI *HSLIB_LPFDRAWTHEMEBACKGROUND)(HTHEME, HDC, int, int, LPCRECT, LPCRECT); #ifdef _HS_GETTHEMEPARTSIZE typedef HRESULT (WINAPI *HSLIB_LPFGETTHEMEPARTSIZE) (HTHEME, HDC, int, int, LPCRECT, THEMESIZE, LPSIZE); #endif typedef BOOL (WINAPI *HSLIB_LPENABLETHEMEDIALOGTEXTURE)(HWND, DWORD); ////////////////////////////////////////////////////////////////////////// #ifdef _HS_GETTHEMEPARTSIZE extern HSLIB_LPFGETTHEMEPARTSIZE hslib_lpfGetThemePartSize; #endif extern HSLIB_LPFOPENTHEMEDATA hslib_lpfOpenThemeData; extern HSLIB_LPFCLOSETHEMEDATA hslib_lpfCloseThemeData; extern HSLIB_LPFDRAWTHEMEBACKGROUND hslib_lpfDrawThemeBackground; extern HSLIB_LPENABLETHEMEDIALOGTEXTURE hslib_lpfEnableThemeDialogTexture; ////////////////////////////////////////////////////////////////////////// #define OnInit_OnDrawWindowSizeGripBox(_h_uxtheme_dll) \ OnInit_UxThemeBaseDrawFuncs(_h_uxtheme_dll) //OnInit_OnDrawWindowSizeGripBox()... #define OnInit_ThemeBaseDrawFuncs(_h_uxtheme_dll) \ OnInit_UxThemeBaseDrawFuncs(_h_uxtheme_dll) //OnInit_ThemeBaseDrawFuncs()... BOOL OnInit_UxThemeBaseDrawFuncs(HINSTANCE h_uxtheme_dll); VOID DrawSizeGripBox_OnPaint(HWND hwnd, HDC hdc); VOID DrawSizeGripBox_OnSizing(HWND hwnd); ////////////////////////////////////////////////////////////////////////// #endif //HS_INC_HEADER_UXTHEMEFUNCS
greglever/opencga
opencga-client/src/main/java/org/opencb/opencga/client/rest/analysis/AlignmentClient.java
/* * Copyright 2015-2017 OpenCB * * 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.opencb.opencga.client.rest.analysis; import org.ga4gh.models.ReadAlignment; import org.opencb.biodata.models.alignment.RegionCoverage; import org.opencb.biodata.tools.alignment.stats.AlignmentGlobalStats; import org.opencb.commons.datastore.core.ObjectMap; import org.opencb.commons.datastore.core.QueryResponse; import org.opencb.opencga.client.config.ClientConfiguration; import org.opencb.opencga.client.rest.AbstractParentClient; import org.opencb.opencga.core.models.Job; import java.io.IOException; /** * Created by pfurio on 11/11/16. */ public class AlignmentClient extends AbstractParentClient { private static final String ALIGNMENT_URL = "analysis/alignment"; public AlignmentClient(String userId, String sessionId, ClientConfiguration configuration) { super(userId, sessionId, configuration); } public QueryResponse<Job> index(String fileIds, ObjectMap params) throws IOException { if (params == null) { params = new ObjectMap(); } params.putIfNotEmpty("file", fileIds); return execute(ALIGNMENT_URL, "index", params, GET, Job.class); } public QueryResponse<ReadAlignment> query(String fileIds, ObjectMap params) throws IOException { if (params == null) { params = new ObjectMap(); } params.putIfNotEmpty("file", fileIds); return execute(ALIGNMENT_URL, "query", params, GET, ReadAlignment.class); } public QueryResponse<AlignmentGlobalStats> stats(String fileIds, ObjectMap params) throws IOException { if (params == null) { params = new ObjectMap(); } params.putIfNotEmpty("file", fileIds); return execute(ALIGNMENT_URL, "stats", params, GET, AlignmentGlobalStats.class); } public QueryResponse<RegionCoverage> coverage(String fileIds, ObjectMap params) throws IOException { if (params == null) { params = new ObjectMap(); } params.putIfNotEmpty("file", fileIds); return execute(ALIGNMENT_URL, "coverage", params, GET, RegionCoverage.class); } }
zaypen/intellij-community
java/java-tests/testData/inspection/dataFlow/fixture/SwitchEnumConstant.java
import org.jetbrains.annotations.*; class InspectionTest { enum Type { PUBLIC, PRIVATE } @Nullable public static String foo(Type type) { Object obj = null; if (type == Type.PUBLIC) { obj = new Object(); } switch (type) { case PUBLIC: return test(obj); case PRIVATE: default: return null; } } public static String test(@NotNull Object a) { return a.toString(); } enum X {A, B, C} void testTernary(@Nullable String foo, X x) { switch (foo == null ? X.A : x) { case A: System.out.println(foo.<warning descr="Method invocation 'trim' may produce 'java.lang.NullPointerException'">trim</warning>()); break; case B: System.out.println(foo.trim()); break; case C: System.out.println(foo.trim()); break; } } }
AlexRogalskiy/DevArtifacts
master/projects-java/projects/chapter04/music-organizer-v5/TrackReader.java
<gh_stars>1-10 import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.stream.Collectors; /** * A helper class for our music application. This class can read files from the file system * from a given folder with a specified suffix. It will interpret the file name as artist/ * track title information. * * It is expected that file names of music tracks follow a standard format of artist name * and track name, separated by a dash. For example: TheBeatles-HereComesTheSun.mp3 * * @author <NAME> and <NAME> * @version 2016.02.29 */ public class TrackReader { /** * Create the track reader, ready to read tracks from the music library folder. */ public TrackReader() { // Nothing to do here. } /** * Read music files from the given library folder * with the given suffix. * @param folder The folder to look for files. * @param suffix The suffix of the audio type. */ public ArrayList<Track> readTracks(String folder, String suffix) { File audioFolder = new File(folder); File[] audioFiles = audioFolder.listFiles((dir, name) -> name.toLowerCase().endsWith(suffix)); // Put all the matching files into the organizer. ArrayList<Track> tracks = Arrays.stream(audioFiles). map(file -> decodeDetails(file)). collect(Collectors.toCollection(ArrayList::new)); return tracks; } /** * Try to decode details of the artist and the title * from the file name. * It is assumed that the details are in the form: * artist-title.mp3 * @param file The track file. * @return A Track containing the details. */ private Track decodeDetails(File file) { // The information needed. String artist = "unknown"; String title = "unknown"; String filename = file.getPath(); // Look for artist and title in the name of the file. String details = file.getName(); String[] parts = details.split("-"); if(parts.length == 2) { artist = parts[0]; String titlePart = parts[1]; // Remove a file-type suffix. parts = titlePart.split("\\."); if(parts.length >= 1) { title = parts[0]; } else { title = titlePart; } } return new Track(artist, title, filename); } }
Web-Dev-Collaborative/DS-ALGO-OFFICIAL
CONTENT/DS-n-Algos/Fifo-Lifo/STACK_S/stack_queue_interview_problems/test/1_balanced_parens_spec.js
<gh_stars>10-100 const { balancedParens } = require("../lib/1_balanced_parens.js"); const { expect } = require("chai"); describe("Problem 1: balancedParens", () => { let result; it("Should exist", () => { expect(balancedParens).to.exist; }); it("Should be a function", () => { expect(balancedParens).to.be.a("function"); }); it("Should return a boolean", () => { result = balancedParens("()"); expect(result).to.exist; expect(typeof result).to.equal("boolean"); }); it("Should return true for an empty string", () => { result = balancedParens(""); expect(result).to.equal(true); }); describe("When the input string contains only parentheses...", () => { it('Should return false for single character open-bracket strings, like: "("', () => { result = balancedParens("("); expect(result).to.equal(false); }); it('Should return false for single character closed-bracket strings, like: ")"', () => { result = balancedParens(")"); expect(result).to.equal(false); }); it('Should return true for non-nested balanced strings, like: "()"', () => { result = balancedParens("()"); expect(result).to.equal(true); }); it('Should return false for non-nested unbalanced strings, like: ")("', () => { result = balancedParens(")("); expect(result).to.equal(false); }); it('Should return true for nested balanced strings, like: "(()())"', () => { result = balancedParens("(()())"); expect(result).to.equal(true); }); it('Should return false for for nested unbalanced strings, like: "()()))"', () => { result = balancedParens("()()))"); expect(result).to.equal(false); }); it('Should return true for super-nested balanced strings, like: "(((((())))))"', () => { result = balancedParens("(((((())))))"); expect(result).to.equal(true); }); it('Should return false for super-nested un-balanced strings, like: "))))))(((((("', () => { result = balancedParens("))))))(((((("); expect(result).to.equal(false); }); }); describe("When the input string contains parentheses and text...", () => { it('Should return true for non-nested, balanced strings, like: "let x = Math.floor(5.2);"', () => { result = balancedParens("let x = Math.floor(5.2);"); expect(result).to.equal(true); }); it('Should return false for non-nested, unbalanced strings, like: "let x = Math.floor(5.2;"', () => { result = balancedParens("let x = (5 + Math.floor(5.2);"); expect(result).to.equal(false); }); it('Should return true for nested, balanced strings, like: "let x = (5 + Math.floor(5.2));"', () => { result = balancedParens("let x = (5 + Math.floor(5.2));"); expect(result).to.equal(true); }); it('Should return false for nested, unbalanced strings, like: "let x = (5 + Math.floor(5.2);"', () => { result = balancedParens("let x = (5 + Math.floor(5.2);"); expect(result).to.equal(false); }); }); describe("When the input string can contain all brackets (but not text) ...", () => { it('Should return false for single character, open square bracket strings, like: "["', () => { result = balancedParens("["); expect(result).to.equal(false); }); it('Should return false for single character, closed sqaure bracket strings, like: "]"', () => { result = balancedParens("]"); expect(result).to.equal(false); }); it('Should return false for single character, open curly bracket strings, like: "{"', () => { result = balancedParens("{"); expect(result).to.equal(false); }); it('Should return false for single character, closed curly bracket strings, like: "}"', () => { result = balancedParens("}"); expect(result).to.equal(false); }); it('Should return true for non-nested, balanced, square bracket strings, like: "[]"', () => { result = balancedParens("[]"); expect(result).to.equal(true); }); it('Should return false for non-nested, unbalanced, square bracket strings, like: "]["', () => { result = balancedParens("]["); expect(result).to.equal(false); }); it('Should return true for non-nested, balanced, curly bracket strings, like: "{}"', () => { result = balancedParens("{}"); expect(result).to.equal(true); }); it('Should return false for non-nested, unbalanced, curly bracket strings, like: "}{"', () => { result = balancedParens("}{"); expect(result).to.equal(false); }); it('Should return true for non-nested, balanced, mixed-bracket strings, like: "()[]{}"', () => { result = balancedParens("()[]{}"); expect(result).to.equal(true); }); it('Should return false for non-nested, unbalanced, mixed-bracket strings, like: "{}][(["', () => { result = balancedParens("{}][(["); expect(result).to.equal(false); }); it('Should return true for nested, balanced, mixed-bracket strings, like: "([{}])"', () => { result = balancedParens("([{}])"); expect(result).to.equal(true); }); it('Should return false for nested, unbalanced, mixed-bracket strings, like: "([}{]})"', () => { result = balancedParens("([}{]})"); expect(result).to.equal(false); }); it('Should return true for super-nested, balanced, mixed-bracket strings, like: "((([[[{{{}}}]]])))"', () => { result = balancedParens("((([[[{{{}}}]]])))"); expect(result).to.equal(true); }); it('Should return false for super-nested, unbalanced, mixed-bracket strings, like: "((([[[{{{]]]}}})))"', () => { result = balancedParens("((([[[{{{]]]}}})))"); expect(result).to.equal(false); }); }); describe("When the input string can contain all bracket and text...", () => { it('Should return true for the string: "const roundDown = function(num) { return Math.floor(num) };"', () => { result = balancedParens( "const roundDown = function(num) { return Math.floor(num) };" ); expect(result).to.equal(true); }); it('Should return true for the string: "{ array: [1, 2, [3, 4], 5], timesTwoMethod: (num) => num * 2; }"', () => { result = balancedParens( "{ array: [1, 2, [3, 4], 5], timesTwoMethod: (num) => num * 2; }" ); expect(result).to.equal(true); }); it('Should return false for the string: "function printThirdElement(array) { console.log(array[3]]] }"', () => { result = balancedParens( "function printThirdElement(array) { console.log(array[3]]] }" ); expect(result).to.equal(false); }); }); });