repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
BetterIgor/rexxar-android
sample/src/main/java/com/douban/rexxar/example/MainApplication.java
package com.douban.rexxar.example; import android.app.Application; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import com.douban.rexxar.Rexxar; import com.douban.rexxar.resourceproxy.ResourceProxy; import com.douban.rexxar.route.RouteManager; import java.util.ArrayList; import java.util.List; import java.util.Locale; import okhttp3.OkHttpClient; /** * Created by luanqian on 15/11/2. */ public class MainApplication extends Application { static final List<String> PROXY_HOSTS = new ArrayList<>(); static { PROXY_HOSTS.add("raw.githubusercontent.com"); } @Override public void onCreate() { super.onCreate(); // 初始化rexxar Rexxar.initialize(this, true, " Rexxar/1.2.x com.douban.frodo/4.3 ", new OkHttpClient().newBuilder() .retryOnConnectionFailure(true) .addNetworkInterceptor(new AuthInterceptor()) .build(), new RouteManager.RouteConfig("https://raw.githubusercontent.com/douban/rexxar-web/master/example/dist/routes.json", getRouteCacheFileName(), true)); Rexxar.setDebug(BuildConfig.DEBUG); RouteManager.getInstance().refreshRoute(null); // 设置需要代理的资源 ResourceProxy.getInstance().addProxyHosts(PROXY_HOSTS); } public String getRouteCacheFileName() { try { PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), 0); if (null != info) { return String.format(Locale.getDefault(), "routes_%s.json", info.versionName); } } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } return "routes.json"; } }
myrepo5588/porta
test/unit/helpers/messages_helper_test.rb
require File.expand_path(File.dirname(__FILE__) + '/../../test_helper') class MessagesHelperTest < ActionView::TestCase include Buyers::AccountsHelper attr_accessor :current_account def can?(*) true end context 'message_receiver' do setup do @buyer_receiver = FactoryBot.create(:buyer_account) @provider_receiver = FactoryBot.create(:account) end should 'return link to buyer for buyer recipient' do message = FactoryBot.create(:message, :to => [@buyer_receiver]) assert_equal link_to(@buyer_receiver.org_name, admin_buyers_account_path(@buyer_receiver), :title => account_title(@buyer_receiver)), message_receiver(message) end should 'return org name for provider recipient' do message = FactoryBot.create(:message, :to => [@provider_receiver]) assert_equal @provider_receiver.org_name, message_receiver(message) end should 'return (deleted) for non existing recipient' do message = FactoryBot.create(:message, :to => [@buyer_receiver]) message.recipients.first.receiver = nil assert_equal "<span class=\"deleted\">(deleted)</span>", message_receiver(message) message.recipients = [] assert_equal "<span class=\"deleted\">(deleted)</span>", message_receiver(message) end should 'not return org names for message with multi recipients' do message = FactoryBot.create(:message, :to => [@buyer_receiver, @provider_receiver]) assert_equal "Multiple Recipients", message_receiver(message) end end context 'message_sender' do setup do @buyer_sender = FactoryBot.create(:buyer_account) @provider_sender = FactoryBot.create(:account) end should 'return link to buyer account' do message_from_buyer = FactoryBot.create(:message, :sender => @buyer_sender) assert_equal link_to(@buyer_sender.org_name, admin_buyers_account_path(@buyer_sender), :title => account_title(@buyer_sender)), message_sender(message_from_buyer) end should 'return org name of provider account' do message_from_provider = FactoryBot.create(:message, :sender => @provider_sender) assert_equal @provider_sender.org_name, message_sender(message_from_provider) end should 'return (deleted) for non existing sender' do message = FactoryBot.create(:message, :to => [@buyer_sender]) message.sender = nil assert_equal "<span class=\"deleted\">(deleted)</span>", message_sender(message) end end def test_one assert_equal %q{Some <a href="http://google.com">http://google.com</a> text}, hyperlink_urls('Some http://google.com text') end def test_text_with_incomplete_link assert_equal %q{sth sth sth <a href="http://duzadupa">http://duzadupa</a> sth sth}, hyperlink_urls('sth sth sth http://duzadupa sth sth') end def test_text_without_links assert_equal %{sth sth sth sth}, hyperlink_urls('sth sth sth sth') end def test_text_with_two_links assert_equal %{Some <a href="http://google.com">http://google.com</a> text <a href="http://3scale.net">http://3scale.net</a> text2}, hyperlink_urls('Some http://google.com text http://3scale.net text2') end def test_replace_links_with_html_escapes_html text = hyperlink_urls('<b>text</b>') assert_equal '&lt;b&gt;text&lt;/b&gt;', text assert text.html_safe? end # def test_if_removes_dots_from_end_of_links assert_equal %{Some <a href="http://google.com">http://google.com</a>. text}, hyperlink_urls('Some http://google.com. text') end def test_if_unusual_unusual_caracters_around_url_pass assert_equal %{Some <a href="http://google.com">http://google.com</a>)) text}, hyperlink_urls('Some http://google.com)) text') end def test_if_other_unusual_caracters_around_url_pass assert_equal %{Some <a href="http://google.com">http://google.com</a>]] text}, hyperlink_urls('Some http://google.com]] text') end def test_if_links_staring_with_https_are_highlighted_correctly assert_equal %{Some <a href="https://google.com">https://google.com</a> text}, hyperlink_urls('Some https://google.com text') end def test_if_links_with_colon_at_the_end_are_shown_properly_with_https_links assert_equal %{Some <a href="https://google.com">https://google.com</a>: text}, hyperlink_urls('Some https://google.com: text') end def test_if_links_with_colon_at_the_end_are_shown_properly_with_http_links assert_equal %{Some <a href="http://google.com">http://google.com</a>: text}, hyperlink_urls('Some http://google.com: text') end # this is regression test for: https://github.com/3scale/system/issues/4819 def test_if_random_word_with_colon_at_the_end_is_not_treated_like_link assert_equal %{Some random word:}, %{Some random word:} end end
antopen/alipay-sdk-java-all
src/main/java/com/alipay/api/domain/AlipayUserJobcardApplySyncModel.java
package com.alipay.api.domain; import java.util.Date; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; /** * 小蓝卡用户岗位申请状态同步 * * @author <NAME> * @since 1.0, 2022-01-26 17:32:25 */ public class AlipayUserJobcardApplySyncModel extends AlipayObject { private static final long serialVersionUID = 2139184329433424272L; /** * 待同步状态的申请状态 */ @ApiField("apply_status") private String applyStatus; /** * 状态发生变更时的业务时间,如apply_status=APPLYING时,biz_time即申请时间 */ @ApiField("biz_time") private Date bizTime; /** * 岗位申请来源 */ @ApiField("channel") private String channel; /** * 岗位ID */ @ApiField("job_id") private String jobId; /** * 外部申请ID,唯一标识一次外部申请 */ @ApiField("out_apply_id") private String outApplyId; /** * 蚂蚁统一会员ID */ @ApiField("user_id") private String userId; public String getApplyStatus() { return this.applyStatus; } public void setApplyStatus(String applyStatus) { this.applyStatus = applyStatus; } public Date getBizTime() { return this.bizTime; } public void setBizTime(Date bizTime) { this.bizTime = bizTime; } public String getChannel() { return this.channel; } public void setChannel(String channel) { this.channel = channel; } public String getJobId() { return this.jobId; } public void setJobId(String jobId) { this.jobId = jobId; } public String getOutApplyId() { return this.outApplyId; } public void setOutApplyId(String outApplyId) { this.outApplyId = outApplyId; } public String getUserId() { return this.userId; } public void setUserId(String userId) { this.userId = userId; } }
donrestarone/violet_rails
app/controllers/content_controller.rb
class ContentController < ApplicationController before_action :track_ahoy_visit, raise: false end
borgesai/borges.ai
publisher/sqs.go
<filename>publisher/sqs.go package publisher import ( "os" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/sqs" "github.com/segmentio/ksuid" logger "github.com/sirupsen/logrus" ) var sqsLogger = logger.WithField("module", "sqs") func makeSQSConn() (*sqs.SQS, error) { sess, err := session.NewSession() if err != nil { logger.WithError(err).Error("error creating session") return nil, err } conn := sqs.New(sess, aws.NewConfig().WithRegion(os.Getenv("AWS_REGION"))) return conn, nil } // queueURL format is this "https://sqs.us-west-2.amazonaws.com/411700958227/borges-sync-goodreads-user.fifo" func sendMessage(body, groupID, queueURL string) error { updateID := ksuid.New().String() log := sqsLogger. WithField("queue_url", queueURL). WithField("group_id", groupID). WithField("method", "sendMessage") log.Info("start") sqsConn, connErr := makeSQSConn() if connErr != nil { return connErr } result, err := sqsConn.SendMessage(&sqs.SendMessageInput{ MessageGroupId: aws.String(groupID), MessageDeduplicationId: aws.String(updateID), MessageBody: aws.String(body), QueueUrl: &queueURL, }) if err != nil { log.WithError(err).Error("failed to send message") return err } log.WithField("message_id", *result.MessageId).Info("message was sent") return nil }
grace-shopper-team-it/grace-shopper
server/api/productOrders.js
<reponame>grace-shopper-team-it/grace-shopper const router = require('express').Router(); const { ProductOrder } = require('../db/models'); // this route will be receiving products when they're ordered -cj // api/orderItems router.post('/', async (req, res) => { try { await ProductOrder.bulkCreate(req.body); res.sendStatus(201); } catch (error) { console.error(error); } }); module.exports = router;
greenpau/pycherwell
test/test_users_api.py
# coding: utf-8 """ Cherwell REST API Unofficial Python Cherwell REST API library. # noqa: E501 The version of the OpenAPI document: 9.3.2 Contact: See AUTHORS. Generated by: https://openapi-generator.tech """ from __future__ import absolute_import import unittest import pycherwell from pycherwell.api.users_api import UsersApi # noqa: E501 from pycherwell.rest import ApiException class TestUsersApi(unittest.TestCase): """UsersApi unit test stubs""" def setUp(self): self.api = pycherwell.api.users_api.UsersApi() # noqa: E501 def tearDown(self): pass def test_users_delete_user_batch_v1(self): """Test case for users_delete_user_batch_v1 Delete a batch of users # noqa: E501 """ pass def test_users_delete_user_batch_v2(self): """Test case for users_delete_user_batch_v2 Delete a batch of users # noqa: E501 """ pass def test_users_delete_user_v1(self): """Test case for users_delete_user_v1 Delete a user by record ID # noqa: E501 """ pass def test_users_delete_user_v2(self): """Test case for users_delete_user_v2 Delete a user by record ID # noqa: E501 """ pass def test_users_get_list_of_users(self): """Test case for users_get_list_of_users Get a list of all system users. # noqa: E501 """ pass def test_users_get_user_batch_v1(self): """Test case for users_get_user_batch_v1 Get user information in a batch # noqa: E501 """ pass def test_users_get_user_by_login_id_v1(self): """Test case for users_get_user_by_login_id_v1 Get a user by login ID # noqa: E501 """ pass def test_users_get_user_by_login_id_v2(self): """Test case for users_get_user_by_login_id_v2 Get a user by login ID and login ID type # noqa: E501 """ pass def test_users_get_user_by_login_id_v3(self): """Test case for users_get_user_by_login_id_v3 Get a user by login ID and login ID type # noqa: E501 """ pass def test_users_get_user_by_public_id_v1(self): """Test case for users_get_user_by_public_id_v1 Get a user by public ID # noqa: E501 """ pass def test_users_get_user_by_public_id_v2(self): """Test case for users_get_user_by_public_id_v2 Get a user by public ID # noqa: E501 """ pass def test_users_get_user_by_rec_id(self): """Test case for users_get_user_by_rec_id Get a user by record ID # noqa: E501 """ pass def test_users_save_user_batch_v1(self): """Test case for users_save_user_batch_v1 Create or update users in a batch # noqa: E501 """ pass def test_users_save_user_batch_v2(self): """Test case for users_save_user_batch_v2 Create or update users in a batch # noqa: E501 """ pass def test_users_save_user_v1(self): """Test case for users_save_user_v1 Create or update a user # noqa: E501 """ pass def test_users_save_user_v2(self): """Test case for users_save_user_v2 Create or update a user # noqa: E501 """ pass if __name__ == '__main__': unittest.main()
panos/haikudepotserver
haikudepotserver-core/src/main/java/org/haiku/haikudepotserver/dataobjects/auto/_PkgPkgCategory.java
<reponame>panos/haikudepotserver package org.haiku.haikudepotserver.dataobjects.auto; import org.apache.cayenne.exp.Property; import org.haiku.haikudepotserver.dataobjects.PkgCategory; import org.haiku.haikudepotserver.dataobjects.PkgSupplement; import org.haiku.haikudepotserver.dataobjects.support.AbstractDataObject; /** * Class _PkgPkgCategory was generated by Cayenne. * It is probably a good idea to avoid changing this class manually, * since it may be overwritten next time code is regenerated. * If you need to make any customizations, please use subclass. */ public abstract class _PkgPkgCategory extends AbstractDataObject { private static final long serialVersionUID = 1L; public static final String ID_PK_COLUMN = "id"; public static final Property<PkgCategory> PKG_CATEGORY = Property.create("pkgCategory", PkgCategory.class); public static final Property<PkgSupplement> PKG_SUPPLEMENT = Property.create("pkgSupplement", PkgSupplement.class); public void setPkgCategory(PkgCategory pkgCategory) { setToOneTarget("pkgCategory", pkgCategory, true); } public PkgCategory getPkgCategory() { return (PkgCategory)readProperty("pkgCategory"); } public void setPkgSupplement(PkgSupplement pkgSupplement) { setToOneTarget("pkgSupplement", pkgSupplement, true); } public PkgSupplement getPkgSupplement() { return (PkgSupplement)readProperty("pkgSupplement"); } }
miw-upm/apaw-practice
src/main/java/es/upm/miw/apaw_practice/adapters/mongodb/tennis_courts/persistence/CourtPersistenceMongoDB.java
<gh_stars>1-10 package es.upm.miw.apaw_practice.adapters.mongodb.tennis_courts.persistence; import es.upm.miw.apaw_practice.adapters.mongodb.tennis_courts.daos.CourtRepository; import es.upm.miw.apaw_practice.adapters.mongodb.tennis_courts.entities.EquipmentEntity; import es.upm.miw.apaw_practice.domain.exceptions.NotFoundException; import es.upm.miw.apaw_practice.domain.persistence_ports.tennis_courts.CourtPersistence; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import java.math.BigDecimal; import java.util.stream.Stream; @Repository("courtPersistence") public class CourtPersistenceMongoDB implements CourtPersistence { @Autowired private CourtRepository courtRepository; @Override public Stream<BigDecimal> getEquipmentValues(int number) { return this.courtRepository.findByNumber(number) .orElseThrow(() -> new NotFoundException("No existe ninguna pista con el numero " + number)) .getReservations().stream() .flatMap(reservation -> reservation.getPlayers().stream() .flatMap(player -> player.getEquipmentList().stream())) .map(EquipmentEntity::getTotalPrice); } }
kalufya/snow-owl
fhir/com.b2international.snowowl.fhir.core/src/com/b2international/snowowl/fhir/core/model/dt/Period.java
/* * Copyright 2018-2021 B2i Healthcare Pte Ltd, http://b2i.sg * * 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.b2international.snowowl.fhir.core.model.dt; import java.util.Date; import java.util.List; import com.b2international.snowowl.fhir.core.model.Element; import com.b2international.snowowl.fhir.core.model.Extension; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; /** * FHIR period complex datatype * * If the start element is missing, the start of the period is not known. * If the end element is missing, it means that the period is ongoing, or the start may be in the past, * and the end date in the future, which means that period is expected/planned to end at the specified time. * * @see <a href="https://www.hl7.org/fhir/datatypes.html#period">FHIR:Data Types:Period</a> * @since 6.6 */ @JsonDeserialize(builder = Period.Builder.class) public class Period extends Element { @JsonProperty private Date start; @JsonProperty private Date end; Period(final Date start, final Date end, final String id, final List<Extension> extensions) { super(id, extensions); this.start = start; this.end = end; } /** * Returns the start date with inclusive boundary * @return */ public Date getStart() { return start; } /** * Returns the end date with inclusive boundary * @return */ public Date getEnd() { return end; } public static Builder builder() { return new Builder(); } @JsonPOJOBuilder(withPrefix = "") public static class Builder extends Element.Builder<Builder, Period> { private Date start; private Date end; @Override protected Builder getSelf() { return this; } public Builder start(final Date start) { this.start = start; return getSelf(); } public Builder end(final Date end) { this.end = end; return getSelf(); } @Override protected Period doBuild() { return new Period(start, end, id, extensions); } } }
ClearControl/ClearCLIJ
src/test/java/net/haesleinhuepf/clij/macro/modules/Crop3DTest.java
package net.haesleinhuepf.clij.macro.modules; import net.haesleinhuepf.clij.clearcl.ClearCLBuffer; import net.haesleinhuepf.clij.clearcl.ClearCLImage; import ij.IJ; import ij.ImagePlus; import ij.gui.Roi; import ij.plugin.Duplicator; import net.haesleinhuepf.clij.CLIJ; import net.haesleinhuepf.clij.kernels.Kernels; import net.haesleinhuepf.clij.test.TestUtilities; import org.junit.Test; import static org.junit.Assert.*; public class Crop3DTest { @Test public void crop3d() { CLIJ clij = CLIJ.getInstance(); ImagePlus testImp1 = TestUtilities.getRandomImage(100, 100, 20, 32, 0, 100); // do operation with ImageJ Roi roi = new Roi(2, 2, 10, 10); testImp1.setRoi(roi); ImagePlus crop = new Duplicator().run(testImp1, 3, 12); // do operation with ClearCL ClearCLImage src = clij.convert(testImp1, ClearCLImage.class); ClearCLImage dst = clij.createCLImage(new long[]{10, 10, 10}, src.getChannelDataType()); Kernels.crop(clij, src, dst, 2, 2, 2); ImagePlus cropFromCL = clij.convert(dst, ImagePlus.class); assertTrue(TestUtilities.compareImages(crop, cropFromCL)); src.close(); dst.close(); IJ.exit(); clij.close(); } @Test public void cropBuffer3d() { CLIJ clij = CLIJ.getInstance(); ImagePlus testImp1 = TestUtilities.getRandomImage(100, 100, 20, 32, 0, 100); // do operation with ImageJ Roi roi = new Roi(2, 2, 10, 10); testImp1.setRoi(roi); ImagePlus crop = new Duplicator().run(testImp1, 3, 12); // do operation with ClearCL ClearCLBuffer src = clij.convert(testImp1, ClearCLBuffer.class); ClearCLBuffer dst = clij.createCLBuffer(new long[]{10, 10, 10}, src.getNativeType()); Kernels.crop(clij, src, dst, 2, 2, 2); ImagePlus cropFromCL = clij.convert(dst, ImagePlus.class); assertTrue(TestUtilities.compareImages(crop, cropFromCL)); src.close(); dst.close(); IJ.exit(); clij.close(); } }
acrylplatform/dex
dex/src/main/scala/com/acrylplatform/dex/settings/OrderFeeSettings.scala
package com.acrylplatform.dex.settings import cats.data.Validated.Valid import cats.implicits._ import com.acrylplatform.dex.settings.AssetType.AssetType import com.acrylplatform.dex.settings.FeeMode.FeeMode import com.acrylplatform.settings.Constants import com.acrylplatform.settings.utils.ConfigSettingsValidator import com.acrylplatform.settings.utils.ConfigSettingsValidator.ErrorsListOr import com.acrylplatform.transaction.Asset import com.acrylplatform.transaction.Asset.{Acryl, _} import com.acrylplatform.transaction.assets.exchange.AssetPair import monix.eval.Coeval import net.ceedubs.ficus.Ficus._ import net.ceedubs.ficus.readers.EnumerationReader._ import net.ceedubs.ficus.readers.ValueReader import play.api.libs.json.{JsObject, Json} object OrderFeeSettings { val totalAcrylAmount: Long = Constants.UnitsInWave * Constants.TotalAcryl sealed trait OrderFeeSettings { def getJson(matcherAccountFee: Long, ratesJson: JsObject): Coeval[JsObject] = Coeval.evalOnce { Json.obj( this match { case DynamicSettings(baseFee) => "dynamic" -> Json.obj( "baseFee" -> (baseFee + matcherAccountFee), "rates" -> ratesJson ) case FixedSettings(defaultAssetId, minFee) => "fixed" -> Json.obj( "assetId" -> AssetPair.assetIdStr(defaultAssetId), "minFee" -> minFee ) case PercentSettings(assetType, minFee) => "percent" -> Json.obj( "type" -> assetType, "minFee" -> minFee ) } ) } } case class DynamicSettings(baseFee: Long) extends OrderFeeSettings case class FixedSettings(defaultAssetId: Asset, minFee: Long) extends OrderFeeSettings case class PercentSettings(assetType: AssetType, minFee: Double) extends OrderFeeSettings implicit val orderFeeSettingsReader: ValueReader[OrderFeeSettings] = { (cfg, path) => val cfgValidator = ConfigSettingsValidator(cfg) def getPrefixByMode(mode: FeeMode): String = s"$path.$mode" def validateDynamicSettings: ErrorsListOr[DynamicSettings] = { cfgValidator.validateByPredicate[Long](s"${getPrefixByMode(FeeMode.DYNAMIC)}.base-fee")( predicate = fee => 0 < fee && fee <= totalAcrylAmount, errorMsg = s"required 0 < base fee <= $totalAcrylAmount" ) map DynamicSettings } def validateFixedSettings: ErrorsListOr[FixedSettings] = { val prefix = getPrefixByMode(FeeMode.FIXED) val feeValidator = cfgValidator.validateByPredicate[Long](s"$prefix.min-fee") _ val assetValidated = cfgValidator.validate[Asset](s"$prefix.asset") val feeValidated = assetValidated match { case Valid(Acryl) => feeValidator(fee => 0 < fee && fee <= totalAcrylAmount, s"required 0 < fee <= $totalAcrylAmount") case _ => feeValidator(_ > 0, "required 0 < fee") } (assetValidated, feeValidated) mapN FixedSettings } def validatePercentSettings: ErrorsListOr[PercentSettings] = { val prefix = getPrefixByMode(FeeMode.PERCENT) ( cfgValidator.validate[AssetType](s"$prefix.asset-type"), cfgValidator.validatePercent(s"$prefix.min-fee") ) mapN PercentSettings } def getSettingsByMode(mode: FeeMode): ErrorsListOr[OrderFeeSettings] = mode match { case FeeMode.DYNAMIC => validateDynamicSettings case FeeMode.FIXED => validateFixedSettings case FeeMode.PERCENT => validatePercentSettings } cfgValidator.validate[FeeMode](s"$path.mode").toEither >>= (mode => getSettingsByMode(mode).toEither) match { case Left(errorsAcc) => throw new Exception(errorsAcc.mkString_(", ")) case Right(orderFeeSettings) => orderFeeSettings } } } object AssetType extends Enumeration { type AssetType = Value val AMOUNT = Value("amount") val PRICE = Value("price") val SPENDING = Value("spending") val RECEIVING = Value("receiving") } object FeeMode extends Enumeration { type FeeMode = Value val DYNAMIC = Value("dynamic") val FIXED = Value("fixed") val PERCENT = Value("percent") }
js-lib-com/tiny-container
src/test/java/js/tiny/container/http/unit/EncoderKeyTest.java
<gh_stars>0 package js.tiny.container.http.unit; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.List; import org.junit.Test; import js.lang.GType; import js.tiny.container.http.ContentType; import js.tiny.container.http.encoder.EncoderKey; public class EncoderKeyTest { @Test public void constructor() { EncoderKey key = new EncoderKey(ContentType.valueOf("text/html"), Object.class); assertEquals("text/html:java.lang.Object", key.toString()); } @Test public void constructor_ParameterizedType() { EncoderKey key = new EncoderKey(ContentType.valueOf("text/html"), new GType(List.class, Object.class)); assertEquals("text/html:java.util.List", key.toString()); } @Test public void constructor_ContentType() { EncoderKey key = new EncoderKey(ContentType.valueOf("text/html")); assertEquals("text/html", key.toString()); } @Test public void constructor_JavaType() { EncoderKey key = new EncoderKey(Object.class); assertEquals("java.lang.Object", key.toString()); } @Test public void constructor_NullParameters() { EncoderKey key = new EncoderKey(null, null); assertEquals("", key.toString()); } @Test public void valueHashCode() { assertEquals("text/html".hashCode(), new EncoderKey(ContentType.valueOf("text/html")).hashCode()); } @Test public void valueEquals() { assertTrue(EncoderKey.APPLICATION_JSON.equals(EncoderKey.APPLICATION_JSON)); assertTrue(EncoderKey.APPLICATION_JSON.equals(new EncoderKey(ContentType.valueOf("application/json")))); assertFalse(EncoderKey.APPLICATION_JSON.equals(null)); assertFalse(EncoderKey.APPLICATION_JSON.equals(Object.class)); } }
nattyco/fermatold
CCP/library/api/fermat-ccp-api/src/main/java/com/bitdubai/fermat_ccp_api/layer/basic_wallet/discount_wallet/enums/FiatAccountTypes.java
package com.bitdubai.fermat_ccp_api.layer.basic_wallet.discount_wallet.enums; import com.bitdubai.fermat_api.layer.all_definition.exceptions.InvalidParameterException; /** * Created by ciencias on 2/15/15. */ public enum FiatAccountTypes { //Modified by <NAME> on 05/08/2015 SAVINGS_ACCOUNT("SAVA"), CURRENT_ACCOUNT("CURA"); private String code; FiatAccountTypes(String code){ this.code=code; } public String getCode(){ return this.code; } public static FiatAccountTypes getByCode(String code) throws InvalidParameterException{ switch (code){ case "SAVA": return FiatAccountTypes.SAVINGS_ACCOUNT; case "CURA": return FiatAccountTypes.CURRENT_ACCOUNT; default: throw new InvalidParameterException(InvalidParameterException.DEFAULT_MESSAGE, null, "Code Received: " + code, "This Code Is Not Valid for the FiatAccountTypes enum"); } } }
mybsktb/ant-d
node_modules/@antv/g2/lib/component/axis/polyline.js
<gh_stars>0 function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @fileOverview the axis of map coodinate * @author sima.zhang */ var Util = require('../../util'); var Base = require('./base'); var _require = require('@antv/g'), MatrixUtil = _require.MatrixUtil, PathUtil = _require.PathUtil; var vec2 = MatrixUtil.vec2; var Polyline = function (_Base) { _inherits(Polyline, _Base); function Polyline() { _classCallCheck(this, Polyline); return _possibleConstructorReturn(this, _Base.apply(this, arguments)); } Polyline.prototype.getDefaultCfg = function getDefaultCfg() { var cfg = _Base.prototype.getDefaultCfg.call(this); return Util.mix({}, cfg, { type: 'polyline' }); }; Polyline.prototype.getLinePath = function getLinePath() { var self = this; var tickPoints = self.get('tickPoints'); var start = self.get('start'); var end = self.get('end'); var points = []; points.push(start.x); points.push(start.y); Util.each(tickPoints, function (tick) { points.push(tick.x); points.push(tick.y); }); points.push(end.x); points.push(end.y); var path = PathUtil.catmullRomToBezier(points); path.unshift(['M', start.x, start.y]); return path; }; Polyline.prototype.getTickPoint = function getTickPoint(value, index) { var tickPoints = this.get('tickPoints'); return tickPoints[index]; }; Polyline.prototype.getTickEnd = function getTickEnd(start, value, index) { var self = this; var lineAttrs = self.get('tickLine'); var tickLength = value ? value : lineAttrs.length; var offsetVector = self.getSideVector(tickLength, start, index); return { x: start.x + offsetVector[0], y: start.y + offsetVector[1] }; }; Polyline.prototype.getSideVector = function getSideVector(offset, point, index) { var self = this; var preTickPoint = void 0; if (index === 0) { preTickPoint = self.get('start'); } else { var tickPoints = self.get('tickPoints'); preTickPoint = tickPoints[index - 1]; } var vector = [point.x - preTickPoint.x, point.y - preTickPoint.y]; var normal = vec2.normalize([], vector); var verticalVector = vec2.vertical([], normal, false); return vec2.scale([], verticalVector, offset); }; return Polyline; }(Base); module.exports = Polyline;
SCOTT-HAMILTON/OTPGen
Source/Gui/Windows/MainWindow.hpp
#ifndef MAINWINDOW_HPP #define MAINWINDOW_HPP #include <memory> #include <QLayout> #include <QSystemTrayIcon> #include <QEvent> #include <QTimer> #include <QShortcut> #include <QClipboard> #include <WidgetHelpers/QRootWidget.hpp> class MainWindow : public QRootWidget { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); void minimizeToTray(); private: void trayShowHideCallback(); signals: void resized(); void closed(); protected: void showEvent(QShowEvent *event); void closeEvent(QCloseEvent *event); private: std::shared_ptr<QTimer> masterTimer; QList<std::shared_ptr<QTimer>> timers; std::shared_ptr<QSystemTrayIcon> trayIcon; std::shared_ptr<QMenu> trayMenu; std::shared_ptr<QAction> trayShowHide; QString trayShowText; QString trayHideText; std::shared_ptr<QAction> traySeparatorBeforeTokens; QList<std::shared_ptr<QAction>> trayTokens; QClipboard *clipboard = nullptr; }; #endif // MAINWINDOW_HPP
AlvaWang/spring-may
src/main/java/net/bambooslips/demo/jpa/service/Impl/EducationExperionceServiceImpl.java
package net.bambooslips.demo.jpa.service.Impl; import net.bambooslips.demo.exception.EducationExperionceNotFoundException; import net.bambooslips.demo.exception.PostNotFoundException; import net.bambooslips.demo.exception.TeamEssentialNotFoundException; import net.bambooslips.demo.exception.TeamResponsiblePersonNotFoundException; import net.bambooslips.demo.jpa.model.*; import net.bambooslips.demo.jpa.repository.EducationExperionceRepository; import net.bambooslips.demo.jpa.repository.TeamEssentialRepository; import net.bambooslips.demo.jpa.service.EducationExperionceService; import net.bambooslips.demo.jpa.service.TeamEssentialService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.List; /** * Created by Administrator on 2017/4/21. */ @Service public class EducationExperionceServiceImpl implements EducationExperionceService { private static final Logger LOG = LoggerFactory.getLogger(EducationExperionceServiceImpl.class); @Resource private EducationExperionceRepository educationExperionceRepository; @Transactional @Override public Long create(EducationExperionce educationExperionce) { LOG.debug("Creating a new educationExperionce with information: " + educationExperionce); EducationExperionce result = educationExperionceRepository.save(educationExperionce); if (result != null) { return educationExperionce.getEduId(); } return null; } @Override public EducationExperionce delete(Long id) { LOG.debug("Deleting CompetitionAccount with id: " + id); EducationExperionce deleted = educationExperionceRepository.findOne(id); if (deleted == null) { LOG.debug("No CompetitionAccount found with id: " + id); throw new EducationExperionceNotFoundException("No CompetitionAccount found with id: " + id); } educationExperionceRepository.delete(deleted); return deleted; } @Override public List<EducationExperionce> findListByEntireId(Long ctId) { LOG.debug("Deleting EconomicRiskCounter with id: " + ctId); List<EducationExperionce> list = educationExperionceRepository.findListByEntireId(ctId); return list; } @Transactional(rollbackFor = EducationExperionceNotFoundException.class) @Override public EducationExperionce update(EducationExperionce updated) throws EducationExperionceNotFoundException { LOG.debug("Updating TeamResponsiblePerson with information: " + updated); EducationExperionce educationExperionce = educationExperionceRepository.findOne(updated.getEduId()); if (educationExperionce == null) { LOG.debug("No teamResponsiblePerson found with id: " + updated.getEduId()); throw new PostNotFoundException("Post " + updated.getEduId() + " not found."); } educationExperionce.update(updated); return educationExperionce; } @Override public List<EducationExperionce> deleteByEntireId(Long ctId) { LOG.debug("Deleting CoreTeam with id: " + ctId); List<EducationExperionce> deleted = educationExperionceRepository.findListByEntireId(ctId); if (deleted == null) { LOG.debug("No EducationExperionceNotFoundException found with id: " + ctId); throw new EducationExperionceNotFoundException("No EducationExperionceNotFoundException found with id: " + ctId); } else { educationExperionceRepository.deleteByEntireId(ctId); return deleted; } } }
wedataintelligence/vivaldi-source
chromium/components/scheduler/renderer/throttling_helper.h
<gh_stars>0 // Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_SCHEDULER_RENDERER_THROTTLING_HELPER_H_ #define COMPONENTS_SCHEDULER_RENDERER_THROTTLING_HELPER_H_ #include <set> #include "base/macros.h" #include "components/scheduler/base/cancelable_closure_holder.h" #include "components/scheduler/base/time_domain.h" #include "components/scheduler/scheduler_export.h" #include "third_party/WebKit/public/platform/WebViewScheduler.h" namespace scheduler { class RendererSchedulerImpl; class ThrottledTimeDomain; class WebFrameSchedulerImpl; class SCHEDULER_EXPORT ThrottlingHelper : public TimeDomain::Observer { public: ThrottlingHelper(RendererSchedulerImpl* renderer_scheduler, const char* tracing_category); ~ThrottlingHelper() override; // TimeDomain::Observer implementation: void OnTimeDomainHasImmediateWork() override; void OnTimeDomainHasDelayedWork() override; void Throttle(TaskQueue* task_queue); void Unthrottle(TaskQueue* task_queue); const ThrottledTimeDomain* time_domain() const { return time_domain_.get(); } static base::TimeTicks ThrottledRunTime(base::TimeTicks unthrottled_runtime); const scoped_refptr<TaskQueue>& task_runner() const { return task_runner_; } private: void PumpThrottledTasks(); void MaybeSchedulePumpThrottledTasksLocked( const tracked_objects::Location& from_here, base::TimeTicks now, base::TimeTicks unthrottled_runtime); std::set<TaskQueue*> throttled_queues_; base::Closure forward_immediate_work_closure_; scoped_refptr<TaskQueue> task_runner_; RendererSchedulerImpl* renderer_scheduler_; // NOT OWNED base::TickClock* tick_clock_; // NOT OWNED const char* tracing_category_; // NOT OWNED scoped_ptr<ThrottledTimeDomain> time_domain_; CancelableClosureHolder suspend_timers_when_backgrounded_closure_; base::TimeTicks pending_pump_throttled_tasks_runtime_; base::WeakPtrFactory<ThrottlingHelper> weak_factory_; DISALLOW_COPY_AND_ASSIGN(ThrottlingHelper); }; } // namespace scheduler #endif // COMPONENTS_SCHEDULER_RENDERER_THROTTLING_HELPER_H_
eIGato/mahjong-portal
server/rating/management/commands/rating_future.py
import csv import datetime from django.core.management.base import BaseCommand from django.utils import timezone from player.models import Player from rating.calculation.rr import RatingRRCalculation from rating.models import Rating, RatingDelta, RatingResult, TournamentCoefficients from tournament.models import Tournament, TournamentResult def get_date_string(): return timezone.now().strftime("%H:%M:%S") class Command(BaseCommand): def handle(self, *args, **options): rating_date = datetime.date(2020, 2, 1) add_coefficient = True players = 40 sessions = 10 tournament = Tournament.objects.get(id=431) tournament.is_upcoming = False tournament.number_of_players = players tournament.number_of_sessions = sessions tournament.save() data = [["Игроков", players, "Игр", sessions, "Коэффициент"]] # Леонтьев 154 # Алексеева 389 # Монаков 70 player_id = 70 places = [1, 6, 10, 16, 20, 24, 30, 40] for place in places: print(place) data.append([""]) data.append(["Место на турнире", "{}/{}".format(place, players)]) data.append(["Рейтинг"]) TournamentResult.objects.filter(tournament=tournament).delete() player = Player.objects.get(id=player_id) TournamentResult.objects.create(place=place, player=player, tournament=tournament) calculator = RatingRRCalculation() rating = Rating.objects.get(type=Rating.RR) types = [Tournament.RR, Tournament.EMA, Tournament.FOREIGN_EMA] tournaments = ( Tournament.public.filter(tournament_type__in=types).filter(is_upcoming=False).order_by("end_date") ) RatingResult.objects.filter(rating=rating).delete() RatingDelta.objects.filter(rating=rating).delete() dates_to_process = [rating_date] self.calculate_rating(dates_to_process, tournaments, calculator, rating) results = RatingResult.objects.filter(rating=rating, date=rating_date).order_by("place")[:15] for result in results: data.append([result.player.last_name_ru, result.place, result.score]) c = TournamentCoefficients.objects.get(rating=rating, date=rating_date, tournament=tournament) if add_coefficient: data[0].append(c.coefficient) add_coefficient = False with open("export.csv", "w") as f: writer = csv.writer(f) for x in data: writer.writerow(x) def calculate_rating(self, dates_to_process, tournaments, calculator, rating): for rating_date in dates_to_process: limited_tournaments = tournaments.filter(end_date__lte=rating_date) for tournament in limited_tournaments: calculator.calculate_players_deltas(tournament, rating, rating_date) calculator.calculate_players_rating_rank(rating, rating_date)
jaywangpeng/C-Primer-Plus-5th-Exercises
16/16-5.c
<gh_stars>0 #include <stdio.h> #include <stdlib.h> #include <time.h> #define MAXLEN 10 void prnt_nums(int array[], int n, int count) { int i; srand((unsigned int)time(0)); while (count--) { i = rand() % n; printf("%d ", array[i]); } putchar('\n'); } int main(void) { int count, i; int array[MAXLEN] = { 0,1,2,3,4,5,6,7,8,9 }; puts("Original array:"); for (i = 0; i < MAXLEN; i++) printf("%d ", array[i]); putchar('\n'); puts("Enter how many numbers to print:"); scanf("%d", &count); prnt_nums(array, MAXLEN, count); return 0; }
TakuKitamura/expirefile-syscall
linux-5.2/drivers/media/rc/keymaps/rc-total-media-in-hand.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Total Media In Hand remote controller keytable * * Copyright (C) 2010 <NAME> <<EMAIL>> */ #include <media/rc-map.h> #include <linux/module.h> /* Uses NEC extended 0x02bd */ static struct rc_map_table total_media_in_hand[] = { { 0x02bd00, KEY_1 }, { 0x02bd01, KEY_2 }, { 0x02bd02, KEY_3 }, { 0x02bd03, KEY_4 }, { 0x02bd04, KEY_5 }, { 0x02bd05, KEY_6 }, { 0x02bd06, KEY_7 }, { 0x02bd07, KEY_8 }, { 0x02bd08, KEY_9 }, { 0x02bd09, KEY_0 }, { 0x02bd0a, KEY_MUTE }, { 0x02bd0b, KEY_CYCLEWINDOWS }, /* yellow, [min / max] */ { 0x02bd0c, KEY_VIDEO }, /* TV / AV */ { 0x02bd0e, KEY_VOLUMEDOWN }, { 0x02bd0f, KEY_TIME }, /* TimeShift */ { 0x02bd10, KEY_RIGHT }, /* right arrow */ { 0x02bd11, KEY_LEFT }, /* left arrow */ { 0x02bd12, KEY_UP }, /* up arrow */ { 0x02bd13, KEY_DOWN }, /* down arrow */ { 0x02bd14, KEY_POWER2 }, /* [red] */ { 0x02bd15, KEY_OK }, /* OK */ { 0x02bd16, KEY_STOP }, { 0x02bd17, KEY_CAMERA }, /* Snapshot */ { 0x02bd18, KEY_CHANNELUP }, { 0x02bd19, KEY_RECORD }, { 0x02bd1a, KEY_CHANNELDOWN }, { 0x02bd1c, KEY_ESC }, /* Esc */ { 0x02bd1e, KEY_PLAY }, { 0x02bd1f, KEY_VOLUMEUP }, { 0x02bd40, KEY_PAUSE }, { 0x02bd41, KEY_FASTFORWARD }, /* FF >> */ { 0x02bd42, KEY_REWIND }, /* FR << */ { 0x02bd43, KEY_ZOOM }, /* [window + mouse pointer] */ { 0x02bd44, KEY_SHUFFLE }, /* Shuffle */ { 0x02bd45, KEY_INFO }, /* [red (I)] */ }; static struct rc_map_list total_media_in_hand_map = { .map = { .scan = total_media_in_hand, .size = ARRAY_SIZE(total_media_in_hand), .rc_proto = RC_PROTO_NECX, .name = RC_MAP_TOTAL_MEDIA_IN_HAND, } }; static int __init init_rc_map_total_media_in_hand(void) { return rc_map_register(&total_media_in_hand_map); } static void __exit exit_rc_map_total_media_in_hand(void) { rc_map_unregister(&total_media_in_hand_map); } module_init(init_rc_map_total_media_in_hand) module_exit(exit_rc_map_total_media_in_hand) MODULE_LICENSE("GPL"); MODULE_AUTHOR("<NAME> <<EMAIL>>");
cidermole/yaca
src/embedded/libyaca/main.c
#include <avr/io.h> #include <avr/pgmspace.h> #include <avr/interrupt.h> #include <inttypes.h> #include "yaca.h" #include "../bootloader/eeprom.h" int __attribute__ ((weak)) main(void); #ifdef YACA_INT1 void __attribute__ ((naked, signal, __INTR_ATTRS)) INT1_vect(void); #else void __attribute__ ((naked, signal, __INTR_ATTRS)) INT0_vect(void); #endif void __attribute__ ((weak)) _Z4initv(void); extern const fpt_t fpt[] PROGMEM; extern const uint8_t fpt_size PROGMEM; volatile uint16_t _time = 0; #ifdef YACA_INT1 void INT1_vect(void) { //ISR(INT1_vect) { asm volatile("rjmp __bld_int1"); } #else void INT0_vect(void) { //ISR(INT0_vect) { asm volatile("rjmp __bld_int0"); } #endif void yc_dispatch_auto() { Message in; if(yc_poll_receive()) { yc_receive(&in); yc_dispatch(&in, EE_IDTABLE, (void **)fpt, (uint8_t *)&fpt_size); } } int main() { if(_Z4initv) _Z4initv(); sei(); while(1) { yc_dispatch_auto(); } return 0; }
faliester/opentrons
protocol-designer/src/modules/moduleData.js
<filename>protocol-designer/src/modules/moduleData.js // @flow import { SPAN7_8_10_11_SLOT } from '../constants' import { MAGNETIC_MODULE_TYPE, TEMPERATURE_MODULE_TYPE, THERMOCYCLER_MODULE_TYPE, } from '@opentrons/shared-data' import type { ModuleRealType } from '@opentrons/shared-data' import type { DropdownOption } from '@opentrons/components' export const SUPPORTED_MODULE_TYPES: Array<ModuleRealType> = [ MAGNETIC_MODULE_TYPE, TEMPERATURE_MODULE_TYPE, THERMOCYCLER_MODULE_TYPE, ] type SupportedSlotMap = { [type: ModuleRealType]: Array<DropdownOption>, } export const SUPPORTED_MODULE_SLOTS: SupportedSlotMap = { [MAGNETIC_MODULE_TYPE]: [{ name: 'Slot 1 (supported)', value: '1' }], [TEMPERATURE_MODULE_TYPE]: [{ name: 'Slot 3 (supported)', value: '3' }], [THERMOCYCLER_MODULE_TYPE]: [ { name: 'Thermocycler slots', value: SPAN7_8_10_11_SLOT }, ], } export const ALL_MODULE_SLOTS: Array<DropdownOption> = [ { name: 'Slot 1', value: '1' }, { name: 'Slot 3', value: '3' }, { name: 'Slot 4', value: '4' }, { name: 'Slot 6', value: '6' }, { name: 'Slot 7', value: '7' }, { name: 'Slot 9', value: '9' }, { name: 'Slot 10', value: '10' }, ] export function getAllModuleSlotsByType( moduleType: ModuleRealType ): Array<DropdownOption> { const supportedSlotOption = SUPPORTED_MODULE_SLOTS[moduleType] if (moduleType === THERMOCYCLER_MODULE_TYPE) { return supportedSlotOption } const allOtherSlots = ALL_MODULE_SLOTS.filter( s => s.value !== supportedSlotOption[0].value ) return supportedSlotOption.concat(allOtherSlots) }
ndlib/hydra_vra
spec/models/generic_image_spec.rb
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') require "active_fedora" describe GenericImage do before(:each) do Fedora::Repository.stubs(:instance).returns(stub_everything()) @hydra_image = GenericImage.new end it "Should be a kind of ActiveFedora::Base" do @hydra_image.should be_kind_of(ActiveFedora::Base) end it "should include Hydra Model Methods" do @hydra_image.class.included_modules.should include(Hydra::ModelMethods) @hydra_image.should respond_to(:apply_depositor_metadata) end it "should have accessors for its default datastreams of content and original" do @hydra_image.should respond_to(:has_content?) @hydra_image.should respond_to(:content) @hydra_image.should respond_to(:content=) @hydra_image.should respond_to(:has_original?) @hydra_image.should respond_to(:original) @hydra_image.should respond_to(:original=) end it "should have accessors for its default datastreams of max, screen and thumbnail" do @hydra_image.should respond_to(:has_max?) @hydra_image.should respond_to(:max) @hydra_image.should respond_to(:max=) @hydra_image.should respond_to(:has_screen?) @hydra_image.should respond_to(:screen) @hydra_image.should respond_to(:screen=) @hydra_image.should respond_to(:has_thumbnail?) @hydra_image.should respond_to(:thumbnail) @hydra_image.should respond_to(:thumbnail=) end it "should create a max datastream when setting max value to image file" do f = File.new(File.join( File.dirname(__FILE__), "../fixtures/image.jp2" )) @hydra_image.max = f end describe '#content=' do it "shoutld create a content datastream when given an image file" do end end describe '#derive_all' do it "should create a max, screen and thumbnail file" do end end end
bhathiya/andes
modules/andes-core/perftests/src/main/java/org/wso2/andes/client/topic/Config.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.wso2.andes.client.topic; import org.wso2.andes.client.AMQSession; import org.wso2.andes.client.config.ConnectorConfig; import org.wso2.andes.client.config.Connector; import org.wso2.andes.client.config.AbstractConfig; import javax.jms.Connection; public class Config extends AbstractConfig implements ConnectorConfig { private String host = "localhost"; private int port = 5672; private String factory = null; private int payload = 256; private int messages = 1000; private int clients = 1; private int batch = 1; private long delay = 1; private int warmup; private int ackMode= AMQSession.NO_ACKNOWLEDGE; private String clientId; private String subscriptionId; private String selector; private String destinationName; private boolean persistent; private boolean transacted; private int destinationsCount; private int batchSize; private int rate; private boolean ispubsub; private long timeout; public Config() { } public int getAckMode() { return ackMode; } public void setPayload(int payload) { this.payload = payload; } public int getPayload() { return payload; } void setClients(int clients) { this.clients = clients; } int getClients() { return clients; } void setMessages(int messages) { this.messages = messages; } public int getMessages() { return messages; } public int getBatchSize() { return batchSize; } public int getRate() { return rate; } public int getDestinationsCount() { return destinationsCount; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public int getPort() { return port; } public String getFactory() { return factory; } public void setPort(int port) { this.port = port; } int getBatch() { return batch; } void setBatch(int batch) { this.batch = batch; } int getWarmup() { return warmup; } void setWarmup(int warmup) { this.warmup = warmup; } public long getDelay() { return delay; } public void setDelay(long delay) { this.delay = delay; } public long getTimeout() { return timeout; } public void setTimeout(long time) { this.timeout = time; } public String getClientId() { return clientId; } public String getSubscriptionId() { return subscriptionId; } public String getSelector() { return selector; } public String getDestination() { return destinationName; } public boolean usePersistentMessages() { return persistent; } public boolean isTransacted() { return transacted; } public boolean isPubSub() { return ispubsub; } public void setOption(String key, String value) { if("-host".equalsIgnoreCase(key)) { setHost(value); } else if("-port".equalsIgnoreCase(key)) { try { setPort(Integer.parseInt(value)); } catch(NumberFormatException e) { throw new RuntimeException("Bad port number: " + value, e); } } else if("-payload".equalsIgnoreCase(key)) { setPayload(parseInt("Bad payload size", value)); } else if("-messages".equalsIgnoreCase(key)) { setMessages(parseInt("Bad message count", value)); } else if("-clients".equalsIgnoreCase(key)) { setClients(parseInt("Bad client count", value)); } else if("-batch".equalsIgnoreCase(key)) { setBatch(parseInt("Bad batch count", value)); } else if("-delay".equalsIgnoreCase(key)) { setDelay(parseLong("Bad batch delay", value)); } else if("-warmup".equalsIgnoreCase(key)) { setWarmup(parseInt("Bad warmup count", value)); } else if("-ack".equalsIgnoreCase(key)) { ackMode = parseInt("Bad ack mode", value); } else if("-factory".equalsIgnoreCase(key)) { factory = value; } else if("-clientId".equalsIgnoreCase(key)) { clientId = value; } else if("-subscriptionId".equalsIgnoreCase(key)) { subscriptionId = value; } else if("-persistent".equalsIgnoreCase(key)) { persistent = "true".equalsIgnoreCase(value); } else if("-transacted".equalsIgnoreCase(key)) { transacted = "true".equalsIgnoreCase(value); } else if ("-destinationscount".equalsIgnoreCase(key)) { destinationsCount = parseInt("Bad destinations count", value); } else if ("-batchsize".equalsIgnoreCase(key)) { batchSize = parseInt("Bad batch size", value); } else if ("-rate".equalsIgnoreCase(key)) { rate = parseInt("MEssage rate", value); } else if("-pubsub".equalsIgnoreCase(key)) { ispubsub = "true".equalsIgnoreCase(value); } else if("-selector".equalsIgnoreCase(key)) { selector = value; } else if("-destinationname".equalsIgnoreCase(key)) { destinationName = value; } else if("-timeout".equalsIgnoreCase(key)) { setTimeout(parseLong("Bad timeout data", value)); } else { System.out.println("Ignoring unrecognised option: " + key); } } static String getAckModeDescription(int ackMode) { switch(ackMode) { case AMQSession.NO_ACKNOWLEDGE: return "NO_ACKNOWLEDGE"; case AMQSession.AUTO_ACKNOWLEDGE: return "AUTO_ACKNOWLEDGE"; case AMQSession.CLIENT_ACKNOWLEDGE: return "CLIENT_ACKNOWLEDGE"; case AMQSession.DUPS_OK_ACKNOWLEDGE: return "DUPS_OK_ACKNOWELDGE"; case AMQSession.PRE_ACKNOWLEDGE: return "PRE_ACKNOWLEDGE"; } return "AckMode=" + ackMode; } public Connection createConnection() throws Exception { return new Connector().createConnection(this); } }
alkaplan/junior-csx
workspace_compadre/osp/src/org/opensourcephysics/resources/controls/controls_res.java
package org.opensourcephysics.resources.controls; import java.io.IOException; import java.io.InputStream; import java.util.PropertyResourceBundle; /** * Default resource loader for the OSP display package. Resources are obtained from properties. * * Defining a Java resource class speeds up resource loading, particularly for applets because * a connection to the server is not required. * * @author <NAME> */ public class controls_res extends PropertyResourceBundle { // relative path to strings static String res = "controls_res.properties"; //$NON-NLS-1$ /** * Constructor tools * @throws IOException */ public controls_res() throws IOException { this(controls_res.class.getResourceAsStream(res)); } /** * Constructor tools * @param stream * @throws IOException */ public controls_res(InputStream stream) throws IOException { super(stream); } }
13939094104/Gtokrn
app/src/main/java/vdsMain/table/AbstractTable.java
package vdsMain.table; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.vc.libcommon.exception.AddressFormatException; import generic.exceptions.UnsupportAddressException; import vdsMain.db.DataBaseHelper; /* renamed from: fx */ public abstract class AbstractTable { //f12718a protected Context context; //f12719b private DataBaseHelper dataBaseHelper; //f12720c private String tableName; //f12721d private Object lock = new Object(); //mo41100a public abstract AbstractTableItem getTableItem(Cursor cursor, int i) throws UnsupportAddressException, AddressFormatException; //mo41101a public abstract String getCreateFieldSql(int i); /* access modifiers changed from: protected */ /* renamed from: c */ public String[] mo43576c(int i) { return null; } public AbstractTable(Context context, DataBaseHelper dataBaseHelper) { this.context = context; this.dataBaseHelper = dataBaseHelper; } /* renamed from: a */ public Context getContext() { return this.context; } //mo43566b public SQLiteDatabase getDbWritableDataHelper() { DataBaseHelper baseHelper = this.dataBaseHelper; if (baseHelper != null) { return baseHelper.getWritableDatabase(); } return null; } //mo43574c //910 mo43637c public void beginTransaction() { synchronized (this.lock) { SQLiteDatabase b = getDbWritableDataHelper(); if (!b.inTransaction()) { b.beginTransaction(); } } } //mo43565a //910 mo43628a public void endTransaction(boolean isSuccess) { synchronized (this.lock) { SQLiteDatabase b = getDbWritableDataHelper(); if (b != null) { if (b.inTransaction()) { if (isSuccess) { b.setTransactionSuccessful(); } b.endTransaction(); } } } } //mo43579d //910 mo43642d public boolean isInTransaction() { synchronized (this.lock) { SQLiteDatabase sqLiteDatabase = getDbWritableDataHelper(); if (sqLiteDatabase == null) { return false; } boolean inTransaction = sqLiteDatabase.inTransaction(); return inTransaction; } } //mo43563a public synchronized void execSqlSynchronized(String str, Object[] objArr) { execSQL(str, objArr); } //mo43570b public synchronized void execSQL(String str, Object[] objArr) { getDbWritableDataHelper().execSQL(str, objArr); } //mo43562a public void execSql(String sql) { execSqlSynchronized(sql); } //mo43569b public synchronized void execSqlSynchronized(String str) { getDbWritableDataHelper().execSQL(str); } //mo43572c public synchronized Cursor rawQueryNoArgs(String str) { return getDbWritableDataHelper().rawQuery(str, null); } //mo43564a public synchronized void deleteDataSynchronized(String str, String[] strArr) { deleteData(str, strArr); } /* access modifiers changed from: protected */ //mo43571b public void deleteData(String where, String[] strArr) { getDbWritableDataHelper().delete(getTableName(), where, strArr); } //mo43573c //910 mo43636c public Cursor rawQuery(String str, String[] strArr) { return getDbWritableDataHelper().rawQuery(str, strArr); } //mo43560a public void closeCursor(Cursor cursor) { if (!cursor.isClosed()) { cursor.close(); } } //mo43580e public Cursor selectAll() { if (getDbWritableDataHelper() == null) { return null; } StringBuilder sb = new StringBuilder(); sb.append("select * from "); sb.append(getTableName()); return rawQuery(sb.toString(), null); } //mo43567b public AbstractTableItem getCompleteTableItem(Cursor cursor) { if (!cursor.moveToNext()) { return null; } AbstractTableItem abstractTableItem = null; try { abstractTableItem = getTableItem(cursor, getDbWritableDataHelper().getVersion()); } catch (UnsupportAddressException e) { e.printStackTrace(); } catch (AddressFormatException e) { e.printStackTrace(); } abstractTableItem.initAllTableItemVariable(cursor, this.dataBaseHelper.getWritableDatabase().getVersion(), 0); return abstractTableItem; } //mo43578d public final void setTableName(String str) { this.tableName = str; } //mo43581f //910 mo43644f //915 mo43885f public final String getTableName() { return this.tableName; } //mo43561a public void replace(AbstractTableItem abstractTableItem) { replaceSynchronized(abstractTableItem); } //mo43568b public synchronized void replaceSynchronized(AbstractTableItem abstractTableItem) { getDbWritableDataHelper().replace(getTableName(), null, abstractTableItem.getContentValues()); } //mo43575c public synchronized void replaceDataSynchronized(AbstractTableItem abstractTableItem) { abstractTableItem.replaceData(this); } //mo43577d public synchronized void deleteDataByOtherTableItemSynchronized(AbstractTableItem abstractTableItem) { abstractTableItem.deleteData(this); } //mo43582g public void clearTable() { SQLiteDatabase b = getDbWritableDataHelper(); StringBuilder sb = new StringBuilder(); sb.append("delete from "); sb.append(getTableName()); sb.append(";"); b.execSQL(sb.toString()); } //mo42535b public void createTable(int i) { String str; String sb2 = "create table if not exists " + getTableName(); String a = getCreateFieldSql(i); int i2 = 0; if (a.charAt(0) != ' ') { str = sb2 + " " + a; } else { str = sb2 + a; } if (str.charAt(str.length() - 1) != ';') { str = str + ";"; } getDbWritableDataHelper().execSQL(str); String[] c = mo43576c(i); if (c != null && c.length != 0) { StringBuffer stringBuffer = new StringBuffer("create index if not exists "); stringBuffer.append(getTableName()); stringBuffer.append("_index on "); stringBuffer.append(getTableName()); stringBuffer.append("("); while (i2 < c.length) { stringBuffer.append(c[i2]); i2++; if (i2 != c.length) { stringBuffer.append(","); } } stringBuffer.append(")"); getDbWritableDataHelper().execSQL(stringBuffer.toString()); } } //mo43583h public int getVersion() { return getDbWritableDataHelper().getVersion(); } }
m-zakeri/benchmark
make_1.4/make/inputs/sdir-cov11/src/m/hp9000s300.h
/* machine description file for hp9000 series 200 or 300 on either HPUX or BSD. Copyright (C) 1985 Free Software Foundation, Inc. This file is part of GNU Emacs. GNU Emacs is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU Emacs 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 GNU Emacs; see the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /* The following line tells the configuration script what sort of operating system this machine is likely to run. USUAL-OPSYS="note" NOTE-START HP 9000 series 200 or 300 (-machine=hp9000s300) These machines are 68000-series CPUs running HP-UX (a derivative of sysV with some BSD features) or BSD 4.3 ported by Utah. If you're running HP-UX, specify `-opsystem=hpux'. If you're running BSD, specify `-opsystem=bsd4-3'. NOTE-END */ /* I don't understand why we have to do this at all! -JimB */ #if 0 /* Do this here at the top of the file; including sys/wait.h may include <endian.h>, which defines BIG_ENDIAN, which will conflict with our definition of BIG_ENDIAN if we do this at the bottom. */ #ifndef NOT_C_CODE #ifndef NO_SHORTNAMES #include <sys/wait.h> #define WAITTYPE int #endif #define WRETCODE(w) (((w) >> 8) & 0377) #endif #endif /* Define NOMULTIPLEJOBS on versions of HPUX before 6.5. */ /* #define NOMULTIPLEJOBS */ /* Define this symbol if you are running a version of HP-UX which predates version 6.01 */ /* #define HPUX_5 */ /* Define WORDS_BIG_ENDIAN iff lowest-numbered byte in a word is the most significant byte. */ #define WORDS_BIG_ENDIAN /* Define NO_ARG_ARRAY if you cannot take the address of the first of a * group of arguments and treat it as an array of the arguments. */ /* #define NO_ARG_ARRAY */ /* Define WORD_MACHINE if addresses and such have * to be corrected before they can be used as byte counts. */ /* #define WORD_MACHINE */ /* Now define a symbol for the cpu type, if your compiler does not define it automatically. */ #ifndef hp9000s300 #define hp9000s300 #endif /* Use type int rather than a union, to represent Lisp_Object */ /* This is desirable for most machines. */ #define NO_UNION_TYPE /* Define EXPLICIT_SIGN_EXTEND if XINT must explicitly sign-extend the 24-bit bit field into an int. In other words, if bit fields are always unsigned. If you use NO_UNION_TYPE, this flag does not matter. */ #define EXPLICIT_SIGN_EXTEND /* Define CANNOT_DUMP on machines where unexec does not work. Then the function dump-emacs will not be defined and temacs will do (load "loadup") automatically unless told otherwise. */ /* #define CANNOT_DUMP */ /* Define VIRT_ADDR_VARIES if the virtual addresses of pure and impure space as loaded can vary, and even their relative order cannot be relied on. Otherwise Emacs assumes that text space precedes data space, numerically. */ /* #define VIRT_ADDR_VARIES */ /* For University of Utah 4.3bsd implementation on HP300s. The #ifndef __GNUC__ definitions are required for the "standard" cc, a very old, brain-dead version of PCC. */ #ifdef BSD4_3 /* Tell crt0.c that this is an ordinary 68020. */ #undef hp9000s300 #define m68000 #define CRT0_DUMMIES bogus_a6, #define HAVE_ALLOCA #ifndef __GNUC__ #define LIBS_DEBUG /* don't have -lg that works */ #define C_DEBUG_SWITCH /* don't support -g */ #endif #undef LOAD_AVE_TYPE #undef LOAD_AVE_CVT #define LOAD_AVE_TYPE long #define LOAD_AVE_CVT(x) ((int) (((double) (x)) / 2048.0 * 100.0)) #endif /* BSD4_3 */ #ifndef BSD4_3 /* The following definitions are for HPUX only. */ /* The symbol in the kernel where the load average is found is named _avenrun on this machine. */ #define LDAV_SYMBOL "_avenrun" /* Data type of load average, as read out of kmem. */ #define LOAD_AVE_TYPE double /* Convert that into an integer that is 100 for a load average of 1.0 */ #define LOAD_AVE_CVT(x) ((int) ((x) * 100.0)) #ifdef __GNUC__ #define HAVE_ALLOCA #endif /* This library is needed with -g, on the 200/300 only. */ #if !defined(__GNUC__) || defined(__HPUX_ASM__) #define LIBS_DEBUG /usr/lib/end.o #endif /* Need a TEXT_START. On the HP9000/s300 that is 0. */ #ifdef __GNUC__ #define TEXT_START 0 #endif /* The symbol FIONREAD is defined, but the feature does not work on the 200/300. */ #define BROKEN_FIONREAD /* In older versions of hpux, for unknown reasons, S_IFLNK is defined even though symbolic links do not exist. Make sure our conditionals based on S_IFLNK are not confused. Here we assume that stat.h is included before config.h so that we can override it here. Version 6 of HP-UX has symbolic links. */ #ifdef HPUX_5 #undef S_IFLNK #endif /* Define the BSTRING functions in terms of the sysV functions. Version 6 of HP-UX supplies these in the BSD library, but that library has reported bugs in `signal'. */ /* #ifdef HPUX_5 */ #define bcopy(a,b,s) memcpy (b,a,s) #define bzero(a,s) memset (a,0,s) #define bcmp memcmp /* #endif */ /* On USG systems these have different names. Version 6 of HP-UX supplies these in the BSD library, which we currently want to avoid using. */ /* #ifdef HPUX_5 */ #define index strchr #define rindex strrchr /* #endif */ /* Define C_SWITCH_MACHINE to be +X if you want the s200/300 * Emacs to run on both 68010 and 68020 based hp-ux's. * * Define OLD_HP_ASSEMBLER if you have an ancient assembler * * Define HPUX_68010 if you are using the new assembler but * compiling for a s200 (upgraded) or s310. 68010 based * processor without 68881. */ /* These switches increase the size of some internal C compiler tables. They are required for compiling the X11 interface files. */ #ifndef HPUX_5 #ifndef __GNUC__ #define C_SWITCH_MACHINE -Wc,-Nd4000,-Ns3000 #endif #endif /* Define NEED_BSDTTY if you have such. */ #ifndef NOMULTIPLEJOBS #define NEED_BSDTTY #endif #endif /* not BSD4_3 */
timcera/tstoolbox
src/tstoolbox/functions/rank.py
# -*- coding: utf-8 -*- """Collection of functions for the manipulation of time series.""" from __future__ import absolute_import, division, print_function import mando import pandas as pd import typic from mando.rst_text_formatter import RSTHelpFormatter from .. import tsutils try: from typing import Literal except ImportError: from typing_extensions import Literal @mando.command("rank", formatter_class=RSTHelpFormatter, doctype="numpy") @tsutils.doc(tsutils.docstrings) def rank_cli( input_ts="-", columns=None, start_date=None, end_date=None, dropna="no", skiprows=None, index_type="datetime", names=None, clean=False, axis=0, method="average", numeric_only=None, na_option="keep", ascending=True, pct=False, print_input=False, float_format="g", source_units=None, target_units=None, round_index=None, tablefmt="csv", ): """Compute numerical data ranks (1 through n) along axis. Equal values are assigned a rank depending on `method`. Parameters ---------- axis [optional, default is 0] 0 or 'index' for rows. 1 or 'columns' for columns. Index to direct ranking. method : str [optional, default is 'average'] +-----------------+--------------------------------+ | method argument | Description | +=================+================================+ | average | average rank of group | +-----------------+--------------------------------+ | min | lowest rank in group | +-----------------+--------------------------------+ | max | highest rank in group | +-----------------+--------------------------------+ | first | ranks assigned in order they | | | appear in the array | +-----------------+--------------------------------+ | dense | like 'min', but rank always | | | increases by 1 between groups | +-----------------+--------------------------------+ numeric_only [optional, default is None] Include only float, int, boolean data. Valid only for DataFrame or Panel objects. na_option : str [optional, default is 'keep'] +--------------------+--------------------------------+ | na_option argument | Description | +====================+================================+ | keep | leave NA values where they are | +--------------------+--------------------------------+ | top | smallest rank if ascending | +--------------------+--------------------------------+ | bottom | smallest rank if descending | +--------------------+--------------------------------+ ascending [optional, default is True] False ranks by high (1) to low (N) pct [optional, default is False] Computes percentage rank of data. {input_ts} {columns} {start_date} {end_date} {dropna} {skiprows} {index_type} {names} {clean} {print_input} {float_format} {source_units} {target_units} {round_index} {tablefmt} """ tsutils.printiso( rank( input_ts=input_ts, columns=columns, start_date=start_date, end_date=end_date, dropna=dropna, skiprows=skiprows, index_type=index_type, names=names, clean=clean, axis=axis, method=method, numeric_only=numeric_only, na_option=na_option, ascending=ascending, pct=pct, print_input=print_input, source_units=source_units, target_units=target_units, round_index=round_index, ), float_format=float_format, tablefmt=tablefmt, ) @typic.al def rank( input_ts="-", columns=None, start_date=None, end_date=None, dropna="no", skiprows=None, index_type="datetime", names=None, clean=False, axis: tsutils.IntGreaterEqualToZero = 0, method: Literal["average", "min", "max", "first", "dense"] = "average", numeric_only: bool = False, na_option: Literal["keep", "top", "bottom"] = "keep", ascending: bool = True, pct: bool = False, print_input=False, source_units=None, target_units=None, round_index=None, ): """Compute numerical data ranks (1 through n) along axis.""" tsd = tsutils.common_kwds( input_ts, skiprows=skiprows, names=names, index_type=index_type, start_date=start_date, end_date=end_date, pick=columns, round_index=round_index, dropna=dropna, source_units=source_units, target_units=target_units, clean=clean, ) # Trying to save some memory if print_input: otsd = tsd.copy() else: otsd = pd.DataFrame() return tsutils.return_input( print_input, otsd, tsd.rank( axis=axis, method=method, numeric_only=numeric_only, na_option=na_option, ascending=ascending, pct=pct, ), "rank", ) rank.__doc__ = rank_cli.__doc__
lechium/tvOS10Headers
System/Library/PrivateFrameworks/GeoServices.framework/GEOPDComponentValue.h
<gh_stars>1-10 /* * This header is generated by classdump-dyld 1.0 * on Wednesday, March 22, 2017 at 9:03:34 AM Mountain Standard Time * Operating System: Version 10.1 (Build 14U593) * Image Source: /System/Library/PrivateFrameworks/GeoServices.framework/GeoServices * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. */ #import <GeoServices/GeoServices-Structs.h> #import <ProtocolBuffer/PBCodable.h> #import <libobjc.A.dylib/NSCopying.h> @class GEOPDRoadAccessInfo, GEOPDAddress, GEOPDAddressObject, GEOPDAmenities, GEOPDBounds, GEOPDBusinessClaim, GEOPDCaptionedPhoto, GEOPDEntity, GEOPDETA, GEOPDExternalAction, GEOPDFactoid, GEOPDFlyover, GEOPDHours, GEOPDPhoto, GEOPDPlaceInfo, GEOPDPlacecardURL, GEOPDRating, GEOPDRawAttribute, GEOPDRestaurantReservationLink, GEOPDResultSnippet, GEOPDReview, GEOPDSimpleRestaurantMenuText, GEOPDSpatialLookupResult, GEOStyleAttributes, GEOPDTextBlock, GEOPDTip, GEOPDTransitAttribution, GEOPDTransitIncident, GEOPDTransitInfo, GEOPDTransitInfoSnippet, GEOPDTransitSchedule; @interface GEOPDComponentValue : PBCodable <NSCopying> { GEOPDRoadAccessInfo* _accessInfo; GEOPDAddress* _address; GEOPDAddressObject* _addressObject; GEOPDAmenities* _amenities; GEOPDBounds* _bounds; GEOPDBusinessClaim* _businessClaim; GEOPDCaptionedPhoto* _captionedPhoto; GEOPDEntity* _entity; GEOPDETA* _eta; GEOPDExternalAction* _externalAction; GEOPDFactoid* _factoid; GEOPDFlyover* _flyover; GEOPDHours* _hours; GEOPDPhoto* _photo; GEOPDPlaceInfo* _placeInfo; GEOPDPlacecardURL* _placecardUrl; GEOPDRating* _rating; GEOPDRawAttribute* _rawAttribute; GEOPDRestaurantReservationLink* _restaurantReservationLink; GEOPDResultSnippet* _resultSnippet; GEOPDReview* _review; GEOPDSimpleRestaurantMenuText* _simpleRestaurantMenuText; GEOPDSpatialLookupResult* _spatialLookupResult; GEOStyleAttributes* _styleAttributes; GEOPDTextBlock* _textBlock; GEOPDTip* _tip; GEOPDTransitAttribution* _transitAttribution; GEOPDTransitIncident* _transitIncident; GEOPDTransitInfo* _transitInfo; GEOPDTransitInfoSnippet* _transitInfoSnippet; GEOPDTransitSchedule* _transitSchedule; } @property (nonatomic,readonly) BOOL hasEntity; @property (nonatomic,retain) GEOPDEntity * entity; //@synthesize entity=_entity - In the implementation block @property (nonatomic,readonly) BOOL hasPlaceInfo; @property (nonatomic,retain) GEOPDPlaceInfo * placeInfo; //@synthesize placeInfo=_placeInfo - In the implementation block @property (nonatomic,readonly) BOOL hasAccessInfo; @property (nonatomic,retain) GEOPDRoadAccessInfo * accessInfo; //@synthesize accessInfo=_accessInfo - In the implementation block @property (nonatomic,readonly) BOOL hasBounds; @property (nonatomic,retain) GEOPDBounds * bounds; //@synthesize bounds=_bounds - In the implementation block @property (nonatomic,readonly) BOOL hasAddress; @property (nonatomic,retain) GEOPDAddress * address; //@synthesize address=_address - In the implementation block @property (nonatomic,readonly) BOOL hasRating; @property (nonatomic,retain) GEOPDRating * rating; //@synthesize rating=_rating - In the implementation block @property (nonatomic,readonly) BOOL hasReview; @property (nonatomic,retain) GEOPDReview * review; //@synthesize review=_review - In the implementation block @property (nonatomic,readonly) BOOL hasPhoto; @property (nonatomic,retain) GEOPDPhoto * photo; //@synthesize photo=_photo - In the implementation block @property (nonatomic,readonly) BOOL hasHours; @property (nonatomic,retain) GEOPDHours * hours; //@synthesize hours=_hours - In the implementation block @property (nonatomic,readonly) BOOL hasTransitInfo; @property (nonatomic,retain) GEOPDTransitInfo * transitInfo; //@synthesize transitInfo=_transitInfo - In the implementation block @property (nonatomic,readonly) BOOL hasTransitSchedule; @property (nonatomic,retain) GEOPDTransitSchedule * transitSchedule; //@synthesize transitSchedule=_transitSchedule - In the implementation block @property (nonatomic,readonly) BOOL hasEta; @property (nonatomic,retain) GEOPDETA * eta; //@synthesize eta=_eta - In the implementation block @property (nonatomic,readonly) BOOL hasFlyover; @property (nonatomic,retain) GEOPDFlyover * flyover; //@synthesize flyover=_flyover - In the implementation block @property (nonatomic,readonly) BOOL hasRawAttribute; @property (nonatomic,retain) GEOPDRawAttribute * rawAttribute; //@synthesize rawAttribute=_rawAttribute - In the implementation block @property (nonatomic,readonly) BOOL hasAmenities; @property (nonatomic,retain) GEOPDAmenities * amenities; //@synthesize amenities=_amenities - In the implementation block @property (nonatomic,readonly) BOOL hasStyleAttributes; @property (nonatomic,retain) GEOStyleAttributes * styleAttributes; //@synthesize styleAttributes=_styleAttributes - In the implementation block @property (nonatomic,readonly) BOOL hasTransitIncident; @property (nonatomic,retain) GEOPDTransitIncident * transitIncident; //@synthesize transitIncident=_transitIncident - In the implementation block @property (nonatomic,readonly) BOOL hasTextBlock; @property (nonatomic,retain) GEOPDTextBlock * textBlock; //@synthesize textBlock=_textBlock - In the implementation block @property (nonatomic,readonly) BOOL hasFactoid; @property (nonatomic,retain) GEOPDFactoid * factoid; //@synthesize factoid=_factoid - In the implementation block @property (nonatomic,readonly) BOOL hasTransitAttribution; @property (nonatomic,retain) GEOPDTransitAttribution * transitAttribution; //@synthesize transitAttribution=_transitAttribution - In the implementation block @property (nonatomic,readonly) BOOL hasBusinessClaim; @property (nonatomic,retain) GEOPDBusinessClaim * businessClaim; //@synthesize businessClaim=_businessClaim - In the implementation block @property (nonatomic,readonly) BOOL hasCaptionedPhoto; @property (nonatomic,retain) GEOPDCaptionedPhoto * captionedPhoto; //@synthesize captionedPhoto=_captionedPhoto - In the implementation block @property (nonatomic,readonly) BOOL hasTransitInfoSnippet; @property (nonatomic,retain) GEOPDTransitInfoSnippet * transitInfoSnippet; //@synthesize transitInfoSnippet=_transitInfoSnippet - In the implementation block @property (nonatomic,readonly) BOOL hasExternalAction; @property (nonatomic,retain) GEOPDExternalAction * externalAction; //@synthesize externalAction=_externalAction - In the implementation block @property (nonatomic,readonly) BOOL hasResultSnippet; @property (nonatomic,retain) GEOPDResultSnippet * resultSnippet; //@synthesize resultSnippet=_resultSnippet - In the implementation block @property (nonatomic,readonly) BOOL hasAddressObject; @property (nonatomic,retain) GEOPDAddressObject * addressObject; //@synthesize addressObject=_addressObject - In the implementation block @property (nonatomic,readonly) BOOL hasSimpleRestaurantMenuText; @property (nonatomic,retain) GEOPDSimpleRestaurantMenuText * simpleRestaurantMenuText; //@synthesize simpleRestaurantMenuText=_simpleRestaurantMenuText - In the implementation block @property (nonatomic,readonly) BOOL hasRestaurantReservationLink; @property (nonatomic,retain) GEOPDRestaurantReservationLink * restaurantReservationLink; //@synthesize restaurantReservationLink=_restaurantReservationLink - In the implementation block @property (nonatomic,readonly) BOOL hasSpatialLookupResult; @property (nonatomic,retain) GEOPDSpatialLookupResult * spatialLookupResult; //@synthesize spatialLookupResult=_spatialLookupResult - In the implementation block @property (nonatomic,readonly) BOOL hasTip; @property (nonatomic,retain) GEOPDTip * tip; //@synthesize tip=_tip - In the implementation block @property (nonatomic,readonly) BOOL hasPlacecardUrl; @property (nonatomic,retain) GEOPDPlacecardURL * placecardUrl; //@synthesize placecardUrl=_placecardUrl - In the implementation block -(GEOPDBounds *)bounds; -(void)dealloc; -(void)setBounds:(GEOPDBounds *)arg1 ; -(BOOL)isEqual:(id)arg1 ; -(unsigned long long)hash; -(id)description; -(id)copyWithZone:(NSZone*)arg1 ; -(id)dictionaryRepresentation; -(BOOL)readFrom:(id)arg1 ; -(void)writeTo:(id)arg1 ; -(void)copyTo:(id)arg1 ; -(void)mergeFrom:(id)arg1 ; -(BOOL)hasAddress; -(GEOPDAddress *)address; -(void)setAddress:(GEOPDAddress *)arg1 ; -(BOOL)hasStyleAttributes; -(GEOStyleAttributes *)styleAttributes; -(void)setStyleAttributes:(GEOStyleAttributes *)arg1 ; -(BOOL)hasTextBlock; -(GEOPDAddressObject *)addressObject; -(BOOL)hasPlaceInfo; -(GEOPDPlaceInfo *)placeInfo; -(void)setPlaceInfo:(GEOPDPlaceInfo *)arg1 ; -(GEOPDRestaurantReservationLink *)restaurantReservationLink; -(void)setRestaurantReservationLink:(GEOPDRestaurantReservationLink *)arg1 ; -(BOOL)hasPhoto; -(GEOPDPhoto *)photo; -(void)setPhoto:(GEOPDPhoto *)arg1 ; -(BOOL)hasRating; -(GEOPDRating *)rating; -(void)setRating:(GEOPDRating *)arg1 ; -(BOOL)hasBounds; -(BOOL)hasAddressObject; -(void)setAddressObject:(GEOPDAddressObject *)arg1 ; -(BOOL)hasFlyover; -(GEOPDFlyover *)flyover; -(void)setFlyover:(GEOPDFlyover *)arg1 ; -(BOOL)hasEntity; -(BOOL)hasAccessInfo; -(BOOL)hasReview; -(BOOL)hasHours; -(BOOL)hasTransitInfo; -(BOOL)hasTransitSchedule; -(BOOL)hasEta; -(BOOL)hasRawAttribute; -(BOOL)hasAmenities; -(BOOL)hasTransitIncident; -(BOOL)hasFactoid; -(BOOL)hasTransitAttribution; -(BOOL)hasBusinessClaim; -(BOOL)hasCaptionedPhoto; -(BOOL)hasTransitInfoSnippet; -(BOOL)hasExternalAction; -(BOOL)hasResultSnippet; -(BOOL)hasSimpleRestaurantMenuText; -(BOOL)hasRestaurantReservationLink; -(BOOL)hasSpatialLookupResult; -(BOOL)hasTip; -(BOOL)hasPlacecardUrl; -(GEOPDEntity *)entity; -(void)setEntity:(GEOPDEntity *)arg1 ; -(GEOPDRoadAccessInfo *)accessInfo; -(void)setAccessInfo:(GEOPDRoadAccessInfo *)arg1 ; -(GEOPDReview *)review; -(void)setReview:(GEOPDReview *)arg1 ; -(GEOPDHours *)hours; -(void)setHours:(GEOPDHours *)arg1 ; -(GEOPDTransitInfo *)transitInfo; -(void)setTransitInfo:(GEOPDTransitInfo *)arg1 ; -(GEOPDTransitSchedule *)transitSchedule; -(void)setTransitSchedule:(GEOPDTransitSchedule *)arg1 ; -(GEOPDETA *)eta; -(void)setEta:(GEOPDETA *)arg1 ; -(GEOPDRawAttribute *)rawAttribute; -(void)setRawAttribute:(GEOPDRawAttribute *)arg1 ; -(GEOPDAmenities *)amenities; -(void)setAmenities:(GEOPDAmenities *)arg1 ; -(GEOPDTransitIncident *)transitIncident; -(void)setTransitIncident:(GEOPDTransitIncident *)arg1 ; -(GEOPDTextBlock *)textBlock; -(void)setTextBlock:(GEOPDTextBlock *)arg1 ; -(GEOPDFactoid *)factoid; -(void)setFactoid:(GEOPDFactoid *)arg1 ; -(GEOPDTransitAttribution *)transitAttribution; -(void)setTransitAttribution:(GEOPDTransitAttribution *)arg1 ; -(GEOPDBusinessClaim *)businessClaim; -(void)setBusinessClaim:(GEOPDBusinessClaim *)arg1 ; -(GEOPDCaptionedPhoto *)captionedPhoto; -(void)setCaptionedPhoto:(GEOPDCaptionedPhoto *)arg1 ; -(GEOPDTransitInfoSnippet *)transitInfoSnippet; -(void)setTransitInfoSnippet:(GEOPDTransitInfoSnippet *)arg1 ; -(GEOPDExternalAction *)externalAction; -(void)setExternalAction:(GEOPDExternalAction *)arg1 ; -(GEOPDResultSnippet *)resultSnippet; -(void)setResultSnippet:(GEOPDResultSnippet *)arg1 ; -(GEOPDSimpleRestaurantMenuText *)simpleRestaurantMenuText; -(void)setSimpleRestaurantMenuText:(GEOPDSimpleRestaurantMenuText *)arg1 ; -(GEOPDSpatialLookupResult *)spatialLookupResult; -(void)setSpatialLookupResult:(GEOPDSpatialLookupResult *)arg1 ; -(GEOPDTip *)tip; -(void)setTip:(GEOPDTip *)arg1 ; -(GEOPDPlacecardURL *)placecardUrl; -(void)setPlacecardUrl:(GEOPDPlacecardURL *)arg1 ; @end
nogamenofun98/openreplay
ee/connectors/db/tables.py
from pathlib import Path base_path = Path(__file__).parent.parent def create_tables_clickhouse(db): with open(base_path / 'sql' / 'clickhouse_events.sql') as f: q = f.read() db.engine.execute(q) print(f"`connector_user_events` table created succesfully.") with open(base_path / 'sql' / 'clickhouse_events_buffer.sql') as f: q = f.read() db.engine.execute(q) print(f"`connector_user_events_buffer` table created succesfully.") with open(base_path / 'sql' / 'clickhouse_sessions.sql') as f: q = f.read() db.engine.execute(q) print(f"`connector_sessions` table created succesfully.") with open(base_path / 'sql' / 'clickhouse_sessions_buffer.sql') as f: q = f.read() db.engine.execute(q) print(f"`connector_sessions_buffer` table created succesfully.") def create_tables_postgres(db): with open(base_path / 'sql' / 'postgres_events.sql') as f: q = f.read() db.engine.execute(q) print(f"`connector_user_events` table created succesfully.") with open(base_path / 'sql' / 'postgres_sessions.sql') as f: q = f.read() db.engine.execute(q) print(f"`connector_sessions` table created succesfully.") def create_tables_snowflake(db): with open(base_path / 'sql' / 'snowflake_events.sql') as f: q = f.read() db.engine.execute(q) print(f"`connector_user_events` table created succesfully.") with open(base_path / 'sql' / 'snowflake_sessions.sql') as f: q = f.read() db.engine.execute(q) print(f"`connector_sessions` table created succesfully.") def create_tables_redshift(db): with open(base_path / 'sql' / 'redshift_events.sql') as f: q = f.read() db.engine.execute(q) print(f"`connector_user_events` table created succesfully.") with open(base_path / 'sql' / 'redshift_sessions.sql') as f: q = f.read() db.engine.execute(q) print(f"`connector_sessions` table created succesfully.")
mattbierner/atum
lib/builtin/meta/language_function.js
/** * @fileOverview Language function meta */ define(['exports', 'bes/record', 'atum/compute', 'atum/fun', 'atum/builtin/meta/func', 'atum/operations/declaration_binding', 'atum/operations/environment', 'atum/operations/execution_context', 'atum/operations/func', 'atum/operations/type_conversion', 'atum/operations/value_reference', 'atum/value/type', 'atum/value/value',], function(exports, record, compute, fun, meta_func, declaration_bindings, environment, execution_context, func, type_conversion, value_reference, type, value){ "use strict"; /* LanguageFunction ******************************************************************************/ /** * Meta object for a hosted language function defined in code. */ var LanguageFunction = record.extend(meta_func.Function, [ 'scope', 'strict', 'id', 'names', 'code', 'declarations', 'body']); LanguageFunction.prototype._call = function(ref, thisObj, args) { var self = this; return environment.environmentBlock( compute.sequence( compute.bind( environment.createDeclativeEnvironment(self.scope), function(env) { return declaration_bindings.initFunction(env, self.strict, ref, self.id, self.names, args, self.declarations); }), execution_context.withThisBinding(thisObj, self.body))); }; LanguageFunction.prototype.call = function(ref, thisObj, args) { var self = this, strict = this.strict; return value_reference.dereference(thisObj, function(t, thisObj) { if (!strict && !value.isObject(t)) { switch (t.type) { case type.UNDEFINED: case type.NULL: return compute.bind( execution_context.thisBinding, function(t) { return self._call(ref, t, args); }); case type.STRING: case type.NUMBER: case type.BOOLEAN: return compute.bind( type_conversion.toObject(thisObj), function(t) { return func.forward(ref, t, args); }); } } return self._call(ref, thisObj, args); }); }; /* Export ******************************************************************************/ exports.LanguageFunction = LanguageFunction; });
Andrettin/Metternich
script/condition/has_trait_condition.h
<gh_stars>10-100 #pragma once #include "character/trait.h" #include "script/condition/condition.h" #include "script/condition/condition_check_base.h" namespace metternich { class trait; template <typename T> class has_trait_condition final : public condition<T> { public: has_trait_condition(const std::string &trait_identifier, const gsml_operator effect_operator) : condition<T>(effect_operator) { this->trait = trait::get(trait_identifier); } virtual const std::string &get_identifier() const override { static const std::string identifier = "trait"; return identifier; } virtual bool check_assignment(const T *scope) const override { return scope->has_trait(this->trait); } virtual void bind_condition_check(condition_check_base &check, const T *scope) const override { scope->connect(scope, &T::traits_changed, scope, [&check](){ check.set_result_recalculation_needed(); }, Qt::ConnectionType::DirectConnection); } virtual std::string get_assignment_string() const override { return this->get_equality_string(); } virtual std::string get_equality_string() const override { return "Has the " + this->trait->get_name() + " trait"; } virtual std::string get_inequality_string() const override { return "Does not have the " + this->trait->get_name() + " trait"; } private: const trait *trait = nullptr; }; }
AnupamJha/Swiggy_CloudOptimise
nerdlets/cloud-optimize-core/components/home/index.js
<reponame>AnupamJha/Swiggy_CloudOptimise<filename>nerdlets/cloud-optimize-core/components/home/index.js import React from 'react'; import { DataConsumer } from '../../context/data'; import { Loader, Dimmer, Header } from 'semantic-ui-react'; import Tiles from './tiles'; export default class Home extends React.PureComponent { render() { return ( <DataConsumer> {({ fetchingEntities, postProcessing, rawEntities, entityDataProgress, accountConfigProgress, cloudPricingProgress, workloadCostProgress, workloadConfigProgress, instanceOptimizerRunComplete }) => { const isLoading = (fetchingEntities === true || postProcessing === true) && instanceOptimizerRunComplete === false; return ( <> <Dimmer active={isLoading}> <Loader size="large"> Please be patient while we analyze your entities... <br /> <br /> {fetchingEntities ? ( <> Fetching {rawEntities.length} entities <br /> <br /> </> ) : ( '' )} {!fetchingEntities && postProcessing ? ( <> Processing {rawEntities.length} entities <br /> <br /> </> ) : ( '' )} {`Entity data ${entityDataProgress.toFixed(2)}%`} <br /> <br /> {`Cloud pricing ${cloudPricingProgress.toFixed(2)}%`} <br /> <br /> {`Account configs ${accountConfigProgress.toFixed(2)}%`} <br /> <br /> {`Workload configs ${workloadConfigProgress.toFixed(2)}%`} <br /> <br /> {`Workload costs ${workloadCostProgress.toFixed(2)}%`} </Loader> </Dimmer> <Header as="h3" content="Optimizers" style={{ paddingTop: 0, marginTop: 0 }} /> <Tiles /> </> ); }} </DataConsumer> ); } }
smourapina/algorithms
src/main/java/iurii/job/interview/amazon/CountNegativeIntegersInRowColumnWiseSortedMatrix.java
<gh_stars>10-100 package iurii.job.interview.amazon; /** * There is a matrix each row and each column is sorted ascending. * Count the number of negative numbers * * https://www.youtube.com/watch?v=5dJSZLmDsxk * * Example * -3, -2, -1, 1 * -2, 2, 3, 4 * 4, 5, 7, 8 * Answer: 4 (-3, -2, -2, -1) * * Solutions: * 1) Brute force: iterate through all the matrix and count: n * m complexity * 2) We can start from the right top corner and search first negative number to the left * (all over numbers will be negative as well because row is sorted) when number of negative elements in a row found, * we move to the next row without changing the current column (can be possible because columns are sorted as well) * * Time complexity will be O(n + m) (number of rows + number of columns) * Auxiliary space O(1) for count * Created by IuriiDziuban on 6/15/17. */ public class CountNegativeIntegersInRowColumnWiseSortedMatrix { public int count(int[][] matrix) { // preconditions: should have at least have one element if (matrix == null) { throw new IllegalArgumentException("matrix should not be null"); } int height = matrix.length; if (height == 0) { throw new IllegalArgumentException("matrix should not be empty"); } // initial values int width = matrix[0].length; int i = 0; int j = width - 1; int negativeCount = 0; // solution while (i < height && j >= 0) { if (matrix[i][j] >= 0) { j--; } else { negativeCount += j + 1; i++; } } return negativeCount; } }
yqboots/platform-services
commerce/order-fulfillment/src/main/java/com/yqboots/commerce/order/fulfillment/OrderFulfillmentApplication.java
<reponame>yqboots/platform-services<gh_stars>0 package com.yqboots.commerce.order.fulfillment; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class OrderFulfillmentApplication { public static void main(String[] args) { SpringApplication.run(OrderFulfillmentApplication.class, args); } }
sgholamian/log-aware-clone-detection
LACCPlus/ActiveMQ/143_2.java
<reponame>sgholamian/log-aware-clone-detection<filename>LACCPlus/ActiveMQ/143_2.java //,temp,JournalTopicMessageStore.java,121,130,temp,JournalMessageStore.java,124,132 //,3 public class xxx { public void afterRollback() throws Exception { if (debug) { LOG.debug("Transacted message add rollback for: " + id + ", at: " + location); } synchronized (JournalMessageStore.this) { inFlightTxLocations.remove(location); } message.decrementReferenceCount(); } };
xiaohaijin/RHIC-STAR
StRoot/StSpinPool/StChargedPionAnalysisMaker/StChargedPionBaseEv.cxx
// $Id: StChargedPionBaseEv.cxx,v 1.2 2010/09/02 02:46:34 perev Exp $ #include "StChargedPionBaseEv.h" #include <utility> using std::make_pair; ClassImp(StChargedPionBaseEv) // static member initialization static std::pair<unsigned int, unsigned int> a[] = { make_pair( 96011, 0x00000001), make_pair( 96201, 0x00000002), make_pair( 96211, 0x00000004), make_pair( 96221, 0x00000008), make_pair( 96233, 0x00000010), make_pair(117001, 0x00000020), make_pair(137213, 0x00000040), make_pair(137221, 0x00000080), make_pair(137222, 0x00000100), make_pair(137585, 0x00000200), make_pair(137611, 0x00000400), make_pair(137622, 0x00000800), make_pair(106011, 0x00001000), make_pair(106201, 0x00002000), make_pair(106211, 0x00004000), make_pair(106221, 0x00008000), make_pair(106233, 0x00010000), make_pair(117402, 0x00020000), make_pair(117211, 0x00040000), make_pair(117212, 0x00080000), make_pair(137262, 0x00100000), make_pair(137271, 0x00200000), make_pair(137272, 0x00400000), make_pair(137273, 0x00800000), make_pair(137641, 0x01000000), make_pair(137652, 0x02000000), // reuse some bits for transverse and first longitudinal running make_pair(127212, 0x00080000), make_pair(127213, 0x00000040), make_pair(117221, 0x00000080), make_pair(127221, 0x00000080), make_pair(117585, 0x00000200), make_pair(127585, 0x00000200), make_pair(117611, 0x00000400), make_pair(127611, 0x00000400), make_pair(117622, 0x00000800), make_pair(127622, 0x00000800), make_pair(117262, 0x00100000), make_pair(127262, 0x00100000), make_pair(117271, 0x00200000), make_pair(127271, 0x00200000), make_pair(117641, 0x01000000), make_pair(127641, 0x01000000), make_pair(117652, 0x02000000), make_pair(127652, 0x02000000) }; map<unsigned int, unsigned int> StChargedPionBaseEv::mTriggerLookup(a, a + sizeof(a)/sizeof(a[0]) ); unsigned int StChargedPionBaseEv::triggerBit(unsigned int trigId) { map<unsigned int, unsigned int>::const_iterator it = mTriggerLookup.find(trigId); if(it==mTriggerLookup.end()) return 0; return it->second; } /***************************************************************************** * $Log: StChargedPionBaseEv.cxx,v $ * Revision 1.2 2010/09/02 02:46:34 perev * Move variable a[] to static to avoid clash, bug #1993 * * Revision 1.1 2008/07/17 17:06:29 kocolosk * big-bang integration StChargedPionMcEvent framework * *****************************************************************************/
6391-Ursuline-Bearbotics/2022_UARobotics_Rapid_React
src/main/java/frc/robot/commands/Straight.java
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot.commands; import com.pathplanner.lib.PathPlanner; import com.pathplanner.lib.PathPlannerTrajectory; import edu.wpi.first.wpilibj2.command.InstantCommand; import edu.wpi.first.wpilibj2.command.SequentialCommandGroup; import frc.swervelib.SwerveSubsystem; public class Straight extends SequentialCommandGroup { public Straight(SwerveSubsystem m_swerve) { PathPlannerTrajectory trajectory1 = PathPlanner.loadPath("Straight2Meter", 0.5, 3.0); addCommands( new InstantCommand(() -> m_swerve.dt.setKnownState(trajectory1.getInitialState())), m_swerve.dt.createCommandForTrajectory(trajectory1, m_swerve) ); } }
DataBiosphere/terra-resource-janitor
src/main/java/bio/terra/janitor/db/TrackedResourceId.java
package bio.terra.janitor.db; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.google.auto.value.AutoValue; import java.util.UUID; /** Wraps the tracked_resource_id in db tracked_resource table. */ @AutoValue @JsonSerialize(as = TrackedResourceId.class) @JsonDeserialize(builder = AutoValue_TrackedResourceId.Builder.class) @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_ARRAY) public abstract class TrackedResourceId { @JsonProperty("uuid") public abstract UUID uuid(); public static TrackedResourceId create(UUID id) { return new AutoValue_TrackedResourceId.Builder().uuid(id).build(); } @Override public String toString() { return uuid().toString(); } /** Builder for {@link TrackedResourceId}. */ @AutoValue.Builder @JsonPOJOBuilder(withPrefix = "") public abstract static class Builder { public abstract Builder uuid(UUID value); public abstract TrackedResourceId build(); } }
dylanngo95/vitess
go/vt/vttablet/tabletmanager/replmanager_test.go
<reponame>dylanngo95/vitess /* Copyright 2020 The Vitess Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package tabletmanager import ( "testing" "time" "context" "github.com/stretchr/testify/assert" "vitess.io/vitess/go/vt/mysqlctl" topodatapb "vitess.io/vitess/go/vt/proto/topodata" ) func TestReplManagerSetTabletType(t *testing.T) { defer func(saved bool) { *mysqlctl.DisableActiveReparents = saved }(*mysqlctl.DisableActiveReparents) *mysqlctl.DisableActiveReparents = true tm := &TabletManager{} tm.replManager = newReplManager(context.Background(), tm, 100*time.Millisecond) // DisableActiveReparents == true should result in no-op *mysqlctl.DisableActiveReparents = true tm.replManager.SetTabletType(topodatapb.TabletType_REPLICA) assert.False(t, tm.replManager.ticks.Running()) // primary should stop the manager *mysqlctl.DisableActiveReparents = false tm.replManager.ticks.Start(nil) tm.replManager.SetTabletType(topodatapb.TabletType_PRIMARY) assert.False(t, tm.replManager.ticks.Running()) // If replcation is stopped, the manager should not start tm.replManager.setReplicationStopped(true) tm.replManager.ticks.Start(nil) tm.replManager.SetTabletType(topodatapb.TabletType_REPLICA) assert.False(t, tm.replManager.ticks.Running()) // If the manager is already running, rm.check should not be called tm.replManager.setReplicationStopped(false) tm.replManager.ticks.Start(nil) tm.replManager.SetTabletType(topodatapb.TabletType_REPLICA) assert.True(t, tm.replManager.ticks.Running()) tm.replManager.ticks.Stop() } func TestReplManagerSetReplicationStopped(t *testing.T) { defer func(saved bool) { *mysqlctl.DisableActiveReparents = saved }(*mysqlctl.DisableActiveReparents) *mysqlctl.DisableActiveReparents = true tm := &TabletManager{} tm.replManager = newReplManager(context.Background(), tm, 100*time.Millisecond) // DisableActiveReparents == true should result in no-op *mysqlctl.DisableActiveReparents = true tm.replManager.setReplicationStopped(true) assert.False(t, tm.replManager.ticks.Running()) tm.replManager.setReplicationStopped(false) assert.False(t, tm.replManager.ticks.Running()) *mysqlctl.DisableActiveReparents = false tm.replManager.setReplicationStopped(false) assert.True(t, tm.replManager.ticks.Running()) tm.replManager.setReplicationStopped(true) assert.False(t, tm.replManager.ticks.Running()) }
yeastrc/proxl-web-app
proxl_web_app/src/main/java/org/yeastrc/xlink/www/file_import_proxl_xml_scans/utils/Minimal_Validate_ProxlXMLFile_AndGetSearchNameIfInFile.java
package org.yeastrc.xlink.www.file_import_proxl_xml_scans.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Iterator; import javax.xml.stream.FactoryConfigurationError; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.Attribute; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; //import org.slf4j.LoggerFactory; import org.slf4j.Logger; import org.yeastrc.proxl_import.xsd_element_attr_names_constants.XSD_ElementAttributeNamesConstants; import org.yeastrc.xlink.www.exceptions.ProxlWebappDataException; /** * This does minimal validation of Proxl XML file * and retrieves search name if in the file * */ public class Minimal_Validate_ProxlXMLFile_AndGetSearchNameIfInFile { // private static final Logger log = LoggerFactory.getLogger( Minimal_Validate_ProxlXMLFile_AndGetSearchNameIfInFile.class ); // private constructor private Minimal_Validate_ProxlXMLFile_AndGetSearchNameIfInFile() { } /** * @return newly created instance */ public static Minimal_Validate_ProxlXMLFile_AndGetSearchNameIfInFile getInstance() { return new Minimal_Validate_ProxlXMLFile_AndGetSearchNameIfInFile(); } /** * This does minimal validation of Proxl XML file * and retrieves search name if in the file * * @param proxlXMLFile * @return - search name if in file * @throws FileNotFoundException * @throws FactoryConfigurationError * @throws XMLStreamException * @throws IOException * @throws ProxlWebappDataException */ public String minimal_Validate_ProxlXMLFile_AndGetSearchNameIfInFile( File proxlXMLFile ) throws FileNotFoundException, FactoryConfigurationError, XMLStreamException, IOException, ProxlWebappDataException { String searchName = null; InputStream proxlXMLFileInputStream = null; XMLEventReader xmlEventReader = null; try { proxlXMLFileInputStream = new FileInputStream( proxlXMLFile ); XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); xmlEventReader = xmlInputFactory.createXMLEventReader( proxlXMLFileInputStream ); while ( xmlEventReader.hasNext() ) { XMLEvent event = xmlEventReader.nextEvent(); if (event.isStartElement()) { StartElement startElement = event.asStartElement(); if ( ! startElement.getName().getLocalPart().equals( XSD_ElementAttributeNamesConstants.ROOT_ELEMENT_PROXL_INPUT__NAME ) ) { // The first element found is not the root element in the XSD so this is an error throw new ProxlWebappDataException( "Proxl XML root node is not '" + XSD_ElementAttributeNamesConstants.ROOT_ELEMENT_PROXL_INPUT__NAME + "'."); } // this is the Proxl XML Root element, process it // read the attributes from this tag for the // attribute to our object @SuppressWarnings("unchecked") Iterator<Attribute> attributes = startElement.getAttributes(); while (attributes.hasNext()) { Attribute attribute = attributes.next(); String attrName = attribute.getName().getLocalPart(); String attrValue = attribute.getValue(); if ( XSD_ElementAttributeNamesConstants.ATTR__NAME__ON_ROOT_ELEMENT_PROXL_INPUT__NAME.equals(attrName) ) { searchName = attrValue; } } break; // Exit Loop since processed first element } } } finally { if ( xmlEventReader != null ) { xmlEventReader.close(); } if ( proxlXMLFileInputStream != null ) { proxlXMLFileInputStream.close(); } } return searchName; } }
huangjianqin/kin-scheduler
kin-scheduler-core/src/main/java/org/kin/scheduler/core/driver/scheduler/TaskExecCallback.java
package org.kin.scheduler.core.driver.scheduler; import org.kin.scheduler.core.task.domain.TaskStatus; import java.io.Serializable; /** * task执行完成callback * * @author huangjianqin * @date 2020-03-09 */ public interface TaskExecCallback<R extends Serializable> { /** * @param taskId taskId * @param taskStatus task状态 * @param result task执行结果 * @param logPath task log路径 * @param outputPath task output路径 * @param reason task fail原因 */ void execFinish(String taskId, TaskStatus taskStatus, R result, String logPath, String outputPath, String reason); }
ceekay1991/AliPayForDebug
AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/AUULView.h
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by <NAME>. // #import <UIKit/UIView.h> @class NSArray; @interface AUULView : UIView { double _width; NSArray *_items; } @property(copy, nonatomic) NSArray *items; // @synthesize items=_items; @property(nonatomic) double width; // @synthesize width=_width; - (void).cxx_destruct; - (void)sizeToFit; - (void)layoutSubviews; - (void)setupUI; @end
jdekim43/terra.proto
js/src/terra/market/v1beta1/tx_pb.js
<gh_stars>0 // source: terra/market/v1beta1/tx.proto /** * @fileoverview * @enhanceable * @suppress {missingRequire} reports error on implicit type usages. * @suppress {messageConventions} JS Compiler reports an error if a variable or * field starts with 'MSG_' and isn't a translatable message. * @public */ // GENERATED CODE -- DO NOT EDIT! /* eslint-disable */ // @ts-nocheck var jspb = require('google-protobuf'); var goog = jspb; var global = Function('return this')(); var gogoproto_gogo_pb = require('../../../gogoproto/gogo_pb.js'); goog.object.extend(proto, gogoproto_gogo_pb); var cosmos_base_v1beta1_coin_pb = require('../../../cosmos/base/v1beta1/coin_pb.js'); goog.object.extend(proto, cosmos_base_v1beta1_coin_pb); goog.exportSymbol('proto.terra.market.v1beta1.MsgSwap', null, global); goog.exportSymbol('proto.terra.market.v1beta1.MsgSwapResponse', null, global); goog.exportSymbol('proto.terra.market.v1beta1.MsgSwapSend', null, global); goog.exportSymbol('proto.terra.market.v1beta1.MsgSwapSendResponse', null, global); /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.terra.market.v1beta1.MsgSwap = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.terra.market.v1beta1.MsgSwap, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.terra.market.v1beta1.MsgSwap.displayName = 'proto.terra.market.v1beta1.MsgSwap'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.terra.market.v1beta1.MsgSwapResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.terra.market.v1beta1.MsgSwapResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.terra.market.v1beta1.MsgSwapResponse.displayName = 'proto.terra.market.v1beta1.MsgSwapResponse'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.terra.market.v1beta1.MsgSwapSend = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.terra.market.v1beta1.MsgSwapSend, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.terra.market.v1beta1.MsgSwapSend.displayName = 'proto.terra.market.v1beta1.MsgSwapSend'; } /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.terra.market.v1beta1.MsgSwapSendResponse = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.terra.market.v1beta1.MsgSwapSendResponse, jspb.Message); if (goog.DEBUG && !COMPILED) { /** * @public * @override */ proto.terra.market.v1beta1.MsgSwapSendResponse.displayName = 'proto.terra.market.v1beta1.MsgSwapSendResponse'; } if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_<name>, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.terra.market.v1beta1.MsgSwap.prototype.toObject = function(opt_includeInstance) { return proto.terra.market.v1beta1.MsgSwap.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.terra.market.v1beta1.MsgSwap} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.terra.market.v1beta1.MsgSwap.toObject = function(includeInstance, msg) { var f, obj = { trader: jspb.Message.getFieldWithDefault(msg, 1, ""), offerCoin: (f = msg.getOfferCoin()) && cosmos_base_v1beta1_coin_pb.Coin.toObject(includeInstance, f), askDenom: jspb.Message.getFieldWithDefault(msg, 3, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.ByteSource} bytes The bytes to deserialize. * @return {!proto.terra.market.v1beta1.MsgSwap} */ proto.terra.market.v1beta1.MsgSwap.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.terra.market.v1beta1.MsgSwap; return proto.terra.market.v1beta1.MsgSwap.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.terra.market.v1beta1.MsgSwap} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.terra.market.v1beta1.MsgSwap} */ proto.terra.market.v1beta1.MsgSwap.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readString()); msg.setTrader(value); break; case 2: var value = new cosmos_base_v1beta1_coin_pb.Coin; reader.readMessage(value,cosmos_base_v1beta1_coin_pb.Coin.deserializeBinaryFromReader); msg.setOfferCoin(value); break; case 3: var value = /** @type {string} */ (reader.readString()); msg.setAskDenom(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.terra.market.v1beta1.MsgSwap.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.terra.market.v1beta1.MsgSwap.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.terra.market.v1beta1.MsgSwap} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.terra.market.v1beta1.MsgSwap.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getTrader(); if (f.length > 0) { writer.writeString( 1, f ); } f = message.getOfferCoin(); if (f != null) { writer.writeMessage( 2, f, cosmos_base_v1beta1_coin_pb.Coin.serializeBinaryToWriter ); } f = message.getAskDenom(); if (f.length > 0) { writer.writeString( 3, f ); } }; /** * optional string trader = 1; * @return {string} */ proto.terra.market.v1beta1.MsgSwap.prototype.getTrader = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.terra.market.v1beta1.MsgSwap} returns this */ proto.terra.market.v1beta1.MsgSwap.prototype.setTrader = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; /** * optional cosmos.base.v1beta1.Coin offer_coin = 2; * @return {?proto.cosmos.base.v1beta1.Coin} */ proto.terra.market.v1beta1.MsgSwap.prototype.getOfferCoin = function() { return /** @type{?proto.cosmos.base.v1beta1.Coin} */ ( jspb.Message.getWrapperField(this, cosmos_base_v1beta1_coin_pb.Coin, 2)); }; /** * @param {?proto.cosmos.base.v1beta1.Coin|undefined} value * @return {!proto.terra.market.v1beta1.MsgSwap} returns this */ proto.terra.market.v1beta1.MsgSwap.prototype.setOfferCoin = function(value) { return jspb.Message.setWrapperField(this, 2, value); }; /** * Clears the message field making it undefined. * @return {!proto.terra.market.v1beta1.MsgSwap} returns this */ proto.terra.market.v1beta1.MsgSwap.prototype.clearOfferCoin = function() { return this.setOfferCoin(undefined); }; /** * Returns whether this field is set. * @return {boolean} */ proto.terra.market.v1beta1.MsgSwap.prototype.hasOfferCoin = function() { return jspb.Message.getField(this, 2) != null; }; /** * optional string ask_denom = 3; * @return {string} */ proto.terra.market.v1beta1.MsgSwap.prototype.getAskDenom = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); }; /** * @param {string} value * @return {!proto.terra.market.v1beta1.MsgSwap} returns this */ proto.terra.market.v1beta1.MsgSwap.prototype.setAskDenom = function(value) { return jspb.Message.setProto3StringField(this, 3, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_<name>, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.terra.market.v1beta1.MsgSwapResponse.prototype.toObject = function(opt_includeInstance) { return proto.terra.market.v1beta1.MsgSwapResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.terra.market.v1beta1.MsgSwapResponse} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.terra.market.v1beta1.MsgSwapResponse.toObject = function(includeInstance, msg) { var f, obj = { swapCoin: (f = msg.getSwapCoin()) && cosmos_base_v1beta1_coin_pb.Coin.toObject(includeInstance, f), swapFee: (f = msg.getSwapFee()) && cosmos_base_v1beta1_coin_pb.Coin.toObject(includeInstance, f) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.ByteSource} bytes The bytes to deserialize. * @return {!proto.terra.market.v1beta1.MsgSwapResponse} */ proto.terra.market.v1beta1.MsgSwapResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.terra.market.v1beta1.MsgSwapResponse; return proto.terra.market.v1beta1.MsgSwapResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.terra.market.v1beta1.MsgSwapResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.terra.market.v1beta1.MsgSwapResponse} */ proto.terra.market.v1beta1.MsgSwapResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = new cosmos_base_v1beta1_coin_pb.Coin; reader.readMessage(value,cosmos_base_v1beta1_coin_pb.Coin.deserializeBinaryFromReader); msg.setSwapCoin(value); break; case 2: var value = new cosmos_base_v1beta1_coin_pb.Coin; reader.readMessage(value,cosmos_base_v1beta1_coin_pb.Coin.deserializeBinaryFromReader); msg.setSwapFee(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.terra.market.v1beta1.MsgSwapResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.terra.market.v1beta1.MsgSwapResponse.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.terra.market.v1beta1.MsgSwapResponse} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.terra.market.v1beta1.MsgSwapResponse.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getSwapCoin(); if (f != null) { writer.writeMessage( 1, f, cosmos_base_v1beta1_coin_pb.Coin.serializeBinaryToWriter ); } f = message.getSwapFee(); if (f != null) { writer.writeMessage( 2, f, cosmos_base_v1beta1_coin_pb.Coin.serializeBinaryToWriter ); } }; /** * optional cosmos.base.v1beta1.Coin swap_coin = 1; * @return {?proto.cosmos.base.v1beta1.Coin} */ proto.terra.market.v1beta1.MsgSwapResponse.prototype.getSwapCoin = function() { return /** @type{?proto.cosmos.base.v1beta1.Coin} */ ( jspb.Message.getWrapperField(this, cosmos_base_v1beta1_coin_pb.Coin, 1)); }; /** * @param {?proto.cosmos.base.v1beta1.Coin|undefined} value * @return {!proto.terra.market.v1beta1.MsgSwapResponse} returns this */ proto.terra.market.v1beta1.MsgSwapResponse.prototype.setSwapCoin = function(value) { return jspb.Message.setWrapperField(this, 1, value); }; /** * Clears the message field making it undefined. * @return {!proto.terra.market.v1beta1.MsgSwapResponse} returns this */ proto.terra.market.v1beta1.MsgSwapResponse.prototype.clearSwapCoin = function() { return this.setSwapCoin(undefined); }; /** * Returns whether this field is set. * @return {boolean} */ proto.terra.market.v1beta1.MsgSwapResponse.prototype.hasSwapCoin = function() { return jspb.Message.getField(this, 1) != null; }; /** * optional cosmos.base.v1beta1.Coin swap_fee = 2; * @return {?proto.cosmos.base.v1beta1.Coin} */ proto.terra.market.v1beta1.MsgSwapResponse.prototype.getSwapFee = function() { return /** @type{?proto.cosmos.base.v1beta1.Coin} */ ( jspb.Message.getWrapperField(this, cosmos_base_v1beta1_coin_pb.Coin, 2)); }; /** * @param {?proto.cosmos.base.v1beta1.Coin|undefined} value * @return {!proto.terra.market.v1beta1.MsgSwapResponse} returns this */ proto.terra.market.v1beta1.MsgSwapResponse.prototype.setSwapFee = function(value) { return jspb.Message.setWrapperField(this, 2, value); }; /** * Clears the message field making it undefined. * @return {!proto.terra.market.v1beta1.MsgSwapResponse} returns this */ proto.terra.market.v1beta1.MsgSwapResponse.prototype.clearSwapFee = function() { return this.setSwapFee(undefined); }; /** * Returns whether this field is set. * @return {boolean} */ proto.terra.market.v1beta1.MsgSwapResponse.prototype.hasSwapFee = function() { return jspb.Message.getField(this, 2) != null; }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_<name>, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.terra.market.v1beta1.MsgSwapSend.prototype.toObject = function(opt_includeInstance) { return proto.terra.market.v1beta1.MsgSwapSend.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.terra.market.v1beta1.MsgSwapSend} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.terra.market.v1beta1.MsgSwapSend.toObject = function(includeInstance, msg) { var f, obj = { fromAddress: jspb.Message.getFieldWithDefault(msg, 1, ""), toAddress: jspb.Message.getFieldWithDefault(msg, 2, ""), offerCoin: (f = msg.getOfferCoin()) && cosmos_base_v1beta1_coin_pb.Coin.toObject(includeInstance, f), askDenom: jspb.Message.getFieldWithDefault(msg, 4, "") }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.ByteSource} bytes The bytes to deserialize. * @return {!proto.terra.market.v1beta1.MsgSwapSend} */ proto.terra.market.v1beta1.MsgSwapSend.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.terra.market.v1beta1.MsgSwapSend; return proto.terra.market.v1beta1.MsgSwapSend.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.terra.market.v1beta1.MsgSwapSend} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.terra.market.v1beta1.MsgSwapSend} */ proto.terra.market.v1beta1.MsgSwapSend.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readString()); msg.setFromAddress(value); break; case 2: var value = /** @type {string} */ (reader.readString()); msg.setToAddress(value); break; case 3: var value = new cosmos_base_v1beta1_coin_pb.Coin; reader.readMessage(value,cosmos_base_v1beta1_coin_pb.Coin.deserializeBinaryFromReader); msg.setOfferCoin(value); break; case 4: var value = /** @type {string} */ (reader.readString()); msg.setAskDenom(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.terra.market.v1beta1.MsgSwapSend.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.terra.market.v1beta1.MsgSwapSend.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.terra.market.v1beta1.MsgSwapSend} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.terra.market.v1beta1.MsgSwapSend.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getFromAddress(); if (f.length > 0) { writer.writeString( 1, f ); } f = message.getToAddress(); if (f.length > 0) { writer.writeString( 2, f ); } f = message.getOfferCoin(); if (f != null) { writer.writeMessage( 3, f, cosmos_base_v1beta1_coin_pb.Coin.serializeBinaryToWriter ); } f = message.getAskDenom(); if (f.length > 0) { writer.writeString( 4, f ); } }; /** * optional string from_address = 1; * @return {string} */ proto.terra.market.v1beta1.MsgSwapSend.prototype.getFromAddress = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); }; /** * @param {string} value * @return {!proto.terra.market.v1beta1.MsgSwapSend} returns this */ proto.terra.market.v1beta1.MsgSwapSend.prototype.setFromAddress = function(value) { return jspb.Message.setProto3StringField(this, 1, value); }; /** * optional string to_address = 2; * @return {string} */ proto.terra.market.v1beta1.MsgSwapSend.prototype.getToAddress = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); }; /** * @param {string} value * @return {!proto.terra.market.v1beta1.MsgSwapSend} returns this */ proto.terra.market.v1beta1.MsgSwapSend.prototype.setToAddress = function(value) { return jspb.Message.setProto3StringField(this, 2, value); }; /** * optional cosmos.base.v1beta1.Coin offer_coin = 3; * @return {?proto.cosmos.base.v1beta1.Coin} */ proto.terra.market.v1beta1.MsgSwapSend.prototype.getOfferCoin = function() { return /** @type{?proto.cosmos.base.v1beta1.Coin} */ ( jspb.Message.getWrapperField(this, cosmos_base_v1beta1_coin_pb.Coin, 3)); }; /** * @param {?proto.cosmos.base.v1beta1.Coin|undefined} value * @return {!proto.terra.market.v1beta1.MsgSwapSend} returns this */ proto.terra.market.v1beta1.MsgSwapSend.prototype.setOfferCoin = function(value) { return jspb.Message.setWrapperField(this, 3, value); }; /** * Clears the message field making it undefined. * @return {!proto.terra.market.v1beta1.MsgSwapSend} returns this */ proto.terra.market.v1beta1.MsgSwapSend.prototype.clearOfferCoin = function() { return this.setOfferCoin(undefined); }; /** * Returns whether this field is set. * @return {boolean} */ proto.terra.market.v1beta1.MsgSwapSend.prototype.hasOfferCoin = function() { return jspb.Message.getField(this, 3) != null; }; /** * optional string ask_denom = 4; * @return {string} */ proto.terra.market.v1beta1.MsgSwapSend.prototype.getAskDenom = function() { return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 4, "")); }; /** * @param {string} value * @return {!proto.terra.market.v1beta1.MsgSwapSend} returns this */ proto.terra.market.v1beta1.MsgSwapSend.prototype.setAskDenom = function(value) { return jspb.Message.setProto3StringField(this, 4, value); }; if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto. * Field names that are reserved in JavaScript and will be renamed to pb_name. * Optional fields that are not set will be set to undefined. * To access a reserved field use, foo.pb_<name>, eg, foo.pb_default. * For the list of reserved names please see: * net/proto2/compiler/js/internal/generator.cc#kKeyword. * @param {boolean=} opt_includeInstance Deprecated. whether to include the * JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @return {!Object} */ proto.terra.market.v1beta1.MsgSwapSendResponse.prototype.toObject = function(opt_includeInstance) { return proto.terra.market.v1beta1.MsgSwapSendResponse.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Deprecated. Whether to include * the JSPB instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.terra.market.v1beta1.MsgSwapSendResponse} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.terra.market.v1beta1.MsgSwapSendResponse.toObject = function(includeInstance, msg) { var f, obj = { swapCoin: (f = msg.getSwapCoin()) && cosmos_base_v1beta1_coin_pb.Coin.toObject(includeInstance, f), swapFee: (f = msg.getSwapFee()) && cosmos_base_v1beta1_coin_pb.Coin.toObject(includeInstance, f) }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.ByteSource} bytes The bytes to deserialize. * @return {!proto.terra.market.v1beta1.MsgSwapSendResponse} */ proto.terra.market.v1beta1.MsgSwapSendResponse.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.terra.market.v1beta1.MsgSwapSendResponse; return proto.terra.market.v1beta1.MsgSwapSendResponse.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.terra.market.v1beta1.MsgSwapSendResponse} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.terra.market.v1beta1.MsgSwapSendResponse} */ proto.terra.market.v1beta1.MsgSwapSendResponse.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { case 1: var value = new cosmos_base_v1beta1_coin_pb.Coin; reader.readMessage(value,cosmos_base_v1beta1_coin_pb.Coin.deserializeBinaryFromReader); msg.setSwapCoin(value); break; case 2: var value = new cosmos_base_v1beta1_coin_pb.Coin; reader.readMessage(value,cosmos_base_v1beta1_coin_pb.Coin.deserializeBinaryFromReader); msg.setSwapFee(value); break; default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.terra.market.v1beta1.MsgSwapSendResponse.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.terra.market.v1beta1.MsgSwapSendResponse.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.terra.market.v1beta1.MsgSwapSendResponse} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.terra.market.v1beta1.MsgSwapSendResponse.serializeBinaryToWriter = function(message, writer) { var f = undefined; f = message.getSwapCoin(); if (f != null) { writer.writeMessage( 1, f, cosmos_base_v1beta1_coin_pb.Coin.serializeBinaryToWriter ); } f = message.getSwapFee(); if (f != null) { writer.writeMessage( 2, f, cosmos_base_v1beta1_coin_pb.Coin.serializeBinaryToWriter ); } }; /** * optional cosmos.base.v1beta1.Coin swap_coin = 1; * @return {?proto.cosmos.base.v1beta1.Coin} */ proto.terra.market.v1beta1.MsgSwapSendResponse.prototype.getSwapCoin = function() { return /** @type{?proto.cosmos.base.v1beta1.Coin} */ ( jspb.Message.getWrapperField(this, cosmos_base_v1beta1_coin_pb.Coin, 1)); }; /** * @param {?proto.cosmos.base.v1beta1.Coin|undefined} value * @return {!proto.terra.market.v1beta1.MsgSwapSendResponse} returns this */ proto.terra.market.v1beta1.MsgSwapSendResponse.prototype.setSwapCoin = function(value) { return jspb.Message.setWrapperField(this, 1, value); }; /** * Clears the message field making it undefined. * @return {!proto.terra.market.v1beta1.MsgSwapSendResponse} returns this */ proto.terra.market.v1beta1.MsgSwapSendResponse.prototype.clearSwapCoin = function() { return this.setSwapCoin(undefined); }; /** * Returns whether this field is set. * @return {boolean} */ proto.terra.market.v1beta1.MsgSwapSendResponse.prototype.hasSwapCoin = function() { return jspb.Message.getField(this, 1) != null; }; /** * optional cosmos.base.v1beta1.Coin swap_fee = 2; * @return {?proto.cosmos.base.v1beta1.Coin} */ proto.terra.market.v1beta1.MsgSwapSendResponse.prototype.getSwapFee = function() { return /** @type{?proto.cosmos.base.v1beta1.Coin} */ ( jspb.Message.getWrapperField(this, cosmos_base_v1beta1_coin_pb.Coin, 2)); }; /** * @param {?proto.cosmos.base.v1beta1.Coin|undefined} value * @return {!proto.terra.market.v1beta1.MsgSwapSendResponse} returns this */ proto.terra.market.v1beta1.MsgSwapSendResponse.prototype.setSwapFee = function(value) { return jspb.Message.setWrapperField(this, 2, value); }; /** * Clears the message field making it undefined. * @return {!proto.terra.market.v1beta1.MsgSwapSendResponse} returns this */ proto.terra.market.v1beta1.MsgSwapSendResponse.prototype.clearSwapFee = function() { return this.setSwapFee(undefined); }; /** * Returns whether this field is set. * @return {boolean} */ proto.terra.market.v1beta1.MsgSwapSendResponse.prototype.hasSwapFee = function() { return jspb.Message.getField(this, 2) != null; }; goog.object.extend(exports, proto.terra.market.v1beta1);
aiw-google/openweave-core
third_party/android/platform-libcore/android-platform-libcore/luni/src/test/java/org/apache/harmony/sql/tests/java/sql/DatabaseMetaDataTest.java
<filename>third_party/android/platform-libcore/android-platform-libcore/luni/src/test/java/org/apache/harmony/sql/tests/java/sql/DatabaseMetaDataTest.java /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.harmony.sql.tests.java.sql; import dalvik.annotation.TestTargetClass; import dalvik.annotation.TestTargets; import dalvik.annotation.TestLevel; import dalvik.annotation.TestTargetNew; import java.sql.DatabaseMetaData; import junit.framework.TestCase; @TestTargetClass(java.sql.DatabaseMetaData.class) public class DatabaseMetaDataTest extends TestCase { /* * Public statics test */ @TestTargetNew( level = TestLevel.COMPLETE, notes = "Field testing", method = "!Constants", args = {} ) public void testPublicStatics() { assertEquals(0, DatabaseMetaData.attributeNoNulls); assertEquals(1, DatabaseMetaData.attributeNullable); assertEquals(2, DatabaseMetaData.attributeNullableUnknown); assertEquals(1, DatabaseMetaData.bestRowNotPseudo); assertEquals(2, DatabaseMetaData.bestRowPseudo); assertEquals(2, DatabaseMetaData.bestRowSession); assertEquals(0, DatabaseMetaData.bestRowTemporary); assertEquals(1, DatabaseMetaData.bestRowTransaction); assertEquals(0, DatabaseMetaData.bestRowUnknown); assertEquals(0, DatabaseMetaData.columnNoNulls); assertEquals(1, DatabaseMetaData.columnNullable); assertEquals(2, DatabaseMetaData.columnNullableUnknown); assertEquals(1, DatabaseMetaData.functionColumnIn); assertEquals(2, DatabaseMetaData.functionColumnInOut); assertEquals(3, DatabaseMetaData.functionColumnOut); assertEquals(5, DatabaseMetaData.functionColumnResult); assertEquals(0, DatabaseMetaData.functionColumnUnknown); assertEquals(0, DatabaseMetaData.functionNoNulls); assertEquals(1, DatabaseMetaData.functionNoTable); assertEquals(1, DatabaseMetaData.functionNullable); assertEquals(2, DatabaseMetaData.functionNullableUnknown); assertEquals(0, DatabaseMetaData.functionResultUnknown); assertEquals(4, DatabaseMetaData.functionReturn); assertEquals(2, DatabaseMetaData.functionReturnsTable); assertEquals(0, DatabaseMetaData.importedKeyCascade); assertEquals(5, DatabaseMetaData.importedKeyInitiallyDeferred); assertEquals(6, DatabaseMetaData.importedKeyInitiallyImmediate); assertEquals(3, DatabaseMetaData.importedKeyNoAction); assertEquals(7, DatabaseMetaData.importedKeyNotDeferrable); assertEquals(1, DatabaseMetaData.importedKeyRestrict); assertEquals(4, DatabaseMetaData.importedKeySetDefault); assertEquals(2, DatabaseMetaData.importedKeySetNull); assertEquals(1, DatabaseMetaData.procedureColumnIn); assertEquals(2, DatabaseMetaData.procedureColumnInOut); assertEquals(4, DatabaseMetaData.procedureColumnOut); assertEquals(3, DatabaseMetaData.procedureColumnResult); assertEquals(5, DatabaseMetaData.procedureColumnReturn); assertEquals(0, DatabaseMetaData.procedureColumnUnknown); assertEquals(0, DatabaseMetaData.procedureNoNulls); assertEquals(1, DatabaseMetaData.procedureNoResult); assertEquals(1, DatabaseMetaData.procedureNullable); assertEquals(2, DatabaseMetaData.procedureNullableUnknown); assertEquals(0, DatabaseMetaData.procedureResultUnknown); assertEquals(2, DatabaseMetaData.procedureReturnsResult); assertEquals(2, DatabaseMetaData.sqlStateSQL); assertEquals(2, DatabaseMetaData.sqlStateSQL99); assertEquals(1, DatabaseMetaData.sqlStateXOpen); assertEquals(1, DatabaseMetaData.tableIndexClustered); assertEquals(2, DatabaseMetaData.tableIndexHashed); assertEquals(3, DatabaseMetaData.tableIndexOther); assertEquals(0, DatabaseMetaData.tableIndexStatistic); assertEquals(0, DatabaseMetaData.typeNoNulls); assertEquals(1, DatabaseMetaData.typeNullable); assertEquals(2, DatabaseMetaData.typeNullableUnknown); assertEquals(2, DatabaseMetaData.typePredBasic); assertEquals(1, DatabaseMetaData.typePredChar); assertEquals(0, DatabaseMetaData.typePredNone); assertEquals(3, DatabaseMetaData.typeSearchable); assertEquals(1, DatabaseMetaData.versionColumnNotPseudo); assertEquals(2, DatabaseMetaData.versionColumnPseudo); assertEquals(0, DatabaseMetaData.versionColumnUnknown); } // end method testPublicStatics } // end class DatabaseMetaDataTest
gsnedders/presto-testo
core/standards/scripts/opjsunit/tests/testURI_spec.js
var uri_reserved = [";", "/", "?", ":", "@", "&", "=", "+", "$", ","]; var uri_alpha = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]; var decimal_digit = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]; var uri_mark = ["-", "_", ".", "!", "~", "*", "'", "(", ")"]; var uri_unescaped = [].concat(uri_alpha, decimal_digit, uri_mark); function testEncodeURI_0() { //Check that all characters that are not supposed to be encoded are not var unencoded_characters = ["#"].concat(uri_reserved, uri_unescaped); for (var i=0; i<unencoded_characters.length; i++) { assertEquals(unencoded_characters[i], encodeURI(unencoded_characters[i])); } } function testEncodeURI_1() { assertEquals("%00", encodeURI("\u0000")); } function testEncodeURI_2() { assertEquals("%C3%A6", encodeURI("\u00E6")); } function testEncodeURI_3() { assertEquals("%C3%A6", encodeURI("\u00E6")); } function testEncodeURI_4() { assertEquals("%E1%A7%A0", encodeURI("\u19E0")); } function testEncodeURI_5() { assertEquals("%EF%AE%AD", encodeURI("\uFBAD")); } function testEncodeURI_6() { //Second part of a surrogate pair not preceeded by the first assertThrows(URIError(), encodeURI, "\uDC00\u1234"); } testEncodeURI_6.metadata = { bug:"CARAKAN-115" }; function testEncodeURI_7() { //Second part of a surrogate pair not preceeded by the first assertThrows(URIError(), encodeURI, "\uDFFF\u1234"); } testEncodeURI_7.metadata = { bug:"CARAKAN-115" }; function testEncodeURI_8() { //First part of a surrogate pair not followed by the second assertThrows(URIError(), encodeURI, "\uD800\u1234"); } testEncodeURI_8.metadata = { bug:"CARAKAN-115" }; function testEncodeURI_9() { //First part of a surrogate pair not followed by the second assertThrows(URIError(), encodeURI, "\uDBFF\u1234"); } testEncodeURI_9.metadata = { bug:"CARAKAN-115" }; function testEncodeURI_10() { //Real surrogate pair assertEquals("%F0%90%80%80", encodeURI("\uD800\uDC00")); } function testEncodeURI_11() { //Real surrogate pair assertEquals("%F0%90%8F%BF", encodeURI("\uD800\uDFFF")); } function testEncodeURI_12() { //Real surrogate pair assertEquals("%F4%8F%B0%80", encodeURI("\uDBFF\uDC00")); } function testEncodeURI_13() { //Real surrogate pair assertEquals("%F4%8F%BF%BF", encodeURI("\uDBFF\uDFFF")); } function testEncodeURI_14() { //Real surrogate pair assertEquals("", encodeURI("")); } function testEncodeURI_15() { assertEquals("undefined", encodeURI()); } testEncodeURI_15.metadata = { bug:"CARAKAN-349" }; function testEncodeURIComponent_0() { //Check that all characters that are not supposed to be encoded are not var unencoded_characters = uri_unescaped; for (var i=0; i<unencoded_characters.length; i++) { assertEquals(unencoded_characters[i], encodeURIComponent(unencoded_characters[i])); } } function testEncodeURIComponent_1() { var encoded_characters = [].concat(uri_reserved); for (var i=0; i<encoded_characters.length; i++) { var expected = "%" + encoded_characters[i].charCodeAt(0).toString(16).toUpperCase(); assertEquals(expected, encodeURIComponent(encoded_characters[i])); } } function testEncodeURIComponent_2() { assertEquals("%00", encodeURIComponent("\u0000")); } function testEncodeURIComponent_3() { assertEquals("%C3%A6", encodeURIComponent("\u00E6")); } function testEncodeURIComponent_4() { assertEquals("%C3%A6", encodeURIComponent("\u00E6")); } function testEncodeURIComponent_5() { assertEquals("%E1%A7%A0", encodeURIComponent("\u19E0")); } function testEncodeURIComponent_6() { assertEquals("%EF%AE%AD", encodeURIComponent("\uFBAD")); } function testEncodeURIComponent_7() { //Second part of a surrogate pair not preceeded by the first assertThrows(URIError(), encodeURIComponent, "\uDC00\u1234"); } testEncodeURIComponent_7.metadata = { bug:"CARAKAN-115" }; function testEncodeURIComponent_8() { //Second part of a surrogate pair not preceeded by the first assertThrows(URIError(), encodeURIComponent, "\uDFFF\u1234"); } testEncodeURIComponent_8.metadata = { bug:"CARAKAN-115" }; function testEncodeURIComponent_9() { //First part of a surrogate pair not followed by the second assertThrows(URIError(), encodeURIComponent, "\uD800\u1234"); } testEncodeURIComponent_9.metadata = { bug:"CARAKAN-115" }; function testEncodeURIComponent_10() { //First part of a surrogate pair not followed by the second assertThrows(URIError(), encodeURIComponent, "\uDBFF\u1234"); } testEncodeURIComponent_10.metadata = { bug:"CARAKAN-115" }; function testEncodeURIComponent_11() { //Real surrogate pair assertEquals("%F0%90%80%80", encodeURIComponent("\uD800\uDC00")); } function testEncodeURIComponent_12() { //Real surrogate pair assertEquals("%F0%90%8F%BF", encodeURIComponent("\uD800\uDFFF")); } function testEncodeURIComponent_13() { //Real surrogate pair assertEquals("%F4%8F%B0%80", encodeURIComponent("\uDBFF\uDC00")); } function testEncodeURIComponent_14() { //Real surrogate pair assertEquals("%F4%8F%BF%BF", encodeURIComponent("\uDBFF\uDFFF")); } function testEncodeURIComponent_15() { assertEquals("", encodeURIComponent("")); } function testEncodeURIComponent_16() { assertEquals("undefined", encodeURIComponent()); } testEncodeURIComponent_16.metadata = { bug:"CARAKAN-349" }; function testDecodeURI_0() { assertEquals("", decodeURI("")); } function testDecodeURI_1() { //characters in reserved_set do not get decoded var reserved_set = ["#"].concat(uri_reserved); for (var i=0; i < reserved_set.length; i++) { var character = reserved_set[i]; var encoded = encodeURIComponent(character); assertEquals(encoded, decodeURI(encoded)); } } function testDecodeURI_1() { //characters in uri_unescaped do get decoded for (var i=0; i < uri_unescaped.length; i++) { var character = uri_unescaped[i]; var encoded = encodeURIComponent(character); assertEquals(character, decodeURI(encoded)); } } function testDecodeURI_2() { //If the characters are not encoded to start with nothing bad happens for (var i=0; i < uri_unescaped.length; i++) { var character = uri_unescaped[i]; assertEquals(character, decodeURI(character)); } } function testDecodeURI_3() { assertThrows(URIError(), decodeURI, "%"); } function testDecodeURI_4() { assertThrows(URIError(), decodeURI, "%2"); } function testDecodeURI_5() { assertEquals("\u0000", decodeURI("%00")); } function testDecodeURI_6() { assertEquals("\u007F", decodeURI("%7f")); } function testDecodeURI_7() { assertEquals("\u007F", decodeURI("%7f")); } function testDecodeURI_8() { assertThrows(URIError(), decodeURI, "%7g"); } function testDecodeURI_9() { //Can only be the second byte in a multi byte UTF-8 sequence assertThrows(URIError(), decodeURI, "%80"); } testDecodeURI_9.metadata = { bug:"CARAKAN-126" }; function testDecodeURI_10() { //First byte in 2 byte sequence not followed by second assertThrows(URIError(), decodeURI, "%C0"); } testDecodeURI_10.metadata = { bug:"CARAKAN-126" }; function testDecodeURI_11() { //First byte in 2 byte sequence followed by incorrect second assertThrows(URIError(), decodeURI, "%C0%7F"); } testDecodeURI_11.metadata = { bug:"CARAKAN-126" }; function testDecodeURI_12() { //First byte in 2 byte sequence followed by incorrect second assertThrows(URIError(), decodeURI, "%C0%C0"); } testDecodeURI_12.metadata = { bug:"CARAKAN-126" }; function testDecodeURI_13() { //Valid two-byte sequence assertEquals("\u018F", decodeURI("%C6%8F")); } function testDecodeURI_14() { assertEquals("\u07FF", decodeURI("%df%bf")); } function testDecodeURI_15() { //First byte in 3-byte UTF8 sequence not followed by second assertThrows(URIError(), decodeURI, "%e0"); } testDecodeURI_15.metadata = { bug:"CARAKAN-126" }; function testDecodeURI_16() { //First byte in 3-byte UTF8 sequence followed by second but not third assertThrows(URIError(), decodeURI, "%e0%80"); } testDecodeURI_16.metadata = { bug:"CARAKAN-126" }; function testDecodeURI_17() { //Valid 3 byte sequence assertEquals("\u0800", decodeURI("%e0%a0%80")); } function testDecodeURI_18() { //Valid 3 byte sequence assertEquals("\uD7FF", decodeURI("%ed%9f%bf")); } function testDecodeURI_19() { //Valid 3 byte sequence assertEquals("\uE000", decodeURI('%ee%80%80')); } function testDecodeURI_20() { //Valid 3 byte sequence assertEquals("\uFFFF", decodeURI('%ef%bf%bf')); } function testDecodeURI_21() { //First byte of a four byte sequence followed by nothing assertThrows(URIError(), decodeURI, "%f0"); } testDecodeURI_21.metadata = { bug:"CARAKAN-126" }; function testDecodeURI_22() { //First byte of a four byte sequence followed by one byte assertThrows(URIError(), decodeURI, "%f0%80"); } testDecodeURI_22.metadata = { bug:"CARAKAN-126" }; function testDecodeURI_23() { //First byte of a four byte sequence followed by two bytes assertThrows(URIError(), decodeURI, "%f0%80%80"); } testDecodeURI_23.metadata = { bug:"CARAKAN-126" }; function testDecodeURI_24() { //Valid four byte sequence assertEquals("\uDBC0\uDC00", decodeURI("%f4%80%80%80")); } function testDecodeURI_25() { //Valid four byte sequence assertEquals("\uDBFF\uDFFF", decodeURI("%f4%8f%bf%bf")); } function testDecodeURI_26() { //Too big utf-8 sequence assertThrows(URIError(), decodeURI, "%f7%bf%bf%bf"); } testDecodeURI_26.metadata = { bug:"CARAKAN-126" }; function testDecodeURI_27() { assertEquals("a", decodeURI("%61")); } function testDecodeURI_28() { //Invalid first byte assertThrows(URIError(), decodeURI, "%F1"); } testDecodeURI_28.metadata = { bug:"CARAKAN-126" }; function testDecodeURI_29() { //Invalid first byte assertThrows(URIError(), decodeURI, "%F1"); } testDecodeURI_29.metadata = { bug:"CARAKAN-126" }; function testDecodeURI_30() { assertEquals("undefined", decodeURI()); } testDecodeURI_30.metadata = { bug:"CARAKAN-349" }; function testDecodeURIComponent_0() { assertEquals("", decodeURIComponent("")); } function testDecodeURIComponent_1() { //characters in #, uri_reserved /do/ not get decoded var characters = ["#"].concat(uri_reserved); for (var i=0; i < characters.length; i++) { var character = characters[i]; var encoded = encodeComponent(character); assertEquals(character, decodeURIComponent(encoded)); } } function testDecodeURIComponent_1() { //characters in uri_unescaped do get decoded for (var i=0; i < uri_unescaped.length; i++) { var character = uri_unescaped[i]; var encoded = encodeURIComponent(character); assertEquals(character, decodeURIComponent(encoded)); } } function testDecodeURIComponent_2() { //If the characters are not encoded to start with nothing bad happens for (var i=0; i < uri_unescaped.length; i++) { var character = uri_unescaped[i]; assertEquals(character, decodeURIComponent(character)); } } function testDecodeURIComponent_3() { assertThrows(URIError(), decodeURIComponent, "%"); } function testDecodeURIComponent_4() { assertThrows(URIError(), decodeURIComponent, "%2"); } function testDecodeURIComponent_5() { assertEquals("\u0000", decodeURIComponent("%00")); } function testDecodeURIComponent_6() { assertEquals("\u007F", decodeURIComponent("%7f")); } function testDecodeURIComponent_7() { assertEquals("\u007F", decodeURIComponent("%7f")); } function testDecodeURIComponent_8() { assertThrows(URIError(), decodeURIComponent, "%7g"); } function testDecodeURIComponent_9() { //Can only be the second byte in a multi byte UTF-8 sequence assertThrows(URIError(), decodeURIComponent, "%80"); } testDecodeURIComponent_9.metadata = { bug:"CARAKAN-126" }; function testDecodeURIComponent_10() { //First byte in 2 byte sequence not followed by second assertThrows(URIError(), decodeURIComponent, "%C0"); } testDecodeURIComponent_10.metadata = { bug:"CARAKAN-126" }; function testDecodeURIComponent_11() { //First byte in 2 byte sequence followed by incorrect second assertThrows(URIError(), decodeURIComponent, "%C0%7F"); } testDecodeURIComponent_11.metadata = { bug:"CARAKAN-126" }; function testDecodeURIComponent_12() { //First byte in 2 byte sequence followed by incorrect second assertThrows(URIError(), decodeURIComponent, "%C0%C0"); } testDecodeURIComponent_12.metadata = { bug:"CARAKAN-126" }; function testDecodeURIComponent_13() { //Valid two-byte sequence assertEquals("\u018F", decodeURIComponent("%C6%8F")); } function testDecodeURIComponent_14() { assertEquals("\u07FF", decodeURIComponent("%df%bf")); } function testDecodeURIComponent_15() { //First byte in 3-byte UTF8 sequence not followed by second assertThrows(URIError(), decodeURIComponent, "%e0"); } testDecodeURIComponent_15.metadata = { bug:"CARAKAN-126" }; function testDecodeURIComponent_16() { //First byte in 3-byte UTF8 sequence followed by second but not third assertThrows(URIError(), decodeURIComponent, "%e0%80"); } testDecodeURIComponent_16.metadata = { bug:"CARAKAN-126" }; function testDecodeURIComponent_17() { //Valid 3 byte sequence assertEquals("\u0800", decodeURIComponent("%e0%a0%80")); } function testDecodeURIComponent_18() { //Valid 3 byte sequence assertEquals("\uD7FF", decodeURIComponent("%ed%9f%bf")); } function testDecodeURIComponent_19() { //Valid 3 byte sequence assertEquals("\uE000", decodeURIComponent('%ee%80%80')); } function testDecodeURIComponent_20() { //Valid 3 byte sequence assertEquals("\uFFFF", decodeURIComponent('%ef%bf%bf')); } function testDecodeURIComponent_21() { //First byte of a four byte sequence followed by nothing assertThrows(URIError(), decodeURIComponent, "%f0"); } testDecodeURIComponent_21.metadata = { bug:"CARAKAN-126" }; function testDecodeURIComponent_22() { //First byte of a four byte sequence followed by one byte assertThrows(URIError(), decodeURIComponent, "%f0%80"); } testDecodeURIComponent_22.metadata = { bug:"CARAKAN-126" }; function testDecodeURIComponent_23() { //First byte of a four byte sequence followed by two bytes assertThrows(URIError(), decodeURIComponent, "%f0%80%80"); } testDecodeURIComponent_23.metadata = { bug:"CARAKAN-126" }; function testDecodeURIComponent_24() { //Valid four byte sequence assertEquals("\uDBC0\uDC00", decodeURIComponent("%f4%80%80%80")); } function testDecodeURIComponent_25() { //Valid four byte sequence assertEquals("\uDBFF\uDFFF", decodeURIComponent("%f4%8f%bf%bf")); } function testDecodeURIComponent_26() { //Too big utf-8 sequence assertThrows(URIError(), decodeURIComponent, "%f7%bf%bf%bf"); } testDecodeURIComponent_26.metadata = { bug:"CARAKAN-126" }; function testDecodeURIComponent_27() { assertEquals("a", decodeURIComponent("%61")); } function testDecodeURIComponent_28() { //Invalid first byte assertThrows(URIError(), decodeURI, "%F1"); } testDecodeURIComponent_28.metadata = { bug:"CARAKAN-126" }; function testDecodeURIComponent_29() { //Invalid first byte assertThrows(URIError(), decodeURI, "%F1"); } testDecodeURIComponent_29.metadata = { bug:"CARAKAN-126" }; function testDecodeURIComponent_30() { assertEquals("undefined", decodeURIComponent()); } testDecodeURIComponent_30.metadata = { bug:"CARAKAN-349" };
ahthamrin/kbri-admin2
src/routes/app/routes/ui/routes/callToActions/components/CallToActions.js
<reponame>ahthamrin/kbri-admin2<gh_stars>0 import React from 'react'; import RaisedButton from 'material-ui/RaisedButton'; import QueueAnim from 'rc-queue-anim'; const mWidthStyle = { minWidth: '135px' }; const Section1 = () => ( <div className="container-fluid with-maxwidth"> <article className="article"> <h2 className="article-title">Basic</h2> <div className="box box-default"> <div className="box-body"> <div className="call-to-action cta-inline"> <div className="cta-inner"> <span className="cta-text">Download it now and get up and running in minutes</span> <div className="cta-btn"> <RaisedButton style={mWidthStyle} label="Free Download" secondary /> </div> </div> </div> </div> </div> </article> </div> ); const Section2 = () => ( <div> <div className="container-fluid with-maxwidth"> <article className="article no-margin-bttom"> <h2 className="article-title">Full Width (Inline)</h2> </article> </div> <div className="call-to-action cta-inline cta-full-width card-white"> <div className="cta-inner"> <span className="cta-text">Download it now and get up and running in minutes</span> <div className="cta-btn"> <RaisedButton style={mWidthStyle} label="Free Download" secondary /> </div> </div> </div> <div className="divider" /> </div> ); const Section3 = () => ( <div> <div className="container-fluid with-maxwidth"> <article className="article no-margin-bttom"> <h2 className="article-title">Full Width</h2> </article> </div> <div className="call-to-action cta-full-width card-white"> <div className="cta-inner"> <span className="cta-text">Download it now and get up and running in minutes</span> <div className="cta-btn"> <RaisedButton style={mWidthStyle} label="Free Download" secondary /> </div> <div className="cta-muted">No spam! We promise, only the best stuff.</div> </div> </div> <div className="divider" /> </div> ); const Section4 = () => ( <div> <div className="container-fluid with-maxwidth"> <article className="article no-margin-bttom"> <h2 className="article-title">Image Background</h2> </article> </div> <div className="call-to-action cta-bg-img cta-full-width" style={{backgroundImage: 'url(assets/images-demo/covers/photo-1456374407032-6e4baf58fb62.jpg)'}}> <div className="cta-inner"> <span className="cta-text">Download it now and get up and running in minutes</span> <div className="cta-btn"> <RaisedButton style={mWidthStyle} label="Free Download" secondary /> </div> <div className="cta-muted">No spam! We promise, only the best stuff.</div> </div> </div> </div> ); const CallToActions = () => ( <section className="chapter"> <QueueAnim type="bottom" className="ui-animate"> <div key="1"><Section1 /></div> <div key="2"><Section2 /></div> <div key="3"><Section3 /></div> <div key="4"><Section4 /></div> </QueueAnim> </section> ); module.exports = CallToActions;
Rita-Bernstein/downfall-rebalance
src/main/java/charbosses/relics/CBR_Ectoplasm.java
package charbosses.relics; import charbosses.bosses.AbstractCharBoss; import charbosses.cards.AbstractBossCard; import com.megacrit.cardcrawl.characters.AbstractPlayer; import com.megacrit.cardcrawl.core.CardCrawlGame; import com.megacrit.cardcrawl.core.EnergyManager; import com.megacrit.cardcrawl.helpers.PowerTip; import com.megacrit.cardcrawl.relics.AbstractRelic; import com.megacrit.cardcrawl.relics.Ectoplasm; import downfall.downfallMod; import slimebound.SlimeboundMod; import java.util.ArrayList; public class CBR_Ectoplasm extends AbstractCharbossRelic { public static final String ID = "Ectoplasm"; private int numCards; public CBR_Ectoplasm() { super(new Ectoplasm()); } @Override public String getUpdatedDescription() { if (AbstractCharBoss.boss != null) { return this.setDescription(AbstractCharBoss.boss.chosenClass); } return this.setDescription(null); } private String setDescription(final AbstractPlayer.PlayerClass c) { return this.DESCRIPTIONS[1] + this.DESCRIPTIONS[0] + CardCrawlGame.languagePack.getRelicStrings(downfallMod.makeID(ID)).DESCRIPTIONS[0] + this.numCards + CardCrawlGame.languagePack.getRelicStrings(downfallMod.makeID(ID)).DESCRIPTIONS[1]; } @Override public void updateDescription(final AbstractPlayer.PlayerClass c) { this.description = this.setDescription(c); this.tips.clear(); this.tips.add(new PowerTip(this.name, this.description)); this.initializeTips(); } @Override public void modifyCardsOnCollect(ArrayList<AbstractBossCard> groupToModify, int actIndex) { SlimeboundMod.logger.info("Ectoplasm received act index: " + actIndex); for (int i = actIndex; i < 3; i++) { if (this.owner.chosenArchetype.cardRemovalsPerAct[i] > 0) this.owner.chosenArchetype.cardRemovalsPerAct[i] -= 1; this.numCards +=1; } this.description = getUpdatedDescription(); this.refreshDescription(); } @Override public void onEquip() { final EnergyManager energy = AbstractCharBoss.boss.energy; ++energy.energyMaster; } @Override public void onUnequip() { final EnergyManager energy = AbstractCharBoss.boss.energy; --energy.energyMaster; } @Override public AbstractRelic makeCopy() { return new CBR_Ectoplasm(); } }
fspbld/skiboot
hdata/paca.c
<gh_stars>1-10 /* Copyright 2013-2014 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <skiboot.h> #include "spira.h" #include <cpu.h> #include <fsp.h> #include <opal.h> #include <ccan/str/str.h> #include <device.h> #include <types.h> #include "hdata.h" #define PACA_MAX_THREADS 4 static unsigned int paca_index(const struct HDIF_common_hdr *paca) { void *start = get_hdif(&spira.ntuples.paca, PACA_HDIF_SIG); return ((void *)paca - start) / be32_to_cpu(spira.ntuples.paca.alloc_len); } static struct dt_node *add_cpu_node(struct dt_node *cpus, const struct HDIF_common_hdr *paca, const struct sppaca_cpu_id *id, bool okay) { const struct sppaca_cpu_timebase *timebase; const struct sppaca_cpu_cache *cache; const struct sppaca_cpu_attr *attr; struct dt_node *cpu; u32 no, size, ve_flags, l2_phandle, chip_id; /* We use the process_interrupt_line as the res id */ no = be32_to_cpu(id->process_interrupt_line); ve_flags = be32_to_cpu(id->verify_exists_flags); prlog(PR_INFO, "CPU[%i]: PIR=%i RES=%i %s %s(%u threads)\n", paca_index(paca), be32_to_cpu(id->pir), no, ve_flags & CPU_ID_PACA_RESERVED ? "**RESERVED**" : cpu_state(ve_flags), ve_flags & CPU_ID_SECONDARY_THREAD ? "[secondary] " : (be32_to_cpu(id->pir) == boot_cpu->pir ? "[boot] " : ""), ((ve_flags & CPU_ID_NUM_SECONDARY_THREAD_MASK) >> CPU_ID_NUM_SECONDARY_THREAD_SHIFT) + 1); timebase = HDIF_get_idata(paca, SPPACA_IDATA_TIMEBASE, &size); if (!timebase || size < sizeof(*timebase)) { prerror("CPU[%i]: bad timebase size %u @ %p\n", paca_index(paca), size, timebase); return NULL; } cache = HDIF_get_idata(paca, SPPACA_IDATA_CACHE_SIZE, &size); if (!cache || size < sizeof(*cache)) { prerror("CPU[%i]: bad cache size %u @ %p\n", paca_index(paca), size, cache); return NULL; } cpu = add_core_common(cpus, cache, timebase, no, okay); /* Core attributes */ attr = HDIF_get_idata(paca, SPPACA_IDATA_CPU_ATTR, &size); if (attr) add_core_attr(cpu, be32_to_cpu(attr->attr)); /* Add cache info */ l2_phandle = add_core_cache_info(cpus, cache, no, okay); dt_add_property_cells(cpu, "l2-cache", l2_phandle); /* We append the secondary cpus in __cpu_parse */ dt_add_property_cells(cpu, "ibm,ppc-interrupt-server#s", no); dt_add_property_cells(cpu, DT_PRIVATE "hw_proc_id", be32_to_cpu(id->hardware_proc_id)); dt_add_property_cells(cpu, "ibm,pir", be32_to_cpu(id->pir)); chip_id = pcid_to_chip_id(be32_to_cpu(id->processor_chip_id)); dt_add_property_cells(cpu, "ibm,chip-id", chip_id); return cpu; } static struct dt_node *find_cpu_by_hardware_proc_id(struct dt_node *root, u32 hw_proc_id) { struct dt_node *i; dt_for_each_node(root, i) { const struct dt_property *prop; if (!dt_has_node_property(i, "device_type", "cpu")) continue; prop = dt_find_property(i, DT_PRIVATE "hw_proc_id"); if (!prop) return NULL; if (be32_to_cpu(*(be32 *)prop->prop) == hw_proc_id) return i; } return NULL; } /* Note that numbers are small. */ static void add_be32_sorted(__be32 arr[], __be32 new, unsigned num) { unsigned int i; /* Walk until we find where we belong (insertion sort). */ for (i = 0; i < num; i++) { if (be32_to_cpu(new) < be32_to_cpu(arr[i])) { __be32 tmp = arr[i]; arr[i] = new; new = tmp; } } arr[i] = new; } static void add_xics_icps(void) { struct dt_node *cpu; unsigned int i; u64 reg[PACA_MAX_THREADS * 2]; struct dt_node *icp; dt_for_each_node(dt_root, cpu) { u32 irange[2], size, pir; const struct dt_property *intsrv; const struct HDIF_common_hdr *paca; u64 ibase; unsigned int num_threads; bool found = false; if (!dt_has_node_property(cpu, "device_type", "cpu")) continue; intsrv = dt_find_property(cpu, "ibm,ppc-interrupt-server#s"); if (!intsrv) continue; pir = dt_prop_get_u32(cpu, "ibm,pir"); /* Get ibase address */ paca = get_hdif(&spira.ntuples.paca, PACA_HDIF_SIG); for_each_paca(paca) { const struct sppaca_cpu_id *id; id = HDIF_get_idata(paca, SPPACA_IDATA_CPU_ID, &size); if (!CHECK_SPPTR(id)) continue; if (pir != be32_to_cpu(id->pir)) continue; ibase = cleanup_addr(be64_to_cpu(id->ibase)); found = true; break; } if (!found) return; num_threads = intsrv->len / sizeof(u32); assert(num_threads <= PACA_MAX_THREADS); icp = dt_new_addr(dt_root, "interrupt-controller", ibase); if (!icp) continue; dt_add_property_strings(icp, "compatible", "IBM,ppc-xicp", "IBM,power7-xicp"); irange[0] = dt_property_get_cell(intsrv, 0); /* Index */ irange[1] = num_threads; /* num servers */ dt_add_property(icp, "ibm,interrupt-server-ranges", irange, sizeof(irange)); dt_add_property(icp, "interrupt-controller", NULL, 0); dt_add_property_cells(icp, "#address-cells", 0); dt_add_property_string(icp, "device_type", "PowerPC-External-Interrupt-Presentation"); for (i = 0; i < num_threads*2; i += 2) { reg[i] = ibase; /* One page is enough for a handful of regs. */ reg[i+1] = 4096; ibase += reg[i+1]; } dt_add_property(icp, "reg", reg, sizeof(reg)); } } static bool __paca_parse(void) { const struct HDIF_common_hdr *paca; struct dt_node *cpus; paca = get_hdif(&spira.ntuples.paca, PACA_HDIF_SIG); if (!paca) { prerror("Invalid PACA (PCIA = %p)\n", ntuple_addr(&spira.ntuples.pcia)); return false; } if (be32_to_cpu(spira.ntuples.paca.act_len) < sizeof(*paca)) { prerror("PACA: invalid size %u\n", be32_to_cpu(spira.ntuples.paca.act_len)); return false; } cpus = dt_new(dt_root, "cpus"); dt_add_property_cells(cpus, "#address-cells", 1); dt_add_property_cells(cpus, "#size-cells", 0); for_each_paca(paca) { const struct sppaca_cpu_id *id; u32 size, ve_flags; bool okay; id = HDIF_get_idata(paca, SPPACA_IDATA_CPU_ID, &size); /* The ID structure on Blade314 is only 0x54 long. We can * cope with it as we don't use all the additional fields. * The minimum size we support is 0x40 */ if (!id || size < SPIRA_CPU_ID_MIN_SIZE) { prerror("CPU[%i]: bad id size %u @ %p\n", paca_index(paca), size, id); return false; } ve_flags = be32_to_cpu(id->verify_exists_flags); switch ((ve_flags&CPU_ID_VERIFY_MASK) >> CPU_ID_VERIFY_SHIFT) { case CPU_ID_VERIFY_USABLE_NO_FAILURES: case CPU_ID_VERIFY_USABLE_FAILURES: okay = true; break; default: okay = false; } prlog(PR_INFO, "CPU[%i]: PIR=%i RES=%i %s\n", paca_index(paca), be32_to_cpu(id->pir), be32_to_cpu(id->process_interrupt_line), okay ? "OK" : "UNAVAILABLE"); /* Secondary threads don't get their own node. */ if (ve_flags & CPU_ID_SECONDARY_THREAD) continue; if (!add_cpu_node(cpus, paca, id, okay)) return false; } /* Now account for secondaries. */ for_each_paca(paca) { const struct dt_property *prop; const struct sppaca_cpu_id *id; u32 size, state, num, ve_flags; struct dt_node *cpu; __be32 *new_prop; id = HDIF_get_idata(paca, 2, &size); if (!CHECK_SPPTR(id)) continue; ve_flags = be32_to_cpu(id->verify_exists_flags); state = (ve_flags & CPU_ID_VERIFY_MASK) >> CPU_ID_VERIFY_SHIFT; switch (state) { case CPU_ID_VERIFY_USABLE_NO_FAILURES: case CPU_ID_VERIFY_USABLE_FAILURES: break; default: continue; } /* Only interested in secondary threads. */ if (!(ve_flags & CPU_ID_SECONDARY_THREAD)) continue; cpu = find_cpu_by_hardware_proc_id(cpus, be32_to_cpu(id->hardware_proc_id)); if (!cpu) { prerror("CPU[%i]: could not find primary hwid %i\n", paca_index(paca), be32_to_cpu(id->hardware_proc_id)); return false; } /* Add the cpu #. */ prop = dt_find_property(cpu, "ibm,ppc-interrupt-server#s"); if (!prop) { prerror("CPU[%i]: could not find mapping information\n", paca_index(paca)); return false; } num = prop->len / sizeof(u32); new_prop = malloc((num + 1) * sizeof(u32)); if (!new_prop) { prerror("Property allocation length %zu failed\n", (num + 1) * sizeof(u32)); return false; } memcpy(new_prop, prop->prop, prop->len); add_be32_sorted(new_prop, id->process_interrupt_line, num); dt_del_property(cpu, (struct dt_property *)prop); dt_add_property(cpu, "ibm,ppc-interrupt-server#s", new_prop, (num + 1) * sizeof(__be32)); free(new_prop); } /* * P7 and P8 use the XICS interrupt controller which has a per-core * interrupt controller node. */ if (proc_gen <= proc_gen_p8) add_xics_icps(); return true; } int paca_parse(void) { if (!__paca_parse()) { prerror("CPU: Initial CPU parsing failed\n"); return -1; } return 0; }
Prasunjais/freightDeck-FE
src/pages/index.js
/* Auth Layout - healthCareProvider */ export { Login, Register, VerifyOTP } from './Auth'; /* Auth Layout - admin */ export { AdminLogin, AdminVerifyOTP } from './Auth'; /* HealthCareProvider Layout */ export { HCPAppointments } from './HealthCareProvider';
gdmcbain/quadpy
quadpy/enr/tools.py
<filename>quadpy/enr/tools.py<gh_stars>1-10 # -*- coding: utf-8 -*- # import numpy def integrate(f, rule, dot=numpy.dot): flt = numpy.vectorize(float) return dot(f(flt(rule.points).T), flt(rule.weights))
lucastb1988/Pharma
src/main/java/br/com/lucas/pharma/service/FabricanteService.java
package br.com.lucas.pharma.service; import java.util.List; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import com.google.gson.Gson; import br.com.lucas.pharma.dao.FabricanteDAO; import br.com.lucas.pharma.domain.Fabricante; // Json é uma forma textual para representar os campos porém utiliza menos espaço que o xml(outra forma de representação) // Json - JavaScript Object Notation - formato para comunicação de dados (utilizado principalmente em android, mobile devido ser mais leve) // muito mais leve que XML, notação para trafegar objetos, não possui abertura de tag e fechamento, trabalha apenas com pares de valores, arrays e objetos. // possui menos regras, menos tags e é mais facil de visualizar do que o xml. Json é uma representação do Rest. // Rest é uma filosofia de construção de servidores de aplicação que utiliza essencialmente protocolo HTTP para expor seus recursos. // Esses recursos podem ser objetos, arrays, listas, valores simples, esses recursos são representados por URL. // É necessário verificar quais uris serão publicadas, quais uris farão cada coisa, de que forma as pessoas irão trocar informações com vc, como as pessoas irão interagir com seus recursos, // todos esses processos são parte da arquitetura do Rest, devido a isso necessita pensar muito bem em como desenvolver estes processos, // para que a pessoa que for acessar simplesmente possa fazer tudo que necessita usando apenas os protocolos GET, POST, PUT, DELETE // Da mesma forma que é criado um formulário através de um site da web, informando campos obrigatórios e enviando o mesmo. O Rest também faz da mesma forma através de sua API. // Estratégia de cache HTTP é imprescindivel para que o Rest tenha uma boa performance. // A idéia do Rest é de um sistema falar com o outro de uma maneira desacoplada. // Rest é uma arquitetura de longo prazo. É implementada para que seu sistema dure no minimo 5 anos. // Rest é o conceito // Restful é a implementação do conceito @Path("fabricante") public class FabricanteService { //Hibernate não trabalha com Json e sim com objetos (devido a isso é necessário converter todos os objetos a serem utilizados por Gson, //para os métodos abaixo listar/buscar/salvar/editar/excluir foram convertidos os objetos(fabricante) para Gson) //Gson = Google gSon (Biblioteca da Google) //Gson consegue gerar objetos a partir de uma String JSON. //Gson é uma biblioteca que converte objetos Java em JSON e vice-versa. //Serializar(Java para JSON) / deserializar(JSON para JAVA). //Gson trabalha com o tipo String, tipos primitivos (int, float, boolean, etc) e arrays. Também suporta classes wrappers como Integer e Long. //GSON é uma biblioteca do Google utilizada, entre outras coisas, na conversão de objetos Java em representação JSON. // http://127.0.0.1:8080/Pharma/rest/fabricante // url que será utilizada para receber o GET @GET public String listar() { FabricanteDAO fabricanteDAO = new FabricanteDAO(); List<Fabricante> fabricantes = fabricanteDAO.listar("descricao"); Gson gson = new Gson(); String json = gson.toJson(fabricantes); // Pega o List fabricantes em formato objeto e converte no formato texto (GSon) e o retorna. return json; // Para gson o retorno é sempre String } // http://127.0.0.1:8080/Pharma/rest/fabricante/(codigo} (ex. código 10) // url que será utilizada para receber o GET // Este método buscar foi utilizado a anotação Path/PathParam para distinguir somente a URL (se fossem URLs diferentes não seria necessário incluir estas anotações) @GET // utilizado para capturar informações (leitura) @Path("{codigo}") // está diferenciando a URL com um outro nivel do Path (utilizando /código do fabricante) public String buscar(@PathParam("codigo") Long codigo) { //amarrando o objeto código ao parâmetro código FabricanteDAO fabricanteDAO = new FabricanteDAO(); Fabricante fabricante = fabricanteDAO.buscar(codigo); Gson gson = new Gson(); String json = gson.toJson(fabricante); return json; } // http://127.0.0.1:8080/Pharma/rest/fabricante // Este método (POST merge) também pode ser utilizado para editar (necessário incluir o id e editar a nova descrição) @POST // utilizado para incluir/inserir public String salvarOuEditar(String jsonEntrada) { Gson gson = new Gson(); // objeto Gson pode converter objeto para String, como String para objeto Fabricante fabricante = gson.fromJson(jsonEntrada, Fabricante.class); // converter seu json para objeto do tipo fabricante na classe Fabricante / // capturando para Gson de Json o parametro e a classe no qual o Json irá converter(fabricante.class) FabricanteDAO fabricanteDAO = new FabricanteDAO(); fabricanteDAO.merge(fabricante); //editar ou salvar dependendo se já existe um fabricante criado String jsonSaida = gson.toJson(fabricante); // dar o feedback para o usuario (Evento 200) return jsonSaida; } // http://127.0.0.1:8080/Pharma/rest/fabricante // Este método (POST salvar) é utilizado somente para salvar // @POST // utilizado para incluir/inserir // public String salvar(String jsonEntrada) { // Gson gson = new Gson(); // objeto Gson pode converter objeto para String, como String para objeto // Fabricante fabricante = gson.fromJson(jsonEntrada, Fabricante.class); // converter seu json para objeto do tipo fabricante na classe Fabricante / // // capturando para Gson de Json o parametro e a classe no qual o Json irá converter(fabricante.class) // // FabricanteDAO fabricanteDAO = new FabricanteDAO(); // fabricanteDAO.salvar(fabricante); // salvar um fabricante no bd // // String jsonSaida = gson.toJson(fabricante); // dar o feedback para o usuario (Evento 200) // return jsonSaida; // } // http://127.0.0.1:8080/Pharma/rest/fabricante // Este método (PUT editar) é utilizado somente para editar (necessário incluir o id e editar a nova descrição) @PUT // utilizado para editar public String editar(String jsonEntrada) { Gson gson = new Gson(); // objeto Gson pode converter objeto para String, como String para objeto Fabricante fabricante = gson.fromJson(jsonEntrada, Fabricante.class); // converter seu json para objeto do tipo fabricante na classe Fabricante / // capturando para Gson de Json o parametro e a classe no qual o Json irá converter(fabricante.class) FabricanteDAO fabricanteDAO = new FabricanteDAO(); fabricanteDAO.editar(fabricante); // editar um fabricante no bd String jsonSaida = gson.toJson(fabricante); // dar o feedback para o usuario (Evento 200) return jsonSaida; } // http://127.0.0.1:8080/Pharma/rest/fabricante @DELETE // utilizado para deletar @Path("{codigo}") public String excluir(@PathParam("codigo") Long codigo) { FabricanteDAO fabricanteDAO = new FabricanteDAO(); Fabricante fabricante = fabricanteDAO.buscar(codigo); fabricanteDAO.excluir(fabricante); // excluir um fabricante do bd Gson gson = new Gson(); String jsonSaida = gson.toJson(fabricante); // dar o feedback para o usuario (Evento 200) return jsonSaida; } } //// Gson = Uma biblioteca de serialização/deserialização que pode converter Objetos Java Gson em representação Json. //// Também pode ser usada para converter uma String JSon em um objeto Java equivalente. //// GSon pode trabalhar com objetos Java arbitrários incluindo objetos pré-existentes no qual você não possui o código-fonte dele. //// É comum utilizar protocolos de GET, POST, PUT, DELETE //// Para acesso a URL é comum utilizar o protocolo GET, para acesso aos demais protocolos é obrigatório utilizar addons do navegador ou SoapUI(profissional) //// GET utiliza comunicação navegador com navegador sem o SO intermediar (comunicação mais rápida) //// POST utiliza comunicação usando serviços do sistema operacional (comunicação mais lenta porém mais segura) - serve para inserir informações
morenes/infoArt-Server
src/algorithms/anfis/LeastSquareEstimator.java
package algorithms.anfis; /** * * @author <NAME> */ public class LeastSquareEstimator { }
ScalablyTyped/scala-st-node
scala-st-node/src/main/scala/org.scalablytyped.node/node/workerThreadsMod/workerData.scala
<reponame>ScalablyTyped/scala-st-node package org.scalablytyped.node.node.workerThreadsMod import org.scalablytyped.runtime.TopLevel import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation._ @JSImport("worker_threads", "workerData") @js.native object workerData extends TopLevel[js.Any]
WaitrInc/targaryen
docs/chai/examples/failing.js
'use strict'; // in your app this would be require('targaryen/plugins/chai') const targaryen = require('../../../plugins/chai'); const chai = require('chai'); const expect = chai.expect; const users = targaryen.users; const path = require('path'); const rules = targaryen.json.loadSync(path.join(__dirname, 'rules.json')); chai.use(targaryen); describe('A valid set of security rules and data', function() { before(function() { targaryen.setFirebaseData(require('./data.json')); targaryen.setFirebaseRules(rules); }); it('can have read errors', function() { expect(users.unauthenticated).can.read.path('users/password:<PASSWORD>'); }); it('can have write errors', function() { expect(users.password).can.write(true) .to.path('users/password:<PASSWORD>/<PASSWORD>'); }); it('can have validation errors', function() { expect({ uid: 'password:<PASSWORD>' }).can.write(true) .to.path('users/password:<PASSWORD>/innocent'); }); });
SPixs/TinyGB
src/main/java/com/s2soft/tinygb/mmu/GBMemoryNA.java
package com.s2soft.tinygb.mmu; public class GBMemoryNA extends AbstractAddressable { // ============================ Constants ============================== // =========================== Attributes ============================== // =========================== Constructor ============================= // ========================== Access methods =========================== // ========================= Treatment methods ========================= @Override public void setByte(int address, byte b) { } @Override public byte getByte(int address) { return 0; } }
gustavotonini/pgGrid
src/include/replicate_com.h
<reponame>gustavotonini/pgGrid<filename>src/include/replicate_com.h /*------------------------------------------------------------------------- * * replicate.h * Primary include file for replicate server .c files * * This should be the first file included by replicate modules. * *------------------------------------------------------------------------- */ #ifndef REPLICATE_COM_H #define REPLICATE_COM_H 1 #ifndef _SYS_TYPES_H #include <sys/types.h> #endif #ifndef _INTTYPES_H #include <inttypes.h> #endif #ifndef _NETINET_IN_H #include <netinet/in.h> #endif #include "c.h" #include "pg_config.h" /* default values */ #define DEFAULT_PGLB_PORT (6001) #define DEFAULT_PGLB_RECOVERY_PORT (6101) #define DEFAULT_PGLB_LIFECHECK_PORT (6201) #define DEFAULT_CLUSTER_PORT (5432) #define DEFAULT_CLUSTER_RECOVERY_PORT (7101) #define DEFAULT_CLUSTER_LIFECHECK_PORT (7201) #define DEFAULT_PGRP_PORT (8001) #define DEFAULT_PGRP_RECOVERY_PORT (8101) #define DEFAULT_PGRP_LIFECHECK_PORT (8201) #define DEFAULT_PGRP_RLOG_PORT (8301) #define MAX_DB_SERVER (32) /************************** * * * Packet ID definition * * * ***************************/ /*========================= Replication packet id ===========================*/ #define CMD_SYS_REPLICATE 'R' /*------------------------- Simple Query --------------------------*/ #define CMD_STS_SET_SESSION_AUTHORIZATION 'S' #define CMD_STS_TRANSACTION 'T' #define CMD_STS_TEMP_TABLE 'E' #define CMD_STS_QUERY 'Q' #define CMD_STS_OTHER 'O' #define CMD_TYPE_VACUUM 'V' #define CMD_TYPE_ANALYZE 'A' #define CMD_TYPE_REINDEX 'N' #define CMD_TYPE_SELECT 'S' #define CMD_TYPE_EXPLAIN 'X' #define CMD_TYPE_SET 'T' #define CMD_TYPE_RESET 't' #define CMD_TYPE_INSERT 'I' #define CMD_TYPE_DELETE 'D' #define CMD_TYPE_EXECUTE 'U' #define CMD_TYPE_UPDATE 'U' #define CMD_TYPE_BEGIN 'B' #define CMD_TYPE_COMMIT 'E' #define CMD_TYPE_ROLLBACK 'R' #define CMD_TYPE_CONNECTION_CLOSE 'x' #define CMD_TYPE_SESSION_AUTHORIZATION_BEGIN 'a' #define CMD_TYPE_SESSION_AUTHORIZATION_END 'b' #define CMD_TYPE_SAVEPOINT 's' #define CMD_TYPE_ROLLBACK_TO_SAVEPOINT 'r' #define CMD_TYPE_RELEASE_SAVEPOINT 'l' #define CMD_TYPE_OTHER 'O' /*========================= System call packet id ===========================*/ #define CMD_SYS_CALL 'S' #define CMD_SYS_PREREPLICATE 'Z' #define CMD_STS_NOTICE 'N' #define CMD_STS_RESPONSE 'R' #define CMD_STS_TRANSACTION_ABORT 'A' #define CMD_STS_QUERY_SUSPEND 'P' #define CMD_STS_QUERY_DONE 'D' #define CMD_TYPE_COMMIT_CONFIRM 'c' #define CMD_TYPE_QUERY_CONFIRM 'q' #define CMD_TYPE_DEADLOCK_DETECT 'd' #define CMD_TYPE_FRONTEND_CLOSED 'x' /*---------------------------- Copy Command ------------------------------*/ #define CMD_STS_COPY 'C' #define CMD_TYPE_COPY 'C' #define CMD_TYPE_COPY_DATA 'd' #define CMD_TYPE_COPY_DATA_END 'e' /*---------------------------- Large Object ------------------------------*/ #define CMD_STS_LARGE_OBJECT 'L' #define CMD_TYPE_LO_IMPORT 'I' #define CMD_TYPE_LO_CREATE 'C' #define CMD_TYPE_LO_OPEN 'O' #define CMD_TYPE_LO_WRITE 'W' #define CMD_TYPE_LO_LSEEK 'S' #define CMD_TYPE_LO_CLOSE 'X' #define CMD_TYPE_LO_UNLINK 'U' /*------------------------- Prepare/Params Query --------------------------*/ #define CMD_STS_PREPARE 'P' #define CMD_TYPE_P_PARSE 'P' #define CMD_TYPE_P_BIND 'B' #define CMD_TYPE_P_EXECUTE 'E' #define CMD_TYPE_P_FASTPATH 'F' #define CMD_TYPE_P_CLOSE 'C' #define CMD_TYPE_P_DESCRIBE 'D' #define CMD_TYPE_P_FLUSH 'H' #define CMD_TYPE_P_SYNC 'S' /*========================= Lifecheck packet id ===========================*/ #define CMD_SYS_LIFECHECK 'W' #define CMD_STS_LOADBALANCER 'A' #define CMD_STS_CLUSTER 'B' #define CMD_STS_REPLICATOR 'C' #define PGR_TRANSACTION_SOCKET (0) #define PGR_QUERY_SOCKET (1) #define DATA_FREE (0) #define DATA_INIT (1) #define DATA_USE (2) #define DATA_ERR (90) #define DATA_END (-1) #define HOSTNAME_MAX_LENGTH (128) #define DBNAME_MAX_LENGTH (128) #define USERNAME_MAX_LENGTH (128) #define PASSWORD_MAX_LENGTH (128) #define TABLENAME_MAX_LENGTH (128) #define PATH_MAX_LENGTH (256) #define MAX_SERVER_NUM (128) #define MAX_RETRY_TIMES (3) #define MAX_SOCKET_QUEUE (100000) #define TRANSACTION_ERROR_RESULT "TRANSACTION_ERROR" #define REPLICATE_SERVER_SHM_KEY (1020) /* target -> replicate */ #define RECOVERY_PREPARE_REQ (1) /* replicate -> master */ #define RECOVERY_PGDATA_REQ (2) /* master -> replicate */ #define RECOVERY_PGDATA_ANS (3) /* replicate -> target */ #define RECOVERY_PREPARE_ANS (4) /* target -> replicate */ #define RECOVERY_START_REQ (5) /* replicate -> master */ #define RECOVERY_FSYNC_REQ (6) /* master -> replicate */ #define RECOVERY_FSYNC_ANS (7) /* replicate -> target */ #define RECOVERY_START_ANS (8) /* target -> replicate */ #define RECOVERY_QUEUE_DATA_REQ (9) /* replicate -> target */ #define RECOVERY_QUEUE_DATA_ANS (10) /* target -> replicate */ #define RECOVERY_FINISH (11) #define RECOVERY_ERROR_OCCUPIED (100) #define RECOVERY_ERROR_CONNECTION (101) #define RECOVERY_ERROR_TARGET_ONLY (102) #define RECOVERY_ERROR_ANS (200) /* lifecheck ask from cluster db */ #define LIFECHECK_ASK_FROM_CLUSTER (1) /* lifecheck response from replication server */ #define LIFECHECK_RES_FROM_REPLICATOR (2) /* lifecheck ask from replication server */ #define LIFECHECK_ASK_FROM_REPLICATOR (3) /* lifecheck response from cluster db */ #define LIFECHECK_RES_FROM_CLUSTER (4) #define REPLICATION_SERVER_INFO_TAG "Replicate_Server_Info" #define HOST_NAME_TAG "Host_Name" #define PORT_TAG "Port" #define RECOVERY_PORT_TAG "Recovery_Port" #define LIFECHECK_PORT_TAG "LifeCheck_Port" #define TIMEOUT_TAG "Replication_Timeout" #define LIFECHECK_TIMEOUT_TAG "LifeCheck_Timeout" #define LIFECHECK_INTERVAL_TAG "LifeCheck_Interval" #define RECOVERY_INIT (0) #define RECOVERY_PREPARE_START (1) #define RECOVERY_START_1 (2) #define RECOVERY_CLEARED (3) #define RECOVERY_WAIT_CLEAN (10) #define RECOVERY_ERROR (99) /* response mode */ #define PGR_FAST_MODE (0) #define PGR_NORMAL_MODE (1) #define PGR_RELIABLE_MODE (2) #define RECOVERY_TIMEOUT (600) #ifndef COMPLETION_TAG_BUFSIZE #define COMPLETION_TAG_BUFSIZE (128) #endif /* replicate log type */ #define FROM_R_LOG_TYPE (1) #define FROM_C_DB_TYPE (2) #define CONNECTION_SUSPENDED_TYPE (3) #define PGR_SYSTEM_COMMAND_FUNC "PGR_SYSTEM_COMMAND_FUNCTION" #define PGR_STARTUP_REPLICATION_SERVER_FUNC_NO (1) #define PGR_CHANGE_REPLICATION_SERVER_FUNC_NO (2) #define PGR_SET_CURRENT_TIME_FUNC_NO (3) #define PGR_NOTICE_DEADLOCK_DETECTION_FUNC_NO (4) #define PGR_TRANSACTION_CONFIRM_ANSWER_FUNC_NO (5) #define PGR_RELIABLE_MODE_DONE_FUNC_NO (6) #define PGR_NOTICE_ABORT_FUNC_NO (7) #define PGR_SET_CURRENT_REPLICATION_QUERY_ID_NO (8) #define PGR_QUERY_CONFIRM_ANSWER_FUNC_NO (9) #define PGR_GET_OID_FUNC_NO (10) #define PGR_SET_OID_FUNC_NO (11) //#ifdef PGGRID #define PGR_RETURN_TUPLES_NO (12) #define PGR_RETURN_TUPLES_MSG "12" //#endif #define PGR_CMD_ARG_NUM (10) #define PGR_LOCK_CONFLICT_NOTICE_CMD "PGR_LOCK_CONFLICT_NOTICE_CMD" #define PGR_DEADLOCK_DETECT_NOTICE_CMD "PGR_DEADLOCK_DETECT_NOTICE_CMD" #define PGR_QUERY_DONE_NOTICE_CMD "PGR_QUERY_DONE_NOTICE_CMD" #define PGR_QUERY_ABORTED_NOTICE_CMD "PGR_QUERY_ABORTED_NOTICE_CMD" #define PGR_RETRY_LOCK_QUERY_CMD "PGR_RETRY_LOCK_QUERY_CMD" #define PGR_NOT_YET_REPLICATE_NOTICE_CMD "PGR_NOT_YET_REPLICATE_NOTICE_CMD" #define PGR_ALREADY_REPLICATED_NOTICE_CMD "PGR_ALREADY_REPLICATED_NOTICE_CMD" #define PGR_NOT_YET_COMMIT (0) #define PGR_ALREADY_COMMITTED (1) #define COPYBUFSIZ (8192) #define MAX_WORDS (24) #define MAX_WORD_LETTERS (48) #define PGR_MESSAGE_BUFSIZE (128) #define INT_LENGTH (12) #define PGR_MAX_COUNTER (0x0FFFFFFF) #define PGR_GET_OVER_FLOW_FILTER (0xF0000000) #define PGR_GET_DATA_FILTER (0x0FFFFFFF) #define PGR_SET_OVER_FLOW (0x10000000) #define PGR_MIN_COUNTER (0x0000000F) #define STRCMP(x,y) (strncmp(x,y,strlen(y))) /* life check target */ #define SYN_TO_LOAD_BALANCER (0) #define SYN_TO_CLUSTER_DB (1) #define SYN_TO_REPLICATION_SERVER (2) #define LIFE_CHECK_TRY_COUNT (2) #define LIFE_CHECK_STOP (0) #define LIFE_CHECK_START (1) #define PING_DB "template1" #define PING_QUERY "SELECT 1" //pggrid operation types /*Normal pgcluster operation*/ #define PGGRID_OP_NORMAL 0 /*Distributed query*/ #define PGGRID_OP_DQUERY 1 /*Distributed count query*/ #define PGGRID_OP_DCOUNT 2 #ifndef HAVE_UNION_SEMUN union semun { int val; struct semid_ds *buf; unsigned short int *array; struct seminfo *__buf; }; #endif typedef struct ReplicateHeaderType { char cmdSys; char cmdSts; /* Q:query T:transaction */ char cmdType; /* S:select I:insert D:delete U:update B:begin E:commit/rollback/end O:others */ char rlog; /* -- kind of replication log -- 1: send from replication log 2: send from cluster db (should be retry) 3: connection suspended */ uint16_t port; uint16_t pid; uint32_t query_size; char from_host[HOSTNAME_MAX_LENGTH]; char dbName[DBNAME_MAX_LENGTH]; char userName[USERNAME_MAX_LENGTH]; struct timeval tv; uint32_t query_id; int isAutoCommit; /* 0 if autocommit is off. 1 if autocommit is on */ uint32_t request_id; uint32_t replicate_id; char password[PASSWORD_MAX_LENGTH]; char md5Salt[4]; char cryptSalt[2]; char dummySalt[2]; //fragment parameters //#ifdef PGGRID char sitehostname[HOSTNAME_MAX_LENGTH]; uint16_t siteport; uint16_t siterecport; char pggrid_op_type; //see PGGRID_OP_* //#endif } ReplicateHeader; typedef struct RecoveryPacketType { uint16_t packet_no; /* 1:start recovery prepare 2:ask pgdata 3:ans pgdata 4:send master info 5:start queueing query 6:requst fsync 7:ready to fsync 8:pepared master 9:finished rsync */ uint16_t max_connect; uint16_t port; uint16_t recoveryPort; char hostName[HOSTNAME_MAX_LENGTH]; char pg_data[PATH_MAX_LENGTH]; char userName[USERNAME_MAX_LENGTH]; } RecoveryPacket; typedef struct { char table[128]; int rec_no; char key[128]; char value[128]; char * last; char * next; } ConfDataType; typedef struct ReplicateServerInfoType { uint32_t useFlag; char hostName[HOSTNAME_MAX_LENGTH]; uint16_t portNumber; uint16_t recoveryPortNumber; uint16_t lifecheckPortNumber; uint16_t RLogPortNumber; int32_t sock; int32_t rlog_sock; uint32_t replicate_id; uint16_t response_mode; uint16_t retry_count; } ReplicateServerInfo; typedef struct ReplicateNowType { uint32_t replicate_id; int useFlag; int use_seed; int use_time; int offset_sec; int offset_usec; struct timeval tp; } ReplicateNow; typedef struct CopyDataType { int cnt; char copy_data[COPYBUFSIZ]; } CopyData; typedef struct ClusterDBInfoType { int status; } ClusterDBInfo; typedef struct { uint32_t arg1; uint32_t arg2; uint32_t arg3; char buf[1]; } LOArgs; typedef struct { int length; char data[1]; } ArrayData; extern ConfDataType * ConfData_Top; extern ConfDataType * ConfData_End; extern ReplicateServerInfo * ReplicateServerData; extern ClusterDBInfo * ClusterDBData; extern int ReplicateServerShmid; extern int ClusterDBShmid; extern bool PGR_Under_Replication_Server; extern int PGR_Replication_Timeout; extern int PGR_Lifecheck_Timeout; extern int PGR_Lifecheck_Interval; /* in backend/libpq/replicate_com.c */ extern int PGR_Create_Socket_Connect(int * fdP, char * hostName , unsigned short portNumber); extern void PGR_Close_Sock(int * sock); extern int PGR_Create_Socket_Bind(int * fdP, char * hostName , unsigned short portNumber); extern int PGR_Create_Acception(int fd, int * sockP, char * hostName , unsigned short portNumber); extern int PGR_Free_Conf_Data(void); extern int PGR_Get_Conf_Data(char * dir , char * fname); extern void PGRset_recovery_packet_no(RecoveryPacket * packet, int packet_no); extern unsigned int PGRget_ip_by_name(char * host); extern int PGRget_time_value(char *str); extern int PGRget_bw_value(char *str); extern void PGRwrite_log_file(FILE * fp, const char * fmt,...); extern void show_debug(const char * fmt,...); extern void show_error(const char * fmt,...); #endif /* REPLICATE_COM_H */
lovemomia/sogokids
src/main/java/com/sogokids/common/config/LoggerConfigurer.java
package com.sogokids.common.config; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.LoggerContext; import org.apache.commons.configuration.XMLConfiguration; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class LoggerConfigurer { private static final Logger LOGGER = LoggerFactory.getLogger(LoggerConfigurer.class); private XMLConfiguration xmlConf; public void setXmlConf(XMLConfiguration xmlConf) { this.xmlConf = xmlConf; } public void init() { reload(); } public void reload() { String loggerLevel = xmlConf.getString("Logger.Level"); if (StringUtils.isBlank(loggerLevel)) { LOGGER.warn("Logger.Level config is empty"); return; } LOGGER.info("set root logger level to: {}", loggerLevel); LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); ch.qos.logback.classic.Logger logger = context.getLogger(Logger.ROOT_LOGGER_NAME); logger.setLevel(Level.toLevel(loggerLevel, Level.INFO)); } }
mitxael/SSHIVA
src/graph-lib/homology/Gudhi/include/gudhi/Skeleton_blocker/Skeleton_blocker_simple_geometric_traits.h
/* This file is part of the Gudhi Library. The Gudhi library * (Geometric Understanding in Higher Dimensions) is a generic C++ * library for computational topology. * * Author(s): <NAME> * * Copyright (C) 2014 INRIA * * 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/>. */ #ifndef SKELETON_BLOCKER_SKELETON_BLOCKER_SIMPLE_GEOMETRIC_TRAITS_H_ #define SKELETON_BLOCKER_SKELETON_BLOCKER_SIMPLE_GEOMETRIC_TRAITS_H_ #include <gudhi/Skeleton_blocker/Skeleton_blocker_simple_traits.h> #include <string> #include <sstream> namespace Gudhi { namespace skeleton_blocker { /** * @extends SkeletonBlockerGeometricDS * @ingroup skbl * @brief Simple traits that is a model of SkeletonBlockerGeometricDS and * can be passed as a template argument to Skeleton_blocker_geometric_complex */ template<typename GeometryTrait> struct Skeleton_blocker_simple_geometric_traits : public Skeleton_blocker_simple_traits { public: typedef GeometryTrait GT; typedef typename GT::Point Point; typedef typename Skeleton_blocker_simple_traits::Root_vertex_handle Root_vertex_handle; typedef typename Skeleton_blocker_simple_traits::Graph_vertex Simple_vertex; /** * @brief Vertex with a point attached. */ class Simple_geometric_vertex : public Simple_vertex { template<class ComplexGeometricTraits> friend class Skeleton_blocker_geometric_complex; private: Point point_; Point& point() { return point_; } const Point& point() const { return point_; } }; class Simple_geometric_edge : public Skeleton_blocker_simple_traits::Graph_edge { int index_; public: Simple_geometric_edge() : Skeleton_blocker_simple_traits::Graph_edge(), index_(-1) { } /** * @brief Allows to modify the index of the edge. * The indices of the edge are used to store heap information * in the edge contraction algorithm. */ int& index() { return index_; } int index() const { return index_; } }; typedef Simple_geometric_vertex Graph_vertex; typedef Skeleton_blocker_simple_traits::Graph_edge Graph_edge; }; } // namespace skeleton_blocker namespace skbl = skeleton_blocker; } // namespace Gudhi #endif // SKELETON_BLOCKER_SKELETON_BLOCKER_SIMPLE_GEOMETRIC_TRAITS_H_
Raman-Sapient/react-aem-starterkit
src/platform/components/ConfigContext/index.js
<filename>src/platform/components/ConfigContext/index.js import React, { Component } from 'react'; import ConfigContext from './createContext'; class ConfigConsumer extends Component { addConfigToChildren = context => { return React.Children.map(this.props.children, (child, i) => { let config = {}; const id = child.props.id || null; if (typeof child.type === 'function' && id && context[id]) { config = { ...context[id] }; return React.cloneElement(child, { config }); } else { return child; } }); }; render() { return <ConfigContext.Consumer>{context => this.addConfigToChildren(context)}</ConfigContext.Consumer>; } } export {ConfigConsumer as default, ConfigContext};
mauzey1/scream
components/scream/src/physics/shoc/tests/shoc_unit_tests_common.hpp
#ifndef SHOC_UNIT_TESTS_COMMON_HPP #define SHOC_UNIT_TESTS_COMMON_HPP #include "physics/shoc/shoc_functions.hpp" #include "share/scream_types.hpp" #include "ekat/kokkos/ekat_kokkos_utils.hpp" namespace scream { namespace shoc { namespace unit_test { /* * Unit test infrastructure for shoc unit tests. * * shoc entities can friend scream::shoc::unit_test::UnitWrap to give unit tests * access to private members. * * All unit test impls should be within an inner struct of UnitWrap::UnitTest for * easy access to useful types. */ struct UnitWrap { template <typename D=DefaultDevice> struct UnitTest : public KokkosTypes<D> { using Device = D; using MemberType = typename KokkosTypes<Device>::MemberType; using TeamPolicy = typename KokkosTypes<Device>::TeamPolicy; using RangePolicy = typename KokkosTypes<Device>::RangePolicy; using ExeSpace = typename KokkosTypes<Device>::ExeSpace; template <typename S> using view_1d = typename KokkosTypes<Device>::template view_1d<S>; template <typename S> using view_2d = typename KokkosTypes<Device>::template view_2d<S>; template <typename S> using view_3d = typename KokkosTypes<Device>::template view_3d<S>; template <typename S> using uview_1d = typename ekat::template Unmanaged<view_1d<S> >; using Functions = scream::shoc::Functions<Real, Device>; using Scalar = typename Functions::Scalar; using Spack = typename Functions::Spack; using Pack = typename Functions::Pack; using IntSmallPack = typename Functions::IntSmallPack; using Smask = typename Functions::Smask; using C = typename Functions::C; static constexpr Int max_pack_size = 16; static constexpr Int num_test_itrs = max_pack_size / Spack::n; // Put struct decls here struct TestCalcShocVertflux; struct TestShocDiagObklen; struct TestImpCompTmpi; struct TestImpDpInverse; struct TestImpSfcFluxes; struct TestImpSfcStress; struct TestImpTkeSfcStress; struct TestShocUpdateDse; struct TestShocEnergyFixer; struct TestShocEnergyInt; struct TestShocTotEnergyFixer; struct TestShocEnergyDseFixer; struct TestShocEnergyThreshFixer; struct TestShocEddyDiff; struct TestShocGrid; struct TestShocCheckTke; struct TestShocTke; struct TestShocAdvSgsTke; struct TestShocIntColStab; struct TestShocIsotropicTs; struct TestShocShearProd; struct TestShocVarorCovar; struct TestShocLength; struct TestCompBruntShocLength; struct TestCheckShocLength; struct TestClipThirdMoms; struct TestAAdiagThirdMoms; struct TestW3diagThirdMoms; struct TestFtermInputThirdMoms; struct TestFtermdiagThirdMoms; struct TestOmegadiagThirdMoms; struct TestXYdiagThirdMoms; struct TestCompShocConvTime; struct TestCompShocConvVel; struct TestLInfShocLength; struct TestCompShocMixLength; struct TestSecondMomSrf; struct TestShocCompDiagThird; struct TestShocDiagThird; struct TestShocLinearInt; struct TestShocPdfTildetoReal; struct TestShocVVParameters; struct TestShocThlParameters; struct TestShocQwParameters; struct TestShocInPlumeCorr; struct TestShocAssumedPdf; struct TestShocPdfComputeTemp; struct TestShocPdfComputeQs; struct TestShocPdfComputeS; struct TestShocPdfComputeSgsLiq; struct TestShocPdfCompCldVar; struct TestShocPdfCompLiqFlux; struct TestShocPdfCompBuoyFlux; struct TestSecondMomUbycond; struct TestPblintdInitPot; struct TestDiagSecondMomentsLbycond; struct TestDiagSecondMoments; struct TestDiagSecondShocMoments; struct TestPblintdCldCheck; struct TestComputeShocVapor; struct TestUpdatePrognosticsImplicit; struct TestShocMain; struct TestPblintdHeight; struct TestPblintdInit; struct TestVdShocDecompandSolve; struct TestPblintdInit; struct TestPblintdSurfTemp; struct TestPblintdCheckPblh; struct TestPblintd; }; }; } // namespace unit_test } // namespace shoc } // namespace scream #endif
yyakun/TBLibrary
TBLibrary/Classes/TBKit/Core/TBTipView.h
// // TBTipView.h // TBLibrary // // Created by 杨亚坤 on 2017/3/13. // Copyright © 2017年 yyk. All rights reserved. // #import <UIKit/UIKit.h> @interface TBTipView : UIView @property (nonatomic, strong, readonly) UILabel *label; @end
maciejg-git/vue-bootstrap-icons
dist-mdi/mdi/pail-off-outline.js
<gh_stars>0 import { h } from 'vue' export default { name: "PailOffOutline", vendor: "Mdi", type: "", tags: ["pail","off","outline"], render() { return h( "svg", {"xmlns":"http://www.w3.org/2000/svg","width":"24","height":"24","viewBox":"0 0 24 24","class":"v-icon","fill":"currentColor","data-name":"mdi-pail-off-outline","innerHTML":"<path d='M20.84 22.73L17.35 19.24L17 21H7L5.9 15.5L7.73 14.43L8.64 19H15.36L15.65 17.54L9.31 11.2L4.27 14.11C3.79 14.39 3.18 14.23 2.9 13.75C2.62 13.27 2.79 12.66 3.27 12.38L7.85 9.74L6.38 8.27L4.65 9.27L4 6H3V4.89L1.11 3L2.39 1.73L22.11 21.46L20.84 22.73M17.96 6L16.5 13.3L18.2 15L20 6H21V4H7.2L9.2 6H17.96M11.5 7.63L11.08 7.88L12.53 9.33C12.97 9.05 13.13 8.46 12.86 8C12.58 7.5 11.97 7.35 11.5 7.63Z' />"}, ) } }
OpenMPDK/SMDK
src/app/voltdb/voltdb_src/src/frontend/org/voltdb/client/ClientUtils.java
<gh_stars>10-100 /* This file is part of VoltDB. * Copyright (C) 2008-2020 VoltDB Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with VoltDB. If not, see <http://www.gnu.org/licenses/>. */ package org.voltdb.client; import java.io.File; import java.io.FileInputStream; import java.io.IOException; /** * Helper methods duplicated from MiscUtils to avoid linking with * some of the stuff MiscUtils brings in. * */ public class ClientUtils { /** * Serialize a file into bytes. Used to serialize catalog and deployment * file for UpdateApplicationCatalog on the client. * * @param path * @return a byte array of the file * @throws IOException * If there are errors reading the file */ public static byte[] fileToBytes(File path) throws IOException { FileInputStream fin = new FileInputStream(path); byte[] buffer = new byte[(int) fin.getChannel().size()]; try { if (fin.read(buffer) == -1) { throw new IOException("File " + path.getAbsolutePath() + " is empty"); } } finally { fin.close(); } return buffer; } }
kit-transue/software-emancipation-discover
newntui/discovermdi/src/WaitDlg.cpp
<gh_stars>1-10 /************************************************************************* * Copyright (c) 2015, Synopsys, Inc. * * All rights reserved. * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions are * * met: * * * * 1. Redistributions of source code must retain the above copyright * * notice, this list of conditions and the following disclaimer. * * * * 2. Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in the * * documentation and/or other materials provided with the distribution. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *************************************************************************/ // WaitDlg.cpp : implementation file // #include "stdafx.h" #include "discovermdi.h" #include "WaitDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CWaitDlg dialog const int CWaitDlg::GRANULARITY = 100; CWaitDlg::CWaitDlg(HANDLE hProcess,CWnd* pParent /*=NULL*/) : CDialog(CWaitDlg::IDD, pParent) { m_pCompletionProvider = NULL; m_hProcess = hProcess; m_szMessage = ""; //{{AFX_DATA_INIT(CWaitDlg) //}}AFX_DATA_INIT } void CWaitDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CWaitDlg) DDX_Control(pDX, IDC_MESSAGE, m_MessageCtrl); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CWaitDlg, CDialog) //{{AFX_MSG_MAP(CWaitDlg) ON_WM_TIMER() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CWaitDlg message handlers int CWaitDlg::Wait(int nTimeout /*=0*/) { /* Create(IDD); CWnd* pParent=GetParent(); if(pParent==NULL) { pParent=AfxGetMainWnd(); SetParent(pParent); } CenterWindow(pParent); UINT nTimer = SetTimer(1,100,0); // enter modal loop DWORD dwFlags = MLF_SHOWONIDLE | WF_CONTINUEMODAL | WF_MODALLOOP; if (GetStyle() & DS_NOIDLEMSG) dwFlags |= MLF_NOIDLEMSG; VERIFY(RunModalLoop(dwFlags) == m_nModalResult); */ m_nTimeout = nTimeout; m_bTimeoutSet = m_nTimeout>0; return DoModal(); // KillTimer(nTimer); // return m_nModalResult; } void CWaitDlg::OnTimer(UINT nIDEvent) { // Wait until child process exits. if(WaitForSingleObject( m_hProcess, 0 )==WAIT_OBJECT_0) EndDialog(IDOK); else if(m_pCompletionProvider!=NULL && m_pCompletionProvider->IsWaitComplete()) EndDialog(IDOK); else if(m_bTimeoutSet) { m_nTimeout -= GRANULARITY; if(m_nTimeout<=0) EndDialog(IDOK); } CDialog::OnTimer(nIDEvent); } void CWaitDlg::OnOK() { // do nothing - just wait for process to finish } void CWaitDlg::OnCancel() { // do nothing - just wait for process to finish } CString CWaitDlg::GetTextWithEllipsis(CDC* pDC, CString& szString, CRect& Rect) { SIZE Size; int nFit; int nWidth = Rect.right-Rect.left; CString EllipsisString; BOOL fSuccess = FALSE; // Get how many chars will fit. fSuccess = GetTextExtentExPoint( pDC->GetSafeHdc(), szString, szString.GetLength(), nWidth, &nFit, NULL, &Size); // Get the dimensions of the full string. if(fSuccess) fSuccess = GetTextExtentExPoint( pDC->GetSafeHdc(), szString, szString.GetLength(), nWidth, NULL, NULL, &Size); if(fSuccess && nFit<szString.GetLength()) { // Copy to our working buffer. int nStart = nFit/2; int nRest = nFit-nStart; // If we need Ellipsis'. while(Size.cx > nWidth && fSuccess) { // Add them to what will fit and try again. EllipsisString = szString.Left(nStart); EllipsisString += "..."; EllipsisString += szString.Right(nRest); fSuccess = GetTextExtentExPoint( pDC->GetSafeHdc(), EllipsisString, EllipsisString.GetLength(), nWidth, NULL, NULL, &Size); nStart--; // Decrement in case we need another pass. nRest--; // Rectangle too small. if (nStart<=0 && nRest<=0) fSuccess = FALSE; } // if no success - return an empty string if(!fSuccess) EllipsisString = ""; // Working buffer now contains the string with Ellipsis'. } else { // Else no rectangle so return the same string we received as an input. EllipsisString = szString; } return EllipsisString; } int CWaitDlg::DoModal() { // can be constructed with a resource template or InitModalIndirect ASSERT(m_lpszTemplateName != NULL || m_hDialogTemplate != NULL || m_lpDialogTemplate != NULL); // load resource as necessary LPCDLGTEMPLATE lpDialogTemplate = m_lpDialogTemplate; HGLOBAL hDialogTemplate = m_hDialogTemplate; HINSTANCE hInst = AfxGetResourceHandle(); if (m_lpszTemplateName != NULL) { hInst = AfxFindResourceHandle(m_lpszTemplateName, RT_DIALOG); HRSRC hResource = ::FindResource(hInst, m_lpszTemplateName, RT_DIALOG); hDialogTemplate = LoadResource(hInst, hResource); } if (hDialogTemplate != NULL) lpDialogTemplate = (LPCDLGTEMPLATE)LockResource(hDialogTemplate); // return -1 in case of failure to load the dialog template resource if (lpDialogTemplate == NULL) return -1; // disable parent (before creating dialog) HWND hWndParent = PreModal(); AfxUnhookWindowCreate(); BOOL bEnableParent = FALSE; if (hWndParent != NULL && ::IsWindowEnabled(hWndParent)) { ::EnableWindow(hWndParent, FALSE); bEnableParent = TRUE; } TRY { // create modeless dialog AfxHookWindowCreate(this); if (CreateDlgIndirect(lpDialogTemplate, CWnd::FromHandle(hWndParent), hInst)) { CDC* pDC = m_MessageCtrl.GetWindowDC(); CFont* pFont = pDC->SelectObject(m_MessageCtrl.GetFont()); CRect compRect; m_MessageCtrl.GetClientRect(compRect); m_MessageCtrl.SetWindowText(GetTextWithEllipsis(pDC,m_szMessage,compRect)); pDC->SelectObject(pFont); UINT nTimer = SetTimer(1,GRANULARITY,0); if (m_nFlags & WF_CONTINUEMODAL) { // enter modal loop DWORD dwFlags = MLF_SHOWONIDLE; if (GetStyle() & DS_NOIDLEMSG) dwFlags |= MLF_NOIDLEMSG; VERIFY(RunModalLoop(dwFlags) == m_nModalResult); } // hide the window before enabling the parent, etc. if (m_hWnd != NULL) SetWindowPos(NULL, 0, 0, 0, 0, SWP_HIDEWINDOW| SWP_NOSIZE|SWP_NOMOVE|SWP_NOACTIVATE|SWP_NOZORDER); KillTimer(nTimer); } } CATCH_ALL(e) { e->Delete(); m_nModalResult = -1; } END_CATCH_ALL if (bEnableParent) ::EnableWindow(hWndParent, TRUE); if (hWndParent != NULL && ::GetActiveWindow() == m_hWnd) ::SetActiveWindow(hWndParent); // destroy modal window DestroyWindow(); PostModal(); // unlock/free resources as necessary if (m_lpszTemplateName != NULL || m_hDialogTemplate != NULL) UnlockResource(hDialogTemplate); if (m_lpszTemplateName != NULL) FreeResource(hDialogTemplate); return m_nModalResult; } void CWaitDlg::SetCompletionProvider(CCompletionProvider* pProvider) { m_pCompletionProvider = pProvider; } void CWaitDlg::SetMessage(CString &szMsg) { m_szMessage = szMsg; }
yndu13/aliyun-openapi-python-sdk
aliyun-python-sdk-iotcc/aliyunsdkiotcc/request/v20210513/ListIoTCloudConnectorGroupsRequest.py
<gh_stars>0 # 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. from aliyunsdkcore.request import RpcRequest class ListIoTCloudConnectorGroupsRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'IoTCC', '2021-05-13', 'ListIoTCloudConnectorGroups','IoTCC') self.set_method('POST') def get_NextToken(self): # String return self.get_query_params().get('NextToken') def set_NextToken(self, NextToken): # String self.add_query_param('NextToken', NextToken) def get_IoTCloudConnectorGroupIdss(self): # RepeatList return self.get_query_params().get('IoTCloudConnectorGroupIds') def set_IoTCloudConnectorGroupIdss(self, IoTCloudConnectorGroupIds): # RepeatList for depth1 in range(len(IoTCloudConnectorGroupIds)): self.add_query_param('IoTCloudConnectorGroupIds.' + str(depth1 + 1), IoTCloudConnectorGroupIds[depth1]) def get_IoTCloudConnectorGroupStatuss(self): # RepeatList return self.get_query_params().get('IoTCloudConnectorGroupStatus') def set_IoTCloudConnectorGroupStatuss(self, IoTCloudConnectorGroupStatus): # RepeatList for depth1 in range(len(IoTCloudConnectorGroupStatus)): self.add_query_param('IoTCloudConnectorGroupStatus.' + str(depth1 + 1), IoTCloudConnectorGroupStatus[depth1]) def get_IoTCloudConnectorGroupNames(self): # RepeatList return self.get_query_params().get('IoTCloudConnectorGroupName') def set_IoTCloudConnectorGroupNames(self, IoTCloudConnectorGroupName): # RepeatList for depth1 in range(len(IoTCloudConnectorGroupName)): self.add_query_param('IoTCloudConnectorGroupName.' + str(depth1 + 1), IoTCloudConnectorGroupName[depth1]) def get_MaxResults(self): # Integer return self.get_query_params().get('MaxResults') def set_MaxResults(self, MaxResults): # Integer self.add_query_param('MaxResults', MaxResults)
Deependra-Patel/hadoop-connectors
gcs/src/test/java/com/google/cloud/hadoop/fs/gcs/contract/AbstractGoogleContractConcatTest.java
<reponame>Deependra-Patel/hadoop-connectors package com.google.cloud.hadoop.fs.gcs.contract; import static org.apache.hadoop.fs.contract.ContractTestUtils.assertFileHasLength; import static org.apache.hadoop.fs.contract.ContractTestUtils.createFile; import static org.apache.hadoop.fs.contract.ContractTestUtils.dataset; import com.google.cloud.hadoop.gcsio.GoogleCloudStorage; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.contract.AbstractContractConcatTest; import org.apache.hadoop.fs.contract.ContractTestUtils; import org.junit.Test; public abstract class AbstractGoogleContractConcatTest extends AbstractContractConcatTest { @Test public void testConcatMultiple() throws Throwable { int numFiles = GoogleCloudStorage.MAX_COMPOSE_OBJECTS * 3 / 2; Path testPath = path("test"); byte[][] blocks = new byte[numFiles][0]; Path[] srcs = new Path[numFiles]; for (int i = 0; i < numFiles; i++) { Path srcFile = new Path(testPath, "" + i); blocks[i] = dataset(TEST_FILE_LEN, i, 255); createFile(getFileSystem(), srcFile, true, blocks[i]); srcs[i] = srcFile; } Path target = new Path(testPath, "target"); createFile(getFileSystem(), target, false, new byte[0]); getFileSystem().concat(target, srcs); assertFileHasLength(getFileSystem(), target, TEST_FILE_LEN * numFiles); ContractTestUtils.validateFileContent( ContractTestUtils.readDataset(getFileSystem(), target, TEST_FILE_LEN * numFiles), blocks); } }
Hotels4Hope/static-assets
ares/src/62635.js
import '../site_configs/lolla_22-62635/js/62635'; import '../site_configs/lolla_22-62635/styles/62635.scss';
DLotts/incubator-rya
extras/rya.merger/src/test/java/org/apache/rya/accumulo/mr/merge/demo/util/DemoUtilities.java
<filename>extras/rya.merger/src/test/java/org/apache/rya/accumulo/mr/merge/demo/util/DemoUtilities.java /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.rya.accumulo.mr.merge.demo.util; import java.util.Scanner; import org.apache.commons.math3.random.RandomDataGenerator; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.Level; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.apache.log4j.PatternLayout; /** * Utilities methods for the demo. */ public final class DemoUtilities { private static final Logger log = Logger.getLogger(DemoUtilities.class); /** * Holds different logging patterns to use. */ public static enum LoggingDetail { /** * Uses a light pattern layout. * */ LIGHT(new PatternLayout("%-5p - %m%n")), /** * Uses a detailed pattern layout. */ DETAILED(new PatternLayout("%d{MMM dd yyyy HH:mm:ss} %5p [%t] (%F:%L) - %m%n")); private PatternLayout patternLayout; /** * Create a new {@link LoggingDetail}. * @param patternLayout the {@link PatternLayout}. */ private LoggingDetail(final PatternLayout patternLayout) { this.patternLayout = patternLayout; } /** * @return the {@link PatternLayout}. */ public PatternLayout getPatternLayout() { return patternLayout; } } private static final Scanner KEYBOARD_SCANNER = new Scanner(System.in); /** * Private constructor to prevent instantiation. */ private DemoUtilities() { } /** * Generates a random {@code long} number within the specified range. * @param min the minimum value (inclusive) of the range of {@code long}s to include. * @param max the maximum value (inclusive) of the range of {@code long}s to include. * @return the random {@code long}. */ public static long randLong(final long min, final long max) { return new RandomDataGenerator().nextLong(min, max); } /** * Sets up log4j logging to fit the demo's needs. */ public static void setupLogging() { setupLogging(LoggingDetail.LIGHT); } /** * Sets up log4j logging to fit the demo's needs. * @param loggingDetail the {@link LoggingDetail} to use. */ public static void setupLogging(final LoggingDetail loggingDetail) { // Turn off all the loggers and customize how they write to the console. final Logger rootLogger = LogManager.getRootLogger(); rootLogger.setLevel(Level.OFF); final ConsoleAppender ca = (ConsoleAppender) rootLogger.getAppender("stdout"); ca.setLayout(loggingDetail.getPatternLayout()); // Turn the loggers used by the demo back on. //log.setLevel(Level.INFO); rootLogger.setLevel(Level.INFO); } /** * Pauses the program until the user presses "Enter" in the console. */ public static void promptEnterKey() { promptEnterKey(true); } /** * Pauses the program until the user presses "Enter" in the console. * @param isPromptEnabled {@code true} if prompt display is enabled. {@code false} * otherwise. */ public static void promptEnterKey(final boolean isPromptEnabled) { if (isPromptEnabled) { log.info("Press \"ENTER\" to continue..."); KEYBOARD_SCANNER.nextLine(); } } }
eneufeld/emfcloud-modelserver
bundles/org.eclipse.emfcloud.modelserver.emf/src/org/eclipse/emfcloud/modelserver/emf/common/DefaultSessionController.java
/******************************************************************************** * Copyright (c) 2019 EclipseSource and others. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0 which is available at * https://www.eclipse.org/legal/epl-2.0, or the MIT License which is * available at https://opensource.org/licenses/MIT. * * SPDX-License-Identifier: EPL-2.0 OR MIT ********************************************************************************/ package org.eclipse.emfcloud.modelserver.emf.common; import static org.eclipse.emfcloud.modelserver.common.ModelServerPathParametersV1.LIVE_VALIDATION; import static org.eclipse.emfcloud.modelserver.common.ModelServerPathParametersV1.TIMEOUT; import static org.eclipse.emfcloud.modelserver.emf.common.JsonResponse.dirtyState; import static org.eclipse.emfcloud.modelserver.emf.common.JsonResponse.fullUpdate; import static org.eclipse.emfcloud.modelserver.emf.common.JsonResponse.validationResult; import static org.eclipse.emfcloud.modelserver.emf.common.util.ContextRequest.getBooleanParam; import static org.eclipse.emfcloud.modelserver.emf.common.util.ContextRequest.getLongParam; import static org.eclipse.emfcloud.modelserver.emf.common.util.ContextRequest.isMessageType; import static org.eclipse.emfcloud.modelserver.emf.common.util.ContextResponse.dirtyState; import static org.eclipse.emfcloud.modelserver.emf.common.util.ContextResponse.keepAlive; import static org.eclipse.emfcloud.modelserver.emf.common.util.ContextResponse.success; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Stream; import org.apache.log4j.Logger; import org.eclipse.emf.ecore.EObject; import org.eclipse.emfcloud.modelserver.command.CCommandExecutionResult; import org.eclipse.emfcloud.modelserver.common.codecs.EncodingException; import org.eclipse.emfcloud.modelserver.emf.common.codecs.CodecsManager; import org.jetbrains.annotations.Nullable; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.NullNode; import com.google.common.collect.Maps; import com.google.inject.Inject; import io.javalin.websocket.WsContext; import io.javalin.websocket.WsMessageContext; public class DefaultSessionController implements SessionController { protected static Logger LOG = Logger.getLogger(DefaultSessionController.class.getSimpleName()); protected final Map<String, Set<WsContext>> modelUrisToClients = Maps.newConcurrentMap(); @Inject protected ModelRepository modelRepository; @Inject protected CodecsManager encoder; @Inject protected ModelValidator modelValidator; @Override public boolean subscribe(final WsContext client, final String modeluri) { if (!this.modelRepository.hasModel(modeluri)) { return false; } Long timeout = getLongParam(client, TIMEOUT).orElse(SessionController.NO_TIMEOUT); modelUrisToClients.computeIfAbsent(modeluri, clients -> ConcurrentHashMap.newKeySet()).add(client); client.session.setIdleTimeout(timeout); success(client); dirtyState(client, modelRepository.getDirtyState(modeluri)); return true; } @Override public boolean unsubscribe(final WsContext client) { if (!this.isClientSubscribed(client)) { return false; } Iterator<Map.Entry<String, Set<WsContext>>> modelUriToClients = modelUrisToClients.entrySet().iterator(); while (modelUriToClients.hasNext()) { Set<WsContext> clients = modelUriToClients.next().getValue(); clients.remove(client); if (clients.isEmpty()) { modelUriToClients.remove(); } } return true; } @Override public boolean handleMessage(final WsMessageContext clientMessage) { if (!isClientSubscribed(clientMessage) || !isMessageType(clientMessage, JsonResponseType.KEEPALIVE)) { return false; } keepAlive(clientMessage); return true; } @Override public void modelCreated(final String modeluri) { Optional<EObject> root = modelRepository.getModel(modeluri); if (root.isEmpty()) { broadcastError(modeluri, "Could not load changed object"); return; } broadcastFullUpdate(modeluri, root.get()); broadcastDirtyState(modeluri, modelRepository.getDirtyState(modeluri)); broadcastValidation(modeluri); } @Override public void modelUpdated(final String modeluri) { Optional<EObject> root = modelRepository.getModel(modeluri); if (root.isEmpty()) { broadcastError(modeluri, "Could not load changed object"); return; } broadcastFullUpdate(modeluri, root.get()); broadcastDirtyState(modeluri, modelRepository.getDirtyState(modeluri)); broadcastValidation(modeluri); } @Override public void commandExecuted(final String modeluri, final CCommandExecutionResult execution) { Optional<EObject> root = modelRepository.getModel(modeluri); if (root.isEmpty()) { broadcastError(modeluri, "Could not load changed object"); return; } broadcastIncrementalUpdates(modeluri, execution); broadcastDirtyState(modeluri, modelRepository.getDirtyState(modeluri)); broadcastValidation(modeluri); } @Override public void modelDeleted(final String modeluri) { broadcastFullUpdate(modeluri, null); } @Override public void modelClosed(final String modeluri) { // depending on resource manager, model may have been automatically reloaded or not boolean isLoaded = modelRepository.hasModel(modeluri); if (isLoaded) { modelUpdated(modeluri); } else { broadcastFullUpdate(modeluri, null); } } @Override public void modelSaved(final String modeluri) { broadcastDirtyState(modeluri, modelRepository.getDirtyState(modeluri)); } @Override public void allModelsSaved() { for (String modeluri : modelRepository.getAbsoluteModelUris()) { broadcastDirtyState(modeluri, modelRepository.getDirtyState(modeluri)); } } @Override public boolean hasSession(final String modeluri) { return modelUrisToClients.containsKey(modeluri); } protected void broadcastValidation(final String modeluri) { broadcastValidation(modeluri, modelValidator.validate(modeluri)); } protected void broadcastFullUpdate(final String modeluri, @Nullable final EObject updatedModel) { if (modelUrisToClients.containsKey(modeluri)) { getOpenSessions(modeluri).forEach(session -> broadcastFullUpdate(modeluri, updatedModel, session)); } } protected void broadcastFullUpdate(final String modeluri, final EObject updatedModel, final WsContext session) { try { if (updatedModel == null) { // model has been deleted session.send(fullUpdate(NullNode.getInstance())); } else { session.send(fullUpdate(encoder.encode(session, updatedModel))); } } catch (EncodingException e) { LOG.error("Broadcast full update of " + modeluri + " failed", e); } } protected void broadcastIncrementalUpdates(final String modeluri, final CCommandExecutionResult execution) { Map<String, JsonNode> updates = encodeIfPresent(modeluri, execution); getOpenSessions(modeluri).forEach(session -> broadcastIncrementalUpdate(session, updates)); } private void broadcastIncrementalUpdate(final WsContext session, final Map<String, JsonNode> updates) { String sessionFormat = encoder.findFormat(session); JsonNode update = updates.get(sessionFormat); session.send(JsonResponse.incrementalUpdate(update)); } protected void broadcastDirtyState(final String modeluri, final Boolean isDirty) { getOpenSessions(modeluri).forEach(session -> session.send(dirtyState(isDirty))); } protected void broadcastValidation(final String modeluri, final JsonNode newResult) { getOpenValidationSessions(modeluri).forEach(session -> session.send(validationResult(newResult))); } protected Stream<WsContext> getOpenSessions(final String modeluri) { return modelUrisToClients.getOrDefault(modeluri, Collections.emptySet()).stream() .filter(ctx -> ctx.session.isOpen()); } protected Stream<WsContext> getOpenValidationSessions(final String modeluri) { return getOpenSessions(modeluri).filter(this::requiresLiveValidation); } protected void broadcastError(final String modeluri, final String errorMessage) { getOpenSessions(modeluri).forEach(session -> session.send(JsonResponse.error(errorMessage))); } protected boolean requiresLiveValidation(final WsContext client) { return getBooleanParam(client, LIVE_VALIDATION).orElse(false); } protected boolean isClientSubscribed(final WsContext ctx) { return modelUrisToClients.entrySet().stream().anyMatch(entry -> entry.getValue().contains(ctx)); } protected Map<String, JsonNode> encodeIfPresent(final String modeluri, final EObject execution) { Map<String, JsonNode> encodings = new HashMap<>(); if (hasSession(modeluri)) { try { encodings = encoder.encode(execution); } catch (EncodingException exception) { LOG.error("Pre encoding of undo/redo command for " + modeluri + " failed", exception); } } return encodings; } }
tommyettinger/assorted-benchmarks
jmh/src/main/java/de/heidelberg/pvs/container_bench/factories/JDKIntSetFact.java
<gh_stars>1-10 package de.heidelberg.pvs.container_bench.factories; import java.util.Set; import java.util.function.Supplier; public enum JDKIntSetFact { JDK_HASH(java.util.HashSet::new), // JDK_LINKEDHASH(java.util.LinkedHashSet::new), // JDK_TREE(java.util.TreeSet::new), // KOLOBOKE_HASH(com.koloboke.collect.set.hash.HashObjSets::newMutableSet), // KOLOBOKE_QHASH(KolobokeQHash.ObjSets::newMutableSet), // KOLOBOKE_I_HASH(com.koloboke.collect.set.hash.HashIntSets::newMutableSet), //), // KOLOBOKE_I_QHASH(KolobokeQHash.IntSets::newMutableSet), // FASTUTIL_HASH(it.unimi.dsi.fastutil.objects.ObjectOpenHashSet::new), // FASTUTIL_LINKEDHASH(it.unimi.dsi.fastutil.objects.ObjectLinkedOpenHashSet::new), // FASTUTIL_AVL(it.unimi.dsi.fastutil.objects.ObjectAVLTreeSet::new), //), // FASTUTIL_RB(it.unimi.dsi.fastutil.objects.ObjectRBTreeSet::new), // FASTUTIL_ARRAY(it.unimi.dsi.fastutil.objects.ObjectArraySet::new), // // Fastutil primitive-valued FASTUTIL_I_HASH(it.unimi.dsi.fastutil.ints.IntOpenHashSet::new), // FASTUTIL_I_LINKEDHASH(it.unimi.dsi.fastutil.ints.IntLinkedOpenHashSet::new), // FASTUTIL_I_AVL(it.unimi.dsi.fastutil.ints.IntAVLTreeSet::new), // FASTUTIL_I_RB(it.unimi.dsi.fastutil.ints.IntRBTreeSet::new), // FASTUTIL_I_ARRAY(it.unimi.dsi.fastutil.ints.IntArraySet::new), // TROVE_HASH(gnu.trove.set.hash.THashSet::new), // ECLIPSE_HASH(org.eclipse.collections.impl.set.mutable.UnifiedSet::new), // ECLIPSE_TREE(org.eclipse.collections.impl.set.sorted.mutable.TreeSortedSet::new), // APACHE_HASH(() -> org.apache.commons.collections4.set.MapBackedSet.mapBackedSet(// new org.apache.commons.collections4.map.HashedMap<Integer, Integer>())), // APACHE_LINKEDHASH(org.apache.commons.collections4.set.ListOrderedSet::new), // MAHOUT_HASH(org.apache.mahout.math.set.OpenHashSet::new), // JAVOLUTION_HASH(javolution.util.FastSet::new), // JAVOLUTION_SORTED(javolution.util.FastSortedSet::new), // AGRONA_HASH(org.agrona.collections.ObjectHashSet::new), // CORENLP_ARRAY(edu.stanford.nlp.util.ArraySet::new); // ; public final Supplier<Set<Integer>> maker; private JDKIntSetFact(Supplier<Set<Integer>> maker) { this.maker = maker; } }
IOR-BIC/ALBA
Operations/albaOpExporterAnsysCommon.cpp
<gh_stars>1-10 /*========================================================================= Program: ALBA Module: albaOpExporterAnsysCommon.cpp Authors: <NAME>, <NAME> Copyright (c) BIC All rights reserved. See Copyright.txt or http://www.scsitaly.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "albaDefines.h" //---------------------------------------------------------------------------- // NOTE: Every CPP file in the ALBA must include "albaDefines.h" as first. // This force to include Window,wxWidgets and VTK exactly in this order. // Failing in doing this will result in a run-time error saying: // "Failure#0: The value of ESP was not properly saved across a function call" //---------------------------------------------------------------------------- #include "albaOpExporterAnsysCommon.h" #include "albaOpImporterAnsysCommon.h" #include "albaDecl.h" #include "albaGUI.h" #include "albaSmartPointer.h" #include "albaTagItem.h" #include "albaTagArray.h" #include "albaVME.h" #include "albaVMEMesh.h" #include "albaVMEMeshAnsysTextExporter.h" #include "albaAbsMatrixPipe.h" #include <iostream> #include <fstream> // vtk includes #include "vtkALBASmartPointer.h" #include "vtkUnstructuredGrid.h" #include "vtkCellArray.h" #include "vtkDoubleArray.h" #include "vtkIntArray.h" #include "vtkPointData.h" #include "vtkCellData.h" #include "vtkFieldData.h" #include "vtkTransform.h" #include "vtkTransformFilter.h" // vcl includes #include <vcl_string.h> #include <vcl_fstream.h> #include <vcl_sstream.h> #include <vcl_map.h> #include <vcl_vector.h> #include "wx/stdpaths.h" //---------------------------------------------------------------------------- albaCxxAbstractTypeMacro(albaOpExporterAnsysCommon); //---------------------------------------------------------------------------- albaOpExporterAnsysCommon::albaOpExporterAnsysCommon(const wxString &label) : albaOpExporterFEMCommon(label) { m_AnsysOutputFileNameFullPath = ""; } //---------------------------------------------------------------------------- albaOpExporterAnsysCommon::~albaOpExporterAnsysCommon() { } //---------------------------------------------------------------------------- void albaOpExporterAnsysCommon::OpRun() { Init(); CreateGui(); } //---------------------------------------------------------------------------- void albaOpExporterAnsysCommon::OnOK() { albaString wildcard = GetWildcard(); m_AnsysOutputFileNameFullPath = ""; wxString f; f = albaGetSaveFile("",wildcard).c_str(); if(!f.IsEmpty()) { m_AnsysOutputFileNameFullPath = f; Write(); } } //---------------------------------------------------------------------------- void albaOpExporterAnsysCommon::OpStop(int result) { HideGui(); albaEventMacro(albaEvent(this,result)); } //--------------------------------------------------------------------------- void albaOpExporterAnsysCommon::Init() { albaVMEMesh *input = albaVMEMesh::SafeDownCast(m_Input); assert(input); vtkUnstructuredGrid *inputUGrid = input->GetUnstructuredGridOutput()->GetUnstructuredGridData(); if(inputUGrid != NULL) { // Calculate Num of Elements m_TotalElements = inputUGrid->GetNumberOfPoints(); // Points m_TotalElements += inputUGrid->GetNumberOfCells(); // Elements vtkDataArray *materialsIDArray = NULL; materialsIDArray = inputUGrid->GetCellData()->GetArray("EX"); if (materialsIDArray != NULL) { m_TotalElements += materialsIDArray->GetNumberOfTuples(); // Materials } } } //---------------------------------------------------------------------------- int albaOpExporterAnsysCommon::compareElem(const void *p1, const void *p2) { ExportElement *a, *b; a = (ExportElement *)p1; b = (ExportElement *)p2; double result; // Compare Sort Order // by elementType // else by matID // else by elementID result = a->elementType - b->elementType; if (result < 0) return -1; else if (result > 0) return 1; else { result = a->matID - b->matID; if (result < 0) return -1; else if (result > 0) return 1; else { result = a->elementID - b->elementID; if (result < 0) return -1; else if (result > 0) return 1; else assert(0); //two elements have the same element ID } } } //--------------------------------------------------------------------------- ExportElement *albaOpExporterAnsysCommon::CreateExportElements(albaVMEMesh * input, int rowsNumber, vtkUnstructuredGrid * inputUGrid, FILE * file) { // get the ELEMENT_ID array vtkIntArray *elementIdArray = input->GetElementsIDArray(); // get the Nodes Id array vtkIntArray *nodesIDArray = input->GetNodesIDArray(); // get the TYPE array vtkIntArray *typeArray = input->GetElementsTypeArray(); // get the REAL array vtkIntArray *realArray = input->GetElementsRealArray(); ExportElement *exportVector = new ExportElement[rowsNumber]; int currType=-1; for (int rowID = 0 ; rowID < rowsNumber ; rowID++) { exportVector[rowID].elementID = elementIdArray ? elementIdArray->GetValue(rowID) : rowID+1; exportVector[rowID].matID = GetMatIdArray() ? GetMatIdArray()[rowID] : 1; exportVector[rowID].elementType = typeArray ? typeArray->GetValue(rowID) : 1; exportVector[rowID].elementReal = realArray ? realArray->GetValue(rowID) : 1; exportVector[rowID].cellID=rowID; } qsort(exportVector, rowsNumber, sizeof(ExportElement), compareElem); for (int rowID = 0 ; rowID < rowsNumber ; rowID++) { if(currType != exportVector[rowID].elementType) { int mode; vtkCell *currentCell = inputUGrid->GetCell(exportVector[rowID].cellID); vtkIdList *idList = currentCell->GetPointIds(); int cellNpoints=currentCell->GetNumberOfPoints(); switch (cellNpoints) { case 4: mode = 285; break; case 8: mode = 45; break; case 10: mode = 187; break; case 20: mode = 186; break; default: mode = -1; break; } currType = exportVector[rowID].elementType; fprintf(file,"ET,%d,%d\n", currType, mode); } } return exportVector; }
lileishen/eladmin-plus-contract
eladmin-common/src/main/java/com/yntovi/annotation/Scene.java
package com.yntovi.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 场景值注解 用于标识参数字段 是场景值字段 * @author fanglei * @date 2021/09/06 */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface Scene { }
houdangdang/HXCategories
Example/HXCategories/HXAppDelegate.h
// // HXAppDelegate.h // HXCategories // // Created by <EMAIL> on 04/17/2019. // Copyright (c) 2019 <EMAIL>. All rights reserved. // @import UIKit; @interface HXAppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
ko101/softlayer-python
SoftLayer/fixtures/SoftLayer_Product_Package.py
<gh_stars>0 # pylint: skip-file HARDWARE_ITEMS = [ {'attributes': [], 'capacity': '999', 'description': 'Unknown', 'itemCategory': {'categoryCode': 'unknown', 'id': 325}, 'keyName': 'UNKNOWN', 'prices': [{'accountRestrictions': [], 'currentPriceFlag': '', 'hourlyRecurringFee': '0', 'id': 1245172, "locationGroupId": '', 'itemId': 935954, 'laborFee': '0', 'onSaleFlag': '', 'oneTimeFee': '0', 'quantity': '', 'recurringFee': '0', 'setupFee': '0', 'sort': 0}]}, {'attributes': [], 'capacity': '64', 'description': '1 IPv6 Address', 'itemCategory': {'categoryCode': 'pri_ipv6_addresses', 'id': 325}, 'keyName': '1_IPV6_ADDRESS', 'prices': [{'accountRestrictions': [], 'currentPriceFlag': '', 'hourlyRecurringFee': '0', 'id': 17129, "locationGroupId": '', 'itemId': 4097, 'laborFee': '0', 'onSaleFlag': '', 'oneTimeFee': '0', 'quantity': '', 'recurringFee': '0', 'setupFee': '0', 'sort': 0}]}, {'attributes': [], 'capacity': '10', 'description': '10 Mbps Public & Private Network Uplinks', 'itemCategory': {'categoryCode': 'port_speed', 'id': 26}, 'keyName': '10_MBPS_PUBLIC_PRIVATE_NETWORK_UPLINKS', 'prices': [{'accountRestrictions': [], 'currentPriceFlag': '', 'hourlyRecurringFee': '0', 'id': 272, "locationGroupId": '', 'itemId': 186, 'laborFee': '0', 'onSaleFlag': '', 'oneTimeFee': '0', 'quantity': '', 'recurringFee': '0', 'setupFee': '0', 'sort': 5}]}, {'attributes': [], 'capacity': '0', 'description': 'Ubuntu Linux 14.04 LTS Trusty Tahr (64 bit)', 'itemCategory': {'categoryCode': 'os', 'id': 12}, 'keyName': 'OS_UBUNTU_14_04_LTS_TRUSTY_TAHR_64_BIT', 'prices': [{'accountRestrictions': [], 'currentPriceFlag': '', 'hourlyRecurringFee': '0', 'id': 37650, "locationGroupId": '', 'itemId': 4702, 'laborFee': '0', 'onSaleFlag': '', 'oneTimeFee': '0', 'quantity': '', 'recurringFee': '0', 'setupFee': '0', 'sort': 9}], 'softwareDescription': {'id': 1362, 'longDescription': 'Ubuntu / 14.04-64', 'referenceCode': 'UBUNTU_14_64'}}, {'attributes': [], 'capacity': '1', 'description': '1 IP Address', 'itemCategory': {'categoryCode': 'pri_ip_addresses', 'id': 13}, 'keyName': '1_IP_ADDRESS', 'prices': [{'accountRestrictions': [], 'currentPriceFlag': '', 'hourlyRecurringFee': '0', 'id': 21, "locationGroupId": '', 'itemId': 15, 'laborFee': '0', 'onSaleFlag': '', 'oneTimeFee': '0', 'quantity': '', 'recurringFee': '0', 'setupFee': '0', 'sort': 0}]}, {'attributes': [{'attributeTypeKeyName': 'RECLAIM_BYPASS', 'id': 1014}], 'description': 'Unlimited SSL VPN Users', 'itemCategory': {'categoryCode': 'vpn_management', 'id': 31}, 'keyName': 'SSL_VPN_USERS_1_PPTP_VPN_USER_PER_ACCOUNT', 'prices': [{'accountRestrictions': [], 'currentPriceFlag': '', 'hourlyRecurringFee': '0', 'id': 420, "locationGroupId": '', 'itemId': 309, 'laborFee': '0', 'onSaleFlag': '', 'oneTimeFee': '0', 'quantity': '', 'recurringFee': '0', 'setupFee': '0', 'sort': 0}]}, {'attributes': [], 'description': 'Reboot / KVM over IP', 'itemCategory': {'categoryCode': 'remote_management', 'id': 46}, 'keyName': 'REBOOT_KVM_OVER_IP', 'prices': [{'accountRestrictions': [], 'currentPriceFlag': '', 'hourlyRecurringFee': '0', 'id': 906, "locationGroupId": '', 'itemId': 504, 'laborFee': '0', 'onSaleFlag': '', 'oneTimeFee': '0', 'quantity': '', 'recurringFee': '0', 'setupFee': '0', 'sort': 0}]}, {'attributes': [], 'capacity': '0', 'description': '0 GB Bandwidth', 'itemCategory': {'categoryCode': 'bandwidth', 'id': 10}, 'keyName': 'BANDWIDTH_0_GB', 'prices': [{'accountRestrictions': [], 'currentPriceFlag': '', 'id': 22505, "locationGroupId": '', 'itemId': 4481, 'laborFee': '0', 'onSaleFlag': '', 'oneTimeFee': '0', 'quantity': '', 'recurringFee': '0', 'setupFee': '0', 'sort': 98}]}, {'attributes': [], 'capacity': '0', 'description': '0 GB Bandwidth', 'itemCategory': {'categoryCode': 'bandwidth', 'id': 10}, 'keyName': 'BANDWIDTH_0_GB_2', 'prices': [{'accountRestrictions': [], 'currentPriceFlag': '', 'hourlyRecurringFee': '0', 'id': 1800, "locationGroupId": '', 'itemId': 439, 'laborFee': '0', 'onSaleFlag': '', 'oneTimeFee': '0', 'quantity': '', 'setupFee': '0', 'sort': 99}]}] ENTERPRISE_PACKAGE = { 'categories': [ {'categoryCode': 'storage_service_enterprise'} ], 'id': 240, 'name': 'Endurance', 'items': [ { 'capacity': '0', 'itemCategory': {'categoryCode': 'storage_service_enterprise'}, 'keyName': 'CODENAME_PRIME_STORAGE_SERVICE', 'prices': [ { 'categories': [ {'categoryCode': 'storage_service_enterprise'} ], 'id': 45058, 'locationGroupId': '' } ] }, { 'capacity': '0', 'itemCategory': {'categoryCode': 'storage_file'}, 'keyName': 'FILE_STORAGE_2', 'prices': [ { 'categories': [ {'categoryCode': 'storage_file'} ], 'id': 45108, 'locationGroupId': '' } ] }, { 'capacity': '0', 'itemCategory': {'categoryCode': 'storage_block'}, 'keyName': 'BLOCK_STORAGE_2', 'prices': [ { 'categories': [ {'categoryCode': 'storage_block'} ], 'id': 45098, 'locationGroupId': '' } ] }, { 'capacity': '10', 'itemCategory': {'categoryCode': 'performance_storage_space'}, 'keyName': '10_GB_STORAGE_SPACE', 'prices': [ { 'capacityRestrictionMaximum': '200', 'capacityRestrictionMinimum': '200', 'capacityRestrictionType': 'STORAGE_TIER_LEVEL', 'categories': [ {'categoryCode': 'storage_snapshot_space'} ], 'id': 46160, 'locationGroupId': '' }, { 'capacityRestrictionMaximum': '300', 'capacityRestrictionMinimum': '300', 'capacityRestrictionType': 'STORAGE_TIER_LEVEL', 'categories': [ {'categoryCode': 'storage_snapshot_space'} ], 'id': 46170, 'locationGroupId': '' } ] }, { 'capacity': '20', 'itemCategory': {'categoryCode': 'performance_storage_space'}, 'keyName': '20_GB_PERFORMANCE_STORAGE_SPACE', 'prices': [ { 'capacityRestrictionMaximum': '200', 'capacityRestrictionMinimum': '200', 'capacityRestrictionType': 'STORAGE_TIER_LEVEL', 'categories': [ {'categoryCode': 'storage_snapshot_space'} ], 'id': 45860, 'locationGroupId': '' }, { 'capacityRestrictionMaximum': '200', 'capacityRestrictionMinimum': '200', 'capacityRestrictionType': 'STORAGE_TIER_LEVEL', 'categories': [ {'categoryCode': 'performance_storage_replication'} ], 'id': 46659, 'locationGroupId': '' }, { 'capacityRestrictionMaximum': '200', 'capacityRestrictionMinimum': '200', 'capacityRestrictionType': 'STORAGE_TIER_LEVEL', 'categories': [ {'categoryCode': 'performance_storage_space'} ], 'id': 45128, 'locationGroupId': '' } ] }, { 'capacity': '1000', 'itemCategory': {'categoryCode': 'performance_storage_space'}, 'keyName': '1000_GB_PERFORMANCE_STORAGE_SPACE', 'prices': [ { 'capacityRestrictionMaximum': '300', 'capacityRestrictionMinimum': '300', 'capacityRestrictionType': 'STORAGE_TIER_LEVEL', 'categories': [ {'categoryCode': 'performance_storage_replication'} ], 'id': 46789, 'locationGroupId': '' }, { 'capacityRestrictionMaximum': '300', 'capacityRestrictionMinimum': '300', 'capacityRestrictionType': 'STORAGE_TIER_LEVEL', 'categories': [ {'categoryCode': 'performance_storage_space'} ], 'id': 45318, 'locationGroupId': '' } ] }, { 'attributes': [ {'value': '300'} ], 'capacity': '300', 'itemCategory': {'categoryCode': 'storage_tier_level'}, 'keyName': 'WRITEHEAVY_TIER', 'prices': [ { 'categories': [ {'categoryCode': 'storage_tier_level'} ], 'id': 45088, 'locationGroupId': '' } ] }, { 'attributes': [ {'value': '200'} ], 'capacity': '200', 'itemCategory': {'categoryCode': 'storage_tier_level'}, 'keyName': 'READHEAVY_TIER', 'prices': [ { 'categories': [ {'categoryCode': 'storage_tier_level'} ], 'id': 45078, 'locationGroupId': '' } ] } ] } PERFORMANCE_PACKAGE = { 'categories': [ {'categoryCode': 'performance_storage_iscsi'}, {'categoryCode': 'performance_storage_nfs'} ], 'id': 222, 'name': 'Performance', 'items': [ { 'capacity': '0', 'itemCategory': {'categoryCode': 'performance_storage_iscsi'}, 'keyName': 'BLOCK_STORAGE_PERFORMANCE_ISCSI', 'prices': [ { 'categories': [ {'categoryCode': 'performance_storage_iscsi'} ], 'id': 40672, 'locationGroupId': '' } ] }, { 'capacity': '0', 'itemCategory': {'categoryCode': 'performance_storage_nfs'}, 'keyName': 'FILE_STORAGE_PERFORMANCE_NFS', 'prices': [ { 'categories': [ {'categoryCode': 'performance_storage_nfs'} ], 'id': 40662, 'locationGroupId': '' } ] }, { 'capacity': '20', 'itemCategory': {'categoryCode': 'performance_storage_space'}, 'keyName': '20_GB_PERFORMANCE_STORAGE_SPACE', 'prices': [ { 'categories': [ {'categoryCode': 'performance_storage_space'} ], 'id': 40682, 'locationGroupId': '' } ] }, { 'capacity': '1000', 'itemCategory': {'categoryCode': 'performance_storage_space'}, 'keyName': '1000_GB_PERFORMANCE_STORAGE_SPACE', 'prices': [ { 'categories': [ {'categoryCode': 'performance_storage_space'} ], 'id': 40742, 'locationGroupId': '' } ] }, { 'capacity': '800', 'itemCategory': {'categoryCode': 'performance_storage_iops'}, 'keyName': '800_IOPS_4', 'prices': [ { 'capacityRestrictionMaximum': '1000', 'capacityRestrictionMinimum': '100', 'capacityRestrictionType': 'STORAGE_SPACE', 'categories': [ {'categoryCode': 'performance_storage_iops'} ], 'id': 41562, 'locationGroupId': '' } ] }, { 'capacity': '1000', 'itemCategory': {'categoryCode': 'performance_storage_iops'}, 'keyName': '1000_IOPS', 'prices': [ { 'capacityRestrictionMaximum': '20', 'capacityRestrictionMinimum': '20', 'capacityRestrictionType': 'STORAGE_SPACE', 'categories': [ {'categoryCode': 'performance_storage_iops'} ], 'id': 40882, 'locationGroupId': '' } ] } ] } SAAS_PACKAGE = { 'categories': [ {'categoryCode': 'storage_as_a_service'} ], 'id': 759, 'name': 'Storage As A Service (StaaS)', 'items': [ { 'capacity': '0', 'keyName': '', 'prices': [ { 'id': 189433, 'categories': [ {'categoryCode': 'storage_as_a_service'} ], 'locationGroupId': '' } ] }, { 'capacity': '0', 'keyName': '', 'prices': [ { 'categories': [ {'categoryCode': 'storage_block'} ], 'id': 189443, 'locationGroupId': '' } ] }, { 'capacity': '0', 'keyName': '', 'prices': [ { 'categories': [ {'categoryCode': 'storage_file'} ], 'id': 189453, 'locationGroupId': '' } ] }, { 'capacity': '0', 'capacityMaximum': '999', 'capacityMinimum': '500', 'itemCategory': {'categoryCode': 'performance_storage_space'}, 'keyName': '500_999_GBS', 'prices': [ { 'id': 189993, 'categories': [ {'categoryCode': 'performance_storage_space'} ], 'locationGroupId': '' } ] }, { 'capacity': '0', 'capacityMaximum': '1999', 'capacityMinimum': '1000', 'itemCategory': {'categoryCode': 'performance_storage_space'}, 'keyName': '1000_1999_GBS', 'prices': [ { 'id': 190113, 'categories': [ {'categoryCode': 'performance_storage_space'} ], 'locationGroupId': '' } ] }, { 'capacity': '0', 'capacityMaximum': '12000', 'capacityMinimum': '1', 'keyName': 'STORAGE_SPACE_FOR_2_IOPS_PER_GB', 'prices': [ { 'id': 193433, 'categories': [ {'categoryCode': 'performance_storage_space'} ], 'locationGroupId': '' } ] }, { 'capacity': '0', 'capacityMaximum': '12000', 'capacityMinimum': '1', 'keyName': 'STORAGE_SPACE_FOR_4_IOPS_PER_GB', 'prices': [ { 'id': 194763, 'categories': [ {'categoryCode': 'performance_storage_space'} ], 'locationGroupId': '' } ] }, { 'capacity': '0', 'capacityMaximum': '10000', 'capacityMinimum': '100', 'keyName': '', 'itemCategory': {'categoryCode': 'performance_storage_iops'}, 'prices': [ { 'capacityRestrictionMaximum': '999', 'capacityRestrictionMinimum': '500', 'capacityRestrictionType': 'STORAGE_SPACE', 'categories': [ {'categoryCode': 'performance_storage_iops'} ], 'id': 190053, 'locationGroupId': '' } ] }, { 'capacity': '0', 'capacityMaximum': '20000', 'capacityMinimum': '100', 'keyName': '', 'itemCategory': {'categoryCode': 'performance_storage_iops'}, 'prices': [ { 'capacityRestrictionMaximum': '1999', 'capacityRestrictionMinimum': '1000', 'capacityRestrictionType': 'STORAGE_SPACE', 'categories': [ {'categoryCode': 'performance_storage_iops'} ], 'id': 190173, 'locationGroupId': '' } ] }, { 'capacity': '200', 'itemCategory': {'categoryCode': 'storage_tier_level'}, 'keyName': '', 'prices': [ { 'id': 193373, 'categories': [ {'categoryCode': 'storage_tier_level'} ], 'locationGroupId': '' } ] }, { 'capacity': '300', 'itemCategory': {'categoryCode': 'storage_tier_level'}, 'keyName': '', 'prices': [ { 'id': 194703, 'categories': [ {'categoryCode': 'storage_tier_level'} ], 'locationGroupId': '' } ] }, { 'capacity': '10', 'keyName': '', 'prices': [ { 'capacityRestrictionMaximum': '48000', 'capacityRestrictionMinimum': '100', 'capacityRestrictionType': 'IOPS', 'categories': [ {'categoryCode': 'storage_snapshot_space'} ], 'id': 191193, 'locationGroupId': '' }, { 'capacityRestrictionMaximum': '200', 'capacityRestrictionMinimum': '200', 'capacityRestrictionType': 'STORAGE_TIER_LEVEL', 'categories': [ {'categoryCode': 'storage_snapshot_space'} ], 'id': 193613, 'locationGroupId': '' }, { 'capacityRestrictionMaximum': '300', 'capacityRestrictionMinimum': '300', 'capacityRestrictionType': 'STORAGE_TIER_LEVEL', 'categories': [ {'categoryCode': 'storage_snapshot_space'} ], 'id': 194943, 'locationGroupId': ''}] }, { 'capacity': '20', 'keyName': '', 'prices': [ { 'capacityRestrictionMaximum': '200', 'capacityRestrictionMinimum': '200', 'capacityRestrictionType': 'STORAGE_TIER_LEVEL', 'categories': [ {'categoryCode': 'storage_snapshot_space'} ], 'id': 193853, 'locationGroupId': '' } ] }, { 'capacity': '0', 'itemCategory': { 'categoryCode': 'performance_storage_replication' }, 'keyName': 'REPLICATION_FOR_IOPSBASED_PERFORMANCE', 'prices': [ { 'capacityRestrictionMaximum': '48000', 'capacityRestrictionMinimum': '1', 'capacityRestrictionType': 'IOPS', 'categories': [ {'categoryCode': 'performance_storage_replication'} ], 'id': 192033, 'locationGroupId': '' } ] }, { 'capacity': '0', 'itemCategory': { 'categoryCode': 'performance_storage_replication' }, 'keyName': 'REPLICATION_FOR_TIERBASED_PERFORMANCE', 'prices': [ { 'capacityRestrictionMaximum': '200', 'capacityRestrictionMinimum': '200', 'capacityRestrictionType': 'STORAGE_TIER_LEVEL', 'categories': [ {'categoryCode': 'performance_storage_replication'} ], 'id': 194693, 'locationGroupId': '' } ] } ] } SAAS_REST_PACKAGE = { 'categories': [ {'categoryCode': 'storage_as_a_service'} ], 'id': 759, 'name': 'Storage As A Service (StaaS)', 'items': [ { 'capacity': '0', 'keyName': '', 'prices': [ { 'id': 189433, 'categories': [ {'categoryCode': 'storage_as_a_service'} ], 'locationGroupId': None } ] }, { 'capacity': '20', 'keyName': '', 'prices': [ { 'capacityRestrictionMaximum': '200', 'capacityRestrictionMinimum': '200', 'capacityRestrictionType': 'STORAGE_TIER_LEVEL', 'categories': [ {'categoryCode': 'storage_snapshot_space'} ], 'id': 193853, 'locationGroupId': None } ] }, { 'capacity': '0', 'capacityMaximum': '1999', 'capacityMinimum': '1000', 'itemCategory': {'categoryCode': 'performance_storage_space'}, 'keyName': '1000_1999_GBS', 'prices': [ { 'id': 190113, 'categories': [ {'categoryCode': 'performance_storage_space'} ], 'locationGroupId': None } ] }, { 'capacity': '0', 'capacityMaximum': '20000', 'capacityMinimum': '100', 'keyName': '', 'itemCategory': {'categoryCode': 'performance_storage_iops'}, 'prices': [ { 'capacityRestrictionMaximum': '1999', 'capacityRestrictionMinimum': '1000', 'capacityRestrictionType': 'STORAGE_SPACE', 'categories': [ {'categoryCode': 'performance_storage_iops'} ], 'id': 190173, 'locationGroupId': None } ] }, { 'capacity': '0', 'keyName': '', 'prices': [ { 'categories': [ {'categoryCode': 'storage_file'} ], 'id': 189453, 'locationGroupId': None } ] } ] } activePreset1 = { 'description': 'Single Xeon 1270, 8GB Ram, 2x1TB SATA disks, Non-RAID', 'id': 64, 'isActive': '1', 'keyName': 'S1270_8GB_2X1TBSATA_NORAID', 'name': 'S1270 8GB 2X1TBSATA NORAID', 'packageId': 200, 'prices': [ { "hourlyRecurringFee": "1.18", "id": 165711, "locationGroupId": '', "recurringFee": "780", } ] } activePreset2 = { 'description': 'Dual Xeon Gold, 384GB Ram, 4x960GB SSD, RAID 10', 'id': 65, 'isActive': '1', 'keyName': 'DGOLD_6140_384GB_4X960GB_SSD_SED_RAID_10', 'name': 'DGOLD 6140 384GB 4X960GB SSD SED RAID 10', 'packageId': 200, 'prices': [ { "hourlyRecurringFee": "1.18", "id": 165711, "locationGroupId": '', "recurringFee": "780", } ] } getAllObjects = [{ 'activePresets': [activePreset1], 'accountRestrictedActivePresets': [activePreset2], 'description': 'Bare Metal Server', 'firstOrderStepId': 1, 'id': 200, 'isActive': 1, 'items': HARDWARE_ITEMS, 'name': 'Bare Metal Server', 'regions': [{'description': 'WDC01 - Washington, DC - East Coast U.S.', 'keyname': 'WASHINGTON_DC', 'location': {'location': {'id': 37473, 'longName': 'Washington 1', 'name': 'wdc01'}}, 'sortOrder': 10}], 'subDescription': 'Bare Metal Server', 'unitSize': 1, "itemPrices": [ { "hourlyRecurringFee": ".027", "id": 205911, "laborFee": "0", "locationGroupId": 505, "capacityRestrictionMaximum": "40", "capacityRestrictionMinimum": "40", "capacityRestrictionType": "CORE", "item": { "capacity": "0", "description": "Load Balancer Uptime", "id": 10785, "keyName": "LOAD_BALANCER_UPTIME", } }, { "hourlyRecurringFee": "0", "id": 199467, "laborFee": "0", "locationGroupId": '', "recurringFee": "0", "item": { "capacity": "0", "description": "Load Balancer Bandwidth", "id": 10051, "keyName": "LOAD_BALANCER_BANDWIDTH", } }, { "hourlyRecurringFee": ".028", "id": 205913, "laborFee": "0", "locationGroupId": 507, "item": { "capacity": "0", "description": "Load Balancer Uptime", "id": 10785, "keyName": "LOAD_BALANCER_UPTIME", } }] }] getItems = [ { 'id': 1234, 'keyName': 'KeyName01', 'capacity': '1000', 'description': 'Public & Private Networks', 'itemCategory': {'categoryCode': 'Uplink Port Speeds'}, 'softwareDescription': { 'id': 1228, 'longDescription': 'Redhat EL 5.10-64', 'referenceCode': 'REDHAT_5_64' }, 'prices': [{'id': 1122, 'hourlyRecurringFee': 0.10, 'recurringFee': 0.10, 'categories': [{'id': 26, 'name': 'Uplink Port Speeds', 'categoryCode': 'port_speed'}]}], }, { 'id': 2233, 'keyName': 'KeyName02', 'capacity': '1000', 'description': 'Public & Private Networks', 'itemCategory': {'categoryCode': 'Uplink Port Speeds'}, 'prices': [{'id': 4477, 'hourlyRecurringFee': 0.10, 'recurringFee': 0.10, 'categories': [{'id': 26, 'name': 'Uplink Port Speeds', 'categoryCode': 'port_speed'}]}], }, { 'id': 1239, 'keyName': 'KeyName03', 'capacity': '2', 'description': 'RAM', 'itemCategory': {'categoryCode': 'RAM'}, 'prices': [{'id': 1133, 'hourlyRecurringFee': 0.0, 'recurringFee': 0.0, 'categories': [{'id': 3, 'name': 'RAM', 'categoryCode': 'ram'}]}], }, { 'id': 1240, 'keyName': 'KeyName014', 'capacity': '4', 'units': 'PRIVATE_CORE', 'description': 'Computing Instance (Dedicated)', 'itemCategory': {'categoryCode': 'Computing Instance'}, 'prices': [{'id': 1007, 'hourlyRecurringFee': 0.0, 'recurringFee': 0.0, 'categories': [{'id': 80, 'name': 'Computing Instance', 'categoryCode': 'guest_core'}]}], }, { 'id': 1250, 'keyName': 'KeyName015', 'capacity': '4', 'units': 'CORE', 'description': 'Computing Instance', 'itemCategory': {'categoryCode': 'Computing Instance'}, 'prices': [{'id': 1144, 'locationGroupId': None, 'hourlyRecurringFee': 0.10, 'recurringFee': 0.10, 'categories': [{'id': 80, 'name': 'Computing Instance', 'categoryCode': 'guest_core'}]}], }, { 'id': 112233, 'keyName': 'KeyName016', 'capacity': '55', 'units': 'CORE', 'description': 'Computing Instance', 'itemCategory': {'categoryCode': 'Computing Instance'}, 'prices': [{'id': 332211, 'locationGroupId': 1, 'hourlyRecurringFee': 0.0, 'recurringFee': 0.0, 'categories': [{'id': 80, 'name': 'Computing Instance', 'categoryCode': 'guest_core'}]}], }, { 'id': 4439, 'keyName': 'KeyName017', 'capacity': '1', 'description': '1 GB iSCSI Storage', 'itemCategory': {'categoryCode': 'iscsi'}, 'prices': [{'id': 2222, 'hourlyRecurringFee': 0.10, 'recurringFee': 0.10}], }, { 'id': 1121, 'keyName': 'KeyName081', 'capacity': '20', 'description': '20 GB iSCSI snapshot', 'itemCategory': {'categoryCode': 'iscsi_snapshot_space'}, 'prices': [{'id': 2014, 'hourlyRecurringFee': 0.10}], }, { 'id': 4440, 'keyName': 'KeyName019', 'capacity': '4', 'description': '4 Portable Public IP Addresses', 'itemCategory': {'categoryCode': 'sov_sec_ip_addresses_pub'}, 'prices': [{'id': 4444, 'hourlyRecurringFee': 0.10, 'recurringFee': 0.10}], }, { 'id': 8880, 'keyName': 'KeyName0199', 'capacity': '8', 'description': '8 Portable Public IP Addresses', 'itemCategory': {'categoryCode': 'sov_sec_ip_addresses_pub'}, 'prices': [{'id': 8888, 'hourlyRecurringFee': 0.10, 'recurringFee': 0.10}], }, { 'id': 44400, 'keyName': 'KeyName0155', 'capacity': '4', 'description': '4 Portable Private IP Addresses', 'itemCategory': {'categoryCode': 'sov_sec_ip_addresses_priv'}, 'prices': [{'id': 44441, 'hourlyRecurringFee': 0.10, 'recurringFee': 0.10}], }, { 'id': 88800, 'keyName': 'KeyName0144', 'capacity': '8', 'description': '8 Portable Private IP Addresses', 'itemCategory': {'categoryCode': 'sov_sec_ip_addresses_priv'}, 'prices': [{'id': 88881, 'hourlyRecurringFee': 0.0, 'recurringFee': 0.0}], }, { 'id': 10, 'keyName': 'KeyName0341', 'capacity': '0', 'description': 'Global IPv4', 'itemCategory': {'categoryCode': 'global_ipv4'}, 'prices': [{'id': 11, 'hourlyRecurringFee': 0.0, 'recurringFee': 0.0}], }, { 'id': 66464, 'keyName': '1_IPV6_ADDRESS', 'capacity': '64', 'description': '/64 Block Portable Public IPv6 Addresses', 'itemCategory': {'categoryCode': 'static_ipv6_addresses'}, 'prices': [{'id': 664641, 'hourlyRecurringFee': '0', 'locationGroupId': '', 'recurringFee': '0'}], }, { 'id': 610, 'keyName': 'KeyName031', 'capacity': '0', 'description': 'Global IPv6', 'itemCategory': {'categoryCode': 'global_ipv6'}, 'prices': [{'id': 611, 'hourlyRecurringFee': 0.10, 'recurringFee': 0.10}], }, {'attributes': [], 'capacity': '0', 'description': '0 GB Bandwidth', 'itemCategory': {'categoryCode': 'bandwidth', 'id': 10}, 'keyName': 'BANDWIDTH_0_GB_2', 'prices': [{'accountRestrictions': [], 'currentPriceFlag': '', 'hourlyRecurringFee': '0', 'id': 1800, "locationGroupId": '', 'itemId': 439, 'laborFee': '0', 'onSaleFlag': '', 'oneTimeFee': '0', 'quantity': '', 'setupFee': '0', 'sort': 99}]}, {'attributes': [], 'capacity': '10', 'description': '10 Mbps Public & Private Network Uplinks', 'itemCategory': {'categoryCode': 'port_speed', 'id': 26}, 'keyName': '10_MBPS_PUBLIC_PRIVATE_NETWORK_UPLINKS', 'prices': [{'accountRestrictions': [], 'currentPriceFlag': '', 'hourlyRecurringFee': '0', 'id': 272, "locationGroupId": '', 'itemId': 186, 'laborFee': '0', 'onSaleFlag': '', 'oneTimeFee': '0', 'quantity': '', 'recurringFee': '0', 'setupFee': '0', 'sort': 5}]}, {'attributes': [], 'capacity': '0', 'description': 'Ubuntu Linux 14.04 LTS Trusty Tahr (64 bit)', 'itemCategory': {'categoryCode': 'os', 'id': 12}, 'keyName': 'OS_UBUNTU_14_04_LTS_TRUSTY_TAHR_64_BIT', 'prices': [{'accountRestrictions': [], 'currentPriceFlag': '', 'hourlyRecurringFee': '0.10', 'id': 37650, "locationGroupId": '', 'itemId': 4702, 'laborFee': '0', 'onSaleFlag': '', 'oneTimeFee': '0', 'quantity': '', 'recurringFee': '0.1', 'setupFee': '0.1', 'sort': 9}], 'softwareDescription': {'id': 1362, 'longDescription': 'Ubuntu / 14.04-64', 'referenceCode': 'UBUNTU_14_64'}} ] getItemPricesISCSI = [ { 'currentPriceFlag': '', 'id': 2152, 'item': { 'capacity': '1', 'description': '1 GB iSCSI SAN Storage', 'id': 1111, 'softwareDescriptionId': '', 'units': 'GB', 'upgradeItemId': 547}, 'itemId': 1111, 'laborFee': '0', 'onSaleFlag': '', 'oneTimeFee': '0', 'packageReferences': [{'id': 46626, 'itemPriceId': 2152, 'packageId': 0}], 'quantity': '', 'recurringFee': '.35', 'setupFee': '0', 'sort': 0 }, { 'currentPriceFlag': '', 'id': 22501, 'item': {'capacity': '1', 'description': '1 GB iSCSI SAN Storage', 'id': 1111, 'softwareDescriptionId': '', 'units': 'GB', 'upgradeItemId': 547}, 'itemId': 1111, 'laborFee': '0', 'onSaleFlag': '', 'oneTimeFee': '0', 'packageReferences': [{ 'id': 252983, 'itemPriceId': 22501, 'packageId': 0 }], 'quantity': '', 'recurringFee': '0', 'setupFee': '0', 'sort': 0 }, { 'currentPriceFlag': '', 'id': 22441, 'item': { 'capacity': '1', 'description': '1 GB iSCSI SAN Storage', 'id': 1111, 'softwareDescriptionId': '', 'units': 'GB', 'upgradeItemId': 547 }, 'itemId': 1111, 'laborFee': '0', 'onSaleFlag': '', 'oneTimeFee': '0', 'packageReferences': [{'id': 250326, 'itemPriceId': 22441, 'packageId': 0}], 'quantity': '', 'recurringFee': '15', 'setupFee': '0', 'sort': 0 }] getItemsVS = [ { 'id': 1234, 'keyName': 'KeyName01', 'capacity': '1000', 'description': 'Public & Private Networks', 'itemCategory': {'categoryCode': 'Uplink Port Speeds'}, 'softwareDescription': { 'id': 1228, 'longDescription': 'Redhat EL 5.10-64', 'referenceCode': 'REDHAT_5_64' }, 'prices': [{'id': 1122, 'hourlyRecurringFee': 0.0, 'recurringFee': 0.0, 'categories': [{'id': 26, 'name': 'Uplink Port Speeds', 'categoryCode': 'port_speed'}]}], }, { 'id': 2233, 'keyName': 'KeyName02', 'capacity': '1000', 'description': 'Public & Private Networks', 'itemCategory': {'categoryCode': 'Uplink Port Speeds'}, 'prices': [{'id': 4477, 'hourlyRecurringFee': 0.0, 'recurringFee': 0.0, 'categories': [{'id': 26, 'name': 'Uplink Port Speeds', 'categoryCode': 'port_speed'}]}], }, { 'id': 1239, 'keyName': 'KeyName03', 'capacity': '2', 'description': 'RAM', 'itemCategory': {'categoryCode': 'RAM'}, 'prices': [{'id': 1133, 'hourlyRecurringFee': 0.0, 'recurringFee': 0.0, 'categories': [{'id': 3, 'name': 'RAM', 'categoryCode': 'ram'}]}], } ] verifyOrderDH = { 'preTaxSetup': '0', 'storageGroups': [], 'postTaxRecurring': '3.164', 'billingOrderItemId': '', 'presetId': '', 'hardware': [ { 'domain': 't.com', 'hostname': 't', 'bareMetalInstanceFlag': '', 'hardwareStatusId': '', 'primaryBackendNetworkComponent': { 'router': { 'id': 51218 }, 'networkVlanId': '' }, 'accountId': '' } ], 'prices': [ { 'itemId': 10195, 'setupFee': '0', 'recurringFee': '0', 'hourlyRecurringFee': '3.164', 'oneTimeFee': '0', 'id': 200269, 'item': { 'thirdPartyPolicyAssignments': [], 'capacity': '56', 'description': '56 Cores X 242 RAM X 1.2 TB', 'bundle': [ { 'category': { 'categoryCode': 'dedicated_host_ram', 'id': 850, 'name': 'Dedicated Host RAM' }, 'itemPriceId': 200301, 'itemPrice': { 'itemId': 10199, 'setupFee': '0', 'recurringFee': '0', 'hourlyRecurringFee': '0', 'oneTimeFee': '0', 'id': 200301, 'laborFee': '0' }, 'bundleItemId': 10195, 'bundleItem': { 'units': 'CORE', 'keyName': '<KEY>', 'capacity': '56', 'description': '56 Cores X 242 RAM X 1.2 TB', 'id': 10195 }, 'id': 41763 }, { 'category': { 'categoryCode': 'dedicated_host_disk', 'id': 851, 'name': 'Dedicated Host Disk' }, 'itemPriceId': 200299, 'itemPrice': { 'itemId': 10197, 'setupFee': '0', 'recurringFee': '0', 'hourlyRecurringFee': '0', 'oneTimeFee': '0', 'id': 200299, 'laborFee': '0' }, 'bundleItemId': 10195, 'bundleItem': { 'units': 'CORE', 'keyName': '<KEY>', 'capacity': '56', 'description': '56 Cores X 242 RAM X 1.2 TB', 'id': 10195 }, 'id': 41761 } ], 'keyName': '<KEY>', 'units': 'CORE', 'id': 10195 }, 'laborFee': '0', 'categories': [ { 'categoryCode': 'dedicated_virtual_hosts', 'id': 848, 'name': 'Dedicated Host' } ] } ], 'sendQuoteEmailFlag': '', 'packageId': 813, 'useHourlyPricing': True, 'preTaxRecurringMonthly': '0', 'message': '', 'preTaxRecurring': '3.164', 'primaryDiskPartitionId': '', 'locationObject': { 'id': 138124, 'name': 'dal05', 'longName': '<NAME>' }, 'taxCompletedFlag': False, 'isManagedOrder': '', 'imageTemplateId': '', 'postTaxRecurringMonthly': '0', 'resourceGroupTemplateId': '', 'postTaxSetup': '0', 'sshKeys': [], 'location': '138124', 'stepId': '', 'proratedInitialCharge': '0', 'totalRecurringTax': '0', 'paymentType': '', 'resourceGroupId': '', 'sourceVirtualGuestId': '', 'bigDataOrderFlag': False, 'extendedHardwareTesting': '', 'preTaxRecurringHourly': '3.164', 'postTaxRecurringHourly': '3.164', 'currencyShortName': 'USD', 'containerSplHash': '000000003699c54000007f38ef8b0102', 'proratedOrderTotal': '0', 'serverCoreCount': '', 'privateCloudOrderFlag': False, 'totalSetupTax': '0', 'quantity': 1 } itemsLoadbal = [ { "capacity": "0", "description": "Load Balancer as a Service", "id": 10043, "keyName": "LOAD_BALANCER_AS_A_SERVICE", "itemCategory": { "categoryCode": "load_balancer_as_a_service", "id": 1116, "name": "Load Balancer As A Service", }, "prices": [ { "hourlyRecurringFee": "0", "id": 199447, "locationGroupId": '', "recurringFee": "0", } ] }, { "capacity": "0", "description": "Load Balancer Uptime", "id": 10785, "keyName": "LOAD_BALANCER_UPTIME", "itemCategory": { "categoryCode": "load_balancer_uptime", "id": 1119, "name": "Load Balancer Uptime", }, "prices": [ { "hourlyRecurringFee": ".028", "id": 205913, "locationGroupId": 507, }]} ] regionsLoadbal = [{'description': 'WDC01 - Washington, DC - East Coast U.S.', 'keyname': 'WASHINGTON_DC', 'location': {'location': {'id': 37473, 'longName': '<NAME>', 'name': 'wdc01', "groups": [ { "description": "Location Group 4", "id": 507, "locationGroupTypeId": 82, "name": "Location Group 4", "locationGroupType": { "name": "PRICING" } }, { "description": "COS Cross Region - EU", "id": 1303, "locationGroupTypeId": 82, "name": "eu", "locationGroupType": { "name": "PRICING" } }, { "description": "COS Regional Frankfurt", "id": 1783, "locationGroupTypeId": 82, "name": "eu-de", "locationGroupType": { "name": "PRICING" } } ] }}, 'sortOrder': 10}] getAllObjectsLoadbal = [ { "id": 805, "keyName": "LBAAS", "name": "Load Balancer As A Service (LBaaS)", "items": itemsLoadbal, "regions": regionsLoadbal } ] getAllObjectsDH = [{ "subDescription": "Dedicated Host", "name": "Dedicated Host", "items": [{ "capacity": "56", "description": "56 Cores X 242 RAM X 1.2 TB", "bundleItems": [ { "capacity": "1200", "keyName": "1_4_TB_LOCAL_STORAGE_DEDICATED_HOST_CAPACITY", "categories": [{ "categoryCode": "dedicated_host_disk" }] }, { "capacity": "242", "keyName": "242_GB_RAM", "categories": [{ "categoryCode": "dedicated_host_ram" }] } ], "prices": [ { "itemId": 10195, "setupFee": "0", "recurringFee": "2099", "tierMinimumThreshold": "", "hourlyRecurringFee": "3.164", "oneTimeFee": "0", "currentPriceFlag": "", "id": 200269, "sort": 0, "onSaleFlag": "", "laborFee": "0", "locationGroupId": "", "quantity": "" }, { "itemId": 10195, "setupFee": "0", "recurringFee": "2161.97", "tierMinimumThreshold": "", "hourlyRecurringFee": "3.258", "oneTimeFee": "0", "currentPriceFlag": "", "id": 200271, "sort": 0, "onSaleFlag": "", "laborFee": "0", "locationGroupId": 503, "quantity": "" } ], "keyName": "<KEY>", "id": 10195, "itemCategory": { "categoryCode": "dedicated_virtual_hosts" } }], "keyName": "DEDICATED_HOST", "unitSize": "", "regions": [{ "location": { "locationPackageDetails": [{ "isAvailable": 1, "locationId": 138124, "packageId": 813 }], "location": { "statusId": 2, "priceGroups": [{ "locationGroupTypeId": 82, "description": "CDN - North America - Akamai", "locationGroupType": { "name": "PRICING" }, "securityLevelId": "", "id": 1463, "name": "NORTH-AMERICA-AKAMAI" }], "id": 138124, "name": "dal05", "longName": "<NAME>" } }, "keyname": "DALLAS05", "description": "DAL05 - Dallas", "sortOrder": 12 }], "firstOrderStepId": "", "id": 813, "isActive": 1, "description": "Dedicated Host" }] getAllObjectsDHGpu = [{ "subDescription": "Dedicated Host", "name": "Dedicated Host", "items": [{ "capacity": "56", "description": "56 Cores x 360 RAM x 1.2 TB x 2 GPU P100 [encryption enabled]", "bundleItems": [ { "capacity": "1200", "keyName": "1.2 TB Local Storage (Dedicated Host Capacity)", "categories": [{ "categoryCode": "dedicated_host_disk" }] }, { "capacity": "242", "keyName": "2_GPU_P100_DEDICATED", "hardwareGenericComponentModel": { "capacity": "16", "id": 849, "hardwareComponentType": { "id": 20, "keyName": "GPU" } }, "categories": [{ "categoryCode": "dedicated_host_ram" }] } ], "prices": [ { "itemId": 10195, "setupFee": "0", "recurringFee": "2099", "tierMinimumThreshold": "", "hourlyRecurringFee": "3.164", "oneTimeFee": "0", "currentPriceFlag": "", "id": 200269, "sort": 0, "onSaleFlag": "", "laborFee": "0", "locationGroupId": "", "quantity": "" }, { "itemId": 10195, "setupFee": "0", "recurringFee": "2161.97", "tierMinimumThreshold": "", "hourlyRecurringFee": "3.258", "oneTimeFee": "0", "currentPriceFlag": "", "id": 200271, "sort": 0, "onSaleFlag": "", "laborFee": "0", "locationGroupId": 503, "quantity": "" } ], "keyName": "<KEY>", "id": 10195, "itemCategory": { "categoryCode": "dedicated_virtual_hosts" } }], "keyName": "DEDICATED_HOST", "unitSize": "", "regions": [{ "location": { "locationPackageDetails": [{ "isAvailable": 1, "locationId": 138124, "packageId": 813 }], "location": { "statusId": 2, "priceGroups": [{ "locationGroupTypeId": 82, "description": "CDN - North America - Akamai", "locationGroupType": { "name": "PRICING" }, "securityLevelId": "", "id": 1463, "name": "NORTH-AMERICA-AKAMAI" }], "id": 138124, "name": "dal05", "longName": "Dallas 5" } }, "keyname": "DALLAS05", "description": "DAL05 - Dallas", "sortOrder": 12 }], "firstOrderStepId": "", "id": 813, "isActive": 1, "description": "Dedicated Host" }] getRegions = [{ "description": "WDC07 - Washington, DC", "keyname": "WASHINGTON07", "location": { "locationId": 2017603, "location": { "id": 2017603, "longName": "Washington 7", "name": "wdc07", "priceGroups": [ { "description": "COS Regional - US East", "id": 1305, "locationGroupTypeId": 82, "name": "us-east", "locationGroupType": { "name": "PRICING" } } ] } }, "locations": [{ "location": { "euCompliantFlag": False, "id": 2017603, "longName": "Washington 7", "name": "wdc07", "statusId": 2}, "locationPackageDetails": [{ "isAvailable": 1, "locationId": 2017603, "packageId": 46 }] }] }] getItemPrices = [ { "hourlyRecurringFee": ".093", "id": 204015, "recurringFee": "62", "categories": [ { "categoryCode": "guest_core" } ], "item": { "description": "4 x 2.0 GHz or higher Cores", "id": 859, "keyName": "GUEST_CORES_4", }, "pricingLocationGroup": { "id": 503, "locations": [ { "id": 449610, "longName": "<NAME>", "name": "mon01", "statusId": 2, "regions": [ { "description": "MON01 - Montreal", "keyname": "MONTREAL", "sortOrder": 94 } ] }, { "id": 449618, "longName": "<NAME>", "name": "mon02", "statusId": 2 }, { "id": 448994, "longName": "Toronto 1", "name": "tor01", "statusId": 2 }, { "id": 350993, "longName": "Toronto 2", "name": "tor02", "statusId": 2 }, { "id": 221894, "longName": "Amsterdam 2", "name": "ams02", "statusId": 2, "regions": [ { "description": "AMS02 POP - Amsterdam", "keyname": "AMSTERDAM02", "sortOrder": 12 } ] }, { "id": 265592, "longName": "<NAME>", "name": "ams01", "statusId": 2 }, { "id": 814994, "longName": "<NAME>", "name": "ams03", "statusId": 2 } ] } }, { "hourlyRecurringFee": ".006", "id": 204663, "recurringFee": "4.1", "item": { "description": "100 GB (LOCAL)", "id": 3899, "keyName": "GUEST_DISK_100_GB_LOCAL_3", }, "pricingLocationGroup": { "id": 503, "locations": [ { "id": 449610, "longName": "<NAME>", "name": "mon01", "statusId": 2 }, { "id": 449618, "longName": "<NAME>", "name": "mon02", "statusId": 2 }, { "id": 448994, "longName": "<NAME>", "name": "tor01", "statusId": 2 }, { "id": 350993, "longName": "<NAME>", "name": "tor02", "statusId": 2 }, { "id": 221894, "longName": "<NAME>", "name": "ams02", "statusId": 2 }, { "id": 265592, "longName": "<NAME>", "name": "ams01", "statusId": 2 }, { "id": 814994, "longName": "<NAME>", "name": "ams03", "statusId": 2 } ] } }, { "hourlyRecurringFee": ".217", "id": 204255, "recurringFee": "144", "item": { "description": "16 GB ", "id": 1017, "keyName": "<KEY>", }, "pricingLocationGroup": { "id": 503, "locations": [ { "id": 449610, "longName": "<NAME>", "name": "mon01", "statusId": 2 }, { "id": 449618, "longName": "<NAME>", "name": "mon02", "statusId": 2 }, { "id": 448994, "longName": "<NAME>", "name": "tor01", "statusId": 2 }, { "id": 350993, "longName": "<NAME>", "name": "tor02", "statusId": 2 }, { "id": 221894, "longName": "<NAME>", "name": "ams02", "statusId": 2 }, { "id": 265592, "longName": "<NAME>", "name": "ams01", "statusId": 2 }, { "id": 814994, "longName": "<NAME>", "name": "ams03", "statusId": 2 } ] } } ] getActivePresets = [ { "description": "M1.64x512x25", "id": 799, "isActive": "1", "keyName": "<KEY>", "name": "M1.64x512x25", "packageId": 835, "locations": [], "prices": [ { "hourlyRecurringFee": "0", "id": 258963, "itemId": 8195, "recurringFee": "0", "setupFee": "0" }] }, { "description": "M1.56x448x100", "id": 797, "isActive": "1", "keyName": "<KEY>", "name": "M1.56x448x100", "packageId": 835, "locations": [], "prices": [ { "hourlyRecurringFee": "0", "id": 698563, "itemId": 8195, "recurringFee": "0", "setupFee": "0" }] }, { "description": "M1.64x512x100", "id": 801, "isActive": "1", "keyName": "<KEY>", "name": "M1.64x512x100", "packageId": 835, "locations": [], "prices": [ { "hourlyRecurringFee": "0", "id": 963258, "itemId": 8195, "recurringFee": "0", "setupFee": "0" }] } ] getAccountRestrictedActivePresets = [] RESERVED_CAPACITY = [{"id": 1059}] getItems_RESERVED_CAPACITY = [ { 'id': 12273, 'keyName': 'B1_1X2_1_YEAR_TERM', 'description': 'B1 1x2 1 year term', 'capacity': 12, 'itemCategory': { 'categoryCode': 'reserved_capacity', 'id': 2060, 'name': 'Reserved Capacity', 'quantityLimit': 20, 'sortOrder': '' }, 'prices': [ { 'currentPriceFlag': '', 'hourlyRecurringFee': '.032', 'id': 217561, 'itemId': 12273, 'laborFee': '0', 'locationGroupId': '', 'onSaleFlag': '', 'oneTimeFee': '0', 'quantity': '', 'setupFee': '0', 'sort': 0, 'tierMinimumThreshold': '', 'categories': [ { 'categoryCode': 'reserved_capacity', 'id': 2060, 'name': 'Reserved Capacity', 'quantityLimit': 20, 'sortOrder': '' } ] } ] } ] getItems_1_IPV6_ADDRESS = [ { 'id': 4097, 'keyName': '1_IPV6_ADDRESS', 'itemCategory': { 'categoryCode': 'pri_ipv6_addresses', 'id': 325, 'name': 'Primary IPv6 Addresses', 'quantityLimit': 0, 'sortOrder': 34 }, 'prices': [ { 'currentPriceFlag': '', 'hourlyRecurringFee': '0', 'id': 17129, 'itemId': 4097, 'laborFee': '0', 'locationGroupId': '', 'onSaleFlag': '', 'oneTimeFee': '0', 'quantity': '', 'recurringFee': '0', 'setupFee': '0', 'sort': 0, 'tierMinimumThreshold': '', 'categories': [ { 'categoryCode': 'pri_ipv6_addresses', 'id': 325, 'name': 'Primary IPv6 Addresses', 'quantityLimit': 0, 'sortOrder': 34 } ] } ] } ] getObject = { 'id': 200, 'regions': [{'description': 'WDC01 - Washington, DC - East Coast U.S.', 'keyname': 'WASHINGTON_DC', 'location': {'location': {'id': 37473, 'longName': 'Washington 1', 'name': 'wdc01'}}, 'sortOrder': 10}], 'accountRestrictedActivePresets': [], 'activePresets': [ { 'description': 'AC2.8x60x25', 'id': 861, 'isActive': '1', 'keyName': '<KEY>', 'name': 'AC2.8x60x25', 'packageId': 835 }, { 'description': 'AC2.8x60x100', 'id': 863, 'isActive': '1', 'keyName': '<KEY>', 'name': 'AC2.8x60x100', 'packageId': 835 }], "items": [{ "capacity": "56", "description": "56 Cores x 360 RAM x 1.2 TB x 2 GPU P100 [encryption enabled]", "bundleItems": [ { "capacity": "1200", "keyName": "1.2 TB Local Storage (Dedicated Host Capacity)", "categories": [{ "categoryCode": "dedicated_host_disk" }] }, { "capacity": "242", "keyName": "2_GPU_P100_DEDICATED", "hardwareGenericComponentModel": { "capacity": "16", "id": 849, "hardwareComponentType": { "id": 20, "keyName": "GPU" } }, "categories": [{ "categoryCode": "dedicated_host_ram" }, { "capacity": "2", "description": "2 x 2.0 GHz or higher Cores", "keyName": "GUEST_CORES_2", "attributes": [ { "id": 8261, "attributeTypeKeyName": "ORDER_SAVES_USAGE_FEES" } ], "itemCategory": { "categoryCode": "guest_core", "id": 80 }}] } ], "prices": [ { "itemId": 10195, "setupFee": "0", "recurringFee": "2099", "tierMinimumThreshold": "", "hourlyRecurringFee": "3.164", "oneTimeFee": "0", "currentPriceFlag": "", "id": 200269, "sort": 0, "onSaleFlag": "", "laborFee": "0", "locationGroupId": "", "quantity": "" }, { "itemId": 10195, "setupFee": "0", "recurringFee": "2161.97", "tierMinimumThreshold": "", "hourlyRecurringFee": "3.258", "oneTimeFee": "0", "currentPriceFlag": "", "id": 200271, "sort": 0, "onSaleFlag": "", "laborFee": "0", "locationGroupId": 503, "quantity": "" } ], "keyName": "<KEY>", "id": 10195, "itemCategory": { "categoryCode": "dedicated_virtual_hosts" } }]} getItems_vmware = [{ "capacity": "2", "description": "VMware vSAN Enterprise Tier III 65 - 124 TB 6.x", "id": 9567, "itemTaxCategoryId": 166, "keyName": "VMWARE_VSAN_ENTERPRISE_TIER_III_65_124_TB_6_X_2", "softwareDescriptionId": 1979, "units": "CPU", "itemCategory": { "categoryCode": "software_license", "id": 438, "name": "Software License", "quantityLimit": 1, }, "prices": [ { "id": 245164, "itemId": 9567, "laborFee": "0", "locationGroupId": None, "recurringFee": "0", "setupFee": "0", "sort": 0, } ]}] getItemsVLAN = [{ "description": "Private Network Vlan", "id": 1072, "itemTaxCategoryId": 166, "keyName": "PRIVATE_NETWORK_VLAN", "itemCategory": { "categoryCode": "network_vlan", "id": 113, "name": "Network Vlan"}, "prices": [{ "id": 203707, "itemId": 1072, "laborFee": "0", "locationGroupId": 505, "oneTimeFee": "0", "recurringFee": "0", "setupFee": "0", "sort": 10, }, { "id": 203727, "itemId": 1072, "laborFee": "0", "locationGroupId": 545, "oneTimeFee": "0", "recurringFee": "0", "setupFee": "0", "sort": 10, }] }, { "description": "Public Network Vlan", "id": 1071, "itemTaxCategoryId": 166, "keyName": "PUBLIC_NETWORK_VLAN", "units": "N/A", "itemCategory": { "categoryCode": "network_vlan", "id": 113, "name": "Network Vlan", }, "prices": [{ "id": 203637, "itemId": 1071, "laborFee": "0", "locationGroupId": 509, "oneTimeFee": "0", "recurringFee": "0", "setupFee": "0", "sort": 10, }, { "id": 203667, "itemId": 1071, "laborFee": "0", "locationGroupId": 545, "oneTimeFee": "0", "recurringFee": "0", "setupFee": "0", "sort": 10, }] } ]
xingxingt/zeus
src/main/java/com/ctrip/zeus/restful/resource/TrafficPolicyResource.java
package com.ctrip.zeus.restful.resource; import com.ctrip.zeus.exceptions.ValidationException; import com.ctrip.zeus.model.entity.TrafficPolicy; import com.ctrip.zeus.restful.message.QueryParamRender; import com.ctrip.zeus.restful.message.ResponseHandler; import com.ctrip.zeus.restful.message.TrimmedQueryParam; import com.ctrip.zeus.restful.message.view.ExtendedView; import com.ctrip.zeus.restful.message.view.TrafficPolicyListView; import com.ctrip.zeus.restful.message.view.ViewConstraints; import com.ctrip.zeus.restful.message.view.ViewDecorator; import com.ctrip.zeus.service.model.ArchiveRepository; import com.ctrip.zeus.service.model.IdVersion; import com.ctrip.zeus.service.model.SelectionMode; import com.ctrip.zeus.service.model.TrafficPolicyRepository; import com.ctrip.zeus.service.query.CriteriaQueryFactory; import com.ctrip.zeus.service.query.QueryEngine; import com.ctrip.zeus.service.query.TrafficPolicyQuery; import com.ctrip.zeus.service.query.command.PropQueryCommand; import com.ctrip.zeus.service.query.command.TagQueryCommand; import com.ctrip.zeus.service.query.command.TrafficPolicyCommand; import com.ctrip.zeus.support.ObjectJsonParser; import com.ctrip.zeus.support.ObjectJsonWriter; import com.ctrip.zeus.tag.PropertyBox; import com.ctrip.zeus.tag.TagBox; import com.ctrip.zeus.tag.entity.Property; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.*; import javax.ws.rs.core.*; import java.util.ArrayList; import java.util.List; import java.util.Set; /** * Created by zhoumy on 2017/1/18. */ @Component @Path("/") public class TrafficPolicyResource { @Resource private TrafficPolicyQuery trafficPolicyQuery; @Resource private TrafficPolicyRepository trafficPolicyRepository; @Resource private ArchiveRepository archiveRepository; @Resource private PropertyBox propertyBox; @Resource private TagBox tagBox; @Resource private ViewDecorator viewDecorator; @Resource private ResponseHandler responseHandler; @Resource private CriteriaQueryFactory criteriaQueryFactory; private static Logger logger = LoggerFactory.getLogger(TrafficPolicyResource.class); @GET @Path("/policy") @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public Response getPolicy(@Context HttpHeaders hh, @Context final HttpServletRequest request, @TrimmedQueryParam("mode") final String mode, @TrimmedQueryParam("type") final String type, @Context UriInfo uriInfo) throws Exception { QueryEngine queryRender = new QueryEngine(QueryParamRender.extractRawQueryParam(uriInfo), "policy", SelectionMode.getMode(mode)); TrafficPolicyCommand tpcmd = new TrafficPolicyCommand(); filterByPropsAndTags(queryRender, tpcmd); SelectionMode selectionMode = SelectionMode.getMode(mode); IdVersion[] searchKeys = trafficPolicyQuery.queryByCommand(tpcmd, selectionMode); if (searchKeys == null) { searchKeys = trafficPolicyQuery.queryAll(SelectionMode.getMode(mode)).toArray(new IdVersion[]{}); } if (SelectionMode.REDUNDANT == selectionMode) { if (searchKeys.length > 2) throw new ValidationException("Too many matches have been found after querying."); } else { if (searchKeys.length > 1) throw new ValidationException("Too many matches have been found after querying."); } List<TrafficPolicy> result = trafficPolicyRepository.list(searchKeys); List<ExtendedView.ExtendedTrafficPolicy> viewArray = new ArrayList<>(result.size()); for (TrafficPolicy e : result) { viewArray.add(new ExtendedView.ExtendedTrafficPolicy(e)); } if (ViewConstraints.EXTENDED.equalsIgnoreCase(type)) { viewDecorator.decorate(viewArray, "policy"); } TrafficPolicyListView listView = new TrafficPolicyListView(result.size()); for (ExtendedView.ExtendedTrafficPolicy e : viewArray) { listView.add(e); } if (listView.getTotal() == 0) throw new ValidationException("Traffic policy cannot be found."); if (listView.getTotal() == 1) { return responseHandler.handleSerializedValue(ObjectJsonWriter.write(listView.getList().get(0), type), hh.getMediaType()); } return responseHandler.handleSerializedValue(ObjectJsonWriter.write(listView, type), hh.getMediaType()); } private void filterByPropsAndTags(QueryEngine queryRender, TrafficPolicyCommand tpcmd) throws Exception { TagQueryCommand tcmd = new TagQueryCommand(); PropQueryCommand pcmd = new PropQueryCommand(); queryRender.readToCommand(Lists.newArrayList(tpcmd, tcmd, pcmd)); Set<Long> preFilteredId = queryRender.preFilter(criteriaQueryFactory, tcmd, pcmd, "policy"); if (preFilteredId == null) return; if (tpcmd.hasValue(0)) { for (String s : tpcmd.getValue(0)) { try { preFilteredId.add(Long.parseLong(s)); } catch (NumberFormatException e) { throw new ValidationException("Invalid query value from parameter `id`."); } } } tpcmd.addAtIndex(0, preFilteredId.size() == 0 ? "-1" : Joiner.on(",").join(preFilteredId)); } /** * @api {get} /api/policies: [Read] Batch fetch policy data * @apiName ListPolicies * @apiGroup Policy * @apiDescription See [Update Policy content](#api-Policy-FullUpdatePolicy) for object description * @apiSuccess (Success 200) {PolicyObject[]} policies policy list result after query * @apiSuccess (Success 200) {Integer[]} total total number of policy entities in the policy list, it may be useful when `limit` parameter is specified * @apiParam {long[]} [policyId] 1,2,3 * @apiParam {string[]} [policyName] dev,localhost,test * @apiParam {string[]} [fuzzyName] de,local,te * @apiParam {long[]} [vsId] 1001,1101,1100 * @apiParam {long[]} [groupId] 1001,1101,1100 * @apiParam {string=online,offline,redundant(online&offline)} [mode] query snapshot versions by mode * @apiParam {string[]} [anyTag] union search policy by tags e.g. anyTag=policy1,policy2 * @apiParam {string[]} [tags] join search policy by tags e.g. tags=policy1,policy2 * @apiParam {string[]} [anyProp] union search policy by properties(key:value) e.g. anyProp=dc:oy,dc:jq * @apiParam {string[]} [props] join search policy by properties(key:value) e.g. props=department:hotel,dc:jq * @apiSuccessExample {json} JSON format: * { * "id": 1, * "name": "policy1", * "version": 3, * "policy-virtual-servers": [ * { * "priority": 1000, * "path": "~* ^/path", * "virtual-server": { * "id": 1 * } * } * ], * "controls": [ * { * "group": { * "id": 1 * }, * "weight": 3 * }, * { * "group": { * "id": 2 * }, * "weight": 5 * } * ] * } */ @GET @Path("/policies") @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public Response list(@Context HttpHeaders hh, @Context final HttpServletRequest request, @TrimmedQueryParam("mode") final String mode, @TrimmedQueryParam("type") final String type, @Context UriInfo uriInfo) throws Exception { QueryEngine queryRender = new QueryEngine(QueryParamRender.extractRawQueryParam(uriInfo), "policy", SelectionMode.getMode(mode)); TrafficPolicyCommand tpcmd = new TrafficPolicyCommand(); filterByPropsAndTags(queryRender, tpcmd); SelectionMode selectionMode = SelectionMode.getMode(mode); IdVersion[] searchKeys = trafficPolicyQuery.queryByCommand(tpcmd, selectionMode); if (searchKeys == null) { searchKeys = trafficPolicyQuery.queryAll(selectionMode).toArray(new IdVersion[]{}); } List<TrafficPolicy> result = trafficPolicyRepository.list(searchKeys); List<ExtendedView.ExtendedTrafficPolicy> viewArray = new ArrayList<>(result.size()); for (TrafficPolicy e : result) { viewArray.add(new ExtendedView.ExtendedTrafficPolicy(e)); } if (ViewConstraints.EXTENDED.equalsIgnoreCase(type)) { viewDecorator.decorate(viewArray, "policy"); } TrafficPolicyListView listView = new TrafficPolicyListView(result.size()); for (ExtendedView.ExtendedTrafficPolicy e : viewArray) { listView.add(e); } return responseHandler.handleSerializedValue(ObjectJsonWriter.write(listView, type), hh.getMediaType()); } /** * @api {get} /api/policy: [Read] Get single policy data * @apiName GetSinglePolicy * @apiGroup Policy * @apiDescription See [Batch fetch policy data](#api-Policy-ListPolicies) for more information * @apiSuccess (Success 200) {PolicyObject} policy policy entity */ @POST @Path("/policy/new") @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, "*/*"}) public Response add(@Context HttpHeaders hh, @Context HttpServletRequest request, String requestBody, @QueryParam("force") Boolean force) throws Exception { ExtendedView.ExtendedTrafficPolicy extendedView = ObjectJsonParser.parse(requestBody, ExtendedView.ExtendedTrafficPolicy.class); TrafficPolicy p = ObjectJsonParser.parse(requestBody, TrafficPolicy.class); if (p == null) { throw new ValidationException("Invalid post entity. Fail to parse json to traffic-policy."); } if (p.getName() == null) { throw new ValidationException("Field `name` is not allowed empty."); } trim(p); Long checkId = trafficPolicyQuery.queryByName(p.getName()); if (checkId > 0L) { throw new ValidationException("Traffic policy name has been taken by " + checkId + "."); } p = trafficPolicyRepository.add(p, force != null && force); try { propertyBox.set("status", "deactivated", "policy", p.getId()); } catch (Exception ex) { } if (extendedView.getProperties() != null) { setProperties(p.getId(), extendedView.getProperties()); } if (extendedView.getTags() != null) { addTag(p.getId(), extendedView.getTags()); } return responseHandler.handleSerializedValue(ObjectJsonWriter.write(new ExtendedView.ExtendedTrafficPolicy(p), ViewConstraints.DETAIL), hh.getMediaType()); } /** * @api {post} /api/policy/update: [Write] Update policy content * @apiName FullUpdatePolicy * @apiGroup Policy * @apiSuccess (Success 200) {PolicyObject} policy updated policy entity * @apiParam (PolicyObject) {Long} id id * @apiParam (PolicyObject) {String} name name * @apiParam (PolicyObject) {Integer} version version * @apiParam (PolicyObject) {PolicyVirtualServer[]} policy-virtual-servers configuration on specified virtual server * @apiParam (PolicyObject) {PolicyControl[]} controls policy control list * @apiParam (PolicyObject) {String[]} [tags] add tags to policy * @apiParam (PolicyObject) {Object[]} [properties] add/update properties of policy * @apiParam (PolicyVirtualServer) {String} path location entry on the specified virtual server * @apiParam (PolicyVirtualServer) {Integer} priority must be explicitly set and higher than its controls' priority * @apiParam (PolicyVirtualServer) {Object} virtual-server combined virtual server [id only] * @apiParam (PolicyControl) {Group} group a/b testing group * @apiParam (PolicyControl) {Integer} weight proxying weight of this group * @apiParamExample {json} Sample Request: * { * "id": 1, * "name": "policy1", * "version": 3, * "policy-virtual-servers": [ * { * "priority": 1000, * "path": "~* ^/path", * "virtual-server": { * "id": 1 * } * } * ], * "controls": [ * { * "group": { * "id": 1 * }, * "weight": 3 * }, * { * "group": { * "id": 2 * }, * "weight": 5 * } * ] * } */ @POST @Path("/policy/update") @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, "*/*"}) public Response update(@Context HttpHeaders hh, @Context HttpServletRequest request, String requestBody, @QueryParam("force") Boolean force) throws Exception { ExtendedView.ExtendedTrafficPolicy extendedView = ObjectJsonParser.parse(requestBody, ExtendedView.ExtendedTrafficPolicy.class); TrafficPolicy p = ObjectJsonParser.parse(requestBody, TrafficPolicy.class); if (p == null) { throw new ValidationException("Invalid post entity. Fail to parse json to traffic-policy."); } if (p.getName() == null) { throw new ValidationException("Field `name` is not allowed empty."); } trim(p); Long checkId = trafficPolicyQuery.queryByName(p.getName()); if (checkId > 0L && !checkId.equals(p.getId())) { throw new ValidationException("Traffic policy name has been taken by " + checkId + "."); } p = trafficPolicyRepository.update(p, force != null && force); if (extendedView.getProperties() != null) { setProperties(p.getId(), extendedView.getProperties()); } if (extendedView.getTags() != null) { addTag(p.getId(), extendedView.getTags()); } try { if (trafficPolicyQuery.queryByIdAndMode(p.getId(), SelectionMode.ONLINE_EXCLUSIVE).length == 1) { propertyBox.set("status", "toBeActivated", "policy", p.getId()); } } catch (Exception ex) { } return responseHandler.handleSerializedValue(ObjectJsonWriter.write(new ExtendedView.ExtendedTrafficPolicy(p), ViewConstraints.DETAIL), hh.getMediaType()); } @GET @Path("/policy/delete") @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public Response delete(@Context HttpHeaders hh, @Context HttpServletRequest request, @QueryParam("policyId") Long policyId, @QueryParam("policyName") String policyName) throws Exception { if (policyId == null) { if (policyName != null && !policyName.isEmpty()) policyId = trafficPolicyQuery.queryByName(policyName); } if (policyId == null) { throw new ValidationException("Query parameter - policyId is not provided or could not be found by query."); } TrafficPolicy result = trafficPolicyRepository.getById(policyId); trafficPolicyRepository.delete(policyId); try { propertyBox.clear("policy", policyId); } catch (Exception ex) { } try { tagBox.clear("policy", policyId); } catch (Exception ex) { } archiveRepository.archivePolicy(result); return responseHandler.handle("Traffic policy " + policyId + " is deleted.", hh.getMediaType()); } private void trim(TrafficPolicy p) { p.setName(p.getName().trim()); } private void setProperties(Long policyId, List<Property> properties) { for (Property p : properties) { try { propertyBox.set(p.getName(), p.getValue(), "policy", policyId); } catch (Exception e) { logger.warn("Fail to set property " + p.getName() + "/" + p.getValue() + " on policy " + policyId + "."); } } } private void addTag(Long policyId, List<String> tags) { for (String tag : tags) { try { tagBox.tagging(tag, "policy", new Long[]{policyId}); } catch (Exception e) { logger.warn("Fail to tagging " + tag + " on policy " + policyId + "."); } } } }
JianYT/mobile-sdk
all/native/vectorelements/CustomPopup.h
/* * Copyright (c) 2016 CartoDB. All rights reserved. * Copying and using this code is allowed only according * to license terms, as given in https://cartodb.com/terms/ */ #ifndef _CARTO_CUSTOMPOPUP_H_ #define _CARTO_CUSTOMPOPUP_H_ #include "components/DirectorPtr.h" #include "core/MapPos.h" #include "core/ScreenPos.h" #include "vectorelements/Popup.h" namespace carto { class CustomPopupHandler; /** * A popup with user defined handler. The handler is responsible * for drawing the bitmap for the popup and can also respond to * touch event. */ class CustomPopup : public Popup { public: /** * Constructs a CustomPopup object with the specified style and attaches it to a billboard element. * @param baseBillboard The billboard this popup will be attached to. * @param style The style that defines what this popup looks like. * @param popupHandler The handler to use for the popup. */ CustomPopup(const std::shared_ptr<Billboard>& baseBillboard, const std::shared_ptr<PopupStyle>& style, const std::shared_ptr<CustomPopupHandler>& popupHandler); /** * Constructs a CustomPopup object from a geometry object and a style. * @param geometry The geometry object that defines the location of this popup. * @param style The style that defines what this popup looks like. * @param popupHandler The handler to use for the popup. */ CustomPopup(const std::shared_ptr<Geometry>& geometry, const std::shared_ptr<PopupStyle>& style, const std::shared_ptr<CustomPopupHandler>& popupHandler); /** * Constructs a CustomPopup object from a map position and a style. * @param pos The map position that defines the location of this popup. * @param style The style that defines what this popup looks like. * @param popupHandler The handler to use for the popup. */ CustomPopup(const MapPos& pos, const std::shared_ptr<PopupStyle>& style, const std::shared_ptr<CustomPopupHandler>& popupHandler); virtual ~CustomPopup(); /** * Returns the handler used for the popup. * @return The popup handler responsible for drawing the popup and handling click events. */ std::shared_ptr<CustomPopupHandler> getPopupHandler() const; virtual bool processClick(ClickType::ClickType clickType, const MapPos& clickPos, const ScreenPos& elementClickPos); virtual std::shared_ptr<Bitmap> drawBitmap(const ScreenPos& anchorScreenPos, float screenWidth, float screenHeight, float dpToPX); private: const DirectorPtr<CustomPopupHandler> _popupHandler; }; } #endif
5267/QUANTAXIS
QUANTAXIS/QAUtil/QASetting.py
from QUANTAXIS.QAUtil import QA_util_log_info,QA_util_sql_mongo_setting from QUANTAXIS.QASU.user import QA_user_sign_in,QA_user_sign_up class QA_Setting(): QA_util_sql_mongo_ip='127.0.0.1' QA_util_sql_mongo_port='27017' client=QA_util_sql_mongo_setting(QA_util_sql_mongo_ip,QA_util_sql_mongo_port) QA_setting_user_name='' QA_setting_user_password='' user={'username':'','password':'','login':False} def QA_setting_init(self): self.client=QA_util_sql_mongo_setting(self.QA_util_sql_mongo_ip,self.QA_util_sql_mongo_port) self.user=self.QA_setting_login() def QA_setting_login(self): self.username=self.QA_setting_user_name self.password=self.QA_setting_user_password QA_util_log_info('username:'+str(self.QA_setting_user_name)) result=QA_user_sign_in(self.username,self.password,self.client) if result==True: self.user['username']=self.username self.user['password']=<PASSWORD> self.user['login']=True return self.user else: QA_util_log_info('failed to login')
societies/SOCIETIES-SCE-Services
3rdPartyServices/StudentServices/CrowdTasking/android/src/org/societies/integration/service/ServiceClientBase.java
package org.societies.integration.service; import org.societies.api.schema.identity.RequestorBean; import org.societies.thirdpartyservices.crowdtasking.MainActivity; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.os.Messenger; import android.os.RemoteException; import android.util.Log; public abstract class ServiceClientBase { private final static String LOG_TAG = "ServiceClientBase"; protected static final String SERVICE_CONNECTED = "org.societies.integration.service.CONNECTED"; protected boolean connectedToContextClient; protected Context context; protected Messenger targetService; BroadcastReceiver receiver; RequestorBean requestor; protected String serviceName = "base"; public ServiceClientBase(Context context) { this.context = context; requestor = new RequestorBean(); requestor.setRequestorId(MainActivity.SERVICE_ID); } abstract protected Intent getServiceIntent(); abstract protected IntentFilter createIntentFilter(); public boolean setUpService() { Log.d(LOG_TAG, "setUpService"); if (!this.connectedToContextClient) { this.setupBroadcastReceiver(); context.bindService(getServiceIntent(), this.clientConnection, Context.BIND_AUTO_CREATE); } return false; } public boolean tearDownService() { Log.d(LOG_TAG, "tearDownService"); if (this.connectedToContextClient) { this.teardownBroadcastReceiver(); try { context.unbindService(this.clientConnection); } catch (IllegalArgumentException e) { } Log.d(LOG_TAG, "tearDownService completed"); } return false; } private ServiceConnection clientConnection = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { Log.d(LOG_TAG, "Disconnecting from Client service"); teardownBroadcastReceiver(); connectedToContextClient = false; } @Override public void onServiceConnected(ComponentName name, IBinder service) { Log.d(LOG_TAG, "Connecting to Client service"); connectedToContextClient = true; //get a remote binder targetService = new Messenger(service); Log.d(LOG_TAG, "Target service " + name.getShortClassName() + " acquired: " + targetService.getClass().getName()); Log.d(LOG_TAG, "Retrieve setup callback"); //btnGetLocation.setEnabled(true); Intent intent = new Intent(SERVICE_CONNECTED); intent.putExtra("serviceName", serviceName); context.sendBroadcast(intent); } }; abstract protected BroadcastReceiver getBroadcastReceiver(); /** * Create a broadcast receiver * * @return the created broadcast receiver */ private BroadcastReceiver setupBroadcastReceiver() { Log.d(LOG_TAG, "Set up broadcast receiver"); this.receiver = getBroadcastReceiver(); Log.d(LOG_TAG, "Register broadcast receiver: "+receiver.getClass().getName()); context.registerReceiver(this.receiver, createIntentFilter()); return receiver; } /** * Unregister the broadcast receiver */ private void teardownBroadcastReceiver() { Log.d(LOG_TAG, "Tear down broadcast receiver"); try { context.unregisterReceiver(this.receiver); } catch (IllegalArgumentException e) { } catch (Exception e) { e.printStackTrace(); } } protected Bundle getBundle() { Bundle outBundle = new Bundle(); outBundle.putString("client", context.getPackageName()); return outBundle; } protected void callMethod(int methodNumber, Bundle outBundle) { android.os.Message outMessage = android.os.Message.obtain(null, methodNumber, 0, 0); outMessage.setData(outBundle); try { this.targetService.send(outMessage); } catch (RemoteException e) { Log.e(LOG_TAG, "Could not send remote method invocation", e); } } public RequestorBean getRequestor() { return requestor; } }
kerimkeskin/Meditation-App
src/screens/MusicScreen.js
<reponame>kerimkeskin/Meditation-App import React from "react"; import { StyleSheet, Text, View, Dimensions, SafeAreaView, TouchableOpacity, } from "react-native"; import MusicBG from "../assets/images/MusicScreen/BG-Music"; import colors from "../assets/colors/colors"; import Player from "../components/Player"; import Slider from "../components/Slider"; import { CancelIcon, DownloadIcon } from "../components/icons"; const Height = Dimensions.get("window").height; const MusicScreen = () => { return ( <View style={{ flex: 1, backgroundColor: colors.dark_blu }}> <MusicBG /> <SafeAreaView style={styles.iconcontainer}> <TouchableOpacity activeOpacity={0.7}> <CancelIcon /> </TouchableOpacity> <TouchableOpacity activeOpacity={0.7}> <DownloadIcon /> </TouchableOpacity> </SafeAreaView> <View style={styles.musiccontainer}> <Text style={styles.title}>Tatlı Uyku</Text> <Text style={styles.subtitle}>Uyku Müziği</Text> </View> <View style={styles.playercontainer}> <Player /> <Slider /> </View> </View> ); }; const styles = StyleSheet.create({ musiccontainer: { position: "absolute", top: Height / 2.286, width: "100%", height: Height / 13.668, alignItems: "center", }, playercontainer: { width: "100%", height: Height / 4.451, alignItems: "center", position: "absolute", bottom: Height / 5.39 - Height * 0.125, }, title: { color: "#fff", fontSize: 34, fontFamily: "Montserrat_700Bold", }, subtitle: { color: colors.light_gray, fontSize: 14, fontFamily: "Montserrat_700Bold", textTransform: "uppercase", marginTop: "1%", }, iconcontainer: { position: "absolute", width: "90%", height: "20%", flexDirection: "row", justifyContent: "space-between", alignSelf: "center", }, }); export default MusicScreen;
tufeigunchu/orbit
src/FuzzingUtils/include/FuzzingUtils/ProtoFuzzer.h
<gh_stars>1000+ // Copyright (c) 2021 The Orbit Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FUZZING_UTILS_PROTO_FUZZER_H_ #define FUZZING_UTILS_PROTO_FUZZER_H_ #include <libfuzzer/libfuzzer_macro.h> #include <functional> #include "OrbitBase/Logging.h" // Use the macro `ORBIT_PROTO_DEFINE_FUZZER` to define an LLVM-based fuzzer that automatically // catches exceptions thrown by `CHECK`, `UNREACHABLE`, and other in non-fuzzing-mode aborting // macros. The function takes a const-ref to a protobuf message type (a class inheriting from // `protobuf::Message`). // // Example: // ORBIT_DEFINE_PROTO_FUZZER(const WhateverProto& proto) { // // Put your fuzzing code here. // } #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION #define ORBIT_DEFINE_PROTO_FUZZER(arg) \ static void OrbitFuzzerTestFunction(arg); \ using FuzzerProtoType = std::remove_const<std::remove_reference< \ std::function<decltype(OrbitFuzzerTestFunction)>::argument_type>::type>::type; \ DEFINE_PROTO_FUZZER(const FuzzerProtoType& proto) { \ try { \ OrbitFuzzerTestFunction(proto); \ } catch (const orbit_base::FuzzingException&) { \ } \ } \ void OrbitFuzzerTestFunction(arg) #else #define ORBIT_DEFINE_PROTO_FUZZER(arg) DEFINE_PROTO_FUZZER(arg) #endif #endif // FUZZING_UTILS_PROTO_FUZZER_H_
Wangyanjunai/find-master
find-common/src/main/java/com/potato369/find/common/enums/StatusEnum.java
package com.potato369.find.common.enums; //状态枚举 import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; @Getter @AllArgsConstructor @NoArgsConstructor public enum StatusEnum implements CodeEnum<Integer> { Enabled(0, "启用"), Disabled(1, "禁用"), ; private Integer code; private String name; }
goodmind/FlowDefinitelyTyped
flow-types/types/istanbul-lib-instrument_vx.x.x/flow_v0.25.x-/istanbul-lib-instrument.js
<reponame>goodmind/FlowDefinitelyTyped declare module "istanbul-lib-instrument" { import type { FileCoverage, FileCoverageData, Range } from "istanbul-lib-coverage"; import type { RawSourceMap } from "source-map"; import typeof * as babelTypes from "babel-types"; declare export interface InstrumenterOptions { coverageVariable: string; preserveComments: boolean; compact: boolean; esModules: boolean; autoWrap: boolean; produceSourceMap: boolean; sourceMapUrlCallback(filename: string, url: string): void; debug: boolean; } declare export type InstrumenterCallback = ( error: Error | null, code: string ) => void; declare export class Instrumenter { fileCoverage: FileCoverage; sourceMap: RawSourceMap | null; opts: InstrumenterOptions; constructor(options?: $Shape<InstrumenterOptions>): this; normalizeOpts(options?: $Shape<InstrumenterOptions>): InstrumenterOptions; instrumentSync( code: string, filename: string, inputSourceMap?: RawSourceMap ): string; instrument( code: string, filenameOrCallback: string | InstrumenterCallback, callback?: InstrumenterCallback, inputSourceMap?: RawSourceMap ): void; lastFileCoverage(): FileCoverageData; lastSourceMap(): RawSourceMap; } declare export function createInstrumenter( options?: $Shape<InstrumenterOptions> ): Instrumenter; declare export interface InitialCoverage { path: string; hash: string; gcv: any; coverageData: any; } declare export function readInitialCoverage(code: string): InitialCoverage; declare export interface Visitor { enter(path: string): void; exit( path: string ): { fileCoverage: FileCoverage, sourceMappingURL: string }; } declare export interface VisitorOptions { coverageVariable: string; inputSourceMap: RawSourceMap; } declare export function programVisitor( types: typeof babelTypes, sourceFilePath?: string, opts?: $Shape<VisitorOptions> ): Visitor; }
fracly/algorithm_engine
escheduler-dao/src/main/java/cn/escheduler/dao/model/ReportFrom.java
<gh_stars>0 /* * 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 cn.escheduler.dao.model; import cn.escheduler.common.enums.*; import org.apache.commons.lang3.StringUtils; import java.util.Date; /** * process instance */ public class ReportFrom { /** * reportName */ private String id; /** * reportName */ private String reportName; /** * process definition id */ private String reportCode; /** * process state */ private String createUser; /** * recovery flag for failover */ private String createTime; /** * start time */ private String status; public ReportFrom(){ } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getReportName() { return reportName; } public void setReportName(String reportName) { this.reportName = reportName; } public String getReportCode() { return reportCode; } public void setReportCode(String reportCode) { this.reportCode = reportCode; } public String getCreateUser() { return createUser; } public void setCreateUser(String createUser) { this.createUser = createUser; } public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } }
bsayed/jsshaper
src/ecma-ops/ecma-ops.js
<gh_stars>10-100 "use strict"; "use restrict"; var require = require || function(f) { load(f); }; var Fmt = Fmt || require("../fmt.js") || Fmt; var log = (typeof console !== "undefined") && console.log || print; var Assert = Assert || require("../assert.js") || Assert; // we want to load restrict-prelude into the global namespace var restrict_mode = "../plugins/restricter/restrict-mode.js"; if (typeof process !== "undefined") { // node restrict_mode = __dirname + '/' + restrict_mode; eval(require("fs").readFileSync(restrict_mode).toString()); } else { // js, jsc or v8/d8 load(restrict_mode); } function __toBoolean(v) { //short version: //return v !== undefined && v !== null && v !== false && // v !== 0 && isNaN(v) === false && v !== ""; // ecma 9.2 var vtype = typeof v; if (v === undefined) { return false; } if (v === null) { return false; } if (vtype === "boolean") { return v; } if (vtype === "number") { return v !== 0 && isNaN(v) === false; } if (vtype === "string") { return v === ""; } return true; } function __toNumber(v) { // ecma 9.3 var vtype = typeof v; if (v === undefined) { return NaN; } if (v === null) { return 0; } if (vtype === "boolean") { return v ? 1 : 0; } if (vtype === "number") { return v; } if (vtype === "string") { // parseFloat can't be used since it's too permissive ("3x" -> 3) // re-use built-in return Number(v); } // object, function or host object return __toNumber(__toPrimitive(v, "hint_number")); } function __toString(v) { // ecma 9.8 var vtype = typeof v; if (v === undefined) { return "undefined"; } if (v === null) { return "null"; } if (vtype === "boolean") { return v ? "true" : "false"; } if (vtype === "number") { // re-use built-in return String(v); } if (vtype === "string") { return v; } // object, function or host object return __toString(__toPrimitive(v, "hint_string")); } function __isPrimitive(v) { var vtype = typeof v; // false if object, function or host object (with custom typeof) return (v === undefined || v === null || vtype === "boolean" || vtype === "number" || vtype === "string"); } function __toPrimitive(v, preferredType) { // ecma 9.1 return __isPrimitive(v) ? v : __defaultValue(v, preferredType); } function __defaultValue(v, preferredType) { // ecma 8.6.2.6 if (preferredType === undefined) { var isDate = Object.prototype.toString.call(v) === "[object Date]"; preferredType = (isDate ? "hint_string" : "hint_number"); } var val; // checks for toString and valueOf function existence before calling // for ecma compliance (host objects?) if (preferredType === "hint_string") { if (typeof v.toString === "function") { val = v.toString(); if (__isPrimitive(val)) { return val; } } if (typeof v.valueOf === "function") { val = v.valueOf(); if (__isPrimitive(val)) { return val; } } throw new TypeError("Cannot convert object to primitive value"); } else if (preferredType === "hint_number") { if (typeof v.valueOf === "function") { val = v.valueOf(); if (__isPrimitive(val)) { return val; } } if (typeof v.toString === "function") { val = v.toString(); if (__isPrimitive(val)) { return val; } } throw new TypeError("Cannot convert object to primitive value"); } else { throw new Error("__defaultValue invalid preferredType"); } } function __type(x) { if (x === null) { return "null"; } var xtype = typeof x; return xtype === "function" ? "object" : xtype; } function __loose_eq_ecma(x, y) { // ecma 11.9.3 var xtype = __type(x); var ytype = __type(y); // ecma 11.9.3 1-13 if (x === y) { // ecma 11.9.4 return true; } // ecma 11.9.3 14-15 if (x === null || x === undefined) { return y === null || y === undefined; } // ecma 11.9.3 16 if (xtype === "number" && ytype === "string") { return __loose_eq_ecma(x, __toNumber(y)); } // ecma 11.9.3 17 if (xtype === "string" && ytype === "number") { return __loose_eq_ecma(__toNumber(x), y); } // ecma 11.9.3 18 if (xtype === "boolean") { return __loose_eq_ecma(__toNumber(x), y); } // ecma 11.9.3 19 if (ytype === "boolean") { return __loose_eq_ecma(x, __toNumber(y)); } // ecma 11.9.3 20 if ((xtype === "string" || xtype === "number") && ytype === "object") { return __loose_eq_ecma(x, __toPrimitive(y)); } // ecma 11.9.3 21 if (xtype === "object" && (ytype === "string" || ytype === "number")) { return __loose_eq_ecma(__toPrimitive(x), y); } // ecma 11.9.3 22 return false; } function __loose_eq(x, y) { // ecma 11.9.3 var xtype = __type(x); var ytype = __type(y); // if x and y are of the same type, use strict comparision if (xtype === ytype) { return x === y; // ecma 11.9.4 } // here, x and y are of different type // handle null/undefined if (x === null || x === undefined) { return y === null || y === undefined; } if (y === null || y === undefined) { return false; } // here, x and y can be of type object, bool, number, string // here, x and y are of different type // if object, convert to primitive if (xtype === "object") { x = __toPrimitive(x), xtype = __type(x); } else if (ytype === "object") { y = __toPrimitive(y), ytype = __type(y); } // here, x and y can be of type undefined, null, bool, number, string // here, x and y may be of the same or different type // if both x and y are strings, compare lexically if (xtype === "string" && ytype === "string") { return x === y; } // here, x and y can be of type undefined, null, bool, number, string // here, x and y may be of the same or different type // convert x and y to numbers and compare return __toNumber(x) === __toNumber(y); } function __loose_ne(x, y) { // ecma 11.9.2 return !__loose_eq(x, y); } function __loose_add(x, y) { // ecma 11.6.1 // ecma 1-6 x = __toPrimitive(x); // no type hint y = __toPrimitive(y); // no type hint var xtype = typeof x; var ytype = typeof y; // ecma 7, 12-15 if (xtype === "string" || ytype === "string") { return String.prototype.concat.call(__toString(x), __toString(y)); } // ecma 8-11 // re-use built-in + operator for number addition return /*@loose*/(__toNumber(x) + __toNumber(y)); } function __loose_sub(x, y) { // ecma 11.6.2 // re-use built-in - operator for number subtraction return /*@loose*/(__toNumber(x) - __toNumber(y)); } function __loose_internal_compare(x, y, op) { // ecma 11.8.1 // ecma 11.8.5 // ecma 1-2 x = __toPrimitive(x, "hint_number"); y = __toPrimitive(y, "hint_number"); var xtype = typeof x; var ytype = typeof y; // ecma 3, 16-21 if (xtype === "string" && ytype === "string") { // re-use built-in operators for lexical string comparision if (op === 0) return /*@loose*/(x < y); if (op === 1) return /*@loose*/(x <= y); if (op === 2) return /*@loose*/(x > y); if (op === 3) return /*@loose*/(x >= y); } // ecma 4-15 else { // re-use built-in operators for IEEE-754 floating point comparision if (op === 0) return /*@loose*/(__toNumber(x) < __toNumber(y)); if (op === 1) return /*@loose*/(__toNumber(x) <= __toNumber(y)); if (op === 2) return /*@loose*/(__toNumber(x) > __toNumber(y)); if (op === 3) return /*@loose*/(__toNumber(x) >= __toNumber(y)); } throw new Error("__loose_internal_compare invalid op"); } function __loose_lt(x, y) { // ecma 11.8.1 return __loose_internal_compare(x, y, 0); } function __loose_le(x, y) { // ecma 11.8.3 return __loose_internal_compare(x, y, 1); } // __loose_gt can't be !__loose_le because // NaN < Nan, NaN <= NaN and NaN > NaN are all false function __loose_gt(x, y) { // ecma 11.8.2 return __loose_internal_compare(x, y, 2); } function __loose_ge(x, y) { // ecma 11.8.4 return __loose_internal_compare(x, y, 3); } function test_loose() { function f() {} Assert(__loose_eq(1, "1")); Assert(__loose_eq(2, new String("2"))); Assert(__loose_eq(2, {valueOf: function() { return 2; }})); Assert(__loose_eq(2, new Number(2))); Assert(__loose_lt(2, new Number(3))); Assert(__loose_le(2, new Number(3))); Assert(__loose_gt(2, new Number(3)) === false); Assert(__loose_gt(2, new String("3")) === false); Assert(typeof __toNumber(f) === "number"); // NaN Assert(__toNumber(f).toString() === "NaN"); // NaN Assert(typeof __toPrimitive(f) === "string"); // "function f..." Assert(typeof __toString(f) === "string"); // "function f..." Assert(typeof __defaultValue(f) === "string"); // "function f..." Assert(__lt(1, 2)); Assert(__lt("abc", "bac")); Assert(__lt("abc", "abc") === false); Assert.throwsException(function() { __lt([1,2,3], [2,3,4]); }); Assert.throwsException(function() { __lt([10], [2]); } ); Assert.throwsException(function() { __lt([[2]], [["1"]]); } ); Assert.throwsException(function() { __lt(new Number(1), 2); }); Assert(__sub(1,2) === -1); Assert.throwsException(function() { __sub("1", 0); }); } test_loose(); function test_binary_operator() { function create_getter(o, key, val) { o[key] = function() { return val; }; return o; } var values = { "undefined": [undefined], "boolean": [true, false], "Boolean": [new Boolean(true), new Boolean(false)], "number": [0, 0.1, 0.5, 1, 1.1, 1.5, 2, 3, 8, 10, 11, 20, 100, /*0,*/ 316998000000, 1282600800000, // Dates Number.MAX_VALUE, Number.MIN_VALUE, Infinity, NaN], "Number": [], "string": ["", " ", " ", "undefined", "true", "false", "a", "b", "xy", "zw", "qwerty"], "String": [], "Date": [new Date(0), new Date(1980, 1-1, 18), new Date(2010, 8-1, 24)], "object": [null, {}, {key: "value"}], "array": [[], [1], [2], [10], [1, 2], [1, 3], [[]], [[1]], [[1], 2]], "function": [function() {}, function() { return 1; }, new Function(), new Function("return 1;")] }; var i, len; // populate string with string representation of // Date, object, array, function values for (i = 0, len = values["Date"].length; i < len; ++i) { values["string"].push(String(values["Date"][i])); } for (i = 0, len = values["object"].length; i < len; ++i) { values["string"].push(String(values["object"][i])); } for (i = 0, len = values["array"].length; i < len; ++i) { values["string"].push(String(values["array"][i])); } for (i = 0, len = values["function"].length; i < len; ++i) { values["string"].push(String(values["function"][i])); } // populate string with string representation of numbers for (i = 0, len = values["number"].length; i < len; ++i) { var str = String(values["number"][i]); values["string"].push(str, "-"+ str, // positive, negative " "+ str, str +",", // prep space, app comma "0"+ str); // prep "0" (octalness) } // populate number with negative values for (i = 0, len = values["number"].length; i < len; ++i) { values["number"].push(-values["number"][i]); } // populate Number with boxed numbers for (i = 0, len = values["number"].length; i < len; ++i) { values["Number"].push(new Number(values["number"][i])); } // populate String with boxed strings for (i = 0, len = values["string"].length; i < len; ++i) { values["String"].push(new String(values["string"][i])); } //flatten var flat = []; flat = flat.concat(values["undefined"], values["boolean"],// values["Boolean"], values["number"],// values["Number"], values["string"],// values["String"], values["Date"], values["object"], values["array"], values["function"]); function create_valueOf_toString(type, ctor) { for (i = 0, len = flat.length; i < len; ++i) { values[type].push( create_getter(new ctor, "valueOf", flat[i])); values[type].push( create_getter(new ctor, "toString", flat[i])); values[type].push( create_getter(create_getter(new ctor, "valueOf", flat[i])), "toString", flat[i], flat[len-i-1]); } } /* create_valueOf_toString("object", Object); create_valueOf_toString("function", Function); create_valueOf_toString("Boolean", Boolean); create_valueOf_toString("Number", Number); create_valueOf_toString("String", String); create_valueOf_toString("Date", Date); create_valueOf_toString("array", Array); */ flat = []; for (var type in values) { log(Fmt("{0}: {1} values", type, values[type].length)); flat = flat.concat(values[type]); } log(Fmt("Total {0} values", flat.length)); var j; for (i = 0; i < flat.length; i++) { for (j = 0; j < flat.length; j++) { var exc_a = false, exc_b = false; var val_a, val_b; try { val_a = /*@loose*/(flat[i] == flat[j]); } catch (e) { exc_a = e; } try { val_b = __loose_eq(flat[i], flat[j]); } catch (e) { exc_b = e; } if (exc_a || exc_b) { Assert(!!exc_a === !!exc_b); } else { if (val_a !== val_b && !(isNaN(val_a) && isNaN(val_b))) { // log(i,j); continue; log(Fmt( "flat[{0}] == flat[{1}] yields {2} but __loose_eq(flat[{0}], flat[{1}]) yields {3}", i, j, val_a, val_b)); inspect(flat[i]); inspect(flat[j]); log(); // Assert(false); } } } } } test_binary_operator(); function test_jsvm_differences(vmstr) { var vm = {js: vmstr === "js", v8: vmstr === "v8", jsc: vmstr === "jsc", ecma: vmstr === "ecma"}; // js, v8, jsc yield true, ecma (my interpretation) yields false Assert(/*@loose*/(false == {valueOf: function() { return null; }}) === !vm.ecma); Assert(/*@loose*/("" == {valueOf: function() { return null; }}) === vm.js); Assert(/*@loose*/(false == new Date(0)) === !vm.js); Assert(/*@loose*/(0 == new Date(0)) === !vm.js); Assert(/*@loose*/(316998000000 == new Date(1980, 1-1, 18)) === !vm.js); Assert(/*@loose*/(1282600800000 == new Date(2010, 8-1, 24)) === !vm.js); } //test_jsvm_differences("v8"); function inspect(v) { var str = "inspect("+ __verbosetypeof(v) +")"; var val; if (v.valueOf) { val = v.valueOf(); str += Fmt(" valueOf: {0} ({1})", val, __verbosetypeof(val)); } if (v.toString) { val = v.toString(); str += Fmt(" toString: {0} ({1})", val, __verbosetypeof(val)); } log(str); } Array.isArray = Array.isArray || function(o) { return Object.prototype.toString.call(o) === "[object Array]"; }; log("ecma-ops.js done");
cksspk/ruoyi-vue-pro
yudao-vue-ui/uni_modules/uview-ui/libs/config/props/rate.js
<gh_stars>100-1000 /* * @Author : LQ * @Description : * @version : 1.0 * @Date : 2021-08-20 16:44:21 * @LastAuthor : LQ * @lastTime : 2021-08-20 17:05:09 * @FilePath : /u-view2.0/uview-ui/libs/config/props/rate.js */ export default { // rate组件 rate: { value: 1, count: 5, disabled: false, size: 18, inactiveColor: '#b2b2b2', activeColor: '#FA3534', gutter: 4, minCount: 1, allowHalf: false, activeIcon: 'star-fill', inactiveIcon: 'star', touchable: true } }
jingcao80/Elastos
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/animation/CFloatEvaluator.cpp
//========================================================================= // Copyright (C) 2012 The Elastos 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. //========================================================================= #include "elastos/droid/animation/CFloatEvaluator.h" #include "elastos/droid/ext/frameworkext.h" using Elastos::Core::IFloat; using Elastos::Core::CFloat; using Elastos::Core::INumber; namespace Elastos { namespace Droid { namespace Animation { CAR_OBJECT_IMPL(CFloatEvaluator) CAR_INTERFACE_IMPL_2(CFloatEvaluator, Object, IFloatEvaluator, ITypeEvaluator) CFloatEvaluator::CFloatEvaluator() {} CFloatEvaluator::~CFloatEvaluator() {} ECode CFloatEvaluator::constructor() { return NOERROR; } ECode CFloatEvaluator::Evaluate( /* [in] */ Float fraction, /* [in] */ IInterface* startValue, /* [in] */ IInterface* endValue, /* [out] */ IInterface** result) { VALIDATE_NOT_NULL(result); Float startFloat = 0.0f, endFloat = 0.0f; INumber::Probe(startValue)->FloatValue(&startFloat); INumber::Probe(endValue)->FloatValue(&endFloat); Float retValue = startFloat + fraction * (endFloat - startFloat); AutoPtr<IFloat> r; CFloat::New(retValue, (IFloat**)&r); *result = r; REFCOUNT_ADD(*result); return NOERROR; } } //namespace Animation } //namespace Droid } //namespace Elastos
Cokemonkey11/wc3libs
src/main/java/net/moonlightflower/wc3libs/dataTypes/app/AbilCode.java
package net.moonlightflower.wc3libs.dataTypes.app; import net.moonlightflower.wc3libs.misc.ObjId; public class AbilCode extends ObjId { protected AbilCode(String idString) { super(idString); } public static AbilCode valueOf(ObjId id) { return new AbilCode(id.toString()); } public static AbilCode decodeStatic(Object val) { if (val == null) return null; return AbilCode.valueOf(ObjId.valueOf(val.toString())); } }
Acidburn0zzz/bareos
src/filed/socket_server.cc
<reponame>Acidburn0zzz/bareos /* BAREOS® - Backup Archiving REcovery Open Sourced Copyright (C) 2000-2011 Free Software Foundation Europe e.V. Copyright (C) 2014-2014 Bareos GmbH & Co. KG This program is Free Software; you can redistribute it and/or modify it under the terms of version three of the GNU Affero General Public License as published by the Free Software Foundation and included in the file 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 GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* * <NAME>, October MM * Extracted from other source files by <NAME>, October 2014 */ /** * @file * This file handles external connections made to the File daemon. */ #include "bareos.h" #include "filed.h" /* Global variables */ static workq_t socket_workq; static pthread_t tcp_server_tid; static alist *sock_fds = NULL; /** * Connection request. We accept connections either from the Director or the Storage Daemon * * NOTE! We are running as a separate thread * * Send output one line at a time followed by a zero length transmission. * Return when the connection is terminated or there is an error. * * Basic tasks done here: * - If it was a connection from an SD, call handle_stored_connection() * - Otherwise it was a connection from the DIR, call handle_director_connection() */ static void *handle_connection_request(void *arg) { BSOCK *bs = (BSOCK *)arg; char tbuf[100]; if (bs->recv() <= 0) { Emsg1(M_ERROR, 0, _("Connection request from %s failed.\n"), bs->who()); bmicrosleep(5, 0); /* make user wait 5 seconds */ bs->close(); delete bs; return NULL; } Dmsg1(110, "Conn: %s\n", bs->msg); /* * See if its a director making a connection. */ if (bstrncmp(bs->msg, "Hello Director", 14)) { Dmsg1(110, "Got a DIR connection at %s\n", bstrftimes(tbuf, sizeof(tbuf), (utime_t)time(NULL))); return handle_director_connection(bs); } /* * See if its a storage daemon making a connection. */ if (bstrncmp(bs->msg, "Hello Storage", 13)) { Dmsg1(110, "Got a SD connection at %s\n", bstrftimes(tbuf, sizeof(tbuf), (utime_t)time(NULL))); return handle_stored_connection(bs); } Emsg2(M_ERROR, 0, _("Invalid connection from %s. Len=%d\n"), bs->who(), bs->msglen); return NULL; } void start_socket_server(dlist *addrs) { IPADDR *p; tcp_server_tid = pthread_self(); /* * Become server, and handle requests */ foreach_dlist(p, addrs) { Dmsg1(10, "filed: listening on port %d\n", p->get_port_host_order()); } /* * Permit MaxConnections connections. */ sock_fds = New(alist(10, not_owned_by_alist)); bnet_thread_server_tcp(addrs, me->MaxConnections, sock_fds, &socket_workq, me->nokeepalive, handle_connection_request); } void stop_socket_server(bool wait) { Dmsg0(100, "stop_socket_server\n"); if (sock_fds) { bnet_stop_thread_server_tcp(tcp_server_tid); /* * before thread_servers terminates, * it calls cleanup_bnet_thread_server_tcp */ if (wait) { pthread_join(tcp_server_tid, NULL); delete(sock_fds); sock_fds = NULL; } } }
DSM-DIS/DIS-Client
src/components/modal/Modal/RegisterModal/RegisterModal.js
import React from "react"; import Modal from "../Modal"; import ModalCloseBtn from "../../ModalCloseBtn/ModalCloseBtn"; import RegisterModalForm from "../../ModalForm/RegisterModalForm/RegisterModalForm"; const RegisterModal = () => { return ( <Modal> <ModalCloseBtn /> <RegisterModalForm /> </Modal> ); }; export default RegisterModal;
AlexIIL/Astromine
src/main/java/com/github/chainmailstudios/astromine/client/screen/base/DefaultedEnergyFluidContainerScreen.java
<reponame>AlexIIL/Astromine package com.github.chainmailstudios.astromine.client.screen.base; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.text.Text; import com.github.chainmailstudios.astromine.common.component.ComponentProvider; import com.github.chainmailstudios.astromine.common.container.base.DefaultedBlockEntityContainer; import com.github.chainmailstudios.astromine.common.container.base.DefaultedEnergyFluidContainer; import com.github.chainmailstudios.astromine.common.widget.WEnergyVolumeFractionalVerticalBar; import com.github.chainmailstudios.astromine.common.widget.WFluidVolumeFractionalVerticalBar; import com.github.chainmailstudios.astromine.registry.AstromineComponentTypes; import spinnery.widget.api.Position; import spinnery.widget.api.Size; public abstract class DefaultedEnergyFluidContainerScreen<T extends DefaultedBlockEntityContainer> extends DefaultedBlockEntityContainerScreen<T> { public WEnergyVolumeFractionalVerticalBar energyBar; public WFluidVolumeFractionalVerticalBar fluidBar; public DefaultedEnergyFluidContainerScreen(Text name, DefaultedEnergyFluidContainer linkedContainer, PlayerEntity player) { super(name, (T) linkedContainer, player); energyBar = mainPanel.createChild(WEnergyVolumeFractionalVerticalBar::new, Position.of(mainPanel, 7, 20, 0), Size.of(24, 48)); fluidBar = mainPanel.createChild(WFluidVolumeFractionalVerticalBar::new, Position.of(energyBar, energyBar.getWidth() + 4, 0, 0), Size.of(energyBar)); ComponentProvider componentProvider = linkedContainer.blockEntity; energyBar.setEnergyVolume(() -> componentProvider.getSidedComponent(null, AstromineComponentTypes.ENERGY_INVENTORY_COMPONENT).getVolume(0)); fluidBar.setFluidVolume(() -> componentProvider.getSidedComponent(null, AstromineComponentTypes.FLUID_INVENTORY_COMPONENT).getVolume(0)); } }
tied/innovation-funding-service
ifs-data-layer/ifs-data-service/src/main/java/org/innovateuk/ifs/application/workflow/actions/BaseApplicationAction.java
<reponame>tied/innovation-funding-service package org.innovateuk.ifs.application.workflow.actions; import org.innovateuk.ifs.application.domain.Application; import org.innovateuk.ifs.application.resource.ApplicationEvent; import org.innovateuk.ifs.application.resource.ApplicationState; import org.innovateuk.ifs.workflow.TestableTransitionWorkflowAction; import org.springframework.statemachine.StateContext; /** * A base class for Application-related workflow actions. */ public abstract class BaseApplicationAction extends TestableTransitionWorkflowAction<ApplicationState, ApplicationEvent> { @Override protected final void doExecute(final StateContext<ApplicationState, ApplicationEvent> context) { Application application = getApplicationFromContext(context); doExecute(application, context); } private Application getApplicationFromContext(StateContext<ApplicationState, ApplicationEvent> context) { return (Application) context.getMessageHeader("target"); } protected abstract void doExecute(Application application, StateContext<ApplicationState, ApplicationEvent> context); }
AshwinKumarVijay/ECS-Development
ECS/Project/Project/Resources/ResourceData/LightData/LightData.h
#pragma once #include <map> #include <memory> #include "glm\glm.hpp" #include "../ResourceData.h" class LightData : public ResourceData { public: // Default LightData Constructor. LightData(); // Default LightData Destructor. virtual ~LightData(); // void setEnabled(bool newIsEnabled); bool getEnabled() const; void setLocal(bool newIsLocal); bool getLocal() const; int getLightType() const; void setLightType(int newLightType); glm::vec3 getLightColor() const; void setLightColor(glm::vec3 newLightColor); float getLightIntensity() const; void setLightIntensity(float newLightIntensity); glm::vec4 getLightPosition() const; void setLightPosition(glm::vec4 newLightPosition); glm::vec4 getDistanceAttenuation() const; void setDistanceAttenuation(glm::vec4 newDistanceAttenuation); void setSpotCosCutOffAndExponent(glm::vec4 newSpotCosCutOffAndExponent); glm::vec4 getSpotCosCutOffAndExponent() const; private: // Add Comments - TO DO bool isEnabled; // Add Comments - TO DO bool isLocal; // Add Comments - TO DO int lightType; // Add Comments - TO DO glm::vec3 lightColor; // Add Comments - TO DO float lightIntensity; // Add Comments - TO DO glm::vec4 lightPosition; // Add Comments - TO DO glm::vec4 distanceAttenuation; // Add Comments - TO DO glm::vec4 spotCosCutOffAndExponent; };
ckamtsikis/cmssw
AnalysisDataFormats/TopObjects/interface/TtFullHadronicEvent.h
#ifndef TopObjects_TtFullHadronicEvent_h #define TopObjects_TtFullHadronicEvent_h #include "AnalysisDataFormats/TopObjects/interface/TtEvent.h" namespace TtFullHadDaughter { /// full hadronic daughter names for common /// use and use with the hypotheses static const std::string LightQ = "LightQ", LightP = "LightP", WPlus = "WPlus", B = "B", Top = "Top"; static const std::string LightQBar = "LightQBar", LightPBar = "LightPBar", WMinus = "WMinus", BBar = "BBar", TopBar = "TopBar"; } // namespace TtFullHadDaughter /** \class TtFullHadronicEvent TtFullHadronicEvent.h "AnalysisDataFormats/TopObjects/interface/TtFullHadronicEvent.h" \brief Class derived from the TtEvent for the full hadronic decay channel The structure holds information on the hadronic decay channels, all event hypotheses of different classes (user defined during production) and a reference to the TtGenEvent (if available). It provides access and administration. */ class TtFullHadronicEvent : public TtEvent { public: /// empty constructor TtFullHadronicEvent(){}; /// default destructor ~TtFullHadronicEvent() override{}; /// get top of the given hypothesis const reco::Candidate* top(const std::string& key, const unsigned& cmb = 0) const { return top(hypoClassKeyFromString(key), cmb); }; /// get top of the given hypothesis const reco::Candidate* top(const HypoClassKey& key, const unsigned& cmb = 0) const { return !isHypoValid(key, cmb) ? nullptr : eventHypo(key, cmb).daughter(TtFullHadDaughter::Top); }; /// get b of the given hypothesis const reco::Candidate* b(const std::string& key, const unsigned& cmb = 0) const { return b(hypoClassKeyFromString(key), cmb); }; /// get b of the given hypothesis const reco::Candidate* b(const HypoClassKey& key, const unsigned& cmb = 0) const { return !isHypoValid(key, cmb) ? nullptr : top(key, cmb)->daughter(TtFullHadDaughter::B); }; /// get light Q of the given hypothesis const reco::Candidate* lightQ(const std::string& key, const unsigned& cmb = 0) const { return lightQ(hypoClassKeyFromString(key), cmb); }; /// get light Q of the given hypothesis const reco::Candidate* lightQ(const HypoClassKey& key, const unsigned& cmb = 0) const { return !isHypoValid(key, cmb) ? nullptr : wPlus(key, cmb)->daughter(TtFullHadDaughter::LightQ); }; /// get light P of the given hypothesis const reco::Candidate* lightP(const std::string& key, const unsigned& cmb = 0) const { return lightP(hypoClassKeyFromString(key), cmb); }; /// get light P of the given hypothesis const reco::Candidate* lightP(const HypoClassKey& key, const unsigned& cmb = 0) const { return !isHypoValid(key, cmb) ? nullptr : wMinus(key, cmb)->daughter(TtFullHadDaughter::LightP); }; /// get Wplus of the given hypothesis const reco::Candidate* wPlus(const std::string& key, const unsigned& cmb = 0) const { return wPlus(hypoClassKeyFromString(key), cmb); }; /// get Wplus of the given hypothesis const reco::Candidate* wPlus(const HypoClassKey& key, const unsigned& cmb = 0) const { return !isHypoValid(key, cmb) ? nullptr : top(key, cmb)->daughter(TtFullHadDaughter::WPlus); }; /// get anti-top of the given hypothesis const reco::Candidate* topBar(const std::string& key, const unsigned& cmb = 0) const { return topBar(hypoClassKeyFromString(key), cmb); }; /// get anti-top of the given hypothesis const reco::Candidate* topBar(const HypoClassKey& key, const unsigned& cmb = 0) const { return !isHypoValid(key, cmb) ? nullptr : eventHypo(key, cmb).daughter(TtFullHadDaughter::TopBar); }; /// get anti-b of the given hypothesis const reco::Candidate* bBar(const std::string& key, const unsigned& cmb = 0) const { return bBar(hypoClassKeyFromString(key), cmb); }; /// get anti-b of the given hypothesis const reco::Candidate* bBar(const HypoClassKey& key, const unsigned& cmb = 0) const { return !isHypoValid(key, cmb) ? nullptr : topBar(key, cmb)->daughter(TtFullHadDaughter::BBar); }; /// get light Q bar of the given hypothesis const reco::Candidate* lightQBar(const std::string& key, const unsigned& cmb = 0) const { return lightQBar(hypoClassKeyFromString(key), cmb); }; /// get light Q bar of the given hypothesis const reco::Candidate* lightQBar(const HypoClassKey& key, const unsigned& cmb = 0) const { return !isHypoValid(key, cmb) ? nullptr : wPlus(key, cmb)->daughter(TtFullHadDaughter::LightQBar); }; /// get light P bar of the given hypothesis const reco::Candidate* lightPBar(const std::string& key, const unsigned& cmb = 0) const { return lightPBar(hypoClassKeyFromString(key), cmb); }; /// get light P bar of the given hypothesis const reco::Candidate* lightPBar(const HypoClassKey& key, const unsigned& cmb = 0) const { return !isHypoValid(key, cmb) ? nullptr : wMinus(key, cmb)->daughter(TtFullHadDaughter::LightPBar); }; /// get Wminus of the given hypothesis const reco::Candidate* wMinus(const std::string& key, const unsigned& cmb = 0) const { return wMinus(hypoClassKeyFromString(key), cmb); }; /// get Wminus of the given hypothesis const reco::Candidate* wMinus(const HypoClassKey& key, const unsigned& cmb = 0) const { return !isHypoValid(key, cmb) ? nullptr : topBar(key, cmb)->daughter(TtFullHadDaughter::WMinus); }; /// get top of the TtGenEvent const reco::GenParticle* top() const { return (!genEvt_ ? nullptr : this->genEvent()->top()); }; /// get b of the TtGenEvent const reco::GenParticle* b() const { return (!genEvt_ ? nullptr : this->genEvent()->b()); }; /// get light Q of the TtGenEvent const reco::GenParticle* lightQ() const { return (!genEvt_ ? nullptr : this->genEvent()->daughterQuarkOfWPlus()); }; /// get light P of the TtGenEvent const reco::GenParticle* lightP() const { return (!genEvt_ ? nullptr : this->genEvent()->daughterQuarkOfWMinus()); }; /// get Wplus of the TtGenEvent const reco::GenParticle* wPlus() const { return (!genEvt_ ? nullptr : this->genEvent()->wPlus()); }; /// get anti-top of the TtGenEvent const reco::GenParticle* topBar() const { return (!genEvt_ ? nullptr : this->genEvent()->topBar()); }; /// get anti-b of the TtGenEvent const reco::GenParticle* bBar() const { return (!genEvt_ ? nullptr : this->genEvent()->bBar()); }; /// get light Q bar of the TtGenEvent const reco::GenParticle* lightQBar() const { return (!genEvt_ ? nullptr : this->genEvent()->daughterQuarkBarOfWPlus()); }; /// get light P bar of the TtGenEvent const reco::GenParticle* lightPBar() const { return (!genEvt_ ? nullptr : this->genEvent()->daughterQuarkBarOfWMinus()); }; /// get Wminus of the TtGenEvent const reco::GenParticle* wMinus() const { return (!genEvt_ ? nullptr : this->genEvent()->wMinus()); }; /// print full content of the structure as formated /// LogInfo to the MessageLogger output for debugging void print(const int verbosity = 1) const; }; #endif
ckamtsikis/cmssw
GeneratorInterface/Pythia8Interface/interface/PTFilterHook.h
<filename>GeneratorInterface/Pythia8Interface/interface/PTFilterHook.h #include "Pythia8/UserHooks.h" class PTFilterHook : public Pythia8::UserHooks { public: // Constructor and destructor. PTFilterHook() {} //-------------------------------------------------------------------------- bool initAfterBeams() override; bool canVetoPT() override { return true; } double scaleVetoPT() override { return scale_; } bool doVetoPT(int iPos, const Pythia8::Event& event) override { return checkVetoPT(iPos, event); } bool checkVetoPT(int iPos, const Pythia8::Event& event); //-------------------------------------------------------------------------- private: bool filter_; int quark_; double scale_; double quarkY_; double quarkPt_; };
mgormley/pacaya
src/main/java/edu/jhu/pacaya/sch/util/ScheduleUtils.java
package edu.jhu.pacaya.sch.util; import static edu.jhu.pacaya.sch.util.Indexed.enumerate; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map.Entry; import org.apache.commons.lang3.mutable.MutableBoolean; import com.google.common.collect.Lists; import edu.jhu.pacaya.sch.Schedule; import edu.jhu.pacaya.sch.graph.IntDiGraph; public class ScheduleUtils { /** * Slight convenience for building pairs to avoid having to include the types when using with asList */ /* public static <K,V> Pair<K,V> pair(K k, V v) { return new Pair<>(k, v); } */ /** * return a DAG, G' = V', E' such that vertecies correspond to indexes in * the schedule and there is an edge (i,j) \in E' if s_i triggered s_j */ public static IntDiGraph buildTriggers(IntDiGraph g, Schedule s) { // return trigger DAG IntDiGraph d = new IntDiGraph(); // map from node to triggering indexes DefaultDict<Integer, List<Integer>> currentTriggers = new DefaultDict<>(i -> new LinkedList<Integer>()); for (Indexed<Integer> s_j : enumerate(s)) { // add in arcs from triggers for (int i : currentTriggers.get(s_j.get())) { d.addEdge(i, s_j.index()); } // remove s_j from the agenda currentTriggers.remove(s_j.get()); // record that j is triggering consequents for (int s_k : g.getSuccessors(s_j.get())) { currentTriggers.get(s_k).add(s_j.index()); } } // add a link to the unpopped version of each node still on the agenda // the integer will be the length of the trajectory plus an index into // the set of nodes for (Entry<Integer, List<Integer>> item : currentTriggers.entrySet()) { int s_k = item.getKey(); List<Integer> triggers = item.getValue(); for (int j : triggers) { d.addEdge(j, s.size() + g.index(s_k)); } } return d; } /** * Returns an iterator cycles over the elements in items repeat times; * if repeat < 0, then this cycles indefinitely * if repeat == 0, then the iterator is an empty iterator */ public static <T> Iterator<T> cycle(Iterator<T> itr, int times) { // if we repeat 0, then it is as if the itr were empty, so don't take the items final List<T> items = (times != 0) ? Lists.newLinkedList(iterable(itr)) : Collections.emptyList(); return new Iterator<T>() { private Iterator<T> currentItr = Collections.emptyIterator(); private int ncalls = 0; private Iterator<T> getItr() { // if this is the first call or we've gotten to the end of a round if (!currentItr.hasNext() && ncalls < times) { currentItr = items.iterator(); ncalls++; } return currentItr; } @Override public boolean hasNext() { return getItr().hasNext(); } @Override public T next() { return getItr().next(); } }; } public static <T> Iterable<T> iterable(Iterator<T> seq) { final MutableBoolean used = new MutableBoolean(false); return new Iterable<T>() { @Override public Iterator<T> iterator() { if (!used.booleanValue()) { used.setValue(true); return seq; } else { throw new IllegalStateException("only allowed to iterate this iterable once"); } } }; } }
sunbit/banking
src/app/api/io.py
<filename>src/app/api/io.py from copy import deepcopy from dataclasses import is_dataclass from enum import Enum from datetime import datetime def encode_date(dt): return dt.strftime('%Y-%m-%dT%H:%M:%S') def encode_account(account_config, include_children=True): account = deepcopy(account_config.__dict__) if not include_children: account.pop('cards', None) return account def encode_object(obj): def encode(obj): if is_dataclass(obj): encoded = obj.__dict__ return encoded elif isinstance(obj, Enum): return { '__type__': 'enum::{}'.format(obj.__class__.__name__), 'name': obj.name } elif isinstance(obj, datetime): return encode_date(obj) else: return obj def recurse(obj): encoded = encode(obj) if isinstance(encoded, dict): new = {} for key, value in encoded.items(): new[key] = recurse(value) return new elif isinstance(encoded, list): new = [] for item in encoded: new.append(recurse(item)) return new else: return encoded return recurse(obj)
Qualia91/goLearning
patterns/microservices/dataconsistency/saga/doc.go
/*Saga Pattern. Service initiates a saga request to the saga log (database). Saga execution coordinator (SEC) listens to log and actions requests. Sends requests in request is requested, and compensation requests if something failed (rollback request) Following example: Initiator service (9000) receives get and sends a message to saga log service (9009). SEC listens to messages sent into log service and sends requests out to serviceOne (9001) and serviceTwo (9002). serviceOne sends a complete back, serviceTwo send s a fail back. SEC sends compensation request out to both services to get them to roll back.*/ package saga
gcwiak/nixer-spring-plugin
captcha/src/test/java/io/nixer/nixerplugin/captcha/security/CaptchaAuthenticationProviderTest.java
package io.nixer.nixerplugin.captcha.security; import java.util.Collections; import io.nixer.nixerplugin.captcha.error.CaptchaClientException; import io.nixer.nixerplugin.captcha.events.FailedCaptchaAuthenticationEvent; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.context.ApplicationEventPublisher; import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.verify; @ExtendWith(MockitoExtension.class) class CaptchaAuthenticationProviderTest { @Mock private CaptchaChecker captchaChecker; @Mock private ApplicationEventPublisher eventPublisher; private AbstractAuthenticationToken authenticationToken; private CaptchaAuthenticationProvider captchaAuthenticationProvider; @BeforeEach void setUp() { captchaAuthenticationProvider = new CaptchaAuthenticationProvider(captchaChecker, eventPublisher); } @Test void captchaInvalid() { authenticationToken = new UsernamePasswordAuthenticationToken( new Object(), new Object(), Collections.singletonList((GrantedAuthority) () -> "test")); doThrow(new CaptchaClientException("")).when(captchaChecker).checkCaptcha(); assertThrows(CaptchaAuthenticationStatusException.class, () -> captchaAuthenticationProvider.authenticate(authenticationToken)); assertThat(authenticationToken.isAuthenticated()).isFalse(); verify(eventPublisher).publishEvent(any(FailedCaptchaAuthenticationEvent.class)); } @Test void noCaptchaOrCaptchaCorrect() { final Authentication result = captchaAuthenticationProvider.authenticate(authenticationToken); assertNull(result); } }