repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
zipated/src
chrome/browser/chromeos/login/quick_unlock/quick_unlock_utils.h
<reponame>zipated/src<filename>chrome/browser/chromeos/login/quick_unlock/quick_unlock_utils.h // Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_CHROMEOS_LOGIN_QUICK_UNLOCK_QUICK_UNLOCK_UTILS_H_ #define CHROME_BROWSER_CHROMEOS_LOGIN_QUICK_UNLOCK_QUICK_UNLOCK_UTILS_H_ namespace base { class TimeDelta; } class PrefRegistrySimple; class PrefService; namespace chromeos { namespace quick_unlock { // Enumeration specifiying the possible intervals before a strong auth // (password) is required to use quick unlock. These values correspond to the // policy items of QuickUnlockTimeout (policy ID 352) in policy_templates.json, // and should be updated accordingly. enum class PasswordConfirmationFrequency { SIX_HOURS = 0, TWELVE_HOURS = 1, DAY = 2, WEEK = 3 }; base::TimeDelta PasswordConfirmationFrequencyToTimeDelta( PasswordConfirmationFrequency frequency); // Register quick unlock prefs. void RegisterProfilePrefs(PrefRegistrySimple* registry); // Returns true if PIN unlock is disabled by policy. bool IsPinDisabledByPolicy(PrefService* pref_service); // Returns true if the quick unlock feature flag is present. bool IsPinEnabled(PrefService* pref_service); // Returns true if the fingerprint unlock feature flag is present. bool IsFingerprintEnabled(); // Forcibly enable all quick-unlock modes for testing. void EnableForTesting(); // Forcibly disable PIN for testing purposes. void DisablePinByPolicyForTesting(bool disable); } // namespace quick_unlock } // namespace chromeos #endif // CHROME_BROWSER_CHROMEOS_LOGIN_QUICK_UNLOCK_QUICK_UNLOCK_UTILS_H_
wwjiang007/spring-xd
spring-xd-integration-test/acceptance-test-sparkapp/src/main/java/spark/SparkPi.java
/* * * * Copyright 2014-2015 the original author or authors. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * 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 spark; import org.apache.spark.SparkConf; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; import org.apache.spark.api.java.function.Function; import org.apache.spark.api.java.function.Function2; import java.util.ArrayList; import java.util.List; /** * SparkPi Sample Code that utilizes spark master calls to generate a rough estimate of pi. * * @author <NAME> */ @SuppressWarnings("serial") public class SparkPi { public static void main(String[] args) throws Exception { SparkConf sparkConf = new SparkConf().setAppName("TestSparkPi"); JavaSparkContext jsc = new JavaSparkContext(sparkConf); int slices = (args.length == 1) ? Integer.parseInt(args[0]) : 2; int n = 100000 * slices; List<Integer> l = new ArrayList<Integer>(n); for (int i = 0; i < n; i++) { l.add(i); } JavaRDD<Integer> dataSet = jsc.parallelize(l, slices); int count = dataSet.map(new Function<Integer, Integer>() { @Override public Integer call(Integer integer) { double x = Math.random() * 2 - 1; double y = Math.random() * 2 - 1; return (x * x + y * y < 1) ? 1 : 0; } }).reduce(new Function2<Integer, Integer, Integer>() { @Override public Integer call(Integer integer, Integer integer2) { return integer + integer2; } }); System.out.println("Pi is roughly " + 4.0 * count / n); System.out.println("Complete"); } }
Vladlgv/TCI_G3
AssignmentG3/src/main/java/casino/idfactory/BetID.java
package casino.idfactory; public class BetID extends GeneralID { }
opentext/storyteller
docplatform/distribution/py/pfdesigns/javascript/locales.js
"use strict"; var repo = require('repo'); function init_data(api_key) { // // Online Exchange Rates API // // see https://openexchangerates.org/ // var local_uri = 'wd:/rates.json'; if (api_key) { var remote_uri = 'http://openexchangerates.org/api/latest.json?app_id=' + api_key; var data = repo.load(remote_uri); repo.save(local_uri, data); return data; } else { return repo.load(local_uri); } } function init_money(data) { var money = require('money'); if (money.rates.length) { throw new Error("Currency rates conflict!"); } var rates = JSON.parse(data); money.base = rates.base; money.rates = rates.rates; return money; } // key => download latest rates // null => use local cache var api_key = null; // '<KEY>'; var money = init_money(init_data(api_key)); var accounting = require('accounting'); // Comes from http://www.localeplanet.com/api/auto/currencymap.json var currencies = JSON.parse(repo.load("wd:/currencies.json")); var moment = require('moment'); exports.reformat_date = function (value, locale, from, to) { var m = moment(value, from); m.locale(locale); return m.format(to); }; exports.reformat_money = function (value, locale, from) { from = from || "USD"; var currency = currencies[locale]; value = accounting.unformat(value); value = money.convert(value, {from: from, to: currency.code}); var options = { symbol: currency.symbol_native, decimal: currency.decimal, thousand: currency.group, precision: currency.decimal_digits, format: currency.format }; return accounting.formatMoney(value, options); };
techstars/quickeebooks
spec/quickeebooks/online/customer_spec.rb
describe "Quickeebooks::Online::Model::Customer" do it "parse customer from XML" do xml = onlineFixture("customer.xml") customer = Quickeebooks::Online::Model::Customer.from_xml(xml) customer.sync_token.should == 1 customer.name.should == "<NAME>" create_time = Date.civil(2011, 9, 29) customer.meta_data.create_time.year.should == create_time.year customer.addresses.count.should == 2 customer.billing_address.line1.should == "123 Main St." customer.shipping_address.line1.should == "123 Shipping St." customer.phones.size.should == 5 customer.primary_phone.free_form_number.should == "(408) 555-1212" customer.secondary_phone.free_form_number.should == "(408) 555-1213" customer.mobile_phone.free_form_number.should == "(408) 555-1214" customer.fax.free_form_number.should == "(408) 555-1215" customer.pager.free_form_number.should == "(408) 555-1216" customer.email.address.should == "<EMAIL>" customer.notes.count.should == 1 customer.notes.first.content.should == "Likes chocolate and horses" customer.custom_fields.count.should == 3 customer.open_balance.amount.should == 6200.0 end it "can assign an email address" do customer = Quickeebooks::Online::Model::Customer.new the_email = "<EMAIL>" customer.email_address = the_email customer.email.is_a?(Quickeebooks::Online::Model::Email).should == true customer.email.address.should == the_email end it "cannot update an invalid model" do customer = Quickeebooks::Online::Model::Customer.new customer.valid_for_update?.should == false customer.to_xml_ns.should match('Customer') customer.errors.keys.include?(:sync_token).should == true end end
ZzoeyYang/Android-StickyNavLayout
libBase/src/main/java/online/sniper/widget/AnimationImageView.java
package online.sniper.widget; import android.content.Context; import android.graphics.Canvas; import android.graphics.drawable.AnimationDrawable; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.widget.ImageView; /** * 自动启动动画的View * Created by wangpeihe on 2016/11/16. */ public class AnimationImageView extends ImageView { private boolean isStarting = false; public AnimationImageView(Context context) { super(context); } public AnimationImageView(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onDraw(Canvas canvas) { Drawable d = getDrawable(); if (d instanceof AnimationDrawable) { if (!isStarting) { ((AnimationDrawable) d).start(); isStarting = true; } } else { isStarting = false; } super.onDraw(canvas); } }
CARV-ICS-FORTH/frisbee
controllers/testplan/lifecycle.go
<reponame>CARV-ICS-FORTH/frisbee /* Copyright 2021 ICS-FORTH. 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 testplan import ( "fmt" "github.com/carv-ics-forth/frisbee/api/v1alpha1" "github.com/carv-ics-forth/frisbee/controllers/utils/expressions" "github.com/sirupsen/logrus" "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) type test struct { expression bool lifecycle v1alpha1.Lifecycle condition metav1.Condition } func (r *Controller) updateLifecycle(t *v1alpha1.TestPlan) v1alpha1.Lifecycle { cycle := t.Status.Lifecycle // Step 1. Skip any CR which are already completed, or uninitialized. if cycle.Phase == v1alpha1.PhaseUninitialized || cycle.Phase == v1alpha1.PhaseSuccess || cycle.Phase == v1alpha1.PhaseFailed { return cycle } // Step 2. Check if metrics-driven assertions are fired if info, fired := expressions.FiredAlert(t); fired { cycle = v1alpha1.Lifecycle{ Phase: v1alpha1.PhaseFailed, Reason: "MetricsAssertion", Message: info, } meta.SetStatusCondition(&cycle.Conditions, metav1.Condition{ Type: v1alpha1.ConditionTerminated.String(), Status: metav1.ConditionTrue, Reason: "MetricsAssertion", Message: info, }) return cycle } // Step 3. Check if state-driven assertions are fired for _, assertion := range t.Status.Executed { if assertion.IsZero() { continue } if assertion.HasStateExpr() { info, fired, err := expressions.FiredState(assertion.State, r.state) if err != nil { cycle = v1alpha1.Lifecycle{ Phase: v1alpha1.PhaseFailed, Reason: "StateQueryError", Message: err.Error(), } meta.SetStatusCondition(&cycle.Conditions, metav1.Condition{ Type: v1alpha1.ConditionTerminated.String(), Status: metav1.ConditionTrue, Reason: "StateQueryError", Message: err.Error(), }) return cycle } if fired { cycle = v1alpha1.Lifecycle{ Phase: v1alpha1.PhaseRunning, Reason: "StateAssertion", Message: info, } meta.SetStatusCondition(&cycle.Conditions, metav1.Condition{ Type: v1alpha1.ConditionTerminated.String(), Status: metav1.ConditionTrue, Reason: "StateAssertion", Message: info, }) return cycle } } } // we are only interested in the number of jobs in each category. expectedJobs := len(t.Spec.Actions) selftests := []test{ { // A job has failed during execution. expression: r.state.FailedJobsNum() > 0, lifecycle: v1alpha1.Lifecycle{ Phase: v1alpha1.PhaseFailed, Reason: "JobHasFailed", Message: fmt.Sprintf("failed jobs: %s", r.state.FailedJobsList()), }, condition: metav1.Condition{ Type: v1alpha1.ConditionJobUnexpectedTermination.String(), Status: metav1.ConditionTrue, Reason: "JobHasFailed", Message: fmt.Sprintf("failed jobs: %s", r.state.FailedJobsList()), }, }, { // All jobs are created, and completed successfully expression: r.state.SuccessfulJobsNum() == expectedJobs, lifecycle: v1alpha1.Lifecycle{ Phase: v1alpha1.PhaseSuccess, Reason: "AllJobsCompleted", Message: fmt.Sprintf("successful jobs: %s", r.state.SuccessfulJobsList()), }, condition: metav1.Condition{ Type: v1alpha1.ConditionAllJobsAreCompleted.String(), Status: metav1.ConditionTrue, Reason: "AllJobsCompleted", Message: fmt.Sprintf("successful jobs: %s", r.state.SuccessfulJobsList()), }, }, { // All jobs are created, and at least one is still running expression: len(t.Status.Executed) == expectedJobs, lifecycle: v1alpha1.Lifecycle{ Phase: v1alpha1.PhaseRunning, Reason: "JobIsRunning", Message: fmt.Sprintf("running jobs: %s", r.state.RunningJobsList()), }, condition: metav1.Condition{ Type: v1alpha1.ConditionAllJobsAreScheduled.String(), Status: metav1.ConditionTrue, Reason: "AllJobsRunning", Message: fmt.Sprintf("running jobs: %s", r.state.RunningJobsList()), }, }, { // Not all Jobs are yet created expression: len(t.Status.Executed) < expectedJobs, lifecycle: v1alpha1.Lifecycle{ Phase: v1alpha1.PhasePending, Reason: "JobIsPending", Message: "at least one jobs has not yet created", }, }, } for _, testcase := range selftests { if testcase.expression { cycle = testcase.lifecycle if testcase.condition != (metav1.Condition{}) { meta.SetStatusCondition(&cycle.Conditions, testcase.condition) } return cycle } } logrus.Warn("TestPlan Debug info \n", " phase ", cycle.Phase, " actions: ", expectedJobs, " executed: ", len(t.Status.Executed), " pending: ", r.state.PendingJobsList(), " running: ", r.state.RunningJobsList(), " successfulJobs: ", r.state.SuccessfulJobsList(), " failedJobs: ", r.state.FailedJobsList(), " cur status: ", t.Status, ) panic("unhandled lifecycle conditions") }
zyq1569/HealthApp
dcm/dcmdata/dcerror.cc
/* * * Copyright (C) 1994-2017, OFFIS e.V. * All rights reserved. See COPYRIGHT file for details. * * This software and supporting documentation were developed by * * OFFIS e.V. * R&D Division Health * Escherweg 2 * D-26121 Oldenburg, Germany * * * Module: dcmdata * * Author: <NAME> * * Purpose: Error handling, codes and strings * */ #include "dcmtk/config/osconfig.h" /* make sure OS specific configuration is included first */ #include "dcmtk/dcmdata/dcerror.h" makeOFConditionConst(EC_InvalidTag, OFM_dcmdata, 1, OF_error, "Invalid tag" ); makeOFConditionConst(EC_TagNotFound, OFM_dcmdata, 2, OF_error, "Tag not found" ); makeOFConditionConst(EC_InvalidVR, OFM_dcmdata, 3, OF_error, "Invalid VR" ); makeOFConditionConst(EC_InvalidStream, OFM_dcmdata, 4, OF_error, "Invalid stream" ); makeOFConditionConst(EC_EndOfStream, OFM_dcmdata, 5, OF_error, "End of stream" ); makeOFConditionConst(EC_CorruptedData, OFM_dcmdata, 6, OF_error, "Corrupted data" ); makeOFConditionConst(EC_IllegalCall, OFM_dcmdata, 7, OF_error, "Illegal call, perhaps wrong parameters" ); makeOFConditionConst(EC_SequEnd, OFM_dcmdata, 8, OF_error, "Sequence end" ); makeOFConditionConst(EC_DoubledTag, OFM_dcmdata, 9, OF_error, "Doubled tag" ); makeOFConditionConst(EC_StreamNotifyClient, OFM_dcmdata, 10, OF_error, "I/O suspension or premature end of stream" ); makeOFConditionConst(EC_WrongStreamMode, OFM_dcmdata, 11, OF_error, "Mode (R/W, random/sequence) is wrong" ); makeOFConditionConst(EC_ItemEnd, OFM_dcmdata, 12, OF_error, "Item end" ); makeOFConditionConst(EC_RepresentationNotFound, OFM_dcmdata, 13, OF_error, "Pixel representation not found" ); makeOFConditionConst(EC_CannotChangeRepresentation, OFM_dcmdata, 14, OF_error, "Pixel representation cannot be changed" ); makeOFConditionConst(EC_UnsupportedEncoding, OFM_dcmdata, 15, OF_error, "Unsupported compression or encryption" ); // error code 16 is reserved for zlib-related error messages makeOFConditionConst(EC_PutbackFailed, OFM_dcmdata, 17, OF_error, "Parser failure: Putback operation failed" ); // error code 18 is reserved for file read error messages // error code 19 is reserved for file write error messages makeOFConditionConst(EC_DoubleCompressionFilters, OFM_dcmdata, 20, OF_error, "Too many compression filters" ); makeOFConditionConst(EC_ApplicationProfileViolated, OFM_dcmdata, 21, OF_error, "Storage media application profile violated" ); // error code 22 is reserved for dcmodify error messages makeOFConditionConst(EC_InvalidOffset, OFM_dcmdata, 23, OF_error, "Invalid offset" ); makeOFConditionConst(EC_TooManyBytesRequested, OFM_dcmdata, 24, OF_error, "Too many bytes requested" ); // error code 25 is reserved for tag path parsing error messages makeOFConditionConst(EC_InvalidBasicOffsetTable, OFM_dcmdata, 26, OF_error, "Invalid basic offset table" ); makeOFConditionConst(EC_ElemLengthLargerThanItem, OFM_dcmdata, 27, OF_error, "Length of element larger than explicit length of surrounding item" ); makeOFConditionConst(EC_FileMetaInfoHeaderMissing, OFM_dcmdata, 28, OF_error, "File meta information header missing" ); makeOFConditionConst(EC_SeqOrItemContentOverflow, OFM_dcmdata, 29, OF_error, "Item or sequence content exceeds maximum of 32-bit length field"); makeOFConditionConst(EC_ValueRepresentationViolated, OFM_dcmdata, 30, OF_error, "Value Representation violated" ); makeOFConditionConst(EC_ValueMultiplicityViolated, OFM_dcmdata, 31, OF_error, "Value Multiplicity violated" ); makeOFConditionConst(EC_MaximumLengthViolated, OFM_dcmdata, 32, OF_error, "Maximum VR length violated" ); makeOFConditionConst(EC_ElemLengthExceeds16BitField, OFM_dcmdata, 33, OF_error, "Length of element value exceeds maximum of 16-bit length field" ); makeOFConditionConst(EC_SequDelimitationItemMissing, OFM_dcmdata, 34, OF_error, "Sequence Delimitation Item missing" ); // error codes 35..36 are reserved for specific character set error messages (see below) // error code 37 is reserved for XML conversion error messages (see below) makeOFConditionConst(EC_ItemDelimitationItemMissing, OFM_dcmdata, 38, OF_error, "Item Delimitation Item missing" ); makeOFConditionConst(EC_PrematureSequDelimitationItem, OFM_dcmdata, 39, OF_error, "Sequence Delimitation Item occurred before Item was completely read" ); makeOFConditionConst(EC_InvalidDICOMDIR, OFM_dcmdata, 40, OF_error, "Invalid DICOMDIR" ); makeOFConditionConst(EC_UnknownVR, OFM_dcmdata, 41, OF_error, "Unknown VR: Tag not found in data dictionary" ); makeOFConditionConst(EC_InvalidValue, OFM_dcmdata, 42, OF_error, "Invalid Value"); makeOFConditionConst(EC_ItemNotFound, OFM_dcmdata, 43, OF_error, "Item not found"); makeOFConditionConst(EC_UnknownTransferSyntax, OFM_dcmdata, 44, OF_error, "Unknown Transfer Syntax"); makeOFConditionConst(EC_CannotCheck, OFM_dcmdata, 45, OF_error, "Cannot perform check"); makeOFConditionConst(EC_MissingValue, OFM_dcmdata, 46, OF_error, "Missing value"); makeOFConditionConst(EC_MissingAttribute, OFM_dcmdata, 47, OF_error, "Missing attribute"); makeOFConditionConst(EC_InternalError, OFM_dcmdata, 48, OF_error, "Internal error"); makeOFConditionConst(EC_InvalidCharacter, OFM_dcmdata, 49, OF_error, "Invalid character"); // error code 50 is reserved for determine start fragment error messages (see below) makeOFConditionConst(EC_UndefinedLengthOBOW, OFM_dcmdata, 51, OF_error, "Illegal element with OB or OW Value Representation and undefined length encountered"); makeOFConditionConst(EC_VOI_LUT_OBOW, OFM_dcmdata, 52, OF_error, "Illegal VOI LUT Sequence element with OB or OW Value Representation and explicit length encountered"); makeOFConditionConst(EC_PixelDataExplLengthIllegal, OFM_dcmdata, 53, OF_error, "Pixel data in top level dataset in compressed Transfer Syntax uses explicit length"); const unsigned short EC_CODE_CannotSelectCharacterSet = 35; const unsigned short EC_CODE_CannotConvertCharacterSet = 36; const unsigned short EC_CODE_CannotConvertToXML = 37; const unsigned short EC_CODE_CannotDetermineStartFragment = 50;
fergy/aplit_linux-5
drivers/net/wireless/realtek/rtlwifi/rtl8192ce/led.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright(c) 2009-2012 Realtek Corporation.*/ #include "../wifi.h" #include "../pci.h" #include "reg.h" #include "led.h" static void _rtl92ce_init_led(struct ieee80211_hw *hw, struct rtl_led *pled, enum rtl_led_pin ledpin) { pled->hw = hw; pled->ledpin = ledpin; pled->ledon = false; } void rtl92ce_sw_led_on(struct ieee80211_hw *hw, struct rtl_led *pled) { u8 ledcfg; struct rtl_priv *rtlpriv = rtl_priv(hw); RT_TRACE(rtlpriv, COMP_LED, DBG_LOUD, "LedAddr:%X ledpin=%d\n", REG_LEDCFG2, pled->ledpin); ledcfg = rtl_read_byte(rtlpriv, REG_LEDCFG2); switch (pled->ledpin) { case LED_PIN_GPIO0: break; case LED_PIN_LED0: rtl_write_byte(rtlpriv, REG_LEDCFG2, (ledcfg & 0xf0) | BIT(5) | BIT(6)); break; case LED_PIN_LED1: rtl_write_byte(rtlpriv, REG_LEDCFG2, (ledcfg & 0x0f) | BIT(5)); break; default: pr_err("switch case %#x not processed\n", pled->ledpin); break; } pled->ledon = true; } void rtl92ce_sw_led_off(struct ieee80211_hw *hw, struct rtl_led *pled) { struct rtl_priv *rtlpriv = rtl_priv(hw); u8 ledcfg; RT_TRACE(rtlpriv, COMP_LED, DBG_LOUD, "LedAddr:%X ledpin=%d\n", REG_LEDCFG2, pled->ledpin); ledcfg = rtl_read_byte(rtlpriv, REG_LEDCFG2); switch (pled->ledpin) { case LED_PIN_GPIO0: break; case LED_PIN_LED0: ledcfg &= 0xf0; if (rtlpriv->ledctl.led_opendrain) rtl_write_byte(rtlpriv, REG_LEDCFG2, (ledcfg | BIT(1) | BIT(5) | BIT(6))); else rtl_write_byte(rtlpriv, REG_LEDCFG2, (ledcfg | BIT(3) | BIT(5) | BIT(6))); break; case LED_PIN_LED1: ledcfg &= 0x0f; rtl_write_byte(rtlpriv, REG_LEDCFG2, (ledcfg | BIT(3))); break; default: pr_info("switch case %#x not processed\n", pled->ledpin); break; } pled->ledon = false; } void rtl92ce_init_sw_leds(struct ieee80211_hw *hw) { struct rtl_priv *rtlpriv = rtl_priv(hw); _rtl92ce_init_led(hw, &rtlpriv->ledctl.sw_led0, LED_PIN_LED0); _rtl92ce_init_led(hw, &rtlpriv->ledctl.sw_led1, LED_PIN_LED1); } static void _rtl92ce_sw_led_control(struct ieee80211_hw *hw, enum led_ctl_mode ledaction) { struct rtl_priv *rtlpriv = rtl_priv(hw); struct rtl_led *pled0 = &rtlpriv->ledctl.sw_led0; switch (ledaction) { case LED_CTL_POWER_ON: case LED_CTL_LINK: case LED_CTL_NO_LINK: rtl92ce_sw_led_on(hw, pled0); break; case LED_CTL_POWER_OFF: rtl92ce_sw_led_off(hw, pled0); break; default: break; } } void rtl92ce_led_control(struct ieee80211_hw *hw, enum led_ctl_mode ledaction) { struct rtl_priv *rtlpriv = rtl_priv(hw); struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw)); if ((ppsc->rfoff_reason > RF_CHANGE_BY_PS) && (ledaction == LED_CTL_TX || ledaction == LED_CTL_RX || ledaction == LED_CTL_SITE_SURVEY || ledaction == LED_CTL_LINK || ledaction == LED_CTL_NO_LINK || ledaction == LED_CTL_START_TO_LINK || ledaction == LED_CTL_POWER_ON)) { return; } RT_TRACE(rtlpriv, COMP_LED, DBG_LOUD, "ledaction %d\n", ledaction); _rtl92ce_sw_led_control(hw, ledaction); }
RocMarshal/fevernova
src/main/java/com/github/fevernova/framework/component/channel/RingbufferChannel.java
<gh_stars>1-10 package com.github.fevernova.framework.component.channel; import com.github.fevernova.framework.common.Constants; import com.github.fevernova.framework.common.context.GlobalContext; import com.github.fevernova.framework.common.context.TaskContext; import com.github.fevernova.framework.common.data.DataEvent; import com.github.fevernova.framework.component.PExceptionHandler; import com.github.fevernova.framework.component.Processor; import com.lmax.disruptor.*; import com.lmax.disruptor.dsl.ProducerType; import org.apache.commons.lang3.Validate; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; public class RingbufferChannel { private RingBuffer<DataEvent> ringBuffer; private GlobalContext globalContext; private SequenceBarrier seqBarrier; private EventProcessor eventProcessor; private WaitStrategy strategy; private AtomicBoolean STARTED = new AtomicBoolean(false); public RingbufferChannel(int producerNum, TaskContext channelContext, GlobalContext globalContext, EventFactory<DataEvent> eventFactory) { this.globalContext = globalContext; int bufferSize = channelContext.getInteger(Constants.SIZE, 512); long timeout = channelContext.getLong("timeout", 1000L); this.strategy = new CustomWaitStrategy(timeout, TimeUnit.MILLISECONDS); this.ringBuffer = RingBuffer.create((producerNum == 1 ? ProducerType.SINGLE : ProducerType.MULTI), eventFactory, bufferSize, this.strategy); this.seqBarrier = this.ringBuffer.newBarrier(); } public EventProcessor integrate(Processor processor) { Validate.isTrue(this.STARTED.compareAndSet(false, true)); if (processor instanceof WaitNotify && this.strategy instanceof CustomWaitStrategy) { ((CustomWaitStrategy) this.strategy).setWaitNotify(processor); } Sequence consumerSequence = new Sequence(-1); this.eventProcessor = new WorkProcessor<>(this.ringBuffer, this.seqBarrier, processor, new PExceptionHandler(this.globalContext), consumerSequence); this.ringBuffer.addGatingSequences(this.eventProcessor.getSequence()); return this.eventProcessor; } public long getNextSeq() { return this.ringBuffer.next(); } public DataEvent getBySeq(long seq) { return this.ringBuffer.get(seq); } public void pushBySeq(long seq) { this.ringBuffer.publish(seq); } public boolean isEmpty() { return this.ringBuffer.remainingCapacity() == this.ringBuffer.getBufferSize(); } public long remainCapacity() { return this.ringBuffer.remainingCapacity(); } public long getBufferSize() { return this.ringBuffer.getBufferSize(); } }
wutobias/collection
shell/resp_it_mol2/ensemble_filter_hb.py
<filename>shell/resp_it_mol2/ensemble_filter_hb.py #!/usr/bin/env python import sys import os fconv = "/nfs/pub/file_utils/fconv" if len(sys.argv) != 3: print "Usage: ensemble_filter_hb.py <ID_vs_hydrogenbondcounts.dat> <ensemble.mol2>" exit() for f in sys.argv: if not os.path.exists(f): print "%s not found. Exit." %f ### Hbond information for ensemble from hbond_information file as obtained from vmd or cpptraj (frame vs. number of hbonds) ### 0 0 ### 1 0 ### 2 0 ### 3 0 ### 4 0 ### 5 0 ### 6 0 ### 7 2 ### 8 0 ### 9 2 ### 10 0 ### 11 0 hbond_counts_tmp = open(sys.argv[1],"r") hbond_counts_file = hbond_counts_tmp.readlines() hbond_counts_tmp.close() outname = sys.argv[2].replace(".mol2", '') + "_nohb.mol2" ensemble_count = 0 hbond_limit = 0 while ensemble_count < 1: n_lines = 0 for line in hbond_counts_file: if len(line.rstrip().split()) == 0: continue if line[0] == '#': continue n_lines += 1 extract_in = '' merge_in = '' if int(line.rstrip().split()[1]) == hbond_limit: #extract it extract_in += " --e=" + str(int(line.rstrip().split()[0])) extract_in += " " + sys.argv[2] extract_in += " --t=tmp_mol.mol2" os.system (fconv + extract_in) if ensemble_count == 0: os.system("mv tmp_mol.mol2 " + outname) ensemble_count += 1 continue #merge it merge_in += " -m " + outname + " tmp_mol.mol2" merge_in += " --t=tmp_ensemble.mol2" os.system (fconv + merge_in) os.system ("cp -f tmp_ensemble.mol2 " + outname) ensemble_count += 1 if n_lines==0: break hbond_limit += 1 #clean if n_lines>0: os.system ("rm -f tmp_ensemble.mol2 tmp_mol.mol2") else: os.system("cp -f %s %s" %(sys.argv[2], outname))
williamclot/MemoryVisualizer
volatility/volatility/plugins/gui/windowstations.py
# Volatility # Copyright (C) 2007-2013 Volatility Foundation # Copyright (C) 2010,2011,2012 <NAME> <<EMAIL>> # # This file is part of Volatility. # # Volatility is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # Volatility 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 Volatility. If not, see <http://www.gnu.org/licenses/>. # import volatility.obj as obj import volatility.utils as utils import volatility.debug as debug import volatility.poolscan as poolscan import volatility.plugins.common as common import volatility.plugins.gui.sessions as sessions class PoolScanWind(poolscan.PoolScanner): """PoolScanner for window station objects""" def __init__(self, address_space): poolscan.PoolScanner.__init__(self, address_space) self.struct_name = "tagWINDOWSTATION" self.object_type = "WindowStation" self.pooltag = obj.VolMagic(address_space).WindPoolTag.v() size = 0x90 # self.address_space.profile.get_obj_size("tagWINDOWSTATION") self.checks = [ # seen as 0x98 on xpsp2 and xpsp3, 0x90 on w2k3*, 0xa0 on w7sp0 ('CheckPoolSize', dict(condition = lambda x: x >= size)), # only look in non-paged or free pools ('CheckPoolType', dict(paged = False, non_paged = True, free = True)), ('CheckPoolIndex', dict(value = 0)), ] class WndScan(common.AbstractScanCommand, sessions.SessionsMixin): """Pool scanner for window stations""" scanners = [PoolScanWind] def calculate(self): addr_space = utils.load_as(self._config) seen = [] for wind in self.scan_results(addr_space): # Find an address space for this window station's session session = self.find_session_space( addr_space, wind.dwSessionId) if not session: continue # Reset the object's native VM so pointers are # dereferenced in session space wind.set_native_vm(session.obj_vm) for winsta in wind.traverse(): if winsta.is_valid() and len([desk for desk in winsta.desktops()]) > 0: offset = winsta.PhysicalAddress if offset in seen: continue seen.append(offset) yield winsta def render_text(self, outfd, data): for window_station in data: outfd.write("*" * 50 + "\n") outfd.write("WindowStation: {0:#x}, Name: {1}, Next: {2:#x}\n".format( window_station.PhysicalAddress, window_station.Name, window_station.rpwinstaNext.v(), )) outfd.write("SessionId: {0}, AtomTable: {1:#x}, Interactive: {2}\n".format( window_station.dwSessionId, window_station.pGlobalAtomTable, window_station.Interactive, )) outfd.write("Desktops: {0}\n".format( ', '.join([desk.Name for desk in window_station.desktops()]) )) outfd.write("ptiDrawingClipboard: pid {0} tid {1}\n".format( window_station.ptiDrawingClipboard.pEThread.Cid.UniqueProcess, window_station.ptiDrawingClipboard.pEThread.Cid.UniqueThread )) outfd.write("spwndClipOpen: {0:#x}, spwndClipViewer: {1:#x} {2} {3}\n".format( window_station.spwndClipOpen.v(), window_station.spwndClipViewer.v(), str(window_station.LastRegisteredViewer.UniqueProcessId or ""), str(window_station.LastRegisteredViewer.ImageFileName or ""), )) outfd.write("cNumClipFormats: {0}, iClipSerialNumber: {1}\n".format( window_station.cNumClipFormats, window_station.iClipSerialNumber, )) outfd.write("pClipBase: {0:#x}, Formats: {1}\n".format( window_station.pClipBase, ",".join([str(clip.fmt) for clip in window_station.pClipBase.dereference()]), ))
maciejg-git/vue-bootstrap-icons
dist-mdi/mdi/robot-angry.js
<gh_stars>0 import { h } from 'vue' export default { name: "RobotAngry", vendor: "Mdi", type: "", tags: ["robot","angry"], 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-robot-angry","innerHTML":"<path d='M22 14H21C21 10.13 17.87 7 14 7H13V5.73C13.6 5.39 14 4.74 14 4C14 2.9 13.11 2 12 2S10 2.9 10 4C10 4.74 10.4 5.39 11 5.73V7H10C6.13 7 3 10.13 3 14H2C1.45 14 1 14.45 1 15V18C1 18.55 1.45 19 2 19H3V20C3 21.11 3.9 22 5 22H19C20.11 22 21 21.11 21 20V19H22C22.55 19 23 18.55 23 18V15C23 14.45 22.55 14 22 14M7.5 18C6.12 18 5 16.88 5 15.5C5 14.68 5.4 13.96 6 13.5L9.83 16.38C9.5 17.32 8.57 18 7.5 18M16.5 18C15.43 18 14.5 17.32 14.17 16.38L18 13.5C18.6 13.96 19 14.68 19 15.5C19 16.88 17.88 18 16.5 18Z' />"}, ) } }
znnnnn/leetcode-cn-resolutions
algorithms/1002. Find Common Characters/1.js
/** * @param {string[]} A * @return {string[]} */ var commonChars = function(A) { return [...new Set(A[0])] .filter(ch => A.every(word => word.includes(ch))) // 1.共有的字母 ["e", "l"] .map(ch => ch.repeat(Math.min(...A.map(x => x.match(new RegExp(ch, 'g')).length))), ) // 将每个共有字母映射成该字母都有最大重复次数的字符串 ["e", "ll"] .join('') // 'ell' .split('') // ['e', 'l', 'l'] }
Asap7772/railrl_evalsawyer
rlkit/torch/vae/biva/__init__.py
__all__ = ["datasets", "evaluation", "model"] from .model import *
OnionBurger/DungeonsOfPain
SOURCE/FovCalc.h
<gh_stars>0 #ifndef _FovCalc_h_ #define _FovCalc_h_ #include "fov.h" class Map; class FovCalc { fov_settings_type fov_settings; Map *map; public: FovCalc(Map *M); void calcFov(); static bool libfovOpacityTest(void *map, int x, int y); static void libfovApplyLighting(void *map, int x, int y, int dx, int dy, void *src); }; #endif
vustac/dse
src/danalyzer/src/danalyzer/executor/Executor.java
package danalyzer.executor; import static danalyzer.gui.DebugUtil.debugPrintCommand; import static danalyzer.gui.DebugUtil.debugPrintCommand_type; import static danalyzer.gui.DebugUtil.debugPrintCallEntry; import static danalyzer.gui.DebugUtil.debugPrintCallExit; import static danalyzer.gui.DebugUtil.debugPrintStackRestore; import static danalyzer.gui.DebugUtil.debugPrintInfo; import static danalyzer.gui.DebugUtil.debugPrintWarning; import static danalyzer.gui.DebugUtil.debugPrintError; import static danalyzer.gui.DebugUtil.debugPrintArrayMap; import static danalyzer.gui.DebugUtil.debugPrintObjectMap; import static danalyzer.gui.DebugUtil.debugPrintObjectField; import static danalyzer.gui.DebugUtil.debugPrintException; import static danalyzer.gui.DebugUtil.debugPrintAgent; import static danalyzer.gui.DebugUtil.debugPrintArrayList; import static danalyzer.gui.DebugUtil.debugPrintObjects; import static danalyzer.gui.DebugUtil.debugPrintArrays; import static danalyzer.gui.DebugUtil.debugPrintSolve; import static danalyzer.gui.DebugUtil.debugPrintBranch; import static danalyzer.gui.DebugUtil.debugPrintDump; import static danalyzer.gui.DebugUtil.debugPrintConstraint; import danalyzer.gui.DebugUtil; import danalyzer.gui.DataConvert; import com.microsoft.z3.ArithExpr; import com.microsoft.z3.ArrayExpr; import com.microsoft.z3.BitVecExpr; import com.microsoft.z3.BoolExpr; import com.microsoft.z3.Context; import com.microsoft.z3.Expr; import com.microsoft.z3.IntExpr; import com.microsoft.z3.Optimize; import com.microsoft.z3.RealExpr; import java.util.ArrayList; import java.util.Arrays; import java.util.Deque; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Stack; /** * * @author zzk */ public class Executor { // used in formatting debugPrintDump private static final String NEWLINE = System.getProperty("line.separator"); private static enum ConstraintType { PATH, // normal path constraint ARRAY, // array out-of-bounds constraint LOOPBOUND, // loop bounds constraint } private StackFrame currentStackFrame; private Stack<StackFrame> executionStack; private boolean initialized; private int threadId; private boolean invokeDynamic; // User-defined Symbolics & Constraints private Map<String, ArrayList<UserSymbolic>> symbolicMap = new HashMap<>(); private Context z3Context; private List<BoolExpr> pathConstraints; private List<BoolExpr> arrayConstraints; private Map<String, Expr> exprMap; private Optimize z3Optimize; // used for handling special uninstrumented methods like String.length() private boolean needReturnValue = true; // for BufferedImage agent commands private HashMap<java.awt.image.BufferedImage, Value[][]> bufferedImageMap = new HashMap<>(); // interface to the solver (dansolver) private SolverInterface solverPort; private int constraintCount; private int numArrayConstraints = 0; Executor(int id, ArrayList<UserSymbolic> symbolicInfo) { /* ----------debug head--------- *@*/ debugPrintInfo(threadId, "Starting Executor[" + id + "]"); // ----------debug tail---------- */ threadId = id; constraintCount = 0; currentStackFrame = null; executionStack = new Stack<>(); invokeDynamic = false; initialized = false; solverPort = new SolverInterface(); // copy the symbolic info over (must use deep-copy loop instead of shallow-copy putAll, // because each Executor will remove entries from their copy when the symbolic/constraint // has been applied so that it won't continue to initialize the usage of the parameter. // A shallow copy would affect the ExecWrapper copy as well as all other Executor copies and // would lose the information. ArrayList<UserSymbolic> symbolicEntries = new ArrayList<>(symbolicInfo); // now let's create a Map to organize the symbolics based on the method for (UserSymbolic entry : symbolicInfo) { String method = entry.methodName; // let's convert the method name passed to use a dot instead of slash between the class // and method name so it can be compared directly to the format of the method names used here. int offset = method.lastIndexOf("("); String signature = method.substring(offset); method = method.substring(0, offset); offset = method.lastIndexOf("/"); method = method.substring(0, offset) + "." + method.substring(offset + 1) + signature; // now add the entry to the list maintained for the specified method ArrayList<UserSymbolic> list; if (symbolicMap.isEmpty() || !symbolicMap.containsKey(method)) { list = new ArrayList<>(); symbolicMap.put(method, list); } else { list = symbolicMap.get(method); } list.add(entry); } exprMap = new HashMap<>(); z3Context = new Context(); pathConstraints = new ArrayList<>(); arrayConstraints = new ArrayList<>(); z3Optimize = z3Context.mkOptimize(); /* ----------debug head--------- *@*/ debugPrintConstraint(threadId, "initialized constraints"); // ----------debug tail---------- */ } public static class UserSymbolic { public String id; // user-defined reference name public String methodName; // name of method the local parameter is defined in public int param; // slot number of the local parameter public int ixStart; // starting opcode offset that param is valid over public int ixEnd; // ending opcode offset that param is valid over public int type; // Value data type of parameter public ArrayList<UserConstraint> constraint; // list of user constraints for this parameter public UserSymbolic(String methName, int slot) { methodName = methName; param = slot; ixStart = 0; ixEnd = 0; // this will encompass entire method range type = Value.INT32; id = methName + "_" + slot + "_0_0"; constraint = new ArrayList<>(); } public UserSymbolic(String methName, int slot, int start, int end, String name, int valtype) { methodName = methName; param = slot; ixStart = start; ixEnd = end; type = valtype; id = name; constraint = new ArrayList<>(); } public static int convertDataType(String dtype) { int valtype = Value.INT32; // set a default type int aryType = 0; // default to not an array // standardize the data type entry if (dtype.startsWith("L")) { dtype = dtype.substring(1); valtype = Value.REF; } if (dtype.endsWith(";")) { dtype = dtype.substring(0, dtype.length() - 1); } dtype = dtype.replaceAll("/", "."); // check for array or multi-dimensional array if (dtype.startsWith("[")) { if (dtype.startsWith("[[")) { aryType = Value.MARY; } else { aryType = Value.ARY; } dtype = dtype.substring(dtype.lastIndexOf("[") + 1); } // now convert it to what we require switch (dtype) { case "Z": case "java.lang.Boolean": valtype = Value.BLN; break; case "C": case "java.lang.Char": valtype = Value.CHR; break; case "B": case "java.lang.Byte": valtype = Value.INT8; break; case "S": case "java.lang.Short": valtype = Value.INT16; break; case "I": case "java.lang.Integer": valtype = Value.INT32; break; case "J": case "java.lang.Long": valtype = Value.INT64; break; case "F": case "java.lang.Float": valtype = Value.FLT; break; case "D": case "java.lang.Double": valtype = Value.DBL; break; case "java.lang.String": case "Value.STR": valtype = Value.STR; break; default: break; } return valtype + aryType; } public String getKeyReference() { return methodName + "_" + param + "_" + ixStart + "_" + ixEnd; } } public static class UserConstraint { public String compareType; public String value; public UserConstraint(String type, String val) { compareType = type; value = val; } } //================================================================ // LOCAL HELPER METHODS //================================================================ /** * this will report the specified error, dump the current stack contents and halt execution. * * @param message - the error message to display */ private void exitError(String message) { debugPrintError(threadId, message); dumpStackInfo(true); System.exit(1); } /** * indicate an error if the specified Value is null. * The program will terminate if the error condition is true. * * @param val - the Value to test * @param opcode - the opcode being run * @param param - the param value tested */ private void assertValueNonNull(Value val, String opcode, String param) { if (val == null) { exitError("(" + opcode + ") - " + param + " is NULL"); } } /** * indicate an error if the specified Value is not of one of the specified types. * The program will terminate if the error condition is true. * * @param val - the Value to test * @param opcode - the opcode being run * @param param - the param value tested * @param types - one or more Value type bits that the Value must have */ private void assertInvalidType(Value val, String opcode, String param, int types) { if (val == null) { exitError("(" + opcode + ") - " + param + " is NULL"); } else if ((types & val.getType()) == 0) { exitError("(" + opcode + ") - " + param + " has invalid data type: " + DataConvert.showValueDataType(val.getType())); } } /** * indicate an error if the specified Reference or Array Value is not an Integer type. * The program will terminate if the error condition is true. * * @param val - the Value for the reference or array * @param opcode - the opcode being run * @param param - the param value tested */ private void assertUnsignedIntValue(Value val, String opcode, String param) { if (val == null) { exitError("(" + opcode + ") - " + param + " Value is NULL"); } else if (val.getValue() == null) { exitError("(" + opcode + ") - " + param + " Value contents is NULL"); } else { String clstype = DataConvert.getClassType(val.getValue()); // NOTE: THIS USES REFLECTION if (!clstype.equals("java.lang.Integer")) { String type = DataConvert.showValueDataType(val.getType()); exitError("(" + opcode + ") - " + param + " Value is not Integer - (" + type + ") class = " + clstype); } else if ((Integer) val.getValue() < 0) { exitError("(" + opcode + ") - " + param + " Value is < 0"); } } } /** * returns the corresponding Opcode character specifying the corresponding data type passed. * * @param type - the data type * @return string consisting of the initial character indicating the data type of the opcode. */ private static String getOpcodeDataType(int type) { switch (type) { case Value.CHR: return "C"; case Value.INT8: return "B"; case Value.INT16: return "S"; case Value.INT32: return "I"; case Value.INT64: return "L"; case Value.FLT: return "F"; case Value.DBL: return "D"; } return "x"; } private static String shortenMethodName(String mtdName) { String shortName = mtdName; int offset = shortName.indexOf("("); if (offset > 0) { shortName = shortName.substring(0, offset); } offset = shortName.lastIndexOf("/"); if (offset > 0) { shortName = shortName.substring(offset + 1); } return shortName; } private ArrayList<UserSymbolic> getSymbolicList(String mtdName) { if (symbolicMap.isEmpty() || !symbolicMap.containsKey(mtdName)) { return null; } ArrayList<UserSymbolic> methList = symbolicMap.get(mtdName); if (methList.isEmpty()) { symbolicMap.remove(mtdName); return null; } /* ----------debug head--------- *@*/ DebugUtil.debugPrintInfo(threadId, DebugUtil.CONSTR, methList.size() + " symbolic entries for: " + mtdName); // ----------debug tail---------- */ return methList; } private UserSymbolic getSymbolicEntry(ArrayList<UserSymbolic> methList, int slot, int opLine) { // search for parameter definition in the symbolic list for (UserSymbolic entry : methList) { String methComp = entry.methodName; /* ----------debug head--------- *@*/ DebugUtil.debugPrintInfo(threadId, DebugUtil.CONSTR, "- entry = " + methComp + ", slot " + entry.param); // ----------debug tail---------- */ // if (methComp.equals(mtdName.replace('.', '/')) && entry.param == slot) { if (entry.param == slot) { // if end == 0, use entire menthod range. else allow the line before start, since local var table // doesn't include the line in which the param is first loaded or stored, but we do. if (entry.ixEnd == 0 || (opLine + 1 >= entry.ixStart && opLine <= entry.ixEnd)) { /* ----------debug head--------- *@*/ DebugUtil.debugPrintInfo(threadId, DebugUtil.CONSTR, "Found symbolic for " + shortenMethodName(methComp) + " (slot " + entry.param + ", line " + opLine + ") : type = " + DataConvert.showValueDataType(entry.type)); // ----------debug tail---------- */ return entry; } } } return null; } private void removeSymbolicEntry(ArrayList<UserSymbolic> methList, UserSymbolic entry) { if (methList != null) { String mtdName = entry.methodName; // if entry found, remove it. if no more entries for method, delete method list if (methList.contains(entry)) { methList.remove(entry); if (methList.isEmpty()) { symbolicMap.remove(mtdName); } } } } /** * Initializes the specified local parameter if it is symbolic but hasn't been initialized yet. * * if the specified method parameter is found in the list of user-defined symbolic parameters, * the initial symbolic value will be returned and will be removed from the list so it won't * be initialized again. * * If not found, it returns a null (not symbolic or already initialized). * * @param slot - param index of method to check * @param type - the type of symbolic parameter * @param opLine - the opcode line number within the method * @param val - for REF and ARY types only, the concrete value * @return initial symbolic value if specified param is symbolic, NULL otherwise */ private Value getInitialSymbolicParam(String mtdName, int slot, int type, int opLine, Value val) { Value symValue = null; com.microsoft.z3.Expr expr; // get the list of symbolics for the specified method ArrayList<UserSymbolic> methList = getSymbolicList(mtdName); if (methList == null) { return null; } UserSymbolic entry = getSymbolicEntry(methList, slot, opLine); if (entry == null) { return null; } // TODO: for now, we can't handle Multi-dim arrays as symbolic if (type == Value.MARY) { exitError("getInitialSymbolicParam: can't handle Multi-dimensional array as symbolic!"); } // if we weren't specific about the type of array, use the value from the symbolic table def if (type == Value.ARY && (entry.type & Value.ARY) != 0) { type = entry.type; } if (entry.type != type) { /* ----------debug head--------- *@*/ DebugUtil.debugPrintWarning(threadId, "Symbolic type does not match opcode access: " + DataConvert.showValueDataType(entry.type) + " != " + DataConvert.showValueDataType(type)); // ----------debug tail---------- */ type = entry.type; } // check for array types, since this bit can be set with several other bits if ((type & Value.ARY) != 0) { if (!val.isType(Value.ARY)) { exitError("getInitialSymbolicParam: concrete value is not ARY type"); } /* ----------debug head--------- *@*/ DebugUtil.debugPrintWarning(threadId, "Symbolic array being loaded!"); // ----------debug tail---------- */ Value[] combo = getArrayCombo(val, type); Value[] array = (Value[]) combo[0].getValue(); int eltype = array[0].getType(); int size = (Integer) combo[1].getValue(); for (int ix = 0; ix < size; ix++) { // this will name each entry in the array by the name of the array folowed by "_N", where // N is the array index value. array[ix] = makeSymbolicPrimitive(entry.id + "_" + ix, eltype, z3Context); } /* ----------debug head--------- *@*/ DebugUtil.debugPrintWarning(threadId, "Array replaced with symbolic entries, size = " + size); // ----------debug tail---------- */ // TODO: this will not return a SYM type to the caller because it is the elements // that are marked as symbolic, not the array itself. If we want to mark the array // as well, uncomment the next line. // symValue = new Value(val.getValue(), Value.SYM | val.getType()); // remove entry from list, since we have initialized this param methList.remove(entry); if (methList.isEmpty()) { symbolicMap.remove(mtdName); } return symValue; } // else, determine type of symbolic value symValue = makeSymbolicPrimitive(entry.id, type, z3Context); if (symValue != null) { // apply the fixed constraints for integer types applyFixedIntegerConstraints(symValue, type); // apply user constraints if any for (UserConstraint constraint : entry.constraint) { applyUserConstraint(constraint, symValue, type); } } // remove entry from list, since we have initialized this param methList.remove(entry); if (methList.isEmpty()) { symbolicMap.remove(mtdName); } return symValue; } /** * Applies the user-defined constraints to the local parameter if it is symbolic but hasn't * been initialized yet. * * This is used for storing to a local parameter, where we have a value to set the parameter to. * In this case, we still need to apply the user-defined constraints if they have not been * applied (they are removed from the table when they have been), but we apply them to the * value that was passed. * * @param value - the symbolic value to set the local parameter to * @param entry - the entry in the symbolics table for the parameter (null if not found) * @return the passed value with the constraints applied */ private Value applyLocalParamConstraints(Value value, UserSymbolic entry) { if (entry != null) { // apply user constraints if any for (UserConstraint constraint : entry.constraint) { // just use the type specified in the Value int type = value.getType() & ~(Value.SYM); applyUserConstraint(constraint, value, type); } } return value; } /** * this makes symbolic entries from a unique string value and saves in a table. * if the field passed in was previously used, it will return the previously made value. * it is up to the user to guarantee that the field values are unique for unique entries. * * @param threadId - the id of the thread * @param constraintName - key for constraint map entry = method name + "_" + param value * @param val - the symbolic parameter value * @param type - the type of constraint (this way we can restrict INT32 to smaller range) */ private void applyUserConstraint(UserConstraint constraint, Value val, int type) { String compType = constraint.compareType; Value constraintVal; int iminval, imaxval, iconst; long lminval, lmaxval, lconst; try { switch (type) { case Value.INT8: if (!val.isType(type | Value.INT32)) { return; } iminval = Byte.MIN_VALUE; imaxval = Byte.MAX_VALUE; iconst = Integer.parseInt(constraint.value); if (iconst < iminval || iconst > imaxval) { /* ----------debug head--------- *@*/ DebugUtil.debugPrintWarning(threadId, "User-constraint limit exceeded for type INT8: " + constraint.value); // ----------debug tail---------- */ return; } constraintVal = new Value(iconst, type); break; case Value.INT16: if (!val.isType(type | Value.INT32)) { return; } iminval = Short.MIN_VALUE; imaxval = Short.MAX_VALUE; iconst = Integer.parseInt(constraint.value); if (iconst < iminval || iconst > imaxval) { /* ----------debug head--------- *@*/ DebugUtil.debugPrintWarning(threadId, "User-constraint limit exceeded for type INT16: " + constraint.value); // ----------debug tail---------- */ return; } constraintVal = new Value(Integer.parseInt(constraint.value), type); break; case Value.INT32: if (!val.isType(type)) { return; } iminval = Integer.MIN_VALUE; imaxval = Integer.MAX_VALUE; iconst = Integer.parseInt(constraint.value); if (iconst < iminval || iconst > imaxval) { /* ----------debug head--------- *@*/ DebugUtil.debugPrintWarning(threadId, "User-constraint limit exceeded for type INT32: " + constraint.value); // ----------debug tail---------- */ return; } constraintVal = new Value(Integer.parseInt(constraint.value), type); break; case Value.INT64: if (!val.isType(type)) { return; } lminval = Long.MIN_VALUE; lmaxval = Long.MAX_VALUE; lconst = Long.parseLong(constraint.value); if (lconst < lminval || lconst > lmaxval) { /* ----------debug head--------- *@*/ DebugUtil.debugPrintWarning(threadId, "User-constraint limit exceeded for type INT64: " + constraint.value); // ----------debug tail---------- */ return; } constraintVal = new Value(Long.parseLong(constraint.value), type); break; case Value.FLT: if (!val.isType(type)) { return; } constraintVal = new Value(Float.parseFloat(constraint.value), type); break; case Value.DBL: if (!val.isType(type)) { return; } constraintVal = new Value(Double.parseDouble(constraint.value), type); break; case Value.STR: // the constraint value is used for limiting the length of the string constraintVal = new Value(Long.parseLong(constraint.value), type); break; default: return; } } catch (NumberFormatException ex) { /* ----------debug head--------- *@*/ DebugUtil.debugPrintWarning(threadId, "User-constraint limit exceeded for type " + DataConvert.showValueDataType(type) + ": " + constraint.value); // ----------debug tail---------- */ return; } // convert input value & constraint to z3 expressions BitVecExpr expr = Util.getBitVector(val, z3Context); BitVecExpr exprConstr = Util.getBitVector(constraintVal, z3Context); // determine boolean z3 expression for comparison BoolExpr exprBool; String conType = ""; switch (compType) { case "EQ": conType = "Eq"; exprBool = z3Context.mkEq(expr, exprConstr); break; case "NE": conType = "Not + Eq"; exprBool = z3Context.mkNot(z3Context.mkEq(expr, exprConstr)); break; case "GT": conType = "BVSGT"; exprBool = z3Context.mkBVSGT(expr, exprConstr); break; case "GE": conType = "BVSGE"; exprBool = z3Context.mkBVSGE(expr, exprConstr); break; case "LT": conType = "BVSLT"; exprBool = z3Context.mkBVSLT(expr, exprConstr); break; case "LE": conType = "BVSLE"; exprBool = z3Context.mkBVSLE(expr, exprConstr); break; default: exitError("applyUserConstraint: Invalid User Constraint { " + compType + ", " + constraintVal + " }"); return; } /* ----------debug head--------- *@*/ debugPrintConstraint(threadId, "added user constraint: " + conType + " " + constraintVal); // ----------debug tail---------- */ pathConstraints.add(exprBool); } /** * this makes symbolic entries from a unique string value and saves in a table. * if the field passed in was previously used, it will return the previously made value. * it is up to the user to guarantee that the field values are unique for unique entries. * * @param threadId - the id of the thread * @param constraintName - key for constraint map entry = method name + "_" + param value * @param val - the symbolic parameter value */ private void applyFixedIntegerConstraints(Value val, int type) { //int type = val.getType() & ~(Value.SYM); // mask off symbolic flag from data type Value minVal, maxVal; switch (type) { case Value.BLN: minVal = new Value(0, type); maxVal = new Value(1, type); break; case Value.CHR: minVal = new Value(Character.MIN_VALUE, type); maxVal = new Value(Character.MAX_VALUE, type); break; case Value.INT8: minVal = new Value(Byte.MIN_VALUE, type); maxVal = new Value(Byte.MAX_VALUE, type); break; case Value.INT16: minVal = new Value(Short.MIN_VALUE, type); maxVal = new Value(Short.MAX_VALUE, type); break; case Value.INT32: minVal = new Value(Integer.MIN_VALUE, type); maxVal = new Value(Integer.MAX_VALUE, type); break; case Value.INT64: minVal = new Value(Long.MIN_VALUE, type); maxVal = new Value(Long.MAX_VALUE, type); break; default: return; } // apply constraints pathConstraints.add(z3Context.mkBVSGE(Util.getBitVector(val, z3Context), Util.getBitVector(minVal, z3Context))); pathConstraints.add(z3Context.mkBVSLE(Util.getBitVector(val, z3Context), Util.getBitVector(maxVal, z3Context))); /* ----------debug head--------- *@*/ debugPrintConstraint(threadId, "added integer constraints for " + DataConvert.showValueDataType(type) + ": BVSGE " + minVal.getValue() + " & BVSLE " + maxVal.getValue()); // ----------debug tail---------- */ } /** * updates the length of the specified combo array. * * @param combo - the array combo * @param conLength - the actual (concrete value) array length * @param arrObj - the reference index value if entry was a reference */ // int newLength = conArray == null ? 0 : conArray.length; private boolean updateValueArrayLength(Value[] combo, int conLength, Object arrObj) { if (combo == null || combo[0] == null || combo[1] == null) { return false; } // determine if the array size is unknown (combo[0] value will = 0) and if so, fix it here. int asnLength = (Integer) combo[1].getValue(); boolean updated = false; if (asnLength == 0 && asnLength != conLength) { // array length does not match the concrete size - must have been unknown on creation // during a getField, so let's remedy the situation now. /* ----------debug head--------- *@*/ debugPrintInfo(threadId, DebugUtil.ARRAYS, "Updating array length from " + asnLength + " to " + conLength); // ----------debug tail---------- */ int type = combo[0].getType(); Value[] origArray = (Value[]) combo[0].getValue(); Value[] newArray = Util.makeValueArray(threadId, type, conLength, origArray[0]); if ((type & Value.MARY) != 0) { debugPrintError(threadId, "updateValueArrayLength: Invalid type - MARY is set"); } // update the combo entries combo[0] = new Value((Value[]) newArray, type | Value.ARY); combo[1] = new Value(conLength, Value.INT32); updated = true; // if reference exists for array, update it as well if (DataConvert.getClassType(arrObj).equals("java.lang.Integer")) { // NOTE: THIS USES REFLECTION ExecWrapper.updateComboValue((Integer) arrObj, combo); /* ----------debug head--------- *@*/ debugPrintArrayMap(threadId, (Integer) arrObj, combo); // ----------debug tail---------- */ } } return updated; } /** * creates a combo from an array of objects and adds it to arrayMap. * * The 'array' object can be one of the following: * - a symbolic value (must have valid 'size' and 'type' specified) * - an array of Values, with each Value entry defining the array entry (some or all can be * symbolic entries. the 'size' can be specified as NULL and the actual size will be determined * from the array.length field). The 'type' must be valid. * - an array of primitives or objects (returned from an uninstrumented call). The 'size' should * be specified as NULL to indicate this is not a Value array. The 'type' can be specified as 0 * if it is not known and it will infer the value from the class of the array type. * - NULL if we need to define a Value array but don't yet know the size. The 'size' should be * specified as 1 initially and will be increased when we determine the actual size. We must * know the data 'type' though. * * @param array - the array of objects * @param size - Value specifying the size of the array (may be symbolic) * @param type - the type to use (0 if infer the type from the object) * @return a value containing a reference to the saved array object */ private Value putArrayCombo(Object array, Value size, int type, boolean isSymbolic) { Value[] combo = new Value[2]; int refType = Value.ARY; if ((type & Value.MARY) != 0) { /* ----------debug head--------- *@*/ debugPrintError(threadId, "putArrayCombo: Invalid type - MARY is set"); // ----------debug tail---------- */ } if (array == null) { // this handles the null array case if (size == null || type == 0) { exitError("putArrayCombo: invalid params for null array"); } combo[0] = new Value((Object[]) array, type | Value.ARY); combo[1] = size; } else if (isSymbolic) { // this handles the symbolic case if (size == null || type == 0) { exitError("putArrayCombo: invalid params for null array"); } combo[0] = new Value(array, type | Value.SYM); combo[1] = size; refType |= Value.SYM; } else { // else, we have a non-symbolic array object // verify the object is an array type of some sort String clstype = DataConvert.getClassType(array); // NOTE: THIS USES REFLECTION if (!clstype.startsWith("[")) { exitError("putArrayCombo: entry is not array type: " + clstype); } // if params not defined, derrive them from object passed if (size == null && clstype.equals("[Ldanalyzer.executor.Value")) { // the size should only be derrived from Value type arrays // (could also do this for any object types, but not for primitives, since we can't // do a cast to Object[] for those) size = new Value(((Object[]) array).length, Value.INT32); } if (type == 0) { type = DataConvert.getValueDataType(clstype); } combo[0] = new Value(array, type & ~(Value.ARY | Value.MARY)); combo[1] = size; } Integer arrCnt = ExecWrapper.putComboValue(combo); /* ----------debug head--------- *@*/ debugPrintArrayMap(threadId, arrCnt, combo); // ----------debug tail---------- */ return new Value(arrCnt, refType); } /** * gets the array combo value for the Value containing an array. * * The 'array' value can be one of the following types: * - a combo value that contains 2 entries: * combo[0] contains the actual Value array (array of Values that comprise the array entity) * combo[1] contains the size of the array * - an Integer value that is a reference key value for finding the combo value in arrayMap. * * Determines if the 'array' entry is a combo or a reference to a combo. If it is a reference * type, it gets the combo value from the arrayMap. * * @param array - the Value that is specified to be an array * @param type - the data type fro the array (0 if not known) * @return the corresponding combo[] value ([0] is the array itself and [1] contains the length) */ private Value[] getArrayCombo(Value array, int type) { if (!array.isType(Value.ARY)) { /* ----------debug head--------- *@*/ debugPrintWarning(threadId, "getArrayCombo: array is not type Value.ARY: " + DataConvert.showValueDataType(type)); // ----------debug tail---------- */ } Value[] combo = ExecWrapper.getComboValue((Integer) array.getValue()); // Value[] combo = null; // String classType = DataConvert.getClassType(array.getValue()); // if (classType.equals("[Ldanalyzer.executor.Value")) { // // this is a combo array // combo = (Value[]) array.getValue(); // } else if (classType.equals("java.lang.Integer")) { // // else this is a reference to a combo array // combo = (Value[]) ExecWrapper.getComboValue((Integer) array.getValue()); // } else { // // unknown type // exitError("getArrayCombo: invalid combo type"); // } // if the entry is NULL, create an initial array which will be expanded when we know the size if (combo == null) { /* ----------debug head--------- *@*/ debugPrintInfo(threadId, DebugUtil.ARRAYS, "getArrayCombo: combo is null - creating initial array entry"); // ----------debug tail---------- */ if (type == 0) { type = Value.REF; // this is just in case no type was entered. } int length = 1; // init the array size to 1 Value[] core = Util.makeValueArray(threadId, type, length, null); combo = new Value[2]; combo[0] = new Value(core, type); combo[1] = new Value(0, Value.INT32); // set size to 0 to indicate we don't know it yet. } return combo; } /** * converts an array returned from an un-instrumented method into a combo value placed in * the array map and returns a reference Value for it. * * @param val - the array (primitives or Objects) * @param type - the data type for the array * * @return a reference Value for the array that was placed in the map */ private Value makeReturnArray(Object val, int type) { // simple array: create a Value-array from the array of primitives or Objects Value[] combo = Util.cvtValueArray(threadId, val, type); // save the combo entry in the map and get its assigned ref index Integer arrCnt = ExecWrapper.putComboValue(combo); /* ----------debug head--------- *@*/ debugPrintArrayMap(threadId, arrCnt, combo); // ----------debug tail---------- */ // return the array reference value return new Value(arrCnt, Value.INT32 | Value.ARY); } /** * This will replace a combo that is composed of an array of primitives or Objects into the * 'normal' Value-wrapped array type. * Arrays that are returned from uninstrumented methods are the unwrapped types, and are denoted * by having a null value for the size entry in the combo. * * @param combo - the current combo value * @param type - the data type for the array */ private void repackCombo(Value[] combo, int type) { // make sure it is not already a Value array if (combo[1] == null) { Value[] newarr = Util.cvtValueArray(threadId, combo[0].getValue(), type); combo[0] = newarr[0]; combo[1] = newarr[1]; } } /** * creates the base combo array data for a mulit-dimensional array of the specified type. * * @param dim - an array of the size of each dimension of the array * @param type - the Value type of the data in the array * @return the reference value to the combo created */ private Value makeNewArrayCombo(ArrayList<Integer> dim, int type) { int total = 1; // total number of array entries needed for (int ix = 0; ix < dim.size(); ix++) { total *= dim.get(ix); } Value[] core = new Value[total]; for (int ix = 0; ix < total; ix++) { // generate the data value to place in the array Value entry; if (type == Value.REF) { entry = Util.makeNewRefValue(threadId, null); } else { entry = new Value (null, type); } core[ix] = entry; } /* ----------debug head--------- *@*/ DebugUtil.debugPrintArrays(threadId, " Created array of type " + DataConvert.showValueDataType(type) + ", length " + total); // ----------debug tail---------- */ // create the array object entry in arrayMap and return reference to it Value size = new Value (total, Value.INT32); Value arrayVal = putArrayCombo(core, size, type, false); return arrayVal; } /** * creates the a mulit-dimensional array of the specified type. * * @param arrayVal - the combo reference to the array data used by the multi-array * @param dim - an array of the size of each dimension of the array * @param type - the Value type of the data in the array * @return the reference value to the multi-array entry created */ private Value makeNewMultiArray(Value arrayVal, ArrayList<Integer> dim, int type) { /* ----------debug head--------- *@*/ DebugUtil.debugPrintArrays(threadId, "makeNewMultiArray: type " + DataConvert.showValueDataType(type) + ", sizes: " + Arrays.toString(dim.toArray())); // ----------debug tail---------- */ // determine the total array size and the number of references the main MultiArrayInfo will need if (dim.size() < 2) { exitError("makeNewMultiArray: invalid number of dimensions: " + dim.size()); return null; } int total = 1; // total number of array entries needed for (int ix = 0; ix < dim.size(); ix++) { total *= dim.get(ix); } // create the MultiArrayInfo for the full array Integer refCnt = (Integer)arrayVal.getValue(); Integer multiRef = ExecWrapper.putMultiArrayInfo(refCnt, type, dim.size(), 0); /* ----------debug head--------- *@*/ DebugUtil.debugPrintArrays(threadId, " Created new MultiArrayInfo[" + multiRef + "] = { Mref " + multiRef + ", Aref " + refCnt + ", type " + DataConvert.showValueDataType(type) + ", lev " + dim.size() + ", offset 0 }"); DebugUtil.debugPrintArrays(threadId, " Creating multi-array dimensions: " + dim.toString()); // ----------debug tail---------- */ // create the entry for the dimensions of the full array ExecWrapper.putMultiArraySizes(refCnt, dim); // create reference entries for all of the sub-arrays that can reference it int mult = 1; int offset = 0; int stepsize = total; // create sub array entries in reverse order of the levels defined for (int lev = dim.size() - 1; lev > 0; lev--) { int curdim = dim.get(lev); stepsize = stepsize / curdim; for (int ix = 0; ix < mult * curdim; ix++) { Integer index = ExecWrapper.addMultiArrayInfo(refCnt, type, lev, offset, multiRef); /* ----------debug head--------- *@*/ DebugUtil.debugPrintArrays(threadId, " Added MultiArrayInfo[" + index + "] = { Mref " + multiRef + ", Aref " + refCnt + ", type " + DataConvert.showValueDataType(type) + ", lev " + lev + ", offset " + offset + " } : L" + lev + "-" + ix + "/" + (mult * curdim)); // ----------debug tail---------- */ offset += stepsize; } mult *= curdim; } // return a Value referencing it Value val = new Value(multiRef, Value.MARY | Value.INT32); return val; } /** * makes a copy of the specified multi-dimensional array. * (references the same base array values, since this makes a copy of the reference only, * not a deep copy). * * @param key - the multi-array reference value * @return the reference value to the multi-array entry created */ private Value cloneMultiArray(Integer key) { // get the info for the current level of the multi-dimensional array ExecWrapper.MultiArrayInfo parentinfo = ExecWrapper.getMultiArrayInfo(key); if (parentinfo == null) { exitError("cloneMultiArray: multi-array reference not found for: " + key + " (max is " + ExecWrapper.getMultiSize() + ")"); return null; } ArrayList<Integer> dimensions = ExecWrapper.getMultiArraySizes(parentinfo.arrayRef); if (dimensions == null) { exitError("cloneMultiArray: array reference not found for: " + parentinfo.arrayRef); return null; } if (dimensions.isEmpty()) { return null; } // get the array being cloned Value[] refcombo = getArrayCombo(new Value (parentinfo.arrayRef, Value.INT32), parentinfo.type); // create a new array reference and set its value equal to the previous Object array = refcombo[0].getValue(); int arrtype = refcombo[0].getType(); Value size = refcombo[1]; boolean isSymbolic = array instanceof com.microsoft.z3.ArrayExpr; Value arrayVal = putArrayCombo(array, size, arrtype, isSymbolic); // now create the multi-array entries return makeNewMultiArray(arrayVal, dimensions, parentinfo.type); } /** * gets an item from the current level of a multi-dimension array. * * @param key - the multi-array reference value (can be a sub-array element from the main array) * @param index - the index into the current dimension of the array * @return the entry of the multi-array, which can be either a reference to a multi-array 1 dimension * less than the previous one if the entry array has a dimension greater than 1. */ private Value getMultiArrayElement(Integer key, int index) { Value element = null; // get the info for the current level of the multi-dimensional array ExecWrapper.MultiArrayInfo parentinfo = ExecWrapper.getMultiArrayInfo(key); if (parentinfo == null) { exitError("getMultiArrayElement: multi-array reference not found for: " + key + " (max is " + ExecWrapper.getMultiSize() + ")"); return null; } ArrayList<Integer> dimensions = ExecWrapper.getMultiArraySizes(parentinfo.arrayRef); if (dimensions == null) { exitError("getMultiArrayElement: array reference not found for: " + parentinfo.arrayRef); return null; } if (!dimensions.isEmpty()) { int type = parentinfo.type; int dim = parentinfo.dim - 1; if (dim < 0 || dim > dimensions.size()) { exitError("getMultiArrayElement: invalid dimension value: " + dim); return null; } else if (dim > 0) { // return another sub-level of the multi-array. need to determine the reference value for it // that is based on the reference of the initial entry Integer refix = key + 1 + index; int level = dimensions.size() - dim; if (level >= 2) { int mult = 1; for (int ix = level - 2; ix >= 0; ix--) { mult *= dimensions.get(ix); } refix += mult; } ExecWrapper.MultiArrayInfo info = ExecWrapper.getMultiArrayInfo(refix); if (info == null) { exitError("getMultiArrayElement: sub-array reference not found for: " + refix); return null; } element = new Value(refix, Value.MARY | Value.INT32); /* ----------debug head--------- *@*/ DebugUtil.debugPrintArrays(threadId, " getMultiArrayElement: MULTI[" + refix + "] has " + info.dim + " dimensions and points to ARRAY[" + info.arrayRef + "][" + info.offset + "]"); // ----------debug tail---------- */ } else { // return the array element value Value arrayRef = new Value(parentinfo.arrayRef, Value.ARY | Value.INT32); Value[] combo = getArrayCombo(arrayRef, type); if (combo == null) { exitError("getMultiArrayElement: combo is null"); return null; } // calculate the number of array entries in the sub-element we are returning. // use this to determine the offset into the full array. int size = 1; for (int ix = dimensions.size() - dim; ix < dimensions.size(); ix++) { size *= dimensions.get(ix); } int offset = parentinfo.offset + index * size; Value[] array = (Value[]) combo[0].getValue(); element = array[offset]; /* ----------debug head--------- *@*/ DebugUtil.debugPrintArrays(threadId, " getMultiArrayElement: MULTI[" + key + "][" + index + "] = ARRAY[" + arrayRef + "][" + offset + "] = " + element.getValue()); // ----------debug tail---------- */ } } return element; } /** * writes an item to the current level of a multi-dimension array. * * @param key - the multi-array reference value (can be a sub-array element from the main array) * @param index - the index into the current dimension of the array * @param element - the entry to set the specified index value to */ private void setMultiArrayElement(Integer key, int index, Value element) { // get the info for the multi-dimensional array ExecWrapper.MultiArrayInfo info = ExecWrapper.getMultiArrayInfo(key); if (info == null) { exitError("setMultiArrayElement: multi-array reference not found for: " + key + " (max is " + ExecWrapper.getMultiSize() + ")"); return; } ArrayList<Integer> dimensions = ExecWrapper.getMultiArraySizes(info.arrayRef); if (dimensions == null) { exitError("setMultiArrayElement: array reference not found for: " + info.arrayRef); return; } if (!dimensions.isEmpty()) { int type = info.type; if (info.dim != 1) { exitError("setMultiArrayElement: element specified is an array of dimension " + info.dim); return; } // return the array element value Value arrayRef = new Value(info.arrayRef, Value.ARY | Value.INT32); Value[] combo = getArrayCombo(arrayRef, type); if (combo == null) { exitError("setMultiArrayElement: combo is null at ARRAY[" + info.arrayRef + "]"); return; } // calculate the number of array entries in the sub-element we are returning. // use this to determine the offset into the full array. int offset = info.offset + index; Value[] array = (Value[]) combo[0].getValue(); array[offset] = element; /* ----------debug head--------- *@*/ DebugUtil.debugPrintArrays(threadId, " setMultiArrayElement: MULTI[" + key + "][" + index + "] = ARRAY[" + info.arrayRef + "][" + offset + "] = " + element.getValue()); // ----------debug tail---------- */ } } private Value makeReturnMultiArray(Object val, int type, int depth) { // extract the size of each dimension from the concrete object ArrayList<Integer> dimArray = new ArrayList<>(); Object[] array = (Object[]) val; // first time thru, convert object to array of level 1 for (int ix = 0; ix < depth; ix++) { if (ix > 0) { // subsequent times thru, convert current object into array of level 1 array = (Object[]) array[0]; } Integer dimSize = array.length; dimArray.add(dimSize); /* ----------debug head--------- *@*/ debugPrintInfo(threadId, DebugUtil.ARRAYS, "makeReturnMultiArray: level " + ix + ": " + dimSize); // ----------debug tail---------- */ } Value arrayVal = makeNewArrayCombo(dimArray, type); Value multiArray = makeNewMultiArray(arrayVal, dimArray, type); return multiArray; } private void putSymbolicExpression(String symbolicParam, Expr ex) { exprMap.put(symbolicParam, ex); } private Expr makeLong(String name, int dataType) { Expr expr = z3Context.mkBVConst(name, Util.getBVLength(dataType)); putSymbolicExpression(name, expr); return expr; } private Expr makeFloat(String name) { return z3Context.mkRealConst(name); } private Value makeSymbolicPrimitive(String paramName, int type, Context z3Context) { Value symValue = null; com.microsoft.z3.Expr expr; switch(type) { case Value.DBL: case Value.FLT: symValue = new Value(makeFloat(paramName), Value.SYM | type); break; case Value.CHR: case Value.BLN: case Value.INT8: case Value.INT16: case Value.INT32: case Value.INT64: symValue = new Value(makeLong(paramName, type), Value.SYM | type); break; case Value.STR: expr = z3Context.mkConst(paramName, z3Context.getStringSort()); symValue = new Value(expr, Value.SYM | type); break; case Value.REF: expr = z3Context.mkString(paramName); // expr = Util.getExpression(val, z3Context); symValue = new Value(expr, Value.SYM | type); break; } return symValue; } private void addArrayIndexConstraints(BitVecExpr index, int length, int opcodeOffset) { BoolExpr expr = null; if (pathConstraints.size() > 0) { expr = pathConstraints.get(0); for (int i = 1; i < pathConstraints.size(); i++) { expr = z3Context.mkAnd(expr, pathConstraints.get(i)); } } BitVecExpr symLen = z3Context.mkBV(length, 32); BitVecExpr symZero = z3Context.mkBV(0, 32); BoolExpr expr1 = z3Context.mkBVSGE(index, symLen); BoolExpr expr2 = z3Context.mkBVSLT(index, symZero); BoolExpr expr3 = z3Context.mkOr(expr1, expr2); expr = expr == null ? expr3 : z3Context.mkAnd(expr3, expr); int num = numArrayConstraints++; //BoolExpr assump[] = new BoolExpr[0]; // no assumptions here //String formula = z3Context.benchmarkToSMTString("benchmark_array_constraint_" + num, "", "unknown", "", assump, expr); z3Optimize.Push(); z3Optimize.Add(expr); String formula = z3Optimize.toString(); z3Optimize.Pop(); /* ----------debug head--------- *@*/ debugPrintSolve(threadId, "Table entry[" + threadId + "][" + constraintCount++ + "]:"); debugPrintSolve(threadId, formula); debugPrintSolve(threadId, "-------------------------"); // ----------debug tail---------- */ // send info to solver boolean pathsel = false; solverPort.sendMessage(threadId, currentStackFrame.getMethodName(), opcodeOffset, pathsel, ConstraintType.ARRAY.toString(), formula); } private void solvePC(int threadId, int opcodeOffset, boolean pathsel, ConstraintType ctype) { // add up the constraints and invert the last one to find a new path // first, start with the last constraint negated (in case there is only 1 constraint) int lastix = pathConstraints.size() - 1; BoolExpr lastExpr = pathConstraints.get(lastix); BoolExpr expr = z3Context.mkNot(lastExpr); // if more than 1, 'and' all the prior constraints plus the last negated one if (lastix > 0) { BoolExpr initexpr = pathConstraints.get(0); for (int i = 1; i < lastix; i++) { initexpr = z3Context.mkAnd(initexpr, pathConstraints.get(i)); } expr = z3Context.mkAnd(initexpr, expr); } for (BoolExpr arrayExpr : arrayConstraints) { expr = z3Context.mkAnd(arrayExpr, expr); } // add optimization z3Optimize.Push(); z3Optimize.Add(expr); String formula = z3Optimize.toString(); z3Optimize.Pop(); // // Original version: let's put this in a String format for saving to mongo // BoolExpr assump[] = new BoolExpr[0]; // no assumptions here // String formula = z3Context.benchmarkToSMTString("benchmark", "", "unknown", "", assump, expr); /* ----------debug head--------- *@*/ debugPrintSolve(threadId, "Table entry[" + threadId + "][" + constraintCount++ + "]:"); debugPrintSolve(threadId, formula); debugPrintSolve(threadId, "-------------------------"); // ----------debug tail---------- */ // send info to solver solverPort.sendMessage(threadId, currentStackFrame.getMethodName(), opcodeOffset, pathsel, ctype.toString(), formula); } private void dumpStackInfo(boolean error) { String contents = ""; contents += "================= Stack trace ====================" + NEWLINE; if (executionStack.isEmpty()) { contents += "stack is empty" + NEWLINE; } else { for (int pos = executionStack.size() - 1; pos >= 0; pos--) { if (executionStack.get(pos) == null) { contents += "[" + pos + "] <null>" + NEWLINE; } else { contents += "[" + pos + "] " + executionStack.get(pos).getMethodName() + NEWLINE; } } } if (error) { contents += "============= Current frame contents =============" + NEWLINE; if (currentStackFrame == null) { contents += "currentStackFrame is NULL" + NEWLINE; } else { contents += currentStackFrame.dumpStack() + NEWLINE; } } contents += "==================================================" + NEWLINE; debugPrintDump(threadId, contents); } // /** // * this makes symbolic entries from a unique string value and saves in a table. // * if the field passed in was previously used, it will return the previously made value. // * it is up to the user to guarantee that the field values are unique for unique entries. // * // * @param fieldName - the identifier for the symbolic parameter // * @return the symbolic parameter // */ // public static Value makeSymbolicValue(String fieldName) { // Value symVal = symbolicConfigMap.get(fieldName); // if (symVal == null) { // BitVecExpr expr = getZ3Context().mkBVConst(fieldName, 64); // getZ3Context().mkBVSLT(expr, getZ3Context().mkBV("" + 2147483648l, 64)); // getZ3Context().mkBVSGT(expr, getZ3Context().mkBV("" + (-2147483649l), 64)); // putSymbolicExpression(fieldName, expr); // // symVal = new Value(expr, Value.SYM | Value.INT32); // // symbolicConfigMap.put(fieldName, symVal); // } // return symVal; // } // // public void retrieveMethodSymbolic(Object conObj, int x, int y) { // /* ----------debug head--------- *@*/ // debugPrintCommand(threadId, "retrieveMethodSymbolic", x, y, conObj); // // ----------debug tail---------- */ // // // create a unique symbolic value for each entry // // for now we keep the key simple - it is the x and y coordinates // Value symVal = makeSymbolicValue(x + "_" + y); // // // push the result onto our stack. // // need to push this item above the next 3, which will be popped off by the // // synchronizeStackFrame call. It's response will not be pushed onto our stack, so we will // // effectively be replacing its return value with this one. // Value arg_Y = currentStackFrame.popValue(); // Value arg_X = currentStackFrame.popValue(); // Value arg_Obj = currentStackFrame.popValue(); // currentStackFrame.pushValue(symVal); // currentStackFrame.pushValue(arg_Obj); // currentStackFrame.pushValue(arg_X); // currentStackFrame.pushValue(arg_Y); // } //================================================================ // INSTRUMENTER METHODS //================================================================ public void unimplementedOpcode(String opcode) { /* ----------debug head--------- *@*/ debugPrintWarning(threadId, opcode + " - unimplementedOpcode"); // ----------debug tail---------- */ } public void noActionOpcode(String opcode) { /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - noActionOpcode"); // ----------debug tail---------- */ } // who is to blame: zzk, dmcd2356 public void initializeExecutor(String[] argv) { // it is only allowed to initialize once (make sure the selected thread is running) if (initialized) { return; } if (currentStackFrame == null) { System.err.println("initializeExecutor: currentStackFrame is NULL"); System.exit(1); } /* ----------debug head--------- *@*/ debugPrintCommand(threadId, "initializeExecutor", currentStackFrame.getMethodName(), argv.length); // ----------debug tail---------- */ initialized = true; // make a concrete array of strings to save main arguments Value arrayVal = putArrayCombo(argv, null, 0, false); currentStackFrame.storeLocalVariable(0, arrayVal); z3Context = new Context(); z3Optimize = z3Context.mkOptimize(); } public void establishStackFrame(String fullName, int paramCnt) { // public boolean establishStackFrame(String fullName, int paramCnt, int maxLocals) { // // get the symbolic list and thread selection or run the GUI to get them // getSymbolicSelections(fullName); /* ----------debug head--------- *@*/ debugPrintCommand(threadId, "establishStackFrame", fullName, paramCnt); debugPrintCallEntry(threadId, fullName); // ----------debug tail---------- */ // No longer need to handle special case, since <clinit> method is now tracked by agent. // Otherwise, we needed to create a new stack frame here and push the prev one. // set the method name of the current stack frame // (the static initializer doesn't create a new frame though) if (currentStackFrame != null) { currentStackFrame.setMethodName(fullName); } } public void newStringObject() { String opcode = "NEW"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - newStringObject", "java/lang/String"); // ----------debug tail---------- */ // add new entry to objectMap Map<String, Value> newMap = new HashMap<>(); int objCnt = ExecWrapper.putReferenceObject(newMap); /* ----------debug head--------- *@*/ debugPrintObjectMap(threadId, objCnt, newMap); // ----------debug tail---------- */ // now, the object is uninitialized Value ref = new Value(objCnt, Value.STR); currentStackFrame.pushValue(ref); } // who is to blame: zzk public void newObject(String clsName) { String opcode = "NEW"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - newObject", clsName); // ----------debug tail---------- */ // add new entry to objectMap Map<String, Value> newMap = new HashMap<>(); Integer objCnt = ExecWrapper.putReferenceObject(newMap); /* ----------debug head--------- *@*/ debugPrintObjectMap(threadId, objCnt, newMap); // ----------debug tail---------- */ // now, the object is uninitialized Value ref = new Value(objCnt, Value.REF); currentStackFrame.pushValue(ref); } public void loadConstant(int val) { String opcode = "ICONST"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - loadConstant <int>", val); // ----------debug tail---------- */ currentStackFrame.pushValue(new Value(val, Value.INT32)); } public void loadConstant(long val) { String opcode = "LCONST"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - loadConstant <long>", val); // ----------debug tail---------- */ currentStackFrame.pushValue(new Value(val, Value.INT64)); } public void loadConstant(float val) { String opcode = "FCONST"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - loadConstant <float>", val); // ----------debug tail---------- */ currentStackFrame.pushValue(new Value(val, Value.FLT)); } public void loadConstant(double val) { String opcode = "DCONST"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - loadConstant <double>", val); // ----------debug tail---------- */ currentStackFrame.pushValue(new Value(val, Value.DBL)); } public void loadConstant(Object val) { String opcode = "ACONST"; Value newval = null; String typstr = DataConvert.getClassType(val); // NOTE: THIS USES REFLECTION if (typstr.equals("java.lang.String")) { // string object newval = new Value(val, Value.STR); } else { // reference object: newval = Util.makeNewRefValue(threadId, val); } /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - loadConstant <" + typstr + ">", val != null ? val.toString() : "<null>"); // ----------debug tail---------- */ currentStackFrame.pushValue(newval); } public void loadConstant(String val) { String opcode = "LDC"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - loadConstant <java.lang.String>", val); // ----------debug tail---------- */ // TODO: should we use a Value.REF | Value.STR and create a field map? currentStackFrame.pushValue(new Value(val, Value.STR)); } public void pushAsInteger(String opcode, int val) { /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - pushAsInteger", val); // ----------debug tail---------- */ currentStackFrame.pushValue(new Value(val, Value.INT32)); } // who is to blame: danielbala // who blames him: zzk public void loadLocalReference(Object conObj, int index, int opline) { String opcode = "ALOAD"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - loadLocalReference", index); // ----------debug tail---------- */ String typestr = DataConvert.getClassType(conObj); // NOTE: THIS USES REFLECTION int type = DataConvert.getValueDataType(typestr); /* ----------debug head--------- *@*/ debugPrintInfo(threadId, DebugUtil.OBJECTS, " object = " + typestr + ": type = " + DataConvert.showValueDataType(type)); // ----------debug tail---------- */ // use the concrete value if the entry on the stack is null Value val = currentStackFrame.getLocalVariable(index); if (val == null) { // TODO: should this ever happen? debugPrintWarning(threadId, "loadLocalReference: null entry on stack"); val = new Value(conObj, type); currentStackFrame.storeLocalVariable(index, val); } // check if the local parameter was defined as symbolic by the user (REF, STR, ARY, MARY) String mtdName = currentStackFrame.getMethodName(); if (!symbolicMap.isEmpty() && symbolicMap.containsKey(mtdName)) { Value symbolicVal = getInitialSymbolicParam(mtdName, index, val.getType(), opline, val); if (symbolicVal != null) { if (val.isType(Value.ARY | Value.MARY)) { // symbolic array currentStackFrame.pushValue(val); } else { // symbolic reference or string currentStackFrame.storeLocalVariable(index, symbolicVal); currentStackFrame.pushValue(symbolicVal); } return; } } // reference is NOT symbolic... if (val.getValue() == null && val.isType(Value.REF)) { // if it is a null reference value, use the concrete value Integer objCnt = ExecWrapper.getConcreteObject(conObj); val = new Value(objCnt, Value.REF); currentStackFrame.storeLocalVariable(index, val); } currentStackFrame.pushValue(val); } public void loadDouble(int index, int opline) { String opcode = "DLOAD"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - loadDouble", index); // ----------debug tail---------- */ // check if no symbolics for this method int type = Value.DBL; String mtdName = currentStackFrame.getMethodName(); if (!symbolicMap.isEmpty() && symbolicMap.containsKey(mtdName)) { // check if the local parameter is defined as symbolic by the user. if so, get its initial value Value symbolicVal = getInitialSymbolicParam(mtdName, index, type, opline, null); if (symbolicVal != null) { currentStackFrame.storeLocalVariable(index, symbolicVal); currentStackFrame.pushValue(symbolicVal); // TODO: bit-vector symbolic value? //Expression expr = new //Value symVal = new Value(expr, Value.SYM | Value.DBL); //currentStackFrame.storeLocalVariable(symVal); //currentStackFrame.pushValue(symVal); return; } } // not symbolic currentStackFrame.loadLocalVariable(index, type); } public void loadFloat(int index, int opline) { String opcode = "FLOAD"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - loadFloat", index); // ----------debug tail---------- */ // check if no symbolics for this method int type = Value.FLT; String mtdName = currentStackFrame.getMethodName(); if (!symbolicMap.isEmpty() && symbolicMap.containsKey(mtdName)) { // check if the local parameter is defined as symbolic by the user. if so, get its initial value Value symbolicVal = getInitialSymbolicParam(mtdName, index, type, opline, null); if (symbolicVal != null) { currentStackFrame.storeLocalVariable(index, symbolicVal); currentStackFrame.pushValue(symbolicVal); return; } } // not symbolic currentStackFrame.loadLocalVariable(index, type); } public void loadInteger(int index, int opline) { String opcode = "ILOAD"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - loadInteger", index); // ----------debug tail---------- */ int type = Value.INT32; Value val = currentStackFrame.getLocalVariable(index); if (val != null) { type = val.getType(); } // check if no symbolics for this method String mtdName = currentStackFrame.getMethodName(); if (!symbolicMap.isEmpty() && symbolicMap.containsKey(mtdName)) { // check if the local parameter is defined as symbolic by the user. if so, get its initial value Value symbolicVal = getInitialSymbolicParam(mtdName, index, type, opline, null); if (symbolicVal != null) { currentStackFrame.storeLocalVariable(index, symbolicVal); currentStackFrame.pushValue(symbolicVal); return; } } // not symbolic currentStackFrame.loadLocalVariable(index, type); } public void loadLong(int index, int opline) { String opcode = "LLOAD"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - loadLong", index); // ----------debug tail---------- */ // check if no symbolics for this method int type = Value.INT64; String mtdName = currentStackFrame.getMethodName(); if (!symbolicMap.isEmpty() && symbolicMap.containsKey(mtdName)) { // check if the local parameter is defined as symbolic by the user. if so, get its initial value Value symbolicVal = getInitialSymbolicParam(mtdName, index, type, opline, null); if (symbolicVal != null) { currentStackFrame.storeLocalVariable(index, symbolicVal); currentStackFrame.pushValue(symbolicVal); return; } } // not symbolic currentStackFrame.loadLocalVariable(index, type); } public void storeLocalReference(Object conObject, int index, int opline) { String opcode = "ASTORE"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - storeLocalReference", index); // ----------debug tail---------- */ // we'd better have an entry on the stack - it is what we are wanting to store! if (currentStackFrame.isEmpty()) { exitError("storeLocalReference: stack is empty!"); return; } Value value = currentStackFrame.popValue(); assertValueNonNull(value, opcode, "value"); // if the ref type is really an array, don't replace with symbolic if (value.isType(Value.MARY | Value.ARY)) { currentStackFrame.storeLocalVariable(index, value); return; } // check if local param is symbolic and whether it is in the table of symbolics. // (if current value is NULL, we can't tell the type, so need to get it from table) Value local = currentStackFrame.getLocalVariable(index); boolean isLocalSymb = (local == null) ? false : local.isType(Value.SYM); // this will set 'entry' to the entry in symbolicMap for the specified symbolic param, // or NULL if param is not symbolic or it has already been initialized. UserSymbolic entry = null; String mtdName = currentStackFrame.getMethodName(); ArrayList<UserSymbolic> methList = getSymbolicList(mtdName); if (methList != null) { entry = getSymbolicEntry(methList, index, opline); } // check for symbolic case if (value.isType(Value.SYM)) { // if input is symbolic, apply user constraints (if any) to it and save as local param value = applyLocalParamConstraints(value, entry); removeSymbolicEntry(methList, entry); } else if (entry != null || isLocalSymb) { // else if local param is symbolic, convert concrete input value to a symbolic // and apply user constraints if any if (!symbolicMap.isEmpty() && symbolicMap.containsKey(mtdName)) { // check if the local parameter is defined as symbolic by the user. if so, get its initial value Value symValue = getInitialSymbolicParam(mtdName, index, value.getType(), opline, null); if (symValue != null) { value = symValue; } } else { // otherwise, local param is symbolic and has already been initialized. Use it. value = local; } } else { // not symbolic, if it is reference type, add entry to concrete list if (value.isType(Value.REF) && value.getValue() != null) { // verify the index entry is an Integer type assertUnsignedIntValue(value, opcode, "objectMap index"); Integer objCnt = (Integer)value.getValue(); boolean added = ExecWrapper.putConcreteObject(conObject, objCnt); /* ----------debug head--------- *@*/ if (added) { debugPrintObjects(threadId, " OBJECT[" + objCnt + "] added to CONCRETE"); } // ----------debug tail---------- */ } } // update the local param currentStackFrame.storeLocalVariable(index, value); } public void storeDouble(int index, int opline) { String opcode = "DSTORE"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - storeDouble", index); // ----------debug tail---------- */ int type = Value.DBL; Value value = currentStackFrame.popValue(); assertValueNonNull(value, opcode, "value"); // check if local param is symbolic and whether it is in the table of symbolics. // (if current value is NULL, we can't tell the type, so need to get it from table) Value local = currentStackFrame.getLocalVariable(index); boolean isLocalSymb = (local == null) ? false : local.isType(Value.SYM); // this will set 'entry' to the entry in symbolicMap for the specified symbolic param, // or NULL if param is not symbolic or it has already been initialized. UserSymbolic entry = null; String mtdName = currentStackFrame.getMethodName(); ArrayList<UserSymbolic> methList = getSymbolicList(mtdName); if (methList != null) { entry = getSymbolicEntry(methList, index, opline); } // check for symbolic case if (value.isType(Value.SYM)) { // if input is symbolic, apply user constraints (if any) to it and save as local param value = applyLocalParamConstraints(value, entry); removeSymbolicEntry(methList, entry); } else if (entry != null || isLocalSymb) { // else if local param is symbolic, convert concrete input value to a symbolic // and apply user constraints if any if (!symbolicMap.isEmpty() && symbolicMap.containsKey(mtdName)) { // check if the local parameter is defined as symbolic by the user. if so, get its initial value Value symValue = getInitialSymbolicParam(mtdName, index, type, opline, null); if (symValue != null) { value = symValue; } } else { // otherwise, local param is symbolic and has already been initialized. Use it. value = local; } } // otherwise value and local param are concrete, just update local currentStackFrame.storeLocalVariable(index, value); } public void storeFloat(int index, int opline) { String opcode = "FSTORE"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - storeFloat", index); // ----------debug tail---------- */ int type = Value.FLT; Value value = currentStackFrame.popValue(); assertValueNonNull(value, opcode, "value"); // check if local param is symbolic and whether it is in the table of symbolics. // (if current value is NULL, we can't tell the type, so need to get it from table) Value local = currentStackFrame.getLocalVariable(index); boolean isLocalSymb = (local == null) ? false : local.isType(Value.SYM); // this will set 'entry' to the entry in symbolicMap for the specified symbolic param, // or NULL if param is not symbolic or it has already been initialized. UserSymbolic entry = null; String mtdName = currentStackFrame.getMethodName(); ArrayList<UserSymbolic> methList = getSymbolicList(mtdName); if (methList != null) { entry = getSymbolicEntry(methList, index, opline); } // check for symbolic case if (value.isType(Value.SYM)) { // if input is symbolic, apply user constraints (if any) to it and save as local param value = applyLocalParamConstraints(value, entry); removeSymbolicEntry(methList, entry); } else if (entry != null || isLocalSymb) { // else if local param is symbolic, convert concrete input value to a symbolic // and apply user constraints if any if (!symbolicMap.isEmpty() && symbolicMap.containsKey(mtdName)) { // check if the local parameter is defined as symbolic by the user. if so, get its initial value Value symValue = getInitialSymbolicParam(mtdName, index, type, opline, null); if (symValue != null) { value = symValue; } } else { // otherwise, local param is symbolic and has already been initialized. Use it. value = local; } } // otherwise value and local param are concrete, just update local currentStackFrame.storeLocalVariable(index, value); } public void storeInteger(int index, int opline) { String opcode = "ISTORE"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - storeInteger", index); // ----------debug tail---------- */ Value value = currentStackFrame.popValue(); assertValueNonNull(value, opcode, "value"); int type = value.getType(); // check if local param is symbolic and whether it is in the table of symbolics. // (if current value is NULL, we can't tell the type, so need to get it from table) Value local = currentStackFrame.getLocalVariable(index); boolean isLocalSymb = (local == null) ? false : local.isType(Value.SYM); // this will set 'entry' to the entry in symbolicMap for the specified symbolic param, // or NULL if param is not symbolic or it has already been initialized. UserSymbolic entry = null; String mtdName = currentStackFrame.getMethodName(); ArrayList<UserSymbolic> methList = getSymbolicList(mtdName); if (methList != null) { entry = getSymbolicEntry(methList, index, opline); } // check for symbolic case if (value.isType(Value.SYM)) { // if input is symbolic, apply user constraints (if any) to it and save as local param value = applyLocalParamConstraints(value, entry); removeSymbolicEntry(methList, entry); } else if (entry != null || isLocalSymb) { // else if local param is symbolic, convert concrete input value to a symbolic // and apply user constraints if any if (!symbolicMap.isEmpty() && symbolicMap.containsKey(mtdName)) { // check if the local parameter is defined as symbolic by the user. if so, get its initial value Value symValue = getInitialSymbolicParam(mtdName, index, type, opline, null); if (symValue != null) { value = symValue; } } else { // otherwise, local param is symbolic and has already been initialized. Use it. value = local; } } // otherwise value and local param are concrete, just update local currentStackFrame.storeLocalVariable(index, value); } public void storeLong(int index, int opline) { String opcode = "LSTORE"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - storeLong", index); // ----------debug tail---------- */ int type = Value.INT64; Value value = currentStackFrame.popValue(); assertValueNonNull(value, opcode, "value"); // check if local param is symbolic and whether it is in the table of symbolics. // (if current value is NULL, we can't tell the type, so need to get it from table) Value local = currentStackFrame.getLocalVariable(index); boolean isLocalSymb = (local == null) ? false : local.isType(Value.SYM); // this will set 'entry' to the entry in symbolicMap for the specified symbolic param, // or NULL if param is not symbolic or it has already been initialized. UserSymbolic entry = null; String mtdName = currentStackFrame.getMethodName(); ArrayList<UserSymbolic> methList = getSymbolicList(mtdName); if (methList != null) { entry = getSymbolicEntry(methList, index, opline); } // check for symbolic case if (value.isType(Value.SYM)) { // if input is symbolic, apply user constraints (if any) to it and save as local param value = applyLocalParamConstraints(value, entry); removeSymbolicEntry(methList, entry); } else if (entry != null || isLocalSymb) { // else if local param is symbolic, convert concrete input value to a symbolic // and apply user constraints if any if (!symbolicMap.isEmpty() && symbolicMap.containsKey(mtdName)) { // check if the local parameter is defined as symbolic by the user. if so, get its initial value Value symValue = getInitialSymbolicParam(mtdName, index, type, opline, null); if (symValue != null) { value = symValue; } } else { // otherwise, local param is symbolic and has already been initialized. Use it. value = local; } } // otherwise value and local param are concrete, just update local currentStackFrame.storeLocalVariable(index, value); } public void loadReferenceFromArray(Object conObj, int index, int opline) { String opcode = "AALOAD"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - loadReferenceFromArray", index); // ----------debug tail---------- */ currentStackFrame.popValue(); // discard the possibly symbolic index value Value array = currentStackFrame.popValue(); assertValueNonNull(array, opcode, "array"); // check for multi-array if (array.isType(Value.MARY)) { Integer key = (Integer) array.getValue(); if (key == null) { exitError("loadReferenceFromArray: Multi-array key value was not defined"); } Value element = getMultiArrayElement(key, index); // if REF type and entry is null, create a new value for it if (element.isType(Value.REF) && element.getValue() == null) { element = Util.makeNewRefValue(threadId, conObj); setMultiArrayElement(key, index, element); } currentStackFrame.pushValue(element); return; } // should be a combo int type = DataConvert.getValueDataType(DataConvert.getClassType(conObj)); // NOTE: THIS USES REFLECTION type &= ~(Value.ARY | Value.MARY); Value[] combo = getArrayCombo(array, type); Value element; if (combo[1] == null) { // this is a combo consisting of a primitive array ([0] is array, [1] is null) // the data type can be inferred from the array type, less the ARY marking Object[] elements = (Object[]) combo[0].getValue(); if (elements == null) { exitError("loadReferenceFromArray: primitive array is null"); return; } if (type == Value.REF) { element = Util.makeNewRefValue(threadId, elements[index]); } else { element = new Value(elements[index], type); } currentStackFrame.pushValue(element); } else { // this is a value-packed array Value[] elements = (Value[]) combo[0].getValue(); if (elements == null) { if (conObj == null) { exitError("loadReferenceFromArray: Value array is null"); return; } else { // this was a case where we didn't have the array info when it was referenced // (such as in getField when the field type was an array). We must create the array // here from the concrete Value. // NOTE: // this assumes that array value itself is an Integer value to reference the entry in // arrayMap, and the arrayMap entry has a combo[0] value of null and combo[1] value of 0. // this is how getField behaves for an array field. Object[] conArray = (Object[]) conObj; int size = conArray.length; elements = new Value[size]; int objCnt = 0; for (int ix = 0; ix < size; ix++) { Map<String, Value> newMap = new HashMap<>(); objCnt = ExecWrapper.putReferenceObject(newMap); /* ----------debug head--------- *@*/ debugPrintObjectMap(threadId, objCnt, newMap); // ----------debug tail---------- */ elements[ix] = new Value (objCnt, Value.REF); } /* ----------debug head--------- *@*/ String arrtype = DataConvert.getObjectValue(conObj); if (arrtype.contains("[")) { arrtype = arrtype.substring(1); } debugPrintArrayList(threadId, (Integer) array.getValue(), objCnt - size, size, arrtype); // ----------debug tail---------- */ combo[0] = new Value(elements, Value.REF); combo[1] = new Value(size, Value.INT32); } } // update the array length from the length of the concrete value if length is incorrect int length = ((Object[]) conObj).length; boolean updated = updateValueArrayLength(combo, length, array.getValue()); if (updated) { // if changed, make sure to update the elements array that was using the original combo value elements = (Value[]) combo[0].getValue(); } element = elements[index]; if (element == null) { type = combo[0].getType(); if (type == Value.REF) { element = Util.makeNewRefValue(threadId, element); elements[index] = element; } else { element = new Value(null, type); // convert null entry to an appropriate Value } } currentStackFrame.pushValue(element); } } private Value readSymbolicArray(int type, int conLength, Value idx, Value[] combo, int opline) { Value val = null; boolean arrSymb = combo[0].isType(Value.SYM); boolean idxSymb = idx.isType(Value.SYM); if (arrSymb) { ArrayExpr core = (ArrayExpr) combo[0].getValue(); BitVecExpr idxExpr = Util.getBitVector(idx, z3Context); Expr element = z3Context.mkSelect(core, idxExpr); z3Optimize.MkMaximize(element); val = new Value(element, type | Value.SYM); } else if (idxSymb) { Util.convertCombo(combo, type, z3Context); ArrayExpr core = (com.microsoft.z3.ArrayExpr) combo[0].getValue(); Expr element = z3Context.mkSelect(core, (BitVecExpr) idx.getValue()); z3Optimize.MkMaximize(element); val = new Value(element, type | Value.SYM); // add constraints on index values BitVecExpr zero = z3Context.mkBV(0, 32); BitVecExpr bound = z3Context.mkBV(conLength, 32); // these are separate from the path constraints because otherwise array // index out of bound constraints will never be satisfiable // see addArrayIndexConstraints arrayConstraints.add(z3Context.mkBVSGE((BitVecExpr) idx.getValue(), zero)); arrayConstraints.add(z3Context.mkBVSLT((BitVecExpr) idx.getValue(), bound)); /* ----------debug head--------- *@*/ debugPrintConstraint(threadId, "added array bounds constraints: BVSGE to 0 & BVSLT to" + bound); // ----------debug tail---------- */ } // only add index constraints if index is symbolic if (idxSymb) { addArrayIndexConstraints((BitVecExpr)idx.getValue(), conLength, opline); } return val; } public void readCharArray(char[] conArray, int opline) { String opcode = "CALOAD"; int type = Value.CHR; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - readCharArray", opline); // ----------debug tail---------- */ Value idx = currentStackFrame.popValue(); Value arr = currentStackFrame.popValue(); // check for multi-array if (arr.isType(Value.MARY)) { Value element = getMultiArrayElement((Integer) arr.getValue(), (Integer) idx.getValue()); currentStackFrame.pushValue(element); return; } // get the array combo entry (and verify) // (in case it was returned from an uninstrumented method, we need to repack info Value[]) Value[] combo = getArrayCombo(arr, type); repackCombo(combo, type); int conLength = conArray == null ? 0 : conArray.length; // determine if this is a symbolic array Value val = readSymbolicArray(type, conLength, idx, combo, opline); if (val == null) { // concrete array... // verify the index is an Integer type assertUnsignedIntValue(idx, opcode, "array index"); // update the array length from the length of the concrete value if length is incorrect updateValueArrayLength(combo, conLength, arr.getValue()); // get the selected array entry and return it int index = (Integer) idx.getValue(); Value[] core = (Value[]) combo[0].getValue(); val = core[index]; // check if we need to translate the z3 context (if sym value was generated in another thread) if (val != null && val.isType(Value.SYM)) { val = new Value(((Expr)val.getValue()).translate(z3Context), val.getType()); } else { // else, use the concrete val = new Value(conArray[index], type); core[index] = val; } } currentStackFrame.pushValue(val); } public void readByteArray(byte[] conArray, int opline) { String opcode = "BALOAD"; int type = Value.INT8; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - readByteArray", opline); // ----------debug tail---------- */ Value idx = currentStackFrame.popValue(); Value arr = currentStackFrame.popValue(); // check for multi-array if (arr.isType(Value.MARY)) { Value element = getMultiArrayElement((Integer) arr.getValue(), (Integer) idx.getValue()); currentStackFrame.pushValue(element); return; } // get the array combo entry (and verify) // (in case it was returned from an uninstrumented method, we need to repack info Value[]) Value[] combo = getArrayCombo(arr, type); repackCombo(combo, type); int conLength = conArray == null ? 0 : conArray.length; // determine if this is a symbolic array Value val = readSymbolicArray(type, conLength, idx, combo, opline); if (val == null) { // concrete array... // verify the index is an Integer type assertUnsignedIntValue(idx, opcode, "array index"); // update the array length from the length of the concrete value if length is incorrect updateValueArrayLength(combo, conLength, arr.getValue()); // get the selected array entry and return it int index = (Integer) idx.getValue(); Value[] core = (Value[]) combo[0].getValue(); val = core[index]; // check if we need to translate the z3 context (if sym value was generated in another thread) if (val != null && val.isType(Value.SYM)) { val = new Value(((Expr)val.getValue()).translate(z3Context), val.getType()); } else { // else, use the concrete val = new Value(conArray[index], type); core[index] = val; } } currentStackFrame.pushValue(val); } public void readShortArray(short[] conArray, int opline) { String opcode = "SALOAD"; int type = Value.INT16; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - readShortArray", opline); // ----------debug tail---------- */ Value idx = currentStackFrame.popValue(); Value arr = currentStackFrame.popValue(); // check for multi-array if (arr.isType(Value.MARY)) { Value element = getMultiArrayElement((Integer) arr.getValue(), (Integer) idx.getValue()); currentStackFrame.pushValue(element); return; } // get the array combo entry (and verify) // (in case it was returned from an uninstrumented method, we need to repack info Value[]) Value[] combo = getArrayCombo(arr, type); repackCombo(combo, type); int conLength = conArray == null ? 0 : conArray.length; // determine if this is a symbolic array Value val = readSymbolicArray(type, conLength, idx, combo, opline); if (val == null) { // concrete array... // verify the index is an Integer type assertUnsignedIntValue(idx, opcode, "array index"); // update the array length from the length of the concrete value if length is incorrect updateValueArrayLength(combo, conLength, arr.getValue()); // get the selected array entry and return it int index = (Integer) idx.getValue(); Value[] core = (Value[]) combo[0].getValue(); val = core[index]; // check if we need to translate the z3 context (if sym value was generated in another thread) if (val != null && val.isType(Value.SYM)) { val = new Value(((Expr)val.getValue()).translate(z3Context), val.getType()); } else { // else, use the concrete val = new Value(conArray[index], type); core[index] = val; } } currentStackFrame.pushValue(val); } public void readIntegerArray(int[] conArray, int opline) { String opcode = "IALOAD"; int type = Value.INT32; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - readIntegerArray", opline); // ----------debug tail---------- */ Value idx = currentStackFrame.popValue(); Value arr = currentStackFrame.popValue(); // check for multi-array if (arr.isType(Value.MARY)) { Value element = getMultiArrayElement((Integer) arr.getValue(), (Integer) idx.getValue()); currentStackFrame.pushValue(element); return; } // get the array combo entry (and verify) // (in case it was returned from an uninstrumented method, we need to repack info Value[]) Value[] combo = getArrayCombo(arr, type); repackCombo(combo, type); int conLength = conArray == null ? 0 : conArray.length; // determine if this is a symbolic array Value val = readSymbolicArray(type, conLength, idx, combo, opline); if (val == null) { // concrete array... // verify the index is an Integer type assertUnsignedIntValue(idx, opcode, "array index"); // update the array length from the length of the concrete value if length is incorrect updateValueArrayLength(combo, conLength, arr.getValue()); // get the selected array entry and return it int index = (Integer) idx.getValue(); Value[] core = (Value[]) combo[0].getValue(); val = core[index]; // check if we need to translate the z3 context (if sym value was generated in another thread) if (val != null && val.isType(Value.SYM)) { val = new Value(((Expr)val.getValue()).translate(z3Context), val.getType()); } else { // else, use the concrete val = new Value(conArray[index], type); core[index] = val; } } currentStackFrame.pushValue(val); } public void readLongArray(long[] conArray, int opline) { String opcode = "LALOAD"; int type = Value.INT64; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - readLongArray", opline); // ----------debug tail---------- */ Value idx = currentStackFrame.popValue(); Value arr = currentStackFrame.popValue(); // check for multi-array if (arr.isType(Value.MARY)) { Value element = getMultiArrayElement((Integer) arr.getValue(), (Integer) idx.getValue()); currentStackFrame.pushValue(element); return; } // get the array combo entry (and verify) // (in case it was returned from an uninstrumented method, we need to repack info Value[]) Value[] combo = getArrayCombo(arr, type); repackCombo(combo, type); int conLength = conArray == null ? 0 : conArray.length; // determine if this is a symbolic array Value val = readSymbolicArray(type, conLength, idx, combo, opline); if (val == null) { // concrete array... // verify the index is an Integer type assertUnsignedIntValue(idx, opcode, "array index"); // update the array length from the length of the concrete value if length is incorrect updateValueArrayLength(combo, conLength, arr.getValue()); // get the selected array entry and return it int index = (Integer) idx.getValue(); Value[] core = (Value[]) combo[0].getValue(); val = core[index]; // check if we need to translate the z3 context (if sym value was generated in another thread) if (val != null && val.isType(Value.SYM)) { val = new Value(((Expr)val.getValue()).translate(z3Context), val.getType()); } else { // else, use the concrete val = new Value(conArray[index], type); core[index] = val; } } currentStackFrame.pushValue(val); } public void readFloatArray(float[] conArray, int opline) { String opcode = "FALOAD"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - readFloatArray"); // ----------debug tail---------- */ Value idx = currentStackFrame.popValue(); Value arr = currentStackFrame.popValue(); // check for multi-array if (arr.isType(Value.MARY)) { Value element = getMultiArrayElement((Integer) arr.getValue(), (Integer) idx.getValue()); currentStackFrame.pushValue(element); return; } // get the array combo entry (and verify) // (in case it was returned from an uninstrumented method, we need to repack info Value[]) int type = Value.FLT; Value[] combo = getArrayCombo(arr, type); repackCombo(combo, type); boolean arrsymb = combo[0].isType(Value.SYM); if (arrsymb) { ArrayExpr core = (ArrayExpr) combo[0].getValue(); BitVecExpr idxExpr = Util.getBitVector(idx, z3Context); Expr element = z3Context.mkSelect(core, idxExpr); currentStackFrame.pushValue(new Value(element, type | Value.SYM)); } else if (idx.isType(Value.SYM)) { //if (!(combo[0].getValue() instanceof com.microsoft.z3.ArrayExpr)) { if (!arrsymb) { Util.convertCombo(combo, type, z3Context); } ArrayExpr core = (com.microsoft.z3.ArrayExpr) combo[0].getValue(); Expr element = z3Context.mkSelect(core, (BitVecExpr) idx.getValue()); currentStackFrame.pushValue(new Value(element, type | Value.SYM)); } else { // verify the entry is an Integer type assertUnsignedIntValue(idx, opcode, "array index"); // update the array length from the length of the concrete value if length is incorrect int conLength = conArray == null ? 0 : conArray.length; updateValueArrayLength(combo, conLength, arr.getValue()); // get the selected array entry and return it int index = (Integer) idx.getValue(); Value[] core = (Value[]) combo[0].getValue(); Value val = core[index]; // check if we need to translate the z3 context (if sym value was generated in another thread) if (val != null && val.isType(Value.SYM)) { val = new Value(((Expr)val.getValue()).translate(z3Context), val.getType()); } else { // else, use the concrete val = new Value(conArray[index], type); core[index] = val; } currentStackFrame.pushValue(val); } } public void readDoubleArray(double[] conArray, int opline) { String opcode = "DALOAD"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - readDoubleArray"); // ----------debug tail---------- */ Value idx = currentStackFrame.popValue(); Value arr = currentStackFrame.popValue(); // check for multi-array if (arr.isType(Value.MARY)) { Value element = getMultiArrayElement((Integer) arr.getValue(), (Integer) idx.getValue()); currentStackFrame.pushValue(element); return; } // get the array combo entry (and verify) // (in case it was returned from an uninstrumented method, we need to repack info Value[]) int type = Value.DBL; Value[] combo = getArrayCombo(arr, type); repackCombo(combo, type); boolean arrsymb = combo[0].isType(Value.SYM); if (arrsymb) { ArrayExpr core = (ArrayExpr) combo[0].getValue(); BitVecExpr idxExpr = Util.getBitVector(idx, z3Context); Expr element = z3Context.mkSelect(core, idxExpr); currentStackFrame.pushValue(new Value(element, type | Value.SYM)); } else if (idx.isType(Value.SYM)) { //if (!(combo[0].getValue() instanceof com.microsoft.z3.ArrayExpr)) { if (!arrsymb) { Util.convertCombo(combo, type, z3Context); } ArrayExpr core = (com.microsoft.z3.ArrayExpr) combo[0].getValue(); Expr element = z3Context.mkSelect(core, (BitVecExpr) idx.getValue()); currentStackFrame.pushValue(new Value(element, type | Value.SYM)); } else { // verify the entry is an Integer type assertUnsignedIntValue(idx, opcode, "array index"); // update the array length from the length of the concrete value if length is incorrect int conLength = conArray == null ? 0 : conArray.length; updateValueArrayLength(combo, conLength, arr.getValue()); // get the selected array entry and return it int index = (Integer) idx.getValue(); Value[] core = (Value[]) combo[0].getValue(); Value val = core[index]; // check if we need to translate the z3 context (if sym value was generated in another thread) if (val != null && val.isType(Value.SYM)) { val = new Value(((Expr)val.getValue()).translate(z3Context), val.getType()); } else { // else, use the concrete val = new Value(conArray[index], type); core[index] = val; } currentStackFrame.pushValue(val); } } // who is to blame: danielbala, dmcd2356 // who blames him: zzk public void writePrimitiveArray(int type, int opline) { String opcode = getOpcodeDataType(type) + "ASTORE"; /* ----------debug head--------- *@*/ debugPrintCommand_type(threadId, opcode + " - writePrimitiveArray", type); // ----------debug tail---------- */ Value val = currentStackFrame.popValue(); // value to write to array Value idx = currentStackFrame.popValue(); // index of array to write to Value arr = currentStackFrame.popValue(); // the array itself // check for multi-array if (arr.isType(Value.MARY)) { setMultiArrayElement((Integer) arr.getValue(), (Integer) idx.getValue(), val); return; } // get the array combo entry (and verify) // (in case it was returned from an uninstrumented method, we need to repack info Value[]) Value[] combo = getArrayCombo(arr, type); repackCombo(combo, type); if (arr.isType(Value.SYM)) { Expr valExpr = Util.getExpression(val, z3Context); BitVecExpr idxExpr = Util.getBitVector(idx, z3Context); ArrayExpr core = (ArrayExpr) combo[0].getValue(); combo[0] = new Value(z3Context.mkStore(core, idxExpr, valExpr), Value.ARY | Value.SYM); } else if (idx.isType(Value.SYM)) { Expr valExpr = Util.getExpression(val, z3Context); BitVecExpr idxExpr = Util.getBitVector(idx, z3Context); Util.convertCombo(combo, type, z3Context); ArrayExpr core = (ArrayExpr) combo[0].getValue(); combo[0] = new Value(z3Context.mkStore(core, idxExpr, valExpr), Value.ARY | Value.SYM); } else { // verify the entry is an Integer type assertUnsignedIntValue(idx, opcode, "array index"); int index = (Integer) idx.getValue(); Value[] core = (Value[]) combo[0].getValue(); core[index] = val; } } public void arrayStore(Object[] conObj, int conIndex, int opline) { String opcode = "AASTORE"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - arrayStore", conIndex); // ----------debug tail---------- */ Value value = currentStackFrame.popValue(); Value index = currentStackFrame.popValue(); // use concrete instead Value array = currentStackFrame.popValue(); String classType = DataConvert.getClassType(conObj); // NOTE: THIS USES REFLECTION int arrlev = 0; for (int ix = 0; classType.charAt(ix) == '['; ix++) { ++arrlev; } if (arrlev < 1) { exitError("arrayStore: called on non-array type: " + classType); } // this just checks to see if we have the ARY flag reported correctly /* ----------debug head--------- *@*/ if (!array.isType(Value.ARY | Value.MARY)) { debugPrintWarning(threadId, "arrayStore: ARY flag missing in type: " + DataConvert.showValueDataType(array.getType())); } // ----------debug tail---------- */ // check for multi-array if (array.isType(Value.MARY)) { Integer key = (Integer) array.getValue(); if (key == null) { exitError("arrayStore: Multi-array key value was not defined"); } setMultiArrayElement(key, conIndex, value); return; } // TODO: do we need to handle symbolics here as we do for writePrimitivaArray ? // (in case it was returned from an uninstrumented method, we need to repack info Value[]) Value[] combo = getArrayCombo(array, DataConvert.getValueDataType(classType)); repackCombo(combo, combo[0].getType()); Value[] elements = (Value[]) combo[0].getValue(); elements[conIndex] = value; } public void executePop() { String opcode = "POP"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - executePop"); // ----------debug tail---------- */ Value value1 = currentStackFrame.popValue(); /* ----------debug head--------- *@*/ if (value1 != null && value1.isType(Value.INT64 | Value.DBL)) { debugPrintError(threadId, "stack entry contains long or double for POP"); } // ----------debug tail---------- */ } public void executePop2() { String opcode = "POP2"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - executePop2"); // ----------debug tail---------- */ Value value1 = currentStackFrame.popValue(); if (!value1.isType(Value.INT64 | Value.DBL)) { Value value2 = currentStackFrame.popValue(); /* ----------debug head--------- *@*/ if (value2 != null && value2.isType(Value.INT64 | Value.DBL)) { debugPrintError(threadId, "stack entry 2 contains long or double for POP2"); } // ----------debug tail---------- */ } } public void executeDup() { String opcode = "DUP"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - executeDup"); // ----------debug tail---------- */ Value value1 = currentStackFrame.peekValue(0); currentStackFrame.pushValue(value1); /* ----------debug head--------- *@*/ if (value1 != null && value1.isType(Value.INT64 | Value.DBL)) { debugPrintError(threadId, "stack entry contains long or double for DUP"); } // ----------debug tail---------- */ } public void executeDup_x1() { String opcode = "DUP_X1"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - executeDup_x1"); // ----------debug tail---------- */ Value value1 = currentStackFrame.popValue(); Value value2 = currentStackFrame.popValue(); currentStackFrame.pushValue(value1); currentStackFrame.pushValue(value2); currentStackFrame.pushValue(value1); /* ----------debug head--------- *@*/ if (value1 != null && value1.isType(Value.INT64 | Value.DBL) || value2 != null && value2.isType(Value.INT64 | Value.DBL)) { debugPrintError(threadId, "stack entry contains long or double for DUP_X1"); } // ----------debug tail---------- */ } public void executeDup_x2() { String opcode = "DUP_X2"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - executeDup_x2"); // ----------debug tail---------- */ Value value1 = currentStackFrame.popValue(); Value value2 = currentStackFrame.popValue(); /* ----------debug head--------- *@*/ if (value1 != null && value1.isType(Value.INT64 | Value.DBL)) { debugPrintError(threadId, "stack entry 1 contains long or double for DUP_X2"); } // ----------debug tail---------- */ if (value2 != null && value2.isType(Value.INT64 | Value.DBL)) { currentStackFrame.pushValue(value1); currentStackFrame.pushValue(value2); currentStackFrame.pushValue(value1); } else { Value value3 = currentStackFrame.popValue(); currentStackFrame.pushValue(value1); currentStackFrame.pushValue(value3); currentStackFrame.pushValue(value2); currentStackFrame.pushValue(value1); } } public void executeDup2() { String opcode = "DUP2"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - executeDup2"); // ----------debug tail---------- */ Value value1 = currentStackFrame.popValue(); if (value1 != null && value1.isType(Value.INT64 | Value.DBL)) { currentStackFrame.pushValue(value1); currentStackFrame.pushValue(value1); } else { Value value2 = currentStackFrame.popValue(); /* ----------debug head--------- *@*/ if (value2 != null && value2.isType(Value.INT64 | Value.DBL)) { debugPrintError(threadId, "stack entry 2 contains long or double for DUP2"); } // ----------debug tail---------- */ currentStackFrame.pushValue(value2); currentStackFrame.pushValue(value1); currentStackFrame.pushValue(value2); currentStackFrame.pushValue(value1); } } public void executeDup2_x1() { String opcode = "DUP2_X1"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - executeDup2_x1"); // ----------debug tail---------- */ Value value1 = currentStackFrame.popValue(); Value value2 = currentStackFrame.popValue(); /* ----------debug head--------- *@*/ if (value2 != null && value2.isType(Value.INT64 | Value.DBL)) { debugPrintError(threadId, "stack entry 2 contains long or double for DUP2_X1"); } // ----------debug tail---------- */ if (value1.isType(Value.INT64 | Value.DBL)) { currentStackFrame.pushValue(value1); currentStackFrame.pushValue(value2); currentStackFrame.pushValue(value1); } else { Value value3 = currentStackFrame.popValue(); /* ----------debug head--------- *@*/ if (value3 != null && value3.isType(Value.INT64 | Value.DBL)) { debugPrintError(threadId, "stack entry 3 contains long or double for DUP2_X1"); } // ----------debug tail---------- */ currentStackFrame.pushValue(value2); currentStackFrame.pushValue(value1); currentStackFrame.pushValue(value3); currentStackFrame.pushValue(value2); currentStackFrame.pushValue(value1); } } public void executeDup2_x2() { String opcode = "DUP2_X2"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - executeDup2_x2"); // ----------debug tail---------- */ Value value1 = currentStackFrame.popValue(); Value value2 = currentStackFrame.popValue(); if (value1 != null && value1.isType(Value.INT64 | Value.DBL) || value2 != null && value2.isType(Value.INT64 | Value.DBL)) { // 2 double entries currentStackFrame.pushValue(value1); // double entry currentStackFrame.pushValue(value2); // double entry currentStackFrame.pushValue(value1); // double entry } else if (value2 != null && value2.isType(Value.INT64 | Value.DBL)) { // invalid selection /* ----------debug head--------- *@*/ debugPrintError(threadId, "stack entry 2 contains long or double for DUP2_X2"); // ----------debug tail---------- */ currentStackFrame.pushValue(value1); currentStackFrame.pushValue(value2); currentStackFrame.pushValue(value1); } else { Value value3 = currentStackFrame.popValue(); if (value1 != null && value1.isType(Value.INT64 | Value.DBL)) { // 1st entry is double, next 2 entries not currentStackFrame.pushValue(value1); // double entry currentStackFrame.pushValue(value3); currentStackFrame.pushValue(value2); currentStackFrame.pushValue(value1); // double entry /* ----------debug head--------- *@*/ if (value3 != null && value3.isType(Value.INT64 | Value.DBL)) { debugPrintError(threadId, "stack entry 3 contains long or double for DUP2_X2"); } // ----------debug tail---------- */ } else if (value3 != null && value3.isType(Value.INT64 | Value.DBL)) { // 1st 2 entries not double, 3 entry is double currentStackFrame.pushValue(value2); currentStackFrame.pushValue(value1); currentStackFrame.pushValue(value3); // double entry currentStackFrame.pushValue(value2); currentStackFrame.pushValue(value1); } else { // 4 entries on stack, none of them double Value value4 = currentStackFrame.popValue(); currentStackFrame.pushValue(value2); currentStackFrame.pushValue(value1); currentStackFrame.pushValue(value4); currentStackFrame.pushValue(value3); currentStackFrame.pushValue(value2); currentStackFrame.pushValue(value1); /* ----------debug head--------- *@*/ if (value4 != null && value4.isType(Value.INT64 | Value.DBL)) { debugPrintError(threadId, "stack entry 4 contains long or double for DUP2_X2"); } // ----------debug tail---------- */ } } } public void executeSwap() { String opcode = "SWAP"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - executeSwap"); // ----------debug tail---------- */ Value value1 = currentStackFrame.popValue(); Value value2 = currentStackFrame.popValue(); currentStackFrame.pushValue(value1); currentStackFrame.pushValue(value2); /* ----------debug head--------- *@*/ if (value1 != null && value1.isType(Value.INT64 | Value.DBL) || value2 != null && value2.isType(Value.INT64 | Value.DBL)) { debugPrintError(threadId, "stack entry contains long or double for SWAP"); } // ----------debug tail---------- */ } public void addDouble() { String opcode = "DADD"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - addDouble"); // ----------debug tail---------- */ Value val2 = currentStackFrame.popValue(); Value val1 = currentStackFrame.popValue(); Value val3 = ValueOp.addRealValue(val1, val2, z3Context); currentStackFrame.pushValue(val3); } public void subDouble() { String opcode = "DSUB"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - subDouble"); // ----------debug tail---------- */ Value val2 = currentStackFrame.popValue(); Value val1 = currentStackFrame.popValue(); Value val3 = ValueOp.subRealValue(val1, val2, z3Context); currentStackFrame.pushValue(val3); } public void mulDouble() { String opcode = "DMUL"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - mulDouble"); // ----------debug tail---------- */ Value val2 = currentStackFrame.popValue(); Value val1 = currentStackFrame.popValue(); Value val3 = ValueOp.mulRealValue(val1, val2, z3Context); currentStackFrame.pushValue(val3); } public void divDouble() { String opcode = "DDIV"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - divDouble"); // ----------debug tail---------- */ Value val2 = currentStackFrame.popValue(); Value val1 = currentStackFrame.popValue(); Value val3 = ValueOp.divRealValue(val1, val2, z3Context); currentStackFrame.pushValue(val3); } public void remDouble() { String opcode = "DREM"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - remDouble"); // ----------debug tail---------- */ Value val2 = currentStackFrame.popValue(); Value val1 = currentStackFrame.popValue(); Value val3 = ValueOp.modRealValue(val1, val2, z3Context); currentStackFrame.pushValue(val3); } public void negDouble() { String opcode = "DNEG"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - negDouble"); // ----------debug tail---------- */ Value val1 = currentStackFrame.popValue(); Value val2 = ValueOp.negRealValue(val1, z3Context); currentStackFrame.pushValue(val2); } public void addFloat() { String opcode = "FADD"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - addFloat"); // ----------debug tail---------- */ Value val2 = currentStackFrame.popValue(); Value val1 = currentStackFrame.popValue(); Value val3 = ValueOp.addRealValue(val1, val2, z3Context); currentStackFrame.pushValue(val3); } public void subFloat() { String opcode = "FSUB"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - subFloat"); // ----------debug tail---------- */ Value val2 = currentStackFrame.popValue(); Value val1 = currentStackFrame.popValue(); Value val3 = ValueOp.subRealValue(val1, val2, z3Context); currentStackFrame.pushValue(val3); } public void mulFloat() { String opcode = "FMUL"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - mulFloat"); // ----------debug tail---------- */ Value val2 = currentStackFrame.popValue(); Value val1 = currentStackFrame.popValue(); Value val3 = ValueOp.mulRealValue(val1, val2, z3Context); currentStackFrame.pushValue(val3); } public void divFloat() { String opcode = "FDIV"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - divFloat"); // ----------debug tail---------- */ Value val2 = currentStackFrame.popValue(); Value val1 = currentStackFrame.popValue(); Value val3 = ValueOp.divRealValue(val1, val2, z3Context); currentStackFrame.pushValue(val3); } public void remFloat() { String opcode = "FREM"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - remFloat"); // ----------debug tail---------- */ Value val2 = currentStackFrame.popValue(); Value val1 = currentStackFrame.popValue(); Value val3 = ValueOp.modRealValue(val1, val2, z3Context); currentStackFrame.pushValue(val3); } public void negFloat() { String opcode = "FNEG"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - negFloat"); // ----------debug tail---------- */ Value val1 = currentStackFrame.popValue(); Value val2 = ValueOp.negRealValue(val1, z3Context); currentStackFrame.pushValue(val2); } public void incInteger(int var, int incr) { String opcode = "IINC"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - incInteger", var, incr); // ----------debug tail---------- */ Value val1 = currentStackFrame.getLocalVariable(var); if (val1 == null) { val1 = new Value(null, Value.INT32); currentStackFrame.storeLocalVariable(var, val1); } Value val2 = new Value(new Integer(incr), Value.INT32); Value val3 = ValueOp.addIntegralValue(val1, val2, z3Context); currentStackFrame.storeLocalVariable(var, val3); } public void addInteger() { String opcode = "IADD"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - addInteger"); // ----------debug tail---------- */ Value val2 = currentStackFrame.popValue(); Value val1 = currentStackFrame.popValue(); Value val3 = ValueOp.addIntegralValue(val1, val2, z3Context); currentStackFrame.pushValue(val3); } public void subInteger() { String opcode = "ISUB"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - subInteger"); // ----------debug tail---------- */ Value val2 = currentStackFrame.popValue(); Value val1 = currentStackFrame.popValue(); Value val3 = ValueOp.subIntegralValue(val1, val2, z3Context); currentStackFrame.pushValue(val3); } public void mulInteger() { String opcode = "IMUL"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - mulInteger"); // ----------debug tail---------- */ Value val2 = currentStackFrame.popValue(); Value val1 = currentStackFrame.popValue(); Value val3 = ValueOp.mulIntegralValue(val1, val2, z3Context); currentStackFrame.pushValue(val3); } public void divInteger() { String opcode = "IDIV"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - divInteger"); // ----------debug tail---------- */ Value val2 = currentStackFrame.popValue(); Value val1 = currentStackFrame.popValue(); Value val3 = ValueOp.divIntegralValue(val1, val2, z3Context); currentStackFrame.pushValue(val3); } public void remInteger() { String opcode = "IREM"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - remInteger"); // ----------debug tail---------- */ Value val2 = currentStackFrame.popValue(); Value val1 = currentStackFrame.popValue(); Value val3 = ValueOp.modIntegralValue(val1, val2, z3Context); currentStackFrame.pushValue(val3); } public void negInteger() { String opcode = "INEG"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - negInteger"); // ----------debug tail---------- */ Value val1 = currentStackFrame.popValue(); Value val2 = ValueOp.negIntegralValue(val1, z3Context); currentStackFrame.pushValue(val2); } public void addLong() { String opcode = "LADD"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - addLong"); // ----------debug tail---------- */ Value val2 = currentStackFrame.popValue(); Value val1 = currentStackFrame.popValue(); Value val3 = ValueOp.addIntegralValue(val1, val2, z3Context); currentStackFrame.pushValue(val3); } public void subLong() { String opcode = "LSUB"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - subLong"); // ----------debug tail---------- */ Value val2 = currentStackFrame.popValue(); Value val1 = currentStackFrame.popValue(); Value val3 = ValueOp.subIntegralValue(val1, val2, z3Context); currentStackFrame.pushValue(val3); } public void mulLong() { String opcode = "LMUL"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - mulLong"); // ----------debug tail---------- */ Value val2 = currentStackFrame.popValue(); Value val1 = currentStackFrame.popValue(); Value val3 = ValueOp.mulIntegralValue(val1, val2, z3Context); currentStackFrame.pushValue(val3); } public void divLong() { String opcode = "LDIV"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - divLong"); // ----------debug tail---------- */ Value val2 = currentStackFrame.popValue(); Value val1 = currentStackFrame.popValue(); Value val3 = ValueOp.divIntegralValue(val1, val2, z3Context); currentStackFrame.pushValue(val3); } public void remLong() { String opcode = "LREM"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - remLong"); // ----------debug tail---------- */ Value val2 = currentStackFrame.popValue(); Value val1 = currentStackFrame.popValue(); Value val3 = ValueOp.modIntegralValue(val1, val2, z3Context); currentStackFrame.pushValue(val3); } public void negLong() { String opcode = "LNEG"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - negLong"); // ----------debug tail---------- */ Value val1 = currentStackFrame.popValue(); Value val2 = ValueOp.negIntegralValue(val1, z3Context); currentStackFrame.pushValue(val2); } public void executeIntegerAnd() { String opcode = "IAND"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - executeIntegerAnd"); // ----------debug tail---------- */ Value val2 = currentStackFrame.popValue(); Value val1 = currentStackFrame.popValue(); Value val3 = ValueOp.andValue(Value.INT32, val1, val2, z3Context); currentStackFrame.pushValue(val3); } public void executeIntegerOr() { String opcode = "IOR"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - executeIntegerOr"); // ----------debug tail---------- */ Value val2 = currentStackFrame.popValue(); Value val1 = currentStackFrame.popValue(); Value val3 = ValueOp.orValue(Value.INT32, val1, val2, z3Context); currentStackFrame.pushValue(val3); } public void executeIntegerXor() { String opcode = "IXOR"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - executeIntegerXor"); // ----------debug tail---------- */ Value val2 = currentStackFrame.popValue(); Value val1 = currentStackFrame.popValue(); Value val3 = ValueOp.xorValue(Value.INT32, val1, val2, z3Context); currentStackFrame.pushValue(val3); } public void executeIntegerShiftLeft() { String opcode = "ISHL"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - executeIntegerShiftLeft"); // ----------debug tail---------- */ Value val2 = currentStackFrame.popValue(); Value val1 = currentStackFrame.popValue(); Value val3 = ValueOp.shiftLeftValue(val1, val2, z3Context); currentStackFrame.pushValue(val3); } public void executeIntegerArithShiftRight() { String opcode = "ISHR"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - executeIntegerArithShiftRight"); // ----------debug tail---------- */ Value val2 = currentStackFrame.popValue(); Value val1 = currentStackFrame.popValue(); Value val3 = ValueOp.shiftRightArithValue(val1, val2, z3Context); currentStackFrame.pushValue(val3); } public void executeIntegerShiftRight() { String opcode = "IUSHR"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - executeIntegerShiftRight"); // ----------debug tail---------- */ Value val2 = currentStackFrame.popValue(); Value val1 = currentStackFrame.popValue(); Value val3 = ValueOp.shiftRightLogicValue(val1, val2, z3Context); currentStackFrame.pushValue(val3); } public void executeLongAnd() { String opcode = "LAND"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - executeLongAnd"); // ----------debug tail---------- */ Value val2 = currentStackFrame.popValue(); Value val1 = currentStackFrame.popValue(); Value val3 = ValueOp.andValue(Value.INT64, val1, val2, z3Context); currentStackFrame.pushValue(val3); } public void executeLongOr() { String opcode = "LOR"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - executeLongOr"); // ----------debug tail---------- */ Value val2 = currentStackFrame.popValue(); Value val1 = currentStackFrame.popValue(); Value val3 = ValueOp.orValue(Value.INT64, val1, val2, z3Context); currentStackFrame.pushValue(val3); } public void executeLongXor() { String opcode = "LXOR"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - executeLongXor"); // ----------debug tail---------- */ Value val2 = currentStackFrame.popValue(); Value val1 = currentStackFrame.popValue(); Value val3 = ValueOp.xorValue(Value.INT64, val1, val2, z3Context); currentStackFrame.pushValue(val3); } public void executeLongShiftLeft() { String opcode = "LSHL"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - executeLongShiftLeft"); // ----------debug tail---------- */ Value val2 = currentStackFrame.popValue(); Value val1 = currentStackFrame.popValue(); Value val3 = ValueOp.shiftLeftValue(val1, val2, z3Context); currentStackFrame.pushValue(val3); } public void executeLongArithShiftRight() { String opcode = "LSHR"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - executeLongArithShiftRight"); // ----------debug tail---------- */ Value val2 = currentStackFrame.popValue(); Value val1 = currentStackFrame.popValue(); Value val3 = ValueOp.shiftRightArithValue(val1, val2, z3Context); currentStackFrame.pushValue(val3); } public void executeLongShiftRight() { String opcode = "LUSHR"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - executeLongShiftRight"); // ----------debug tail---------- */ Value val2 = currentStackFrame.popValue(); Value val1 = currentStackFrame.popValue(); Value val3 = ValueOp.shiftRightLogicValue(val1, val2, z3Context); currentStackFrame.pushValue(val3); } public void convertToDouble(char optype) { String opcode = optype + "2D"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - convertToDouble"); // ----------debug tail---------- */ Value val1 = currentStackFrame.popValue(); assertValueNonNull(val1, opcode, "val1"); if (val1.isType(Value.SYM)) { if (val1.isType(Value.FLT)) { currentStackFrame.pushValue(val1); } else if (val1.isType(Value.INT8 | Value.INT16 | Value.INT32 | Value.INT64)) { // Is there an alternative way to do this? IntExpr intExpr = z3Context.mkBV2Int((BitVecExpr) val1.getValue(), true); RealExpr realExpr = z3Context.mkInt2Real(intExpr); currentStackFrame.pushValue(new Value(realExpr, Value.SYM | Value.DBL)); } return; } double newvalue = 0; switch (val1.getValue().getClass().getName()) { // NOTE: THIS USES REFLECTION case "java.lang.Integer": newvalue = ((Integer) val1.getValue()).doubleValue(); break; case "java.lang.Long": newvalue = ((Long) val1.getValue()).doubleValue(); break; case "java.lang.Float": newvalue = ((Float) val1.getValue()).doubleValue(); break; default: /* ----------debug head--------- *@*/ debugPrintError(threadId, "Invalid type conversion!"); // ----------debug tail---------- */ break; } Value val2 = new Value(newvalue, Value.DBL); currentStackFrame.pushValue(val2); } public void convertToFloat(char optype) { String opcode = optype + "2F"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - convertToFloat"); // ----------debug tail---------- */ Value val1 = currentStackFrame.popValue(); assertValueNonNull(val1, opcode, "val1"); if (val1.isType(Value.SYM)) { if (val1.isType(Value.FLT)) { currentStackFrame.pushValue(val1); } else if (val1.isType(Value.INT8 | Value.INT16 | Value.INT32 | Value.INT64)) { // Is there an alternative way to do this? IntExpr intExpr = z3Context.mkBV2Int((BitVecExpr) val1.getValue(), true); RealExpr realExpr = z3Context.mkInt2Real(intExpr); currentStackFrame.pushValue(new Value(realExpr, Value.SYM | Value.DBL)); } return; } float newvalue = 0; switch (val1.getValue().getClass().getName()) { // NOTE: THIS USES REFLECTION case "java.lang.Integer": newvalue = ((Integer) val1.getValue()).floatValue(); break; case "java.lang.Long": newvalue = ((Long) val1.getValue()).floatValue(); break; case "java.lang.Double": newvalue = ((Double) val1.getValue()).floatValue(); break; default: /* ----------debug head--------- *@*/ debugPrintError(threadId, "Invalid type conversion!"); // ----------debug tail---------- */ break; } Value val2 = new Value(newvalue, Value.FLT); currentStackFrame.pushValue(val2); } public void convertToLong(char optype) { String opcode = optype + "2L"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - convertToLong"); // ----------debug tail---------- */ Value val1 = currentStackFrame.popValue(); assertValueNonNull(val1, opcode, "val1"); if (val1.isType(Value.SYM)) { if (val1.isType(Value.INT8 | Value.INT16 | Value.INT32 | Value.INT64)) { currentStackFrame.pushValue(val1); } else if (val1.isType(Value.FLT | Value.DBL)) { // Is there an alternative way to do this? IntExpr intExpr = z3Context.mkReal2Int((RealExpr) val1.getValue()); BitVecExpr bvExpr = z3Context.mkInt2BV(64, intExpr); currentStackFrame.pushValue(new Value(bvExpr, Value.SYM | Value.INT64)); } return; } long newvalue = 0; switch (val1.getValue().getClass().getName()) { // NOTE: THIS USES REFLECTION case "java.lang.Integer": newvalue = ((Integer) val1.getValue()).longValue(); break; case "java.lang.Float": newvalue = ((Float) val1.getValue()).longValue(); break; case "java.lang.Double": newvalue = ((Double) val1.getValue()).longValue(); break; default: /* ----------debug head--------- *@*/ debugPrintError(threadId, "Invalid type conversion!"); // ----------debug tail---------- */ break; } Value val2 = new Value(newvalue, Value.INT64); currentStackFrame.pushValue(val2); } public void convertToInteger(char optype) { String opcode = optype + "2I"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - convertToInteger"); // ----------debug tail---------- */ Value val1 = currentStackFrame.popValue(); assertValueNonNull(val1, opcode, "val1"); if (val1.isType(Value.SYM)) { BitVecExpr bvExpr; switch(val1.getType() & ~Value.SYM) { case Value.INT8: bvExpr = (BitVecExpr) val1.getValue(); bvExpr = z3Context.mkSignExt(24, bvExpr); currentStackFrame.pushValue(new Value(bvExpr, Value.INT32)); break; case Value.INT16: bvExpr = (BitVecExpr) val1.getValue(); bvExpr = z3Context.mkSignExt(16, bvExpr); currentStackFrame.pushValue(new Value(bvExpr, Value.INT32)); break; case Value.INT32: currentStackFrame.pushValue(val1); break; case Value.INT64: bvExpr = (BitVecExpr) val1.getValue(); bvExpr = z3Context.mkExtract(31, 0, bvExpr); currentStackFrame.pushValue(new Value(bvExpr, Value.INT32)); break; case Value.FLT: case Value.DBL: // Is there an alternative way to do this? IntExpr intExpr = z3Context.mkReal2Int((RealExpr) val1.getValue()); bvExpr = z3Context.mkInt2BV(32, intExpr); currentStackFrame.pushValue(new Value(bvExpr, Value.SYM | Value.INT32)); break; } return; } int newvalue = 0; switch (val1.getValue().getClass().getName()) { // NOTE: THIS USES REFLECTION case "java.lang.Long": newvalue = ((Long) val1.getValue()).intValue(); break; case "java.lang.Float": newvalue = ((Float) val1.getValue()).intValue(); break; case "java.lang.Double": newvalue = ((Double) val1.getValue()).intValue(); break; default: /* ----------debug head--------- *@*/ debugPrintError(threadId, "Invalid type conversion!"); // ----------debug tail---------- */ break; } Value val2 = new Value(newvalue, Value.INT32); currentStackFrame.pushValue(val2); } public void convertToShort() { String opcode = "I2S"; Value val1 = currentStackFrame.popValue(); assertValueNonNull(val1, opcode, "val1"); /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - convertToShort"); // ----------debug tail---------- */ if (val1.isType(Value.SYM)) { BitVecExpr bvExpr = (BitVecExpr) val1.getValue(); bvExpr = z3Context.mkExtract(15, 0, bvExpr); bvExpr = z3Context.mkSignExt(16, bvExpr); currentStackFrame.pushValue(new Value(bvExpr, Value.INT16 | Value.SYM)); return; } Value val2; int mask = 0x7FFF; int signbit = mask + 1; if (val1.getValue().getClass().getName().equals("java.lang.Integer")) { // NOTE: THIS USES REFLECTION int intval = (Integer) val1.getValue(); intval = (intval & signbit) == 0 ? intval & mask : -(intval & mask); val2 = new Value(intval, Value.INT16); } else { /* ----------debug head--------- *@*/ debugPrintError(threadId, "Invalid type conversion!"); // ----------debug tail---------- */ val2 = new Value(0, Value.INT16); } currentStackFrame.pushValue(val2); } public void convertToChar() { String opcode = "I2C"; Value val1 = currentStackFrame.popValue(); assertValueNonNull(val1, opcode, "val1"); /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - convertToChar"); // ----------debug tail---------- */ if (val1.isType(Value.SYM)) { BitVecExpr bvExpr = (BitVecExpr) val1.getValue(); bvExpr = z3Context.mkExtract(15, 0, bvExpr); bvExpr = z3Context.mkSignExt(16, bvExpr); currentStackFrame.pushValue(new Value(bvExpr, Value.CHR | Value.SYM)); return; } Value val2; int mask = 0xFFFF; if (val1.getValue().getClass().getName().equals("java.lang.Integer")) { // NOTE: THIS USES REFLECTION val2 = new Value((Integer) val1.getValue() & mask, Value.CHR); } else { /* ----------debug head--------- *@*/ debugPrintError(threadId, "Invalid type conversion!"); // ----------debug tail---------- */ val2 = new Value(0, Value.CHR); } currentStackFrame.pushValue(val2); } public void convertToByte() { String opcode = "I2B"; Value val1 = currentStackFrame.popValue(); assertValueNonNull(val1, opcode, "val1"); /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - convertToByte"); // ----------debug tail---------- */ if (val1.isType(Value.SYM)) { BitVecExpr bvExpr = (BitVecExpr) val1.getValue(); bvExpr = z3Context.mkExtract(7, 0, bvExpr); bvExpr = z3Context.mkSignExt(24, bvExpr); currentStackFrame.pushValue(new Value(bvExpr, Value.INT32 | Value.SYM)); return; } Value val2; int mask = 0x7F; int signbit = mask + 1; if (val1.getValue().getClass().getName().equals("java.lang.Integer")) { // NOTE: THIS USES REFLECTION int intval = (Integer) val1.getValue(); intval = (intval & signbit) == 0 ? intval & mask : -(intval & mask); val2 = new Value(intval, Value.INT8); } else { /* ----------debug head--------- *@*/ debugPrintError(threadId, "Invalid type conversion!"); // ----------debug tail---------- */ val2 = new Value(0, Value.INT8); } currentStackFrame.pushValue(val2); } public void executeLongCompare() { String opcode = "LCMP"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - executeLongCompare"); // ----------debug tail---------- */ Value val1 = currentStackFrame.popValue(); Value val2 = currentStackFrame.popValue(); boolean isSymbolic1 = val1.isType(Value.SYM); boolean isSymbolic2 = val2.isType(Value.SYM); if (!isSymbolic1 && !isSymbolic2) { long l1 = (Long) val1.getValue(); long l2 = (Long) val2.getValue(); int res = (l1 == l2) ? 0 : (l2 > l1) ? 1 : -1; currentStackFrame.pushValue(new Value(res, Value.INT32)); return; } com.microsoft.z3.BitVecExpr expr1 = isSymbolic1 ? (com.microsoft.z3.BitVecExpr) val1.getValue() : z3Context.mkBV((Long) val1.getValue(), 64); com.microsoft.z3.BitVecExpr expr2 = isSymbolic2 ? (com.microsoft.z3.BitVecExpr) val2.getValue() : z3Context.mkBV((Long) val2.getValue(), 64); com.microsoft.z3.BitVecExpr zero = z3Context.mkBV(0, 64); com.microsoft.z3.BitVecExpr posOne = z3Context.mkBV(1, 64); com.microsoft.z3.BitVecExpr negOne = z3Context.mkBV(-1, 64); com.microsoft.z3.Expr res = z3Context.mkITE( z3Context.mkEq(expr1, expr2), zero, z3Context.mkITE( z3Context.mkBVSGT(expr2, expr1), posOne, negOne)); currentStackFrame.pushValue(new Value(res, Value.SYM | Value.INT32)); } public void compareIntegerEquality(String opcode, int con1, int con2, int line, String method) { /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - compareIntegerEquality", con1, con2); // ----------debug tail---------- */ Value val2 = currentStackFrame.popValue(); Value val1 = currentStackFrame.popValue(); boolean sym2 = val2.isType(Value.SYM); boolean sym1 = val1.isType(Value.SYM); // get compare status boolean pathsel = con1 == con2; /* ----------debug head--------- *@*/ if (sym1 || sym2) { debugPrintBranch(threadId, opcode + " " + pathsel + " " + line + " " + method); } else { debugPrintInfo(threadId, DebugUtil.BRANCH, opcode + " " + pathsel + " " + line + " " + method); } // ----------debug tail---------- */ if (!sym2 && !sym1) { return; // ignore non-symbolic compares } Expr expr2 = Util.getBitVector(Value.INT32, val2, z3Context); Expr expr1 = Util.getBitVector(Value.INT32, val1, z3Context); BoolExpr expr3 = z3Context.mkEq(expr2, expr1); expr3 = pathsel ? expr3 : z3Context.mkNot(expr3); pathConstraints.add(expr3); /* ----------debug head--------- *@*/ debugPrintConstraint(threadId, "added " + opcode + " constraint: " + (pathsel ? "Eq" : "Eq + Not") + " for " + con1 + " ? " + con2); // ----------debug tail---------- */ solvePC(threadId, line, pathsel, ConstraintType.PATH); } public void compareIntegerGreaterThan(String opcode, int con1, int con2, int line, String method) { /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - compareIntegerGreaterThan", con1, con2); // ----------debug tail---------- */ Value val2 = currentStackFrame.popValue(); Value val1 = currentStackFrame.popValue(); boolean sym2 = val2.isType(Value.SYM); boolean sym1 = val1.isType(Value.SYM); // get compare status boolean pathsel = con1 > con2; // check if we are inverting the comparison result boolean dobranch = pathsel; if (opcode.equals("IFLE") || opcode.equals("IF_ICMPLE")) { dobranch = ! dobranch; } /* ----------debug head--------- *@*/ if (sym1 || sym2) { debugPrintBranch(threadId, opcode + " " + dobranch + " " + line + " " + method); } else { debugPrintInfo(threadId, DebugUtil.BRANCH, opcode + " " + dobranch + " " + line + " " + method); } // ----------debug tail---------- */ if (!sym2 && !sym1) { return; // ignore non-symbolic compares } BitVecExpr expr2 = Util.getBitVector(Value.INT32, val2, z3Context); BitVecExpr expr1 = Util.getBitVector(Value.INT32, val1, z3Context); BoolExpr expr3 = null; expr3 = pathsel ? z3Context.mkBVSGT(expr1, expr2) : z3Context.mkBVSLE(expr1, expr2); pathConstraints.add(expr3); /* ----------debug head--------- *@*/ debugPrintConstraint(threadId, "added " + opcode + " constraint: " + (pathsel ? "BVSGT" : "BVSLE") + " for " + con1 + " ? " + con2); // ----------debug tail---------- */ solvePC(threadId, line, dobranch, ConstraintType.PATH); } public void compareIntegerLessThan(String opcode, int con1, int con2, int line, String method) { /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - compareIntegerLessThan", con1, con2); // ----------debug tail---------- */ Value val2 = currentStackFrame.popValue(); Value val1 = currentStackFrame.popValue(); boolean sym2 = val2.isType(Value.SYM); boolean sym1 = val1.isType(Value.SYM); // get compare status boolean pathsel = con1 < con2; // check if we are inverting the comparison result boolean dobranch = pathsel; if (opcode.equals("IFGE") || opcode.equals("IF_ICMPGE")) { dobranch = ! dobranch; } /* ----------debug head--------- *@*/ if (sym1 || sym2) { debugPrintBranch(threadId, opcode + " " + dobranch + " " + line + " " + method); } else { debugPrintInfo(threadId, DebugUtil.BRANCH, opcode + " " + dobranch + " " + line + " " + method); } // ----------debug tail---------- */ if (!sym2 && !sym1) { return; // ignore non-symbolic compares } BitVecExpr expr2 = Util.getBitVector(Value.INT32, val2, z3Context); BitVecExpr expr1 = Util.getBitVector(Value.INT32, val1, z3Context); BoolExpr expr3 = pathsel ? z3Context.mkBVSLT(expr1, expr2) : z3Context.mkBVSGE(expr1, expr2); pathConstraints.add(expr3); /* ----------debug head--------- *@*/ debugPrintConstraint(threadId, "added " + opcode + " constraint: " + (pathsel ? "BVSLT" : "BVSGE") + " for " + con1 + " ? " + con2); // ----------debug tail---------- */ solvePC(threadId, line, dobranch, ConstraintType.PATH); } public void maxCompareIntegerLessThan(String opcode, int con1, int con2, int line, String method) { /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - maxCompareIntegerLessThan", con1, con2); // ----------debug tail---------- */ Value val2 = currentStackFrame.popValue(); Value val1 = currentStackFrame.popValue(); boolean sym2 = val2.isType(Value.SYM); boolean sym1 = val1.isType(Value.SYM); // get compare status boolean pathsel = con1 < con2; // check if we are inverting the comparison result boolean dobranch = pathsel; if (opcode.equals("IFGE") || opcode.equals("IF_ICMPGE")) { dobranch = ! dobranch; } /* ----------debug head--------- *@*/ if (sym1 || sym2) { debugPrintBranch(threadId, opcode + " " + dobranch + " " + line + " " + method); } else { debugPrintInfo(threadId, DebugUtil.BRANCH, opcode + " " + dobranch + " " + line + " " + method); } // ----------debug tail---------- */ if (!sym2 && !sym1) { return; // ignore non-symbolic compares } BitVecExpr expr2 = Util.getBitVector(Value.INT32, val2, z3Context); BitVecExpr expr1 = Util.getBitVector(Value.INT32, val1, z3Context); BoolExpr expr3 = pathsel ? z3Context.mkBVSLT(expr1, expr2) : z3Context.mkBVSGE(expr1, expr2); pathConstraints.add(expr3); /* ----------debug head--------- *@*/ debugPrintConstraint(threadId, "added " + opcode + " constraint: " + (pathsel ? "BVSLT" : "BVSGE") + " for " + con1 + " ? " + con2); // ----------debug tail---------- */ // try to maximize the loop bound if it's symbolic if (sym2) { z3Optimize.Push(); z3Optimize.MkMaximize(expr2); } solvePC(threadId, line, dobranch, ConstraintType.LOOPBOUND); if (sym2) { z3Optimize.Pop(); } } public void compareFloatGreater(String opcode) { /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - compareFloatGreater"); // ----------debug tail---------- */ Value val2 = currentStackFrame.popValue(); Value val1 = currentStackFrame.popValue(); boolean sym2 = val2.isType(Value.SYM); boolean sym1 = val1.isType(Value.SYM); if (!sym2 && !sym1) { float con2 = (Float) val2.getValue(); float con1 = (Float) val1.getValue(); int res = (con1 == con2) ? 0 : (con1 < con2 ? -1 : 1); currentStackFrame.pushValue((new Value(res, Value.INT32))); return; } ArithExpr expr2 = Util.getReal(val2, z3Context); ArithExpr expr1 = Util.getReal(val1, z3Context); BitVecExpr zero = z3Context.mkBV(0, 32); BitVecExpr negOne = z3Context.mkBV(-1, 32); BitVecExpr posOne = z3Context.mkBV(1, 32); Expr expr3 = z3Context.mkITE( z3Context.mkEq(expr1, expr2), zero, z3Context.mkITE( z3Context.mkLt(expr1, expr2), negOne, posOne)); currentStackFrame.pushValue(new Value(expr3, Value.SYM | Value.INT32)); } public void compareDoubleGreater(String opcode) { /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - compareDoubleGreater"); // ----------debug tail---------- */ Value val2 = currentStackFrame.popValue(); Value val1 = currentStackFrame.popValue(); boolean sym2 = val2.isType(Value.SYM); boolean sym1 = val1.isType(Value.SYM); if (!sym2 && !sym1) { double con2 = (Double) val2.getValue(); double con1 = (Double) val1.getValue(); int res = (con1 == con2) ? 0 : (con1 < con2 ? -1 : 1); currentStackFrame.pushValue((new Value(res, Value.INT32))); return; } ArithExpr expr2 = Util.getReal(val2, z3Context); ArithExpr expr1 = Util.getReal(val1, z3Context); BitVecExpr zero = z3Context.mkBV(0, 32); BitVecExpr negOne = z3Context.mkBV(-1, 32); BitVecExpr posOne = z3Context.mkBV(1, 32); Expr expr3 = z3Context.mkITE( z3Context.mkEq(expr1, expr2), zero, z3Context.mkITE( z3Context.mkLt(expr1, expr2), negOne, posOne)); currentStackFrame.pushValue(new Value(expr3, Value.SYM | Value.INT32)); } public void executeIfReferenceEqual(Object con1, Object con2, int line, String method) { String opcode = "IF_ACMPEQ"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - executeIfReferenceEqual", con1, con2); // ----------debug tail---------- */ Value ref2 = currentStackFrame.popValue(); Value ref1 = currentStackFrame.popValue(); if (ref2.getValue() == null || ref1.getValue() == null) { return; } boolean isSymbolic2 = ref2.isType(Value.SYM); boolean isSymbolic1 = ref1.isType(Value.SYM); boolean isEqual = con1 == con2; /* ----------debug head--------- *@*/ if (isSymbolic1 || isSymbolic2) { debugPrintBranch(threadId, opcode + " " + isEqual + " " + line + " " + method); } else { debugPrintInfo(threadId, DebugUtil.BRANCH, opcode + " " + isEqual + " " + line + " " + method); } // ----------debug tail---------- */ if (!isSymbolic1 && !isSymbolic2) { return; // ignore non-symbolic compares } Object rawVal2 = ref2.getValue(); Object rawVal1 = ref1.getValue(); com.microsoft.z3.BoolExpr expr = z3Context.mkEq((com.microsoft.z3.Expr) rawVal2, (com.microsoft.z3.Expr) rawVal1); expr = isEqual ? expr : z3Context.mkNot(expr); pathConstraints.add(expr); /* ----------debug head--------- *@*/ debugPrintConstraint(threadId, "added IF_ACMPEQ constraint: " + (isEqual ? "Eq" : "Eq + Not")); // ----------debug tail---------- */ solvePC(threadId, line, isEqual, ConstraintType.PATH); // TODO: construct symbolic counterpart of the concrete object } public void executeIfReferenceNotEqual(Object con1, Object con2, int line, String method) { String opcode = "IF_ACMPNE"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - executeIfReferenceNotEqual", con1, con2); // ----------debug tail---------- */ Value ref2 = currentStackFrame.popValue(); Value ref1 = currentStackFrame.popValue(); if (ref2.getValue() == null || ref1.getValue() == null) { return; } boolean isSymbolic2 = ref2.isType(Value.SYM); boolean isSymbolic1 = ref1.isType(Value.SYM); boolean isNotEqual = con1 != con2; /* ----------debug head--------- *@*/ if (isSymbolic1 || isSymbolic2) { debugPrintBranch(threadId, opcode + " " + isNotEqual + " " + line + " " + method); } else { debugPrintInfo(threadId, DebugUtil.BRANCH, opcode + " " + isNotEqual + " " + line + " " + method); } // ----------debug tail---------- */ if (!isSymbolic1 && !isSymbolic2) { return; // ignore non-symbolic compares } // if (isSymbolic1 && isSymbolic2) { Object rawVal2 = ref2.getValue(); Object rawVal1 = ref1.getValue(); com.microsoft.z3.BoolExpr expr = z3Context.mkEq((com.microsoft.z3.Expr) rawVal2, (com.microsoft.z3.Expr) rawVal1); expr = isNotEqual ? expr : z3Context.mkNot(expr); pathConstraints.add(expr); /* ----------debug head--------- *@*/ debugPrintConstraint(threadId, "added IF_ACMPNE constraint: " + (isNotEqual ? "Eq" : "Eq + Not")); // ----------debug tail---------- */ solvePC(threadId, line, isNotEqual, ConstraintType.PATH); // } // TODO: construct symbolic counterpart of the concrete object } public void executeIfReferenceNull(Object con1) { String opcode = "IFNULL"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - executeIfReferenceNull", con1); // ----------debug tail---------- */ Value val = currentStackFrame.popValue(); /* ----------debug head--------- *@*/ if (val != null && val.isType(Value.SYM)) { debugPrintWarning(threadId, "Warning: not handling symbolic null reference comparison."); } // ----------debug tail---------- */ } public void executeIfReferenceNonNull(Object con1) { String opcode = "IFNONNULL"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - executeIfReferenceNonNull", con1); // ----------debug tail---------- */ Value val = currentStackFrame.popValue(); /* ----------debug head--------- *@*/ if (val != null && val.isType(Value.SYM)) { debugPrintWarning(threadId, "Warning: not handling symbolic null reference comparison."); } // ----------debug tail---------- */ } public void returnReference() { String opcode = "ARETURN"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - returnReference"); debugPrintCallExit(threadId); // ----------debug tail---------- */ } public void returnDouble() { String opcode = "DRETURN"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - returnDouble"); debugPrintCallExit(threadId); // ----------debug tail---------- */ } public void returnFloat() { String opcode = "FRETURN"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - returnFloat"); debugPrintCallExit(threadId); // ----------debug tail---------- */ } public void returnInteger() { String opcode = "IRETURN"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - returnInteger"); debugPrintCallExit(threadId); // ----------debug tail---------- */ } public void returnLong() { String opcode = "LRETURN"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - returnLong"); debugPrintCallExit(threadId); // ----------debug tail---------- */ } public void returnVoid() { String opcode = "RETURN"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - returnVoid"); debugPrintCallExit(threadId); // ----------debug tail---------- */ } public void returnStaticVoid() { String opcode = "RETURN"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - returnStaticVoid"); debugPrintCallExit(threadId); // ----------debug tail---------- */ } public void getField(Object conObj, String fieldName, String fieldType) { String opcode = "GETFIELD"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - getField", fieldName, fieldType); debugPrintInfo(threadId, DebugUtil.COMMAND, " concrete data type: " + DataConvert.getClassType(conObj)); // ----------debug tail---------- */ Value ref = currentStackFrame.popValue(); assertValueNonNull(ref, opcode, "ref"); // DON'T COMMENT OUT! - this checks for fatal error & dumps stack contents if so. if (ref.getValue() == null) { exitError("getField: field entry '" + fieldName + "' - stack value is null, must be a refCnt"); return; } // verify the entry is an Integer type assertUnsignedIntValue(ref, opcode, "objectMap index"); Integer objCnt = (Integer) ref.getValue(); Map<String, Value> obj = ExecWrapper.getReferenceObject(objCnt); if (obj == null) { exitError("getField: field entry '" + fieldName + "' - object value is null"); return; } Value field = obj.get(fieldName); // Multiple contexts due to multithreading if (field != null && field.isType(Value.SYM)) { // if entry is a reference (to an array or object), just return the reference value. // Otherwise it is a symbolic expression that we need to translate and return. if (!DataConvert.getClassType(field.getValue()).equals("java.lang.Integer")) { // NOTE: THIS USES REFLECTION Expr expr = (Expr)field.getValue(); field = new Value(expr.translate(z3Context), field.getType()); /* ----------debug head--------- *@*/ debugPrintInfo(threadId, DebugUtil.COMMAND, "Converted to new context!"); // ----------debug tail---------- */ } } if (field == null) { /* ----------debug head--------- *@*/ debugPrintInfo(threadId, DebugUtil.COMMAND, "- Field not found: " + fieldName); // ----------debug tail---------- */ // determine if the field is an array if (fieldType.startsWith("[")) { // create a new array of primitives. // initially make it a size of 1 (we will fix the size later, when we know it) but // set the size value to 0, so we will know to update it. int elementType = DataConvert.getValueDataType(fieldType) & ~(Value.ARY | Value.MARY | Value.SYM); Value[] arraynew = Util.makeValueArray(threadId, elementType, 1, null); // place it in a combo and add to array map (set size to 0 since it is unknown) field = putArrayCombo(arraynew, new Value(0, Value.INT32), elementType, false); } else { // determine if the field is a primitive or string switch(fieldType) { case "Z": field = new Value((Boolean) conObj, Value.BLN); break; case "C": field = new Value((Character) conObj, Value.CHR); break; case "B": field = new Value((Byte) conObj, Value.INT8); break; case "S": field = new Value((Short) conObj, Value.INT16); break; case "I": field = new Value((Integer) conObj, Value.INT32); break; case "J": field = new Value((Long) conObj, Value.INT64); break; case "F": field = new Value((Float) conObj, Value.FLT); break; case "D": field = new Value((Double) conObj, Value.DBL); break; case "Ljava/lang/String;": field = new Value((String) conObj, Value.STR); break; default: // field is an object - create a new reference entry for the field Integer newCnt = ExecWrapper.putReferenceObject(new HashMap<>()); field = new Value(newCnt, Value.REF); /* ----------debug head--------- *@*/ debugPrintObjectField(threadId, objCnt, fieldName, field); // ----------debug tail---------- */ break; } } // add the entry to list of fields for the object obj.put(fieldName, field); } /* ----------debug head--------- *@*/ debugPrintObjectMap(threadId, objCnt, obj); // ----------debug tail---------- */ currentStackFrame.pushValue(field); } // who is to blame: zzk public void putField(String fieldName) { String opcode = "PUTFIELD"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - putField", fieldName); // ----------debug tail---------- */ Value val = currentStackFrame.popValue(); Value ref = currentStackFrame.popValue(); // verify the entry is an Integer type assertUnsignedIntValue(ref, opcode, "objectMap index"); Integer objCnt = (Integer) ref.getValue(); Map<String, Value> obj = ExecWrapper.getReferenceObject(objCnt); if (obj == null) { exitError("putField: field entry '" + fieldName + "' - object value is null"); return; } obj.put(fieldName, val); /* ----------debug head--------- *@*/ debugPrintObjectField(threadId, objCnt, fieldName, val); // ----------debug tail---------- */ } // who is to blame: zzk public void getStaticField(String fieldName, String fieldType) { String opcode = "GETSTATIC"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - getStaticField", fieldName, fieldType); // ----------debug tail---------- */ Value staticField = ExecWrapper.getStaticFieldObject(fieldName); if (staticField == null) { /* ----------debug head--------- *@*/ debugPrintInfo(threadId, DebugUtil.COMMAND, fieldName + " field not found - creating null field"); // ----------debug tail---------- */ // determine if the field is an array if (fieldType.startsWith("[")) { // create a new array of primitives. // initially make it a size of 1 (we will fix the size later, when we know it) but // set the size value to 0, so we will know to update it. int elementType = DataConvert.getValueDataType(fieldType) & ~(Value.ARY | Value.MARY | Value.SYM); Value[] arraynew = Util.makeValueArray(threadId, elementType, 1, null); // place it in a combo and add to array map (set size to 0 since it is unknown) staticField = putArrayCombo(arraynew, new Value(0, Value.INT32), elementType, false); } else { // determine if the field is a primitive or string switch(fieldType) { case "Z": staticField = new Value(null, Value.BLN); break; case "C": staticField = new Value(null, Value.CHR); break; case "B": staticField = new Value(null, Value.INT8); break; case "S": staticField = new Value(null, Value.INT16); break; case "I": staticField = new Value(null, Value.INT32); break; case "J": staticField = new Value(null, Value.INT64); break; case "F": staticField = new Value(null, Value.FLT); break; case "D": staticField = new Value(null, Value.DBL); break; case "Ljava/lang/String;": staticField = new Value(null, Value.STR); break; default: // field is an object - create a new reference entry for the field Integer objCnt = ExecWrapper.putReferenceObject(new HashMap<>()); staticField = new Value(objCnt, Value.REF); /* ----------debug head--------- *@*/ debugPrintObjectField(threadId, objCnt, fieldName + " (static)", null); // ----------debug tail---------- */ break; } } // add the entry to list of fields for the object ExecWrapper.putStaticFieldObject(fieldName, staticField); } currentStackFrame.pushValue(staticField); } // who is to blame: zzk public void putStaticField(String fieldName) { String opcode = "PUTSTATIC"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - putStaticField", fieldName); // ----------debug tail---------- */ Value val = currentStackFrame.popValue(); ExecWrapper.putStaticFieldObject(fieldName, val); } // who is to blame: zzk public void newArray(int type) { String opcode = "ANEWARRAY"; /* ----------debug head--------- *@*/ debugPrintCommand_type(threadId, opcode + " - newArray", type, currentStackFrame.peekValue(0)); // ----------debug tail---------- */ if (type == 0) { exitError("newArray: (" + opcode + ") specified type is 0"); return; } // all arrays (symbolic/concrete) are packaged in a combo structure // if the size is symbolic, we have to introduce a symbolic array; otherwise, concrete Value size = currentStackFrame.popValue(); if (size.isType(Value.SYM)) { // if type is STR, make a symbolic string array // if type is FLT/DBL, make a symbolic real array // otherwise, type is REF/BLN/INT8/INT16/INT32/INT64/CHR, make a symbolic integer array ArrayExpr core = null; if ((type & Value.STR) != 0) { core = z3Context.mkArrayConst("array", z3Context.mkBitVecSort(32), z3Context.mkStringSort()); } else if ((type & Value.FLT) != 0 || (type & Value.DBL) != 0) { core = z3Context.mkArrayConst("array", z3Context.mkBitVecSort(32), z3Context.mkRealSort()); } else if ((type & Value.INT64) != 0) { core = z3Context.mkArrayConst("array", z3Context.mkBitVecSort(32), z3Context.mkBitVecSort(64)); } else { core = z3Context.mkArrayConst("array", z3Context.mkBitVecSort(32), z3Context.mkBitVecSort(32)); } // create the array object entry in arrayMap and return reference to it Value arrayVal = putArrayCombo(core, size, type, true); currentStackFrame.pushValue(arrayVal); } else { // verify the entry is an Integer type assertUnsignedIntValue(size, opcode, "array size"); // make a Value array with the concrete size and fill in each entry with default values Value[] core = NativeCode.newArrayNative((Integer) size.getValue(), type); // create the array object entry in arrayMap and return reference to it Value arrayVal = putArrayCombo(core, size, type, false); currentStackFrame.pushValue(arrayVal); } } public void multiNewArray(int type, int dimensions) { String opcode = "MULTIANEWARRAY"; /* ----------debug head--------- *@*/ debugPrintCommand_type(threadId, opcode + " - multiNewArray", type, dimensions + ""); // ----------debug tail---------- */ // type will never have ARY or MARY bits set if (type == 0) { exitError("multiNewArray: (" + opcode + ") specified type is 0"); return; } // TODO: ignoring symbolic case for now // get the total array size (the size of each dimension is pulled from stack) ArrayList<Integer> dimArray = new ArrayList<>(); for (int ix = 0; ix < dimensions; ix++) { Value valSize = currentStackFrame.popValue(); assertUnsignedIntValue(valSize, opcode, "multi-dim array size"); Integer dimSize = (Integer) valSize.getValue(); dimArray.add(dimSize); } // create the multi-dimension array structure and return reference to it Value arrayVal = makeNewArrayCombo(dimArray, type); Value multiArray = makeNewMultiArray(arrayVal, dimArray, type); currentStackFrame.pushValue(multiArray); } public void arrayLength(int length) { String opcode = "ARRAYLENGTH"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - arrayLength", length); // ----------debug tail---------- */ // in case the array has not been allocated, default length to 0 Value array = currentStackFrame.popValue(); Value conLength = null; if (array.isType(Value.SYM)) { // if symbolic, use size from symbolic stack if (array.isType(Value.MARY)) { // get the info for the multi-dimensional array Integer key = (Integer) array.getValue(); ExecWrapper.MultiArrayInfo info = ExecWrapper.getMultiArrayInfo(key); if (info == null) { exitError("arrayLength: multi-array reference not found for: " + key); return; } ArrayList<Integer> dimensions = ExecWrapper.getMultiArraySizes(info.arrayRef); if (dimensions == null) { exitError("arrayLength: array reference not found for: " + info.arrayRef); return; } if (!dimensions.isEmpty()) { int offset = dimensions.size() - info.dim; int dimlength = offset < 0 ? 0 : dimensions.get(offset); conLength = new Value(dimlength, Value.INT32); } } else { Value[] combo = getArrayCombo(array, 0); conLength = combo[1]; } } else { // if not symbolic, use the concrete length value conLength = new Value(length, Value.INT32); // update the array length from the length of the concrete value if length is incorrect if (!array.isType(Value.MARY)) { Value[] combo = getArrayCombo(array, 0); updateValueArrayLength(combo, length, array.getValue()); } } currentStackFrame.pushValue(conLength); } public void checkInstanceOf() { String opcode = "INSTANCEOF"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - checkInstanceOf"); // ----------debug tail---------- */ // we do nothing here, let concrete execution decides whether instanceof is true or false currentStackFrame.popValue(); } public void invoke(String opcode, String fullmethod) { /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - " + fullmethod); // ----------debug tail---------- */ } public void invoke(Object conObj, int parmCount, String opcode, String fullmethod) { /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - " + fullmethod); // ----------debug tail---------- */ // pop off arguments for (int ix = 0; ix < parmCount; ix++) { currentStackFrame.popValue(); } // push return value currentStackFrame.pushValue(new Value(conObj, Value.DBL)); } public void invokeDynamicEnter() { String opcode = "INVOKEDYNAMIC"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - enter"); // ----------debug tail---------- */ // the following allows us to mark the agent log output when we enter/exit the INVOKEDYNAMIC //System.out.println("Executor.invokeDynamic - enter"); // set flag to prevent agent Enter/Exit method calls from modifying stack invokeDynamic = true; } public void invokeDynamicExit(Object conObj) { String opcode = "INVOKEDYNAMIC"; /* ----------debug head--------- *@*/ debugPrintCommand(threadId, opcode + " - exit - return: " + DataConvert.getClassType(conObj)); // ----------debug tail---------- */ // the following allows us to mark the agent log output when we enter/exit the INVOKEDYNAMIC //System.out.println("Executor.invokeDynamic - exit"); Value stackVal; stackVal = Util.makeNewRefValue(threadId, conObj); currentStackFrame.pushValue(stackVal); // restore flag for handling stack on method Enter/Exit calls invokeDynamic = false; } public void catchException(Throwable except, int line, String fullName) { /* ----------debug head--------- *@*/ debugPrintException(threadId, except.toString(), line, fullName); // ----------debug tail---------- */ // check if entry was in concrete list. if not, create new entry Value val = Util.makeNewRefValue(threadId, except); while (!currentStackFrame.getMethodName().equals(fullName) && !executionStack.empty()) { currentStackFrame = executionStack.pop(); if (currentStackFrame != null) { currentStackFrame.setStackLevel(executionStack.size()); } /* ----------debug head--------- *@*/ debugPrintStackRestore(threadId, currentStackFrame.getMethodName(), executionStack.size()); // ----------debug tail---------- */ } // clear out the stack frame in which the exception is handled & push the exception object while (!currentStackFrame.isEmpty()) { currentStackFrame.popValue(); } currentStackFrame.pushValue(val); } //================================================================ // DANHELPER AGENT CALLBACK METHODS //================================================================ // caller and callee both instrumented public void popFrameAndPush(boolean isVoid, boolean except) { /* ----------debug head--------- *@*/ debugPrintAgent(threadId, "I-I Exit - popFrameAndPush: isVoid = " + isVoid + ", except = " + except); // ----------debug tail---------- */ if (executionStack.empty()) { exitError("popFrameAndPush: executionStack empty!"); } if (isVoid || except) { currentStackFrame = executionStack.pop(); if (currentStackFrame != null) { currentStackFrame.setStackLevel(executionStack.size()); } } else { Value val = currentStackFrame.popValue(); currentStackFrame = executionStack.pop(); if (currentStackFrame != null) { currentStackFrame.setStackLevel(executionStack.size()); } currentStackFrame.pushValue(val); } /* ----------debug head--------- *@*/ debugPrintStackRestore(threadId, currentStackFrame.getMethodName(), executionStack.size()); // ----------debug tail---------- */ } public void createFrame(int numParams, int maxLocals) { /* ----------debug head--------- *@*/ debugPrintAgent(threadId, "I-I Enter - createFrame: numParams = " + numParams + ", maxLocals = " + maxLocals); // ----------debug tail---------- */ Deque<Value> valDeck = new LinkedList<>(); for (int i = 0; i < numParams; ++i) { Value val = currentStackFrame.popValue(); valDeck.addFirst(val); } executionStack.push(currentStackFrame); currentStackFrame = new StackFrame("dummy", maxLocals, threadId, executionStack.size()); int index = 0; for (Value val : valDeck) { currentStackFrame.storeLocalVariable(index, val); // accomodate indexing offsets following a double or long if (val != null & val.isType(Value.INT64 | Value.DBL)) { index += 2; } else { ++index; } } } // caller uninstrumented, callee instrumented public void popFrame(boolean except) { /* ----------debug head--------- *@*/ debugPrintAgent(threadId, "I-U Exit - popFrame: except = " + except); // ----------debug tail---------- */ if (!executionStack.isEmpty()) { currentStackFrame = executionStack.pop(); if (currentStackFrame != null) { currentStackFrame.setStackLevel(executionStack.size()); } /* ----------debug head--------- *@*/ debugPrintStackRestore(threadId, currentStackFrame == null ? "null" : currentStackFrame.getMethodName(), executionStack.size()); // ----------debug tail---------- */ } } public void addBooleanParameter(boolean b, int slot) { /* ----------debug head--------- *@*/ debugPrintAgent(threadId, "U-I Enter - addBooleanParameter: slot = " + slot + ", val = " + b); // ----------debug tail---------- */ currentStackFrame.storeLocalVariable(slot, new Value(b, Value.BLN)); } public void addCharParameter(char c, int slot) { /* ----------debug head--------- *@*/ debugPrintAgent(threadId, "U-I Enter - addCharParameter: slot = " + slot + ", val = " + c); // ----------debug tail---------- */ currentStackFrame.storeLocalVariable(slot, new Value(c, Value.CHR)); } public void addByteParameter(byte b, int slot) { /* ----------debug head--------- *@*/ debugPrintAgent(threadId, "U-I Enter - addByteParameter: slot = " + slot + ", val = " + b); // ----------debug tail---------- */ currentStackFrame.storeLocalVariable(slot, new Value(b, Value.INT8)); } public void addShortParameter(short s, int slot) { /* ----------debug head--------- *@*/ debugPrintAgent(threadId, "U-I Enter - addShortParameter: slot = " + slot + ", val = " + s); // ----------debug tail---------- */ currentStackFrame.storeLocalVariable(slot, new Value(s, Value.INT16)); } public void addIntegerParameter(int i, int slot) { /* ----------debug head--------- *@*/ debugPrintAgent(threadId, "U-I Enter - addIntegerParameter: slot = " + slot + ", val = " + i); // ----------debug tail---------- */ currentStackFrame.storeLocalVariable(slot, new Value(i, Value.INT32)); } public void addLongParameter(long l, int slot) { /* ----------debug head--------- *@*/ debugPrintAgent(threadId, "U-I Enter - addLongParameter: slot = " + slot + ", val = " + l); // ----------debug tail---------- */ currentStackFrame.storeLocalVariable(slot, new Value(l, Value.INT64)); } public void addFloatParameter(float f, int slot) { /* ----------debug head--------- *@*/ debugPrintAgent(threadId, "U-I Enter - addFloatParameter: slot = " + slot + ", val = " + f); // ----------debug tail---------- */ currentStackFrame.storeLocalVariable(slot, new Value(f, Value.FLT)); } public void addDoubleParameter(double d, int slot) { /* ----------debug head--------- *@*/ debugPrintAgent(threadId, "U-I Enter - addDoubleParameter: slot = " + slot + ", val = " + d); // ----------debug tail---------- */ currentStackFrame.storeLocalVariable(slot, new Value(d, Value.DBL)); } public void addObjectParameter(Object obj, int slot) { /* ----------debug head--------- *@*/ // package the object in a Value so we can display the contents int type = DataConvert.getClassType(obj).equals("java.lang.String") ? Value.STR : Value.REF; String showVal = DataConvert.valueToString(new Value(obj, type)); debugPrintAgent(threadId, "U-I Enter - addObjectParameter: slot = " + slot + ", val = " + showVal); // ----------debug tail---------- */ Value stackVal = Util.makeNewRefValue(threadId, obj); currentStackFrame.storeLocalVariable(slot, stackVal); } public void addArrayParameter(Object arr, int slot, int depth, int type) { /* ----------debug head--------- *@*/ debugPrintAgent(threadId, "U-I Enter - addArrayParameter: slot = " + slot + ", depth = " + depth + ", type = " + DataConvert.showValueDataType(type)); // + ", val = " + arr); // ----------debug tail---------- */ if (arr == null) { exitError("addArrayParameter: array value was null"); return; } Value newarr; // check the number of dimensions of the array if (depth == 1) { // simple array: create a Value-array from the array of primitives or Objects newarr = makeReturnArray(arr, type); } else { // multi-dimensional: extract the size of each dimension from the concrete object ArrayList<Integer> dimArray = new ArrayList<>(); Object[] marray = (Object[]) arr; // first time thru, convert object to array of level 1 for (int ix = 0; ix < depth; ix++) { if (ix > 0) { // subsequent times thru, convert current object into array of level 1 marray = (Object[]) marray[0]; } Integer dimSize = marray.length; dimArray.add(dimSize); /* ----------debug head--------- *@*/ debugPrintInfo(threadId, DebugUtil.ARRAYS, "addArrayParameter: level " + ix + ": " + dimSize); // ----------debug tail---------- */ } // now create the multi-dim array Value arrayVal = makeNewArrayCombo(dimArray, type); newarr = makeNewMultiArray(arrayVal, dimArray, type); } currentStackFrame.storeLocalVariable(slot, newarr); } public void beginFrame(int maxLocals) { /* ----------debug head--------- *@*/ debugPrintAgent(threadId, "U-I Enter - beginFrame: maxLocals = " + maxLocals); // ----------debug tail---------- */ executionStack.push(currentStackFrame); if (currentStackFrame != null) { currentStackFrame.setStackLevel(executionStack.size()); } currentStackFrame = new StackFrame("dummy", maxLocals, threadId, executionStack.size()); } public void pushIntegralType(int val, int type) { /* ----------debug head--------- *@*/ debugPrintAgent(threadId, "U-I Exit - pushIntegralType: val = " + val + ", type = " + DataConvert.showValueDataType(type)); // ----------debug tail---------- */ if (needReturnValue) { currentStackFrame.pushValue(new Value(val, type)); } needReturnValue = true; } public void pushLongType(long val, int type) { /* ----------debug head--------- *@*/ debugPrintAgent(threadId, "U-I Exit - pushLonglType: val = " + val + ", type = " + DataConvert.showValueDataType(type)); // ----------debug tail---------- */ currentStackFrame.pushValue(new Value(val, Value.INT64)); } public void pushFloatType(float val, int type) { /* ----------debug head--------- *@*/ debugPrintAgent(threadId, "U-I Exit - pushFloatType: val = " + val + ", type = " + DataConvert.showValueDataType(type)); // ----------debug tail---------- */ currentStackFrame.pushValue(new Value(val, Value.FLT)); } public void pushDoubleType(double val, int type) { /* ----------debug head--------- *@*/ debugPrintAgent(threadId, "U-I Exit - pushDoubleType: val = " + val + ", type = " + DataConvert.showValueDataType(type)); // ----------debug tail---------- */ currentStackFrame.pushValue(new Value(val, Value.DBL)); } public void pushReferenceType(Object val, int type) { /* ----------debug head--------- *@*/ debugPrintAgent(threadId, "U-I Exit - pushReferenceType: type = " + DataConvert.showValueDataType(type)); // ----------debug tail---------- */ // exit if we are running an INVOKEDYNAMIC opcode if (invokeDynamic) { return; } if (needReturnValue) { Value stackVal; if (type != Value.REF) { // this would be the STR type /* ----------debug head--------- *@*/ debugPrintInfo(threadId, DebugUtil.AGENT, " object: " + (String) val); // ----------debug tail---------- */ stackVal = new Value(val, type); } else if (val == null) { /* ----------debug head--------- *@*/ debugPrintInfo(threadId, DebugUtil.AGENT, " object: null"); // ----------debug tail---------- */ stackVal = Util.makeNewRefValue(threadId, val); } else { // for REF type, we need to verify whether this is truly a REF or maybe an array or boxed // primitive - it was only marked as REF because the signature of the method was an // object type (i.e. was of the "Lxxxxx;" foemat). However, this could have been // Ljava.lang.Long; which is a boxed primitive or an array object. We must use reflection // here to determine this from the actual object itself (if it's not null, of course). // reflectively get the object's class String classType = DataConvert.getClassType(val); // NOTE: THIS USES REFLECTION /* ----------debug head--------- *@*/ debugPrintInfo(threadId, DebugUtil.AGENT, " class: " + classType); // ----------debug tail---------- */ // if it is an array, we will handle it as such instead of as a reference int depth = 0; type = DataConvert.getValueDataType(classType) & ~(Value.ARY | Value.MARY); while (classType.startsWith("[")) { classType = classType.substring(1); ++depth; } if (depth > 1) { // multi-dimensional array stackVal = makeReturnMultiArray(val, type, depth); } else if (depth > 0) { // array value stackVal = makeReturnArray(val, type); } else { // reference value stackVal = Util.makeNewRefValue(threadId, val); } } currentStackFrame.pushValue(stackVal); } needReturnValue = true; } public void pushArrayType(Object val, int type, int depth) { /* ----------debug head--------- *@*/ debugPrintAgent(threadId, "U-I Exit - pushArrayType: type = " + DataConvert.showValueDataType(type) + ", depth = " + depth); // ----------debug tail---------- */ if (val == null) { exitError("pushArrayType: array object is null"); } Value ary; if (depth > 1) { ary = makeReturnMultiArray(val, type, depth); } else { ary = makeReturnArray(val, type); } currentStackFrame.pushValue(ary); } public void pushVoidType() { /* ----------debug head--------- *@*/ debugPrintAgent(threadId, "U-I Exit - pushVoidType"); // ----------debug tail---------- */ } public void objectCloneExit() { /* ----------debug head--------- *@*/ debugPrintAgent(threadId, "U-I Exit - objectCloneExit"); // ----------debug tail---------- */ } public void exception() { /* ----------debug head--------- *@*/ debugPrintAgent(threadId, "U-I Exit - exception"); // ----------debug tail---------- */ } public void removeParams(int numParams) { /* ----------debug head--------- *@*/ debugPrintAgent(threadId, "I-U Enter - removeParams: numParams = " + numParams); // ----------debug tail---------- */ // exit if we are running an INVOKEDYNAMIC opcode if (invokeDynamic) { return; } for (int i = 0; i < numParams; i++) { currentStackFrame.popValue(); } } public void objectCloneEnter() { /* ----------debug head--------- *@*/ debugPrintAgent(threadId, "I-U Enter - objectCloneEnter"); // ----------debug tail---------- */ Value val = currentStackFrame.popValue(); int type = val.getType(); if (type == Value.REF) { // reference type // get the object being cloned assertUnsignedIntValue(val, "objectCloneEnter", "objectMap index"); Integer refCnt = (Integer) val.getValue(); Map<String, Value> obj = ExecWrapper.getReferenceObject(refCnt); // create a new object reference and set its value equal to the previous int objCnt = ExecWrapper.putReferenceObject(obj); /* ----------debug head--------- *@*/ debugPrintObjectMap(threadId, objCnt, obj); // ----------debug tail---------- */ // return the cloned reference object on the stack currentStackFrame.pushValue(new Value(objCnt, Value.REF)); } else if ((type & Value.ARY) != 0) { // array type // get the array being cloned Value[] refcombo = getArrayCombo(val, type); // create a new array reference and set its value equal to the previous Object array = refcombo[0].getValue(); int arrtype = refcombo[0].getType(); Value size = refcombo[1]; boolean isSymbolic = array instanceof com.microsoft.z3.ArrayExpr; Value arrayVal = putArrayCombo(array, size, arrtype, isSymbolic); // return the cloned array object on the stack currentStackFrame.pushValue(arrayVal); } else if ((type & Value.MARY) != 0) { // create a new multi-array and copy the info to it Value multiArray = cloneMultiArray((Integer) val.getValue()); // return the cloned multi-array object on the stack currentStackFrame.pushValue(multiArray); } else { exitError("objectCloneEnter: Invalid object type being cloned: " + DataConvert.showValueDataType(type)); } // (NOTE: this function performs both the I-U Entry and the U-I Exit functionality because // we won't have access to the info to push onto the stack unless we do it here. // We compensate by not doing anything for the Exit function.) } public void stringLength() { /* ----------debug head--------- *@*/ debugPrintAgent(threadId, "I-U Enter - stringLength"); // ----------debug tail---------- */ Value val = currentStackFrame.popValue(); if (val.isType(Value.SYM) && val.isType(Value.STR)) { // System.out.println("Pushing symbolic length onto stack!"); com.microsoft.z3.SeqExpr expr = (com.microsoft.z3.SeqExpr) val.getValue(); BitVecExpr bvExpr = z3Context.mkInt2BV(32, z3Context.mkLength(expr)); currentStackFrame.pushValue(new Value(bvExpr, Value.INT32 | Value.SYM)); needReturnValue = false; } } public void stringEquals(String conStr1, Object conObj) { /* ----------debug head--------- *@*/ debugPrintAgent(threadId, "I-U Enter - stringEqualsMethod"); // ----------debug tail---------- */ Value str2 = currentStackFrame.popValue(); Value str1 = currentStackFrame.popValue(); if (!(conObj instanceof String)) return; String conStr2 = (String) conObj; // System.out.println("Concrete string is: " + conStr2); if (!str1.isType(Value.SYM) && !str2.isType(Value.SYM)) { // System.out.println("No symbolics in string equals"); return; } com.microsoft.z3.Expr expr1 = str1.isType(Value.SYM) ? (com.microsoft.z3.Expr) str1.getValue() : z3Context.mkString(conStr1); com.microsoft.z3.Expr expr2 = str2.isType(Value.SYM) ? (com.microsoft.z3.Expr) str2.getValue() : z3Context.mkString(conStr2); com.microsoft.z3.Expr expr3 = z3Context.mkITE(z3Context.mkEq(expr1, expr2), z3Context.mkBV(1, 32), z3Context.mkBV(0, 32)); currentStackFrame.pushValue(new Value(expr3, Value.SYM | Value.BLN)); needReturnValue = false; } public void stringSubstring(String conStr, int conOffset) { /* ----------debug head--------- *@*/ debugPrintAgent(threadId, "I-U Enter - stringSubstringMethod"); // ----------debug tail---------- */ Value off = currentStackFrame.popValue(); Value str = currentStackFrame.popValue(); if (!off.isType(Value.SYM) && !str.isType(Value.SYM)) { // System.out.println("No symbolics in string substring"); return; } else if (off.isType(Value.SYM) && str.isType(Value.SYM)) { com.microsoft.z3.BitVecExpr symOff = (com.microsoft.z3.BitVecExpr) off.getValue(); com.microsoft.z3.SeqExpr symStr = (com.microsoft.z3.SeqExpr) str.getValue(); com.microsoft.z3.SeqExpr symRes //= z3Context.mkExtract(symStr, z3Context.mkInt(0), z3Context.mkBV2Int(symOff, true)); = z3Context.mkExtract(symStr, z3Context.mkBV2Int(symOff, true), (IntExpr) z3Context.mkSub( z3Context.mkLength(symStr), z3Context.mkBV2Int(symOff, true))); currentStackFrame.pushValue(new Value(symRes, Value.SYM | Value.STR)); } else if (off.isType(Value.SYM)) { com.microsoft.z3.BitVecExpr symOff = (com.microsoft.z3.BitVecExpr) off.getValue(); com.microsoft.z3.SeqExpr symStr = z3Context.mkString(conStr); com.microsoft.z3.SeqExpr symRes //= z3Context.mkExtract(symStr, z3Context.mkInt(0), z3Context.mkBV2Int(symOff, true)); = z3Context.mkExtract(symStr, z3Context.mkBV2Int(symOff, true), (IntExpr) z3Context.mkSub( z3Context.mkLength(symStr), z3Context.mkBV2Int(symOff, true))); currentStackFrame.pushValue(new Value(symRes, Value.SYM | Value.STR)); } else { com.microsoft.z3.SeqExpr symStr = (com.microsoft.z3.SeqExpr) str.getValue(); com.microsoft.z3.IntExpr symLen = z3Context.mkLength(symStr); // TODO: Z3 bug causes some solutions to be printed as "" // The line below will test that it can find a valid solution //symLen = (IntExpr) z3Context.mkSub(symLen, z3Context.mkInt(1)); com.microsoft.z3.IntExpr symOff = z3Context.mkInt(conOffset); com.microsoft.z3.IntExpr symSize = (com.microsoft.z3.IntExpr) z3Context.mkSub(symLen, symOff); com.microsoft.z3.SeqExpr symRes = z3Context.mkExtract(symStr, symOff, symSize); currentStackFrame.pushValue(new Value(symRes, Value.SYM | Value.STR)); } System.out.println("Pushed symbolic substring onto stack!"); needReturnValue = false; } public void bufferedImageGetRGB(Object objImage, int x, int y) { // System.out.println("Inside symbolic buffered image"); Value symY = currentStackFrame.popValue(); Value symX = currentStackFrame.popValue(); Value symImage = currentStackFrame.popValue(); boolean bSym = symImage.isType(Value.SYM); /* ----------debug head--------- *@*/ debugPrintAgent(threadId, "I-U Enter - bufferedImageGetRGB: (" + x + "," + y + ") = " + (bSym ? "(Symbolic)" : "(Concrete)")); // ----------debug tail---------- */ if (!bSym) { return; } System.out.println("bufferedImageGetRGB: symbolic: (" + x + "," + y + ")"); java.awt.image.BufferedImage image = (java.awt.image.BufferedImage)objImage; Value[][] pixels = null; if (bufferedImageMap.containsKey(objImage)) { pixels = bufferedImageMap.get(objImage); } else { int width = image.getWidth(); int height = image.getHeight(); pixels = new Value[width][height]; for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { pixels[i][j] = new Value(makeLong("x_" + i + "_y_" + j, Value.INT32), Value.INT32 | Value.SYM); } } bufferedImageMap.put(image, pixels); } currentStackFrame.pushValue(pixels[x][y]); needReturnValue = false; } public void bufferedImageSetRGB(Object objImage, int x, int y, int rgb) { // System.out.println("Inside symbolic buffered image set rgb"); Value symRGB = currentStackFrame.popValue(); Value symY = currentStackFrame.popValue(); Value symX = currentStackFrame.popValue(); Value symImage = currentStackFrame.popValue(); boolean bSym = symImage.isType(Value.SYM); /* ----------debug head--------- *@*/ debugPrintAgent(threadId, "I-U Enter - bufferedImageSetRGB: (" + x + "," + y + ") = " + rgb + (bSym ? "(Symbolic)" : "(Concrete)")); // ----------debug tail---------- */ if (!bSym) { return; } System.out.println("bufferedImageSetRGB: symbolic: (" + x + "," + y + ") = " + rgb); java.awt.image.BufferedImage image = (java.awt.image.BufferedImage)objImage; Value[][] pixels = null; if (bufferedImageMap.containsKey(objImage)) { pixels = bufferedImageMap.get(objImage); } else { int width = image.getWidth(); int height = image.getHeight(); pixels = new Value[width][height]; for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { pixels[i][j] = new Value(makeLong("x_" + i + "_y_" + j, Value.INT32), Value.INT32 | Value.SYM); } } bufferedImageMap.put(image, pixels); } pixels[x][y] = symRGB; } public void bufferedReaderReadLine() { Expr expr = z3Context.mkConst("bufferedReaderString", z3Context.mkStringSort()); currentStackFrame.pushValue(new Value(expr, Value.STR | Value.SYM)); needReturnValue = false; } public void integerParseInt() { Value val = currentStackFrame.popValue(); if (val.isType(Value.SYM | Value.STR)) { Value ret = new Value(makeLong("parsedInt", Value.INT32), Value.INT32 | Value.SYM); currentStackFrame.pushValue(ret); needReturnValue = false; } } }
layeredapps/dashboard
src/www/api/user/reset-account-password.js
<reponame>layeredapps/dashboard const crypto = require('crypto') const dashboard = require('../../../../index.js') module.exports = { auth: false, patch: async (req) => { if (!req.body || !req.body['secret-code']) { throw new Error('invalid-secret-code') } if (!req.body.username) { throw new Error('invalid-username') } if (!req.body.username || !req.body.username.length || global.minimumUsernameLength > req.body.username.length) { throw new Error('invalid-username') } if (!req.body['new-password'] || !req.body['new-password'].length) { throw new Error('invalid-password') } if (global.minimumPasswordLength > req.body['new-password'].length) { throw new Error('invalid-password-length') } if (!req.body['secret-code'] || !req.body['secret-code'].length) { throw new Error('invalid-secret-code') } let dashboardEncryptionKey = global.dashboardEncryptionKey if (req.server) { dashboardEncryptionKey = req.server.dashboardEncryptionKey || dashboardEncryptionKey } const usernameHash = await dashboard.Hash.sha512Hash(req.body.username, dashboardEncryptionKey) const accountInfo = await dashboard.Storage.Account.findOne({ where: { usernameHash, appid: req.appid || global.appid } }) if (!accountInfo) { throw new Error('invalid-username') } const query = req.query req.query = { accountid: accountInfo.dataValues.accountid } const account = await global.api.administrator.Account.get(req) req.query = query if (!account) { throw new Error('invalid-username') } if (account.deletedAt) { throw new Error('invalid-account') } if (new Date(account.deletedAt).getTime() < new Date().getTime()) { throw new Error('invalid-account') } const secretCodeHash = await dashboard.Hash.sha512Hash(req.body['secret-code'], dashboardEncryptionKey) const codeInfo = await dashboard.Storage.ResetCode.findOne({ where: { secretCodeHash, appid: req.appid || global.appid } }) if (!codeInfo) { throw new Error('invalid-reset-code') } const passwordHash = await dashboard.Hash.bcryptHashHash(req.body['new-password'], dashboardEncryptionKey) await dashboard.Storage.Account.update({ passwordHash, resetCodeLastUsedAt: new Date(), sessionKey: crypto.randomBytes(32).toString('hex'), sessionKeyLastResetAt: new Date(), passwordLastChangedAt: new Date(), sessionKeyNumber: account.sessionKeyNumber + 1 }, { where: { accountid: accountInfo.dataValues.accountid, appid: req.appid || global.appid } }) await dashboard.StorageCache.remove(codeInfo.dataValues.accountid) await dashboard.Storage.ResetCode.destroy({ where: { codeid: codeInfo.dataValues.codeid, appid: req.appid || global.appid } }) return true } }
Jorch72/BetterWithMods
src/main/java/betterwithmods/integration/MineTweaker.java
package betterwithmods.integration; import betterwithmods.integration.minetweaker.*; import minetweaker.MineTweakerAPI; /** * Created by tyler on 9/4/16. */ public class MineTweaker { public static void init() { MineTweakerAPI.registerClass(Saw.class); MineTweakerAPI.registerClass(Kiln.class); MineTweakerAPI.registerClass(Cauldron.class); MineTweakerAPI.registerClass(StokedCauldron.class); MineTweakerAPI.registerClass(Crucible.class); MineTweakerAPI.registerClass(StokedCrucible.class); MineTweakerAPI.registerClass(Mill.class); MineTweakerAPI.registerClass(Buoyancy.class); } }
nistefan/cmssw
CommonTools/RecoAlgos/plugins/CompositeDimuonAndSelector.cc
#include "CommonTools/CandAlgos/interface/CompositeCandSelector.h" #include "CommonTools/UtilAlgos/interface/AndPairSelector.h" #include "CommonTools/UtilAlgos/interface/StringCutObjectSelector.h" #include "CommonTools/UtilAlgos/interface/SingleObjectSelector.h" #include "DataFormats/MuonReco/interface/Muon.h" #include "FWCore/Framework/interface/MakerMacros.h" typedef SingleObjectSelector< reco::CandidateView, CompositeCandSelector< AndPairSelector< StringCutObjectSelector<reco::Muon>, StringCutObjectSelector<reco::Muon> >, reco::Muon > > CompositeDimuonAndSelector; DEFINE_FWK_MODULE(CompositeDimuonAndSelector);
abhirocks1211/litho
litho-it/src/test/resources/processor/sections/FullDiffSectionSpec.java
/* * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ package com.facebook.litho.sections.processor.integration.resources; import android.view.View; import com.facebook.litho.ClickEvent; import com.facebook.litho.Component; import com.facebook.litho.Diff; import com.facebook.litho.StateValue; import com.facebook.litho.annotations.FromEvent; import com.facebook.litho.annotations.OnCreateInitialState; import com.facebook.litho.annotations.OnEvent; import com.facebook.litho.annotations.OnUpdateState; import com.facebook.litho.annotations.Param; import com.facebook.litho.annotations.Prop; import com.facebook.litho.annotations.ShouldUpdate; import com.facebook.litho.annotations.State; import com.facebook.litho.sections.ChangeSet; import com.facebook.litho.sections.SectionContext; import com.facebook.litho.sections.annotations.DiffSectionSpec; import com.facebook.litho.sections.annotations.OnBindService; import com.facebook.litho.sections.annotations.OnCreateService; import com.facebook.litho.sections.annotations.OnDataBound; import com.facebook.litho.sections.annotations.OnDiff; import com.facebook.litho.sections.annotations.OnRefresh; import com.facebook.litho.sections.annotations.OnUnbindService; import com.facebook.litho.sections.annotations.OnViewportChanged; import java.util.List; @DiffSectionSpec(events = TestEvent.class) public class FullDiffSectionSpec<T> { @OnCreateInitialState static void onCreateInitialState( SectionContext c, @Prop Integer prop1, StateValue<Object> state1) {} @OnDiff protected static <T> void onDiff( SectionContext c, ChangeSet changeSet, @Prop Diff<List<T>> data, @Prop Diff<Component> prop3, @State Diff<Object> state1) {} @OnUpdateState protected static void updateState(StateValue<Object> state1, @Param Object param) {} @OnCreateService static String onCreateService( SectionContext c, @Prop(optional = true) String prop2) { return prop2; } @OnBindService static void bindService( SectionContext c, String service) { } @OnUnbindService static void unbindService( SectionContext c, String service) { } @OnRefresh static void onRefresh( SectionContext c, String service) { } @OnDataBound static void onDataBound( SectionContext c) { } @ShouldUpdate static boolean shouldUpdate(@Prop Diff<Integer> prop1) { return true; } @OnViewportChanged static void onViewportChanged( SectionContext c, int firstVisibleIndex, int lastVisibleIndex, int totalCount, int firstFullyVisibleIndex, int lastFullyVisibleIndex) { } @OnEvent(ClickEvent.class) static void testEvent(SectionContext c, @FromEvent View view, @Param int someParam) {} }
GongYuanLearning/javaee
spring_core/spring_aop/src/main/java/com/example/aspect/LogsAspect.java
package com.example.aspect; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component; /** * 切面类。 * */ @Aspect // 申明该类是一个切面类 @Component("logsAspect") public class LogsAspect { // 切入点的定义 @Pointcut("execution(* com.example.service.*.*(..))") public void pointCut() { } /** * 前置通知。参数是JoinPoint类型。返回类型为void。 * * @param jp */ @Before(value = "pointCut()") public void before(JoinPoint jp) { // getTarget获取目标对象 System.out.println("前置通知:" + jp.getTarget()); // getSignature获取目标方法的签名 System.out.println("进入方法:" + jp.getSignature().getName()); } /** * 环绕通知。参数是ProceedingJoinPoint类型。返回类型为Object。 * * @param pjp */ @Around(value = "execution(* com.example.service.*.*(..))") public Object around(ProceedingJoinPoint pjp) throws Throwable { System.out.println("环绕通知, 方法执行前:"); // proceed方法调用目标方法。返回的就是目标方法的返回值。 final Object result = pjp.proceed(); System.out.println("环绕通知, 方法执行后:"); return result; } /** * 后置返回通知。参数是JoinPoint类型。返回类型为void。 * * @param jp */ @AfterReturning(value = "pointCut()") public void afterReturning(JoinPoint jp) { System.out.println("后置返回通知:" + jp.getSignature().getName()); } /** * 后置通知。参数是JoinPoint类型。返回类型为void。 * * @param jp */ @After(value = "pointCut()") public void after(JoinPoint jp) { System.out.println("后置最终通知:" + jp.getSignature().getName()); } /** * 异常通知。参数是Throwable类型以及子类IllegalArgumentException。 * 返回类型为void。 * * @param ex */ @AfterThrowing(value = "execution(* com.example.service.*.*(..))", throwing = "ex") public void exception(Throwable ex) { System.out.println("异常通知:" + ex.getMessage()); } }
rvhub/MultipathODL
opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/module/abs/AbsModuleGeneratedObjectFactoryTest.java
<gh_stars>0 /* * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.controller.config.yangjmxgenerator.plugin.module.abs; import com.google.common.base.Optional; import org.junit.Test; import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry; import org.opendaylight.controller.config.yangjmxgenerator.ServiceInterfaceEntry; import org.opendaylight.controller.config.yangjmxgenerator.plugin.gofactory.AbsModuleGeneratedObjectFactory; import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.FullyQualifiedName; import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.GeneratedObject; import org.opendaylight.controller.config.yangjmxgenerator.plugin.module.AbstractGeneratedObjectTest; import org.opendaylight.yangtools.yang.common.QName; import java.io.File; import java.io.IOException; import java.util.Map; import java.util.Map.Entry; public class AbsModuleGeneratedObjectFactoryTest extends AbstractGeneratedObjectTest { @Test public void test() throws IOException { Map<QName,ServiceInterfaceEntry> serviceInterfaceEntryMap = loadThreadsServiceInterfaceEntries("packages.sis"); Map<String, ModuleMXBeanEntry> namesToMBEs = loadThreadsJava(serviceInterfaceEntryMap, "packages.pack2"); ModuleMXBeanEntry dynamicThreadPool = namesToMBEs.get(THREADPOOL_DYNAMIC_MXB_NAME); parseGeneratedFile(dynamicThreadPool); } private void parseGeneratedFile(ModuleMXBeanEntry moduleMXBeanEntry) throws IOException { Optional<String> copyright = Optional.absent(); GeneratedObject generatedObject = new AbsModuleGeneratedObjectFactory().toGeneratedObject(moduleMXBeanEntry, copyright); Entry<FullyQualifiedName,File> entry = generatedObject.persist(generatorOutputPath).get(); File dstFile = entry.getValue(); parse(dstFile); } }
leetcode-pp/leetcode-pp1
code/ch04/4.2.1.24game.py
<reponame>leetcode-pp/leetcode-pp1<gh_stars>10-100 from typing import List class Solution: def judgePoint24(self, nums: List[int]) -> bool: permutations = self.permuteUnique(nums) for permutation in permutations: if self.compute(permutation): return True return False def compute(self, nums: List[float]) -> bool: if len(nums) == 1: return abs(nums[0] - 24) <= 0.00001 for i in range(len(nums) - 1): # compute possible result from + - * / tmp = [] tmp.append(nums[i] + nums[i + 1]) tmp.append(nums[i] - nums[i + 1]) tmp.append(nums[i] * nums[i + 1]) if nums[i + 1] != 0: tmp.append(nums[i] / nums[i + 1]) for num in tmp: new_list = nums[:] new_list[i] = num new_list.pop(i + 1) if self.compute(new_list): return True return False def permuteUnique(self, nums: List[int]) -> List[List[int]]: permutations = [] nums.sort() tmp = [] visited = [False] * len(nums) self.backtracking(nums, tmp, visited, permutations) return permutations def backtracking( self, nums: List[int], tmp: List[float], visited: List[bool], perm: List[int], ) -> None: if len(nums) == len(tmp): perm.append(tmp[:]) return for i in range(len(nums)): if visited[i]: continue if i > 0 and nums[i] == nums[i - 1] and not visited[i - 1]: continue visited[i] = True tmp.append(nums[i]) self.backtracking(nums, tmp, visited, perm) visited[i] = False tmp.pop()
BasisTI/madre
prescricao/src/main/java/br/com/basis/madre/prescricao/service/ItemPrescricaoDietaService.java
<gh_stars>1-10 package br.com.basis.madre.prescricao.service; import br.com.basis.madre.prescricao.domain.ItemPrescricaoDieta; import br.com.basis.madre.prescricao.repository.ItemPrescricaoDietaRepository; import br.com.basis.madre.prescricao.repository.search.ItemPrescricaoDietaSearchRepository; import br.com.basis.madre.prescricao.service.dto.ItemPrescricaoDietaDTO; import br.com.basis.madre.prescricao.service.mapper.ItemPrescricaoDietaMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Optional; import static org.elasticsearch.index.query.QueryBuilders.*; /** * Service Implementation for managing {@link ItemPrescricaoDieta}. */ @Service @Transactional public class ItemPrescricaoDietaService { private final Logger log = LoggerFactory.getLogger(ItemPrescricaoDietaService.class); private final ItemPrescricaoDietaRepository itemPrescricaoDietaRepository; private final ItemPrescricaoDietaMapper itemPrescricaoDietaMapper; private final ItemPrescricaoDietaSearchRepository itemPrescricaoDietaSearchRepository; public ItemPrescricaoDietaService(ItemPrescricaoDietaRepository itemPrescricaoDietaRepository, ItemPrescricaoDietaMapper itemPrescricaoDietaMapper, ItemPrescricaoDietaSearchRepository itemPrescricaoDietaSearchRepository) { this.itemPrescricaoDietaRepository = itemPrescricaoDietaRepository; this.itemPrescricaoDietaMapper = itemPrescricaoDietaMapper; this.itemPrescricaoDietaSearchRepository = itemPrescricaoDietaSearchRepository; } /** * Save a itemPrescricaoDieta. * * @param itemPrescricaoDietaDTO the entity to save. * @return the persisted entity. */ public ItemPrescricaoDietaDTO save(ItemPrescricaoDietaDTO itemPrescricaoDietaDTO) { log.debug("Request to save ItemPrescricaoDieta : {}", itemPrescricaoDietaDTO); ItemPrescricaoDieta itemPrescricaoDieta = itemPrescricaoDietaMapper.toEntity(itemPrescricaoDietaDTO); itemPrescricaoDieta = itemPrescricaoDietaRepository.save(itemPrescricaoDieta); ItemPrescricaoDietaDTO result = itemPrescricaoDietaMapper.toDto(itemPrescricaoDieta); itemPrescricaoDietaSearchRepository.save(itemPrescricaoDieta); return result; } /** * Get all the itemPrescricaoDietas. * * @param pageable the pagination information. * @return the list of entities. */ @Transactional(readOnly = true) public Page<ItemPrescricaoDietaDTO> findAll(Pageable pageable) { log.debug("Request to get all ItemPrescricaoDietas"); return itemPrescricaoDietaRepository.findAll(pageable) .map(itemPrescricaoDietaMapper::toDto); } /** * Get one itemPrescricaoDieta by id. * * @param id the id of the entity. * @return the entity. */ @Transactional(readOnly = true) public Optional<ItemPrescricaoDietaDTO> findOne(Long id) { log.debug("Request to get ItemPrescricaoDieta : {}", id); return itemPrescricaoDietaRepository.findById(id) .map(itemPrescricaoDietaMapper::toDto); } /** * Delete the itemPrescricaoDieta by id. * * @param id the id of the entity. */ public void delete(Long id) { log.debug("Request to delete ItemPrescricaoDieta : {}", id); itemPrescricaoDietaRepository.deleteById(id); itemPrescricaoDietaSearchRepository.deleteById(id); } /** * Search for the itemPrescricaoDieta corresponding to the query. * * @param query the query of the search. * @param pageable the pagination information. * @return the list of entities. */ @Transactional(readOnly = true) public Page<ItemPrescricaoDietaDTO> search(String query, Pageable pageable) { log.debug("Request to search for a page of ItemPrescricaoDietas for query {}", query); return itemPrescricaoDietaSearchRepository.search(queryStringQuery(query), pageable) .map(itemPrescricaoDietaMapper::toDto); } }
isabella232/ioc-unit
modules/ioc-unit-analyzer/src/test/java/com/oneandone/iocunit/analyzer/typed/UsingClass.java
package com.oneandone.iocunit.analyzer.typed; import javax.inject.Inject; /** * @author aschoerk */ public class UsingClass { @Inject BaseClass baseClass; @Inject TypedSubClass typedSubClass; }
wyllie/AwAws
tests/Session/test_resource.py
<filename>tests/Session/test_resource.py import inspect import os from unittest.mock import patch, ANY from AwAws.Session.resource import Resource def test_resource(): resource = Resource() assert resource.resource is None assert resource.region_name is None inspect.isclass(Resource) assert isinstance(resource, Resource) def test_init_with_region(): test_region = 'us-least-6' resource = Resource(region_name=test_region) assert resource.region_name == 'us-least-6' def test_set_region(): test_region = 'us-least-7' resource = Resource() assert resource.region_name is None resource.set_region_name(test_region) assert resource.region_name == 'us-least-7' def test_set_region_env(): resource = Resource() assert resource.region_name is None os.environ['AWS_REGION'] = 'us-least-8' resource.set_region_name() assert resource.region_name == 'us-least-8' os.environ.pop('AWS_REGION') @patch('boto3.session.Session.resource', autospec=True, return_value='boto!') def test_get_resource(mock_resource): resource = Resource(region_name='us-least-9') chk = resource.get_resource('project-thunderball') assert chk == 'boto!' mock_resource.assert_called_with(ANY, 'project-thunderball', region_name='us-least-9')
heliosRX/heliosRX
dist/heliosrx.common.js
/** * heliosRX v0.2.4 * (c) 2020 <NAME> * @license MIT */ 'use strict'; function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } var Vue = _interopDefault(require('vue')); var Vuex = _interopDefault(require('vuex')); var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } var loglevel = createCommonjsModule(function (module) { /* * loglevel - https://github.com/pimterry/loglevel * * Copyright (c) 2013 <NAME> * Licensed under the MIT license. */ (function (root, definition) { if ( module.exports) { module.exports = definition(); } else { root.log = definition(); } }(commonjsGlobal, function () { // Slightly dubious tricks to cut down minimized file size var noop = function() {}; var undefinedType = "undefined"; var isIE = (typeof window !== undefinedType) && ( /Trident\/|MSIE /.test(window.navigator.userAgent) ); var logMethods = [ "trace", "debug", "info", "warn", "error" ]; // Cross-browser bind equivalent that works at least back to IE6 function bindMethod(obj, methodName) { var method = obj[methodName]; if (typeof method.bind === 'function') { return method.bind(obj); } else { try { return Function.prototype.bind.call(method, obj); } catch (e) { // Missing bind shim or IE8 + Modernizr, fallback to wrapping return function() { return Function.prototype.apply.apply(method, [obj, arguments]); }; } } } // Trace() doesn't print the message in IE, so for that case we need to wrap it function traceForIE() { if (console.log) { if (console.log.apply) { console.log.apply(console, arguments); } else { // In old IE, native console methods themselves don't have apply(). Function.prototype.apply.apply(console.log, [console, arguments]); } } if (console.trace) { console.trace(); } } // Build the best logging method possible for this env // Wherever possible we want to bind, not wrap, to preserve stack traces function realMethod(methodName) { if (methodName === 'debug') { methodName = 'log'; } if (typeof console === undefinedType) { return false; // No method possible, for now - fixed later by enableLoggingWhenConsoleArrives } else if (methodName === 'trace' && isIE) { return traceForIE; } else if (console[methodName] !== undefined) { return bindMethod(console, methodName); } else if (console.log !== undefined) { return bindMethod(console, 'log'); } else { return noop; } } // These private functions always need `this` to be set properly function replaceLoggingMethods(level, loggerName) { /*jshint validthis:true */ for (var i = 0; i < logMethods.length; i++) { var methodName = logMethods[i]; this[methodName] = (i < level) ? noop : this.methodFactory(methodName, level, loggerName); } // Define log.log as an alias for log.debug this.log = this.debug; } // In old IE versions, the console isn't present until you first open it. // We build realMethod() replacements here that regenerate logging methods function enableLoggingWhenConsoleArrives(methodName, level, loggerName) { return function () { if (typeof console !== undefinedType) { replaceLoggingMethods.call(this, level, loggerName); this[methodName].apply(this, arguments); } }; } // By default, we use closely bound real methods wherever possible, and // otherwise we wait for a console to appear, and then try again. function defaultMethodFactory(methodName, level, loggerName) { /*jshint validthis:true */ return realMethod(methodName) || enableLoggingWhenConsoleArrives.apply(this, arguments); } function Logger(name, defaultLevel, factory) { var self = this; var currentLevel; var storageKey = "loglevel"; if (name) { storageKey += ":" + name; } function persistLevelIfPossible(levelNum) { var levelName = (logMethods[levelNum] || 'silent').toUpperCase(); if (typeof window === undefinedType) { return; } // Use localStorage if available try { window.localStorage[storageKey] = levelName; return; } catch (ignore) {} // Use session cookie as fallback try { window.document.cookie = encodeURIComponent(storageKey) + "=" + levelName + ";"; } catch (ignore) {} } function getPersistedLevel() { var storedLevel; if (typeof window === undefinedType) { return; } try { storedLevel = window.localStorage[storageKey]; } catch (ignore) {} // Fallback to cookies if local storage gives us nothing if (typeof storedLevel === undefinedType) { try { var cookie = window.document.cookie; var location = cookie.indexOf( encodeURIComponent(storageKey) + "="); if (location !== -1) { storedLevel = /^([^;]+)/.exec(cookie.slice(location))[1]; } } catch (ignore) {} } // If the stored level is not valid, treat it as if nothing was stored. if (self.levels[storedLevel] === undefined) { storedLevel = undefined; } return storedLevel; } /* * * Public logger API - see https://github.com/pimterry/loglevel for details * */ self.name = name; self.levels = { "TRACE": 0, "DEBUG": 1, "INFO": 2, "WARN": 3, "ERROR": 4, "SILENT": 5}; self.methodFactory = factory || defaultMethodFactory; self.getLevel = function () { return currentLevel; }; self.setLevel = function (level, persist) { if (typeof level === "string" && self.levels[level.toUpperCase()] !== undefined) { level = self.levels[level.toUpperCase()]; } if (typeof level === "number" && level >= 0 && level <= self.levels.SILENT) { currentLevel = level; if (persist !== false) { // defaults to true persistLevelIfPossible(level); } replaceLoggingMethods.call(self, level, name); if (typeof console === undefinedType && level < self.levels.SILENT) { return "No console available for logging"; } } else { throw "log.setLevel() called with invalid level: " + level; } }; self.setDefaultLevel = function (level) { if (!getPersistedLevel()) { self.setLevel(level, false); } }; self.enableAll = function(persist) { self.setLevel(self.levels.TRACE, persist); }; self.disableAll = function(persist) { self.setLevel(self.levels.SILENT, persist); }; // Initialize with the right level var initialLevel = getPersistedLevel(); if (initialLevel == null) { initialLevel = defaultLevel == null ? "WARN" : defaultLevel; } self.setLevel(initialLevel, false); } /* * * Top-level API * */ var defaultLogger = new Logger(); var _loggersByName = {}; defaultLogger.getLogger = function getLogger(name) { if (typeof name !== "string" || name === "") { throw new TypeError("You must supply a name when creating a logger."); } var logger = _loggersByName[name]; if (!logger) { logger = _loggersByName[name] = new Logger( name, defaultLogger.getLevel(), defaultLogger.methodFactory); } return logger; }; // Grab the current global log variable in case of overwrite var _log = (typeof window !== undefinedType) ? window.log : undefined; defaultLogger.noConflict = function() { if (typeof window !== undefinedType && window.log === defaultLogger) { window.log = _log; } return defaultLogger; }; defaultLogger.getLoggers = function getLoggers() { return _loggersByName; }; return defaultLogger; })); }); var WARNING_DEFINE_UNKNOWN_PROP = 'store/define-unknown-prop'; var WARNING_RESET_MAX_DEPTH = 'store/reset-max-depth-reached'; var WARNING_NO_CREATE_FUNCTION = 'model/no-create-function'; var WARNING_INVALID_ID = 'model/invalid-id'; var WARNING_EMPTY_SCHEMA = 'model/empty-schema'; var WARNING_UKNONWN_VALIDATION_TYPE = 'model/unknown-validation-type'; var WARNING_MODEL_INVALID_MOMENT = 'model/invalid-moment'; var WARNING_MODEL_OTHER = 'model/other'; var WARNING_NO_SCHEMA = 'model/no-schema'; var WARNING_NAME_CONFLICT = 'model/no-name-conflict'; var WARNING_CLIENT_VALIDATION = 'model/client-validation-failed'; var WARNING_UNKNOWN_TIMESTAMP_TYPE = 'model/unknown-timestamp-type'; var WARNING_WRITING_UNDEFINED = 'model/writing-undefined'; var WARNING_INVALID_TIMESTAMP_SERVER = 'model/invalid-timestamp-from-server'; var WARNING_MOMENT_INVALID_DATE = 'moment/invalid-date'; var WARNING_DEPRECATED = 'common/deprecated'; var WARNING_COMMON = 'common/common'; var WARNING_SYNCING_SUBSET_DATA = 'read/sync-subset-data'; var WARNING_SYNCING_INDIVIDUAL = 'read/sync-individial-but-list-supported'; var WARNING_SYNCING_EXISTING_QUERY_PATH = 'read/sync-existing-query-path'; var WARNING_ACCESSING_UNSYNCED_DATA = 'read/accessing-unsynced-data'; var WARNING_PERMISSION_DENIED = 'read/permission-denied'; var INFO_COMMON = 'common'; var INFO_MODEL = 'model'; var INFO_COLLECTION = 'collection'; var INFO_STORE = 'store'; var INFO_STORE_WRITE = 'store-write'; var INFO_MOMENT = 'moment'; var INFO_REGISTRY = 'registry'; var INFO_DEEPMERGE = 'deep-merge'; var INFO_PERMISSION = 'permission'; var INFO_AUTO_UNSUBSCRIBE = 'store/unsubscribe/auto'; var INFO_SUBSCRIBE = 'store/subscribe'; var INFO_SUBSCRIBE_QUERY = 'store/subscurbe/query'; var INFO_SUBSCRIBE_DETAILS = 'store/subscribe/details'; var INFO_READ_INIT = 'store/subscribe/init'; var INFO_READ_REMOVE = 'store/unsubscribe'; var loggerChannel = /*#__PURE__*/Object.freeze({ __proto__: null, WARNING_DEFINE_UNKNOWN_PROP: WARNING_DEFINE_UNKNOWN_PROP, WARNING_RESET_MAX_DEPTH: WARNING_RESET_MAX_DEPTH, WARNING_NO_CREATE_FUNCTION: WARNING_NO_CREATE_FUNCTION, WARNING_INVALID_ID: WARNING_INVALID_ID, WARNING_EMPTY_SCHEMA: WARNING_EMPTY_SCHEMA, WARNING_UKNONWN_VALIDATION_TYPE: WARNING_UKNONWN_VALIDATION_TYPE, WARNING_MODEL_INVALID_MOMENT: WARNING_MODEL_INVALID_MOMENT, WARNING_MODEL_OTHER: WARNING_MODEL_OTHER, WARNING_NO_SCHEMA: WARNING_NO_SCHEMA, WARNING_NAME_CONFLICT: WARNING_NAME_CONFLICT, WARNING_CLIENT_VALIDATION: WARNING_CLIENT_VALIDATION, WARNING_UNKNOWN_TIMESTAMP_TYPE: WARNING_UNKNOWN_TIMESTAMP_TYPE, WARNING_WRITING_UNDEFINED: WARNING_WRITING_UNDEFINED, WARNING_INVALID_TIMESTAMP_SERVER: WARNING_INVALID_TIMESTAMP_SERVER, WARNING_MOMENT_INVALID_DATE: WARNING_MOMENT_INVALID_DATE, WARNING_DEPRECATED: WARNING_DEPRECATED, WARNING_COMMON: WARNING_COMMON, WARNING_SYNCING_SUBSET_DATA: WARNING_SYNCING_SUBSET_DATA, WARNING_SYNCING_INDIVIDUAL: WARNING_SYNCING_INDIVIDUAL, WARNING_SYNCING_EXISTING_QUERY_PATH: WARNING_SYNCING_EXISTING_QUERY_PATH, WARNING_ACCESSING_UNSYNCED_DATA: WARNING_ACCESSING_UNSYNCED_DATA, WARNING_PERMISSION_DENIED: WARNING_PERMISSION_DENIED, INFO_COMMON: INFO_COMMON, INFO_MODEL: INFO_MODEL, INFO_COLLECTION: INFO_COLLECTION, INFO_STORE: INFO_STORE, INFO_STORE_WRITE: INFO_STORE_WRITE, INFO_MOMENT: INFO_MOMENT, INFO_REGISTRY: INFO_REGISTRY, INFO_DEEPMERGE: INFO_DEEPMERGE, INFO_PERMISSION: INFO_PERMISSION, INFO_AUTO_UNSUBSCRIBE: INFO_AUTO_UNSUBSCRIBE, INFO_SUBSCRIBE: INFO_SUBSCRIBE, INFO_SUBSCRIBE_QUERY: INFO_SUBSCRIBE_QUERY, INFO_SUBSCRIBE_DETAILS: INFO_SUBSCRIBE_DETAILS, INFO_READ_INIT: INFO_READ_INIT, INFO_READ_REMOVE: INFO_READ_REMOVE }); loglevel.noConflict(); loglevel.setDefaultLevel('warn'); loglevel.setLevel('warn'); var PREFIX_LIST = {}; PREFIX_LIST[INFO_COMMON] = 'heliosRX'; PREFIX_LIST[INFO_MODEL] = 'heliosRX'; PREFIX_LIST[INFO_COLLECTION] = 'heliosRX'; PREFIX_LIST[INFO_STORE] = 'heliosRX'; PREFIX_LIST[INFO_STORE_WRITE] = 'heliosRX:write'; PREFIX_LIST[INFO_MOMENT] = 'heliosRX:moment'; PREFIX_LIST[INFO_REGISTRY] = 'heliosRX:REGISTRY'; PREFIX_LIST[INFO_DEEPMERGE] = 'heliosRX:DEEPMERGE'; PREFIX_LIST[INFO_PERMISSION] = 'heliosRX:permission'; PREFIX_LIST[INFO_AUTO_UNSUBSCRIBE] = 'heliosRX:auto-unsubscribe'; PREFIX_LIST[INFO_SUBSCRIBE] = 'heliosRX:subscribe'; PREFIX_LIST[INFO_SUBSCRIBE_DETAILS] = 'heliosRX:subscribe'; PREFIX_LIST[INFO_SUBSCRIBE_QUERY] = 'heliosRX:query'; PREFIX_LIST[INFO_READ_INIT] = 'heliosRX:moment'; PREFIX_LIST[INFO_READ_REMOVE] = 'heliosRX:moment'; /* USAGE: import { warn, WARNING_MODEL_INVALID_MOMENT } from "../util/log" warn( WARNING_MODEL_INVALID_MOMENT, ... ) */ function warn ( warning ) { var ref; var args = [], len = arguments.length - 1; while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ]; return (ref = loglevel.getLogger( warning )).warn.apply( ref, args ) } /* USAGE: import { info, INFO_MODEL } from "../util/log" info( INFO_MODEL, ... ) */ function info ( target ) { var ref; var args = [], len = arguments.length - 1; while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ]; var prefix = PREFIX_LIST[ target ] || target; return (ref = loglevel.getLogger( target )).info.apply( ref, [ ("[" + prefix + "]") ].concat( args ) ) } function trace ( target ) { var ref; var args = [], len = arguments.length - 1; while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ]; var prefix = PREFIX_LIST[ target ] || target; return (ref = loglevel.getLogger( target )).info.apply( ref, [ ("[" + prefix + "]") ].concat( args ) ) } loglevel.getLogger( WARNING_SYNCING_INDIVIDUAL ).setLevel('silent'); /* const _log_group = (name, id, ...args) => { console.groupCollapsed('[GENS:READ:' + name + '] ' + ( id ? '{' + id + '}' : '*')); args.forEach(arg => console.log('INFO:', arg)); console.trace(); console.groupEnd(); } */ /* const _log = (name, ...args) => { // Enable logging per store instance if ( !name.includes('commitmentDailySettings') ) { return } console.log("[GENS:READ:" + name + "]", ...args) }; */ /* let originalFactory = log.methodFactory; log.methodFactory = function (methodName, logLevel, loggerName) { let rawMethod = originalFactory(methodName, logLevel, loggerName); return function (message) { rawMethod("Newsflash: " + message); }; }; */ function isValidId( id ) { // length slugid = 22, length pushid = 20 return isString( id ) && id.length && id.length >= 20; } function isString (obj) { return (Object.prototype.toString.call(obj) === '[object String]'); } function isNumeric(n) { return !isNaN(parseFloat(n)) && isFinite(n); } function isValue(v) { return /* !isNaN(v) && */ v !== undefined && v !== null } function isFunction(f) { return (typeof f === "function"); } function isObject(o) { return typeof o === 'object' && o !== null; } function isArray(a) { return Array.isArray( a ); } function matchUserInputDuration(str) { return null // TODO } function isBoolean(v) { return v === true || v === false; } var firebase = { database: { ServerValue: { TIMESTAMP: {".sv": "timestamp"} } }, firestore: { FieldValue: { serverTimestamp: function serverTimestamp() { throw new Error('Not Implemented') } } } }; /* momen plugin for helios specific date time conversions */ var moment = require("moment-timezone/builds/moment-timezone-with-data-2012-2022.min.js"); /******************************************************************************* TODO: Check out Vue.util.defineReactive TODO: Load tz data async: - moment.tz.load(require('./data/packed/latest.json')); - check with: moment.tz.zone("UnloadedZone"); TODO: prevent moment from being called directly moment() *******************************************************************************/ var localStorage; if ( !process.browser ) { localStorage = { getItem: function getItem() { return 'Europe/Berlin' }, /* This will cause a death spiral, when enabled in a browser! */ setItem: function setItem() {} }; } else { localStorage = window.localStorage; } var convert_timezoneNeutral_to_qualifiedMomentObj = function (momentObj, userTimezone) { /* This funcion is used to convert 'timezone neutral' moment object, that are used to describe timeslots in timeslot collection, into 'qualified moment object', which means that the current user timezone gets 'appended' making the moment object timezone specific or 'timezoned'. */ // moment.parseZone() ? /* Get utc formated ISO string like "2018-12-09T03:41:19Z" and remove last character 'Z' */ var isoString = momentObj.clone().utc().format(); var timezoneNeutralIsoString = isoString.substring(0, isoString.length - 1); /* Append the current user timezone to the "timezone neutral" datetime, so that '2018-05-06T14:00' + 'America/New_York' becomes '2018-05-06T14:00:00-04:00'. */ return moment.tz(timezoneNeutralIsoString, userTimezone); }; function enhanceMomentJS( moment ) { info(INFO_MOMENT, "enhanceMomentJS"); /* ... */ moment.isEnhanced = true; moment.prototype.isEnhanced = true; /* ------------------------------------------------------------------------ */ moment.fromFirestore = function ( firestoreDatetimeObject ) { /* This funcion is mostly called to convert exceptions timestamps to moment object. It can probably be used to convert 'neutral' utc timestmaps to qualified calendar input. ( Also we have to check if it is used anywhere else ) */ if ( firestoreDatetimeObject && typeof firestoreDatetimeObject === 'object' && firestoreDatetimeObject.constructor.name === 'Timestamp' ) { // TODO: might not work in production return moment( firestoreDatetimeObject.toDate() ); } else { return moment( firestoreDatetimeObject ) } }; moment.fromRealtimeDB = function ( timestamp ) { return moment.unix( timestamp ); }; moment.fromRealtimeServerTime = function ( timestamp ) { return moment( timestamp ); }; moment.fromStore = function (ISOString) { return moment( ISOString ); /* Deserialize moment object */ }; /* ------------------------------------------------------------------------ */ moment.prototype.toFirestore = function() { // TODO: Check timezones return firebase.firestore.Timestamp.fromDate( this.toDate() ); }; moment.prototype.toRealtimeDB = function() { return this.unix(); }; moment.prototype.toRealtimeServerTime = function() { // We store timestmaps in seconds, while ServerTime is in milliseconds return this.valueOf(); }; moment.prototype.toBackend = function(backend) { return backend === 'REALTIMEDB' ? this.toRealtimeDB() : this.toFirestore() }; moment.prototype.toStore = function () { return this.format(); /* Serialize moment object */ }; moment.prototype.formatDateLong = function () { return this.format(this.user_dateformat); /* Serialize moment object */ }; /* ------------------------------------------------------------------------ */ moment.prototype.isTimezoneNeutral = false; // TODO moment.fromDateAndTime = function (ISODate, time) { if ( !time ) { throw new Error('Not implemented'); } /* Moment's string parsing functions like moment(string) and moment.utc(string) accept offset information if provided, but convert the resulting Moment object to local or UTC time. In contrast, moment.parseZone() parses the string but keeps the resulting Moment object in a fixed-offset timezone with the provided offset in the string. What parseZone really means here, is: parseZone => createDateWithoutZone Why so complicated? */ // let momentObj = moment.parseZone( ISODate + 'T' + time ); /* The moment.tz constructor takes all the same arguments as the moment constructor, but uses the last argument as a time zone identifier. */ var momentObj = moment.tz( ISODate + 'T' + time, moment.user_timezone); /* This function is used when creating timeslot for a given time and a give date. Usually we want to treat time preferences in the user timezone */ momentObj.isTimezoneNeutral = true; return momentObj; }; moment.fromTimezoneNeutral = function ( date ) { if ( !moment.isValidDate( date ) ) { warn(WARNING_MOMENT_INVALID_DATE, "[fromTimezoneNeutral]", "Invalid date", date); return null } if ( !date.isTimezoneNeutral ) { throw new Error('Input is not timezone neutral') } // TODO: How do we want to handle 'timezone neutral'? return convert_timezoneNeutral_to_qualifiedMomentObj( date, moment.user_timezone ); }; moment.prototype.changeTimezoneButKeepTime = function(timezone) { return convert_timezoneNeutral_to_qualifiedMomentObj( this, timezone ); }; /* ------------------------------------------------------------------------ */ moment.isValidDate = function(obj) { return obj && moment.isMoment(obj) && !!obj.isEnhanced && obj.isValid(); // TODO: move util function here }; moment.currentTime = function () { /* WHY: This function should return the same result as moment(), even when a custom timezone is set, since we set .locale(). Using this function is still the prefered way to get the current time, because it adds an extra layer of control. */ if ( !moment.user_timezone ) { throw new Error('User timezone is not set') } return moment().tz( moment.user_timezone ); }; moment.currentTimeUTC = function () { return moment().utc(); }; moment.currentDate = function ( ) { return moment().tz( moment.user_timezone ).startOf('day'); }; moment.currentDateISO = function ( ) { moment().tz( moment.user_timezone ).format('YYYY-MM-DD'); }; moment.currentDateSleepCorrected = function () { var sleepDayBreak = 3; // Daybreak at 3 AM in the morning return moment() .tz(moment.user_timezone) .subtract(sleepDayBreak, 'hours') .startOf('day'); }; moment.currentCalendarweek = function () { return moment().tz( moment.user_timezone ).format('W'); }; moment.currentTimeServer = function ( backend ) { return backend === 'REALTIMEDB' ? firebase.database.ServerValue.TIMESTAMP // {".sv": "timestamp"} : firebase.firestore.FieldValue.serverTimestamp(); }; /* converts 'HH:mm' to fractional time in hours */ moment.convertHHmmToFractional = function (value) { return (moment(value, 'HH:mm') - moment().startOf('day')) / 3600 / 1e3 }; /* converts fractional time in hours to 'HH:mm' */ moment.convertFractionalToHHmm = function (value) { return moment.utc( value * 3600 * 1e3 ).format('HH:mm') }; /* Parse time */ moment.parseTimeNatural = function (input, referenceTime ) { if ( referenceTime === void 0 ) referenceTime = null; var formats = ["HH:mm", "HH:mm A", "HH A", "HH"]; input = (input || '').trim(); if ( !input ) { return null } if ( input[0] === '+' || input[0] === '-' ) { var sign = input[0] === '-' ? -1 : +1; var text = input.slice(1); if ( !/[mhs]/i.test(text) ) { text += "m"; } var durationInfo = matchUserInputDuration(); if ( !durationInfo.match ) { return null; } var duration = sign * durationInfo.duration; return moment( referenceTime, 'HH:mm' ).add( duration, 'seconds' ) } else if ( input === 'now' ) { return moment(); } return moment(input, formats); }; if ( process.browser ) { window.moment = moment; } } // export function attachTimezoneWatcher( moment, store ) { // // info(INFO_MOMENT, "attaching timezone watcher"); // // /* Install watcher in store and wait until we get the user timezone. This // also means that the store is now initialized and was using a moment // object with a potentially different timezone... we have to take care of // that */ // let unwatch_user_get_timezone = store.watch( // (state, getters) => getters["app/user_get_timezone"], // user_timezone => { // // info(INFO_MOMENT, "got new user_timezone", user_timezone); // // // TODO: The user might not have a timezone configured, in this case // // we use the timezone of the operating system, which is perfectly // // fine. // // if ( user_timezone === 'I/DONT/KNOW' ) { // /* HACK: we don't know the TZ yet - do nothing */ // // TODO: null // return; // } // // if ( localStorage.getItem('timezone') !== user_timezone ) { // /* We have a problem: The user has a different timezone then we // assumed, this means the store is fucked up */ // warn(WARNING_DIFFERENT_LOCAL_TIMZONE, "locally saved timezone does not match user timezone", // localStorage.getItem('timezone'), "!=", user_timezone); // // /* Update local storage */ // localStorage.setItem('timezone', user_timezone); // // // TODO: Ask the user if we should set his timezone to moment.tz.guess, // // but only ask once // // // TODO: Also we should check if the users operating system changed // // the timezone (e.g. travel) // // We can do this by further checking if // // localStorage.timezone !== moment.tz.guess // // Again, we should only ask once after every change and only // // if the user has a timezone configured. // // if ( location /* check if this is a browser */ ) { // // TODO: Make absolutly sure, that we don't end up in a death sprial */ // location.reload() // } else { // throw new Error('Timezone mismatch detected. Timezone consistency can not be guaranteed.') // } // } // // info(INFO_MOMENT, "Setting user timezone in moment object"); // // /* Set default timezone */ // moment.tz.setDefault(user_timezone) // // moment.tz.setDefault("Europe/Berlin"); // Don't do that, see FAQ // // moment.tz.setDefault(String); // // // TODO: This only works because it is fast // // but moment.user_timezone is not reactive! // moment.user_timezone = user_timezone; // // Either create getter that will tell templates when tz is ready // // or delay everything // // // TODO: Testen... // Vue.util.defineReactive(moment, 'user_timezone', user_timezone, null, true) // // // info(INFO_MOMENT, "unwatch_user_get_timezone", unwatch_user_get_timezone); // if ( unwatch_user_get_timezone ) { // info(INFO_MOMENT, "Self destroying watcher"); // unwatch_user_get_timezone(); // Self destroy // } // }, // { immediate: true } // ); // /// or ... store.subscribe((mutation, state)) // } var localeSetUp = (function () { info(INFO_MOMENT, "set up"); info(INFO_MOMENT, "localStorage.getItem('timezone')", localStorage.getItem('timezone')); if ( !localStorage.getItem('timezone') ) { /* Let's be optimistic and assume that the user configured the same timezone that moment.tz.guess will give us. If not we deal with that later... */ localStorage.setItem('timezone', moment.tz.guess()); } /* Set default values */ var user_timezone = localStorage.getItem('timezone'); info(INFO_MOMENT, "Setting user timezone to", user_timezone); moment.tz.setDefault(user_timezone); moment.user_timezone = user_timezone; // moment.locale("en"); // -> i18n // momentDurationFormatSetup( moment ); enhanceMomentJS( moment ); })(); var UIDMethod = { CUSTOM: 1, SLUGID: 2, // R0qHTeS8TyWfV2_thfFn5w (Default) PUSHID: 3, // -JhLeOlGIEjaIOFHR0xd TIMESTAMP: 4, // 1548573128294 (unix?) LOCAL_TIMESTAMP: 5, // 1553700866 DATE: 6, // DDMMYYYY / 01032019 OTHER_USER_ID: 7, MY_USER_ID: 8, // fOjaiwtyxoQdOGe6Z2zULK18ggv2 ARRAY: 9, // 0,1,2,3,... EMAIL: 10, // <EMAIL> }; var DeleteMode = { SOFT: 0, HARD: 1 }; /* Variant 1: Source: https://stackoverflow.com/questions/29182244/convert-a-string-to-a-template-string Source : https://stackoverflow.com/questions/30003353/can-es6-template-literals-be-substituted-at-runtime-or-reused Example: const template = 'Example text: ${text}'; const result = interpolate(template, { text: 'Foo Boo' }); Beware: That this template string is kinda 'hidden' to transpilation (i.e. webpack) and thus will NOT transpile into something sufficiently compatible (i.e. IE11) on client-side...! */ /* export function tplInterpolate(template, params) { const names = Object.keys(params); const vals = Object.values(params); return new Function(...names, `return \`${template}\`;`)(...vals); } */ /* Variant 2: Source: https://gist.github.com/smeijer/6580740a0ff468960a5257108af1384e#file-parse-es6-template-js Example: const template = '{name} is now master of the {galaxy}' parseTpl(template, { name: 'John', galaxy: 'Milky Way' }); */ // function get(path, obj, fb = `$\{${path}}`) { function get(path, obj, fb) { if ( fb === void 0 ) fb = "{" + path + "}"; return path.split('.').reduce(function (res, key) { return res[key] || fb; }, obj); } function parseTpl(template, map, fallback) { // return template.replace(/\$\{.+?}/g, (match) => { return template.replace(/\{.+?}/g, function (match) { // const path = match.substr(2, match.length - 3).trim(); var path = match.substr(1, match.length - 2).trim(); return get(path, map, fallback); }); } /* Example: analyzeTpl(parseTpl("/test/${test}/${uid}/ABC/${abc}", {abc: 1})) (2) ["test", "uid"] */ function analyzeTpl(template) { // return template.match(/\$\{.+?}/g).map(match => match.slice(2, -1)); return ( template.match(/\{.+?}/g) || [] ).map(function (match) { return match.slice(1, -1); }); } /* const template = 'Example text: ${text}'; const result = interpolate(template, { text: 'Foo Boo' }); */ // TODO: Make sure it's the same 'Vue' // bind on install var _Vue = Vue; var _Vuex = Vuex; var _Firebase; var _registry; var _models = {}; var _db = {}; function setup( options ) { if ( options.Vue ) { _Vue = options.Vue; } if ( options.Vuex ) { _Vuex = options.Vuex; } if ( options.Firebase ) { _Firebase = options.Firebase; } if ( options.registry ) { _registry = options.registry; } if ( options.models ) { _models = options.models; } if ( options.db ) { _db = options.db; } } function getRegistry() { return _registry; } // import { info, INFO_HMR } from "../util/log" var factory = { configure: function configure(ref) { var GenericList = ref.GenericList; var GenericModel = ref.GenericModel; this.GenericList = GenericList; this.GenericModel = GenericModel; }, // ----------------------------------------------------------------------------- make_reactive_list: function make_reactive_list( modelDefinition, dataList, context, no_reactive_getters ) { if ( no_reactive_getters === void 0 ) no_reactive_getters = false; // TODO: Error when not inintialized var name = context.model.name; var reactive_list = new this.GenericList( name ); if ( dataList ) { for ( var id in dataList ) { var item = this.make_reactive_model( modelDefinition, dataList[ id ], context ); item.$id = id; item._update_data( dataList[ id ], modelDefinition.schema.fields ); // DOPPELT? reactive_list._add_child( id, item ); } reactive_list.$readyAll = true; reactive_list.$numReady = Object.keys( dataList ).length; } // TODO: Implementd custom global actions / getters here too if ( modelDefinition.listActions ) { reactive_list._decorate_actions( modelDefinition.listActions, context ); } if ( modelDefinition.listGetters && !no_reactive_getters && !modelDefinition.no_reactive_getters ) { reactive_list._decorate_getters( modelDefinition.listGetters, context ); } _Vue.observable( reactive_list ); return reactive_list }, // ----------------------------------------------------------------------------- make_reactive_model: function make_reactive_model( modelDefinition, data, context, is_dirty, no_reactive_getters ) { if ( is_dirty === void 0 ) is_dirty = false; if ( no_reactive_getters === void 0 ) no_reactive_getters = false; // TODO: Error when not inintialized var name = context.model.name; var load_result = new this.GenericModel( null, null, name ); load_result._set_generic_store( context.model ); if ( modelDefinition.schema && modelDefinition.schema.fields ) { load_result._autogenerate_props( modelDefinition.schema.fields, data, is_dirty ); } else { warn(WARNING_NO_SCHEMA, 'Making a reactive model without schema. This means props are not autogenerated and only accessible through model.$state. Please provide a schema for ' + name + '.'); } if ( data ) { load_result._update_data( data, modelDefinition.schema.fields ); load_result.$ready = true; } if ( modelDefinition.modelActions ) { load_result._decorate_actions( modelDefinition.modelActions, context ); } /* add model getters: - attach vm only if there are getters - otherwise there is no need - attach vm only if flag 'no_reactive_getters' is not set in model definition - attach vm only if flag 'no_reactive_getters' is not set during model instantiation */ if ( modelDefinition.modelGetters && !no_reactive_getters && !modelDefinition.no_reactive_getters ) { load_result._decorate_getters( modelDefinition.modelGetters, context ); } /* TODO: Implement HMR if ( module.hot && modelDefinition.hotUpdate ) { // TODO: Testen let hotUpdateList = modelDefinition.hotUpdate(); let filelist = [] for ( let relative_filename in hotUpdateList ) { let filename = './src/models/' + name + '/' + relative_filename; filelist.push( filename ) } info(INFO_HMR, "list", filelist); module.hot.accept([filelist], (updated_file, deps) => { info(INFO_HMR, "update model", updated_file, deps); // Parse "./src/api/<moduleName>.js" let moduleName = updated_file[0].split('/').pop(); info(INFO_HMR, "update model %c<" + moduleName + ">", 'color: #42b983'); let target = hotUpdateList[ moduleName ]; let moduleData = require('./src/models/' + name + '/' + moduleName) for ( var prop in moduleData ) { target[ prop ] = moduleData[ prop ] } // Why not just update entire model? }) } */ _Vue.observable( load_result ); return load_result; } }; var lodash_clonedeep = createCommonjsModule(function (module, exports) { /** * lodash (Custom Build) <https://lodash.com/> * Build: `lodash modularize exports="npm" -o ./` * Copyright jQuery Foundation and other contributors <https://jquery.org/> * Released under MIT license <https://lodash.com/license> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright <NAME>, DocumentCloud and Investigative Reporters & Editors */ /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', mapTag = '[object Map]', numberTag = '[object Number]', objectTag = '[object Object]', promiseTag = '[object Promise]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', symbolTag = '[object Symbol]', weakMapTag = '[object WeakMap]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** * Used to match `RegExp` * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). */ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; /** Used to match `RegExp` flags from their coerced string values. */ var reFlags = /\w*$/; /** Used to detect host constructors (Safari). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/; /** Used to identify `toStringTag` values supported by `_.clone`. */ var cloneableTags = {}; cloneableTags[argsTag] = cloneableTags[arrayTag] = cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = cloneableTags[boolTag] = cloneableTags[dateTag] = cloneableTags[float32Tag] = cloneableTags[float64Tag] = cloneableTags[int8Tag] = cloneableTags[int16Tag] = cloneableTags[int32Tag] = cloneableTags[mapTag] = cloneableTags[numberTag] = cloneableTags[objectTag] = cloneableTags[regexpTag] = cloneableTags[setTag] = cloneableTags[stringTag] = cloneableTags[symbolTag] = cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; cloneableTags[errorTag] = cloneableTags[funcTag] = cloneableTags[weakMapTag] = false; /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal; /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); /** Detect free variable `exports`. */ var freeExports = exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** * Adds the key-value `pair` to `map`. * * @private * @param {Object} map The map to modify. * @param {Array} pair The key-value pair to add. * @returns {Object} Returns `map`. */ function addMapEntry(map, pair) { // Don't return `map.set` because it's not chainable in IE 11. map.set(pair[0], pair[1]); return map; } /** * Adds `value` to `set`. * * @private * @param {Object} set The set to modify. * @param {*} value The value to add. * @returns {Object} Returns `set`. */ function addSetEntry(set, value) { // Don't return `set.add` because it's not chainable in IE 11. set.add(value); return set; } /** * A specialized version of `_.forEach` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEach(array, iteratee) { var index = -1, length = array ? array.length : 0; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; } /** * Appends the elements of `values` to `array`. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to append. * @returns {Array} Returns `array`. */ function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index]; } return array; } /** * A specialized version of `_.reduce` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {boolean} [initAccum] Specify using the first element of `array` as * the initial value. * @returns {*} Returns the accumulated value. */ function arrayReduce(array, iteratee, accumulator, initAccum) { var index = -1, length = array ? array.length : 0; if (initAccum && length) { accumulator = array[++index]; } while (++index < length) { accumulator = iteratee(accumulator, array[index], index, array); } return accumulator; } /** * The base implementation of `_.times` without support for iteratee shorthands * or max array length checks. * * @private * @param {number} n The number of times to invoke `iteratee`. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the array of results. */ function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) { result[index] = iteratee(index); } return result; } /** * Gets the value at `key` of `object`. * * @private * @param {Object} [object] The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function getValue(object, key) { return object == null ? undefined : object[key]; } /** * Checks if `value` is a host object in IE < 9. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a host object, else `false`. */ function isHostObject(value) { // Many host objects are `Object` objects that can coerce to strings // despite having improperly defined `toString` methods. var result = false; if (value != null && typeof value.toString != 'function') { try { result = !!(value + ''); } catch (e) {} } return result; } /** * Converts `map` to its key-value pairs. * * @private * @param {Object} map The map to convert. * @returns {Array} Returns the key-value pairs. */ function mapToArray(map) { var index = -1, result = Array(map.size); map.forEach(function(value, key) { result[++index] = [key, value]; }); return result; } /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } /** * Converts `set` to an array of its values. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the values. */ function setToArray(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = value; }); return result; } /** Used for built-in method references. */ var arrayProto = Array.prototype, funcProto = Function.prototype, objectProto = Object.prototype; /** Used to detect overreaching core-js shims. */ var coreJsData = root['__core-js_shared__']; /** Used to detect methods masquerading as native. */ var maskSrcKey = (function() { var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); return uid ? ('Symbol(src)_1.' + uid) : ''; }()); /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** Built-in value references. */ var Buffer = moduleExports ? root.Buffer : undefined, Symbol = root.Symbol, Uint8Array = root.Uint8Array, getPrototype = overArg(Object.getPrototypeOf, Object), objectCreate = Object.create, propertyIsEnumerable = objectProto.propertyIsEnumerable, splice = arrayProto.splice; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeGetSymbols = Object.getOwnPropertySymbols, nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, nativeKeys = overArg(Object.keys, Object); /* Built-in method references that are verified to be native. */ var DataView = getNative(root, 'DataView'), Map = getNative(root, 'Map'), Promise = getNative(root, 'Promise'), Set = getNative(root, 'Set'), WeakMap = getNative(root, 'WeakMap'), nativeCreate = getNative(Object, 'create'); /** Used to detect maps, sets, and weakmaps. */ var dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map), promiseCtorString = toSource(Promise), setCtorString = toSource(Set), weakMapCtorString = toSource(WeakMap); /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; /** * Creates a hash object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Hash(entries) { var index = -1, length = entries ? entries.length : 0; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the hash. * * @private * @name clear * @memberOf Hash */ function hashClear() { this.__data__ = nativeCreate ? nativeCreate(null) : {}; } /** * Removes `key` and its value from the hash. * * @private * @name delete * @memberOf Hash * @param {Object} hash The hash to modify. * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function hashDelete(key) { return this.has(key) && delete this.__data__[key]; } /** * Gets the hash value for `key`. * * @private * @name get * @memberOf Hash * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function hashGet(key) { var data = this.__data__; if (nativeCreate) { var result = data[key]; return result === HASH_UNDEFINED ? undefined : result; } return hasOwnProperty.call(data, key) ? data[key] : undefined; } /** * Checks if a hash value for `key` exists. * * @private * @name has * @memberOf Hash * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function hashHas(key) { var data = this.__data__; return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key); } /** * Sets the hash `key` to `value`. * * @private * @name set * @memberOf Hash * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the hash instance. */ function hashSet(key, value) { var data = this.__data__; data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; return this; } // Add methods to `Hash`. Hash.prototype.clear = hashClear; Hash.prototype['delete'] = hashDelete; Hash.prototype.get = hashGet; Hash.prototype.has = hashHas; Hash.prototype.set = hashSet; /** * Creates an list cache object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function ListCache(entries) { var index = -1, length = entries ? entries.length : 0; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the list cache. * * @private * @name clear * @memberOf ListCache */ function listCacheClear() { this.__data__ = []; } /** * Removes `key` and its value from the list cache. * * @private * @name delete * @memberOf ListCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function listCacheDelete(key) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { return false; } var lastIndex = data.length - 1; if (index == lastIndex) { data.pop(); } else { splice.call(data, index, 1); } return true; } /** * Gets the list cache value for `key`. * * @private * @name get * @memberOf ListCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function listCacheGet(key) { var data = this.__data__, index = assocIndexOf(data, key); return index < 0 ? undefined : data[index][1]; } /** * Checks if a list cache value for `key` exists. * * @private * @name has * @memberOf ListCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function listCacheHas(key) { return assocIndexOf(this.__data__, key) > -1; } /** * Sets the list cache `key` to `value`. * * @private * @name set * @memberOf ListCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the list cache instance. */ function listCacheSet(key, value) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { data.push([key, value]); } else { data[index][1] = value; } return this; } // Add methods to `ListCache`. ListCache.prototype.clear = listCacheClear; ListCache.prototype['delete'] = listCacheDelete; ListCache.prototype.get = listCacheGet; ListCache.prototype.has = listCacheHas; ListCache.prototype.set = listCacheSet; /** * Creates a map cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function MapCache(entries) { var index = -1, length = entries ? entries.length : 0; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the map. * * @private * @name clear * @memberOf MapCache */ function mapCacheClear() { this.__data__ = { 'hash': new Hash, 'map': new (Map || ListCache), 'string': new Hash }; } /** * Removes `key` and its value from the map. * * @private * @name delete * @memberOf MapCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function mapCacheDelete(key) { return getMapData(this, key)['delete'](key); } /** * Gets the map value for `key`. * * @private * @name get * @memberOf MapCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function mapCacheGet(key) { return getMapData(this, key).get(key); } /** * Checks if a map value for `key` exists. * * @private * @name has * @memberOf MapCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function mapCacheHas(key) { return getMapData(this, key).has(key); } /** * Sets the map `key` to `value`. * * @private * @name set * @memberOf MapCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the map cache instance. */ function mapCacheSet(key, value) { getMapData(this, key).set(key, value); return this; } // Add methods to `MapCache`. MapCache.prototype.clear = mapCacheClear; MapCache.prototype['delete'] = mapCacheDelete; MapCache.prototype.get = mapCacheGet; MapCache.prototype.has = mapCacheHas; MapCache.prototype.set = mapCacheSet; /** * Creates a stack cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Stack(entries) { this.__data__ = new ListCache(entries); } /** * Removes all key-value entries from the stack. * * @private * @name clear * @memberOf Stack */ function stackClear() { this.__data__ = new ListCache; } /** * Removes `key` and its value from the stack. * * @private * @name delete * @memberOf Stack * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function stackDelete(key) { return this.__data__['delete'](key); } /** * Gets the stack value for `key`. * * @private * @name get * @memberOf Stack * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function stackGet(key) { return this.__data__.get(key); } /** * Checks if a stack value for `key` exists. * * @private * @name has * @memberOf Stack * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function stackHas(key) { return this.__data__.has(key); } /** * Sets the stack `key` to `value`. * * @private * @name set * @memberOf Stack * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the stack cache instance. */ function stackSet(key, value) { var cache = this.__data__; if (cache instanceof ListCache) { var pairs = cache.__data__; if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { pairs.push([key, value]); return this; } cache = this.__data__ = new MapCache(pairs); } cache.set(key, value); return this; } // Add methods to `Stack`. Stack.prototype.clear = stackClear; Stack.prototype['delete'] = stackDelete; Stack.prototype.get = stackGet; Stack.prototype.has = stackHas; Stack.prototype.set = stackSet; /** * Creates an array of the enumerable property names of the array-like `value`. * * @private * @param {*} value The value to query. * @param {boolean} inherited Specify returning inherited property names. * @returns {Array} Returns the array of property names. */ function arrayLikeKeys(value, inherited) { // Safari 8.1 makes `arguments.callee` enumerable in strict mode. // Safari 9 makes `arguments.length` enumerable in strict mode. var result = (isArray(value) || isArguments(value)) ? baseTimes(value.length, String) : []; var length = result.length, skipIndexes = !!length; for (var key in value) { if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && (key == 'length' || isIndex(key, length)))) { result.push(key); } } return result; } /** * Assigns `value` to `key` of `object` if the existing value is not equivalent * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignValue(object, key, value) { var objValue = object[key]; if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || (value === undefined && !(key in object))) { object[key] = value; } } /** * Gets the index at which the `key` is found in `array` of key-value pairs. * * @private * @param {Array} array The array to inspect. * @param {*} key The key to search for. * @returns {number} Returns the index of the matched value, else `-1`. */ function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq(array[length][0], key)) { return length; } } return -1; } /** * The base implementation of `_.assign` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssign(object, source) { return object && copyObject(source, keys(source), object); } /** * The base implementation of `_.clone` and `_.cloneDeep` which tracks * traversed objects. * * @private * @param {*} value The value to clone. * @param {boolean} [isDeep] Specify a deep clone. * @param {boolean} [isFull] Specify a clone including symbols. * @param {Function} [customizer] The function to customize cloning. * @param {string} [key] The key of `value`. * @param {Object} [object] The parent object of `value`. * @param {Object} [stack] Tracks traversed objects and their clone counterparts. * @returns {*} Returns the cloned value. */ function baseClone(value, isDeep, isFull, customizer, key, object, stack) { var result; if (customizer) { result = object ? customizer(value, key, object, stack) : customizer(value); } if (result !== undefined) { return result; } if (!isObject(value)) { return value; } var isArr = isArray(value); if (isArr) { result = initCloneArray(value); if (!isDeep) { return copyArray(value, result); } } else { var tag = getTag(value), isFunc = tag == funcTag || tag == genTag; if (isBuffer(value)) { return cloneBuffer(value, isDeep); } if (tag == objectTag || tag == argsTag || (isFunc && !object)) { if (isHostObject(value)) { return object ? value : {}; } result = initCloneObject(isFunc ? {} : value); if (!isDeep) { return copySymbols(value, baseAssign(result, value)); } } else { if (!cloneableTags[tag]) { return object ? value : {}; } result = initCloneByTag(value, tag, baseClone, isDeep); } } // Check for circular references and return its corresponding clone. stack || (stack = new Stack); var stacked = stack.get(value); if (stacked) { return stacked; } stack.set(value, result); if (!isArr) { var props = isFull ? getAllKeys(value) : keys(value); } arrayEach(props || value, function(subValue, key) { if (props) { key = subValue; subValue = value[key]; } // Recursively populate clone (susceptible to call stack limits). assignValue(result, key, baseClone(subValue, isDeep, isFull, customizer, key, value, stack)); }); return result; } /** * The base implementation of `_.create` without support for assigning * properties to the created object. * * @private * @param {Object} prototype The object to inherit from. * @returns {Object} Returns the new object. */ function baseCreate(proto) { return isObject(proto) ? objectCreate(proto) : {}; } /** * The base implementation of `getAllKeys` and `getAllKeysIn` which uses * `keysFunc` and `symbolsFunc` to get the enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @param {Function} keysFunc The function to get the keys of `object`. * @param {Function} symbolsFunc The function to get the symbols of `object`. * @returns {Array} Returns the array of property names and symbols. */ function baseGetAllKeys(object, keysFunc, symbolsFunc) { var result = keysFunc(object); return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); } /** * The base implementation of `getTag`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { return objectToString.call(value); } /** * The base implementation of `_.isNative` without bad shim checks. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. */ function baseIsNative(value) { if (!isObject(value) || isMasked(value)) { return false; } var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor; return pattern.test(toSource(value)); } /** * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeys(object) { if (!isPrototype(object)) { return nativeKeys(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty.call(object, key) && key != 'constructor') { result.push(key); } } return result; } /** * Creates a clone of `buffer`. * * @private * @param {Buffer} buffer The buffer to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Buffer} Returns the cloned buffer. */ function cloneBuffer(buffer, isDeep) { if (isDeep) { return buffer.slice(); } var result = new buffer.constructor(buffer.length); buffer.copy(result); return result; } /** * Creates a clone of `arrayBuffer`. * * @private * @param {ArrayBuffer} arrayBuffer The array buffer to clone. * @returns {ArrayBuffer} Returns the cloned array buffer. */ function cloneArrayBuffer(arrayBuffer) { var result = new arrayBuffer.constructor(arrayBuffer.byteLength); new Uint8Array(result).set(new Uint8Array(arrayBuffer)); return result; } /** * Creates a clone of `dataView`. * * @private * @param {Object} dataView The data view to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned data view. */ function cloneDataView(dataView, isDeep) { var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); } /** * Creates a clone of `map`. * * @private * @param {Object} map The map to clone. * @param {Function} cloneFunc The function to clone values. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned map. */ function cloneMap(map, isDeep, cloneFunc) { var array = isDeep ? cloneFunc(mapToArray(map), true) : mapToArray(map); return arrayReduce(array, addMapEntry, new map.constructor); } /** * Creates a clone of `regexp`. * * @private * @param {Object} regexp The regexp to clone. * @returns {Object} Returns the cloned regexp. */ function cloneRegExp(regexp) { var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); result.lastIndex = regexp.lastIndex; return result; } /** * Creates a clone of `set`. * * @private * @param {Object} set The set to clone. * @param {Function} cloneFunc The function to clone values. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned set. */ function cloneSet(set, isDeep, cloneFunc) { var array = isDeep ? cloneFunc(setToArray(set), true) : setToArray(set); return arrayReduce(array, addSetEntry, new set.constructor); } /** * Creates a clone of the `symbol` object. * * @private * @param {Object} symbol The symbol object to clone. * @returns {Object} Returns the cloned symbol object. */ function cloneSymbol(symbol) { return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; } /** * Creates a clone of `typedArray`. * * @private * @param {Object} typedArray The typed array to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned typed array. */ function cloneTypedArray(typedArray, isDeep) { var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); } /** * Copies the values of `source` to `array`. * * @private * @param {Array} source The array to copy values from. * @param {Array} [array=[]] The array to copy values to. * @returns {Array} Returns `array`. */ function copyArray(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++index < length) { array[index] = source[index]; } return array; } /** * Copies properties of `source` to `object`. * * @private * @param {Object} source The object to copy properties from. * @param {Array} props The property identifiers to copy. * @param {Object} [object={}] The object to copy properties to. * @param {Function} [customizer] The function to customize copied values. * @returns {Object} Returns `object`. */ function copyObject(source, props, object, customizer) { object || (object = {}); var index = -1, length = props.length; while (++index < length) { var key = props[index]; var newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined; assignValue(object, key, newValue === undefined ? source[key] : newValue); } return object; } /** * Copies own symbol properties of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbols(source, object) { return copyObject(source, getSymbols(source), object); } /** * Creates an array of own enumerable property names and symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeys(object) { return baseGetAllKeys(object, keys, getSymbols); } /** * Gets the data for `map`. * * @private * @param {Object} map The map to query. * @param {string} key The reference key. * @returns {*} Returns the map data. */ function getMapData(map, key) { var data = map.__data__; return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map; } /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = getValue(object, key); return baseIsNative(value) ? value : undefined; } /** * Creates an array of the own enumerable symbol properties of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbols = nativeGetSymbols ? overArg(nativeGetSymbols, Object) : stubArray; /** * Gets the `toStringTag` of `value`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ var getTag = baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11, // for data views in Edge < 14, and promises in Node.js. if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || (Map && getTag(new Map) != mapTag) || (Promise && getTag(Promise.resolve()) != promiseTag) || (Set && getTag(new Set) != setTag) || (WeakMap && getTag(new WeakMap) != weakMapTag)) { getTag = function(value) { var result = objectToString.call(value), Ctor = result == objectTag ? value.constructor : undefined, ctorString = Ctor ? toSource(Ctor) : undefined; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag; case mapCtorString: return mapTag; case promiseCtorString: return promiseTag; case setCtorString: return setTag; case weakMapCtorString: return weakMapTag; } } return result; }; } /** * Initializes an array clone. * * @private * @param {Array} array The array to clone. * @returns {Array} Returns the initialized clone. */ function initCloneArray(array) { var length = array.length, result = array.constructor(length); // Add properties assigned by `RegExp#exec`. if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { result.index = array.index; result.input = array.input; } return result; } /** * Initializes an object clone. * * @private * @param {Object} object The object to clone. * @returns {Object} Returns the initialized clone. */ function initCloneObject(object) { return (typeof object.constructor == 'function' && !isPrototype(object)) ? baseCreate(getPrototype(object)) : {}; } /** * Initializes an object clone based on its `toStringTag`. * * **Note:** This function only supports cloning values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to clone. * @param {string} tag The `toStringTag` of the object to clone. * @param {Function} cloneFunc The function to clone values. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the initialized clone. */ function initCloneByTag(object, tag, cloneFunc, isDeep) { var Ctor = object.constructor; switch (tag) { case arrayBufferTag: return cloneArrayBuffer(object); case boolTag: case dateTag: return new Ctor(+object); case dataViewTag: return cloneDataView(object, isDeep); case float32Tag: case float64Tag: case int8Tag: case int16Tag: case int32Tag: case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: return cloneTypedArray(object, isDeep); case mapTag: return cloneMap(object, isDeep, cloneFunc); case numberTag: case stringTag: return new Ctor(object); case regexpTag: return cloneRegExp(object); case setTag: return cloneSet(object, isDeep, cloneFunc); case symbolTag: return cloneSymbol(object); } } /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { length = length == null ? MAX_SAFE_INTEGER : length; return !!length && (typeof value == 'number' || reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length); } /** * Checks if `value` is suitable for use as unique object key. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is suitable, else `false`. */ function isKeyable(value) { var type = typeof value; return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') ? (value !== '__proto__') : (value === null); } /** * Checks if `func` has its source masked. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` is masked, else `false`. */ function isMasked(func) { return !!maskSrcKey && (maskSrcKey in func); } /** * Checks if `value` is likely a prototype object. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ function isPrototype(value) { var Ctor = value && value.constructor, proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; return value === proto; } /** * Converts `func` to its source code. * * @private * @param {Function} func The function to process. * @returns {string} Returns the source code. */ function toSource(func) { if (func != null) { try { return funcToString.call(func); } catch (e) {} try { return (func + ''); } catch (e) {} } return ''; } /** * This method is like `_.clone` except that it recursively clones `value`. * * @static * @memberOf _ * @since 1.0.0 * @category Lang * @param {*} value The value to recursively clone. * @returns {*} Returns the deep cloned value. * @see _.clone * @example * * var objects = [{ 'a': 1 }, { 'b': 2 }]; * * var deep = _.cloneDeep(objects); * console.log(deep[0] === objects[0]); * // => false */ function cloneDeep(value) { return baseClone(value, true, true); } /** * Performs a * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ function eq(value, other) { return value === other || (value !== value && other !== other); } /** * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, * else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ function isArguments(value) { // Safari 8.1 makes `arguments.callee` enumerable in strict mode. return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); } /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ function isArrayLike(value) { return value != null && isLength(value.length) && !isFunction(value); } /** * This method is like `_.isArrayLike` except that it also checks if `value` * is an object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array-like object, * else `false`. * @example * * _.isArrayLikeObject([1, 2, 3]); * // => true * * _.isArrayLikeObject(document.body.children); * // => true * * _.isArrayLikeObject('abc'); * // => false * * _.isArrayLikeObject(_.noop); * // => false */ function isArrayLikeObject(value) { return isObjectLike(value) && isArrayLike(value); } /** * Checks if `value` is a buffer. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. * @example * * _.isBuffer(new Buffer(2)); * // => true * * _.isBuffer(new Uint8Array(2)); * // => false */ var isBuffer = nativeIsBuffer || stubFalse; /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 8-9 which returns 'object' for typed array and other constructors. var tag = isObject(value) ? objectToString.call(value) : ''; return tag == funcTag || tag == genTag; } /** * Checks if `value` is a valid array-like length. * * **Note:** This method is loosely based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return !!value && (type == 'object' || type == 'function'); } /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return !!value && typeof value == 'object'; } /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * for more details. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ function keys(object) { return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); } /** * This method returns a new empty array. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {Array} Returns the new empty array. * @example * * var arrays = _.times(2, _.stubArray); * * console.log(arrays); * // => [[], []] * * console.log(arrays[0] === arrays[1]); * // => false */ function stubArray() { return []; } /** * This method returns `false`. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {boolean} Returns `false`. * @example * * _.times(2, _.stubFalse); * // => [false, false] */ function stubFalse() { return false; } module.exports = cloneDeep; }); // ----------------------------------------------------------------------------- function add_custom_getters( context, target, getters ) { if ( target.getters ) { warn(WARNING_NAME_CONFLICT, "Name conflict: property getters already exists"); } else { target.getters = {}; } var computed = {}; var loop = function ( key ) { var fn = getters[key]; computed[ key ] = function () { return fn.apply(target, context); }; /* if ( Object.prototype.hasOwnProperty.call( target, key ) ) { let name = context.$model.name; warn(WARNING_NAME_CONFLICT, `Name conflict: property "${key}" has same name as an existing class property "${key}" in ${name}`); continue } */ Object.defineProperty( target.getters, key, { get: function () { return _vm[key]; }, enumerable: true }); }; for ( var key in getters ) loop( key ); var _vm = new _Vue({ computed: computed }); return _vm; } // ----------------------------------------------------------------------------- function add_custom_actions( context, target, actions, reset ) { var loop = function ( key ) { var action = actions[ key ]; if ( reset ) { delete target[ key ]; } if ( Object.prototype.hasOwnProperty.call( target, key ) ) { var name = context.$model.name; warn(WARNING_NAME_CONFLICT, ("Name conflict: action \"" + key + "\" has same name as another method or property \"" + key + "\" in " + name)); return } Object.defineProperty( target, key, { value: function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; // Assign $models at run time if ( context.$modelsGetter ) { context.$models = context.$modelsGetter(); } return action.apply(target, [context ].concat( args) ); }, enumerable: true // otherwise not cloned }); }; for ( var key in actions ) loop( key ); } // export default from './moment-enhanced'; /** * * @param {any} o * @returns {boolean} */ function isObject$1 (o) { return o && typeof o === 'object' && !Array.isArray(o); } /** * walkGet * * first item in path MUST exist * * @param {Record<string, any>} obj * @param {string} path * @returns {any} or undefined if path not found */ function walkGet (obj, path) { return path.split('.').reduce(function (target, key) { return target[key]; }, obj) } /** * walkGet * * @param {Record<string, any>} obj * @param {string} path * @returns {any} or {} if path not found */ function walkGetObjectSave (obj, path) { return path.split('.').reduce(function (target, key) { return target[key] || {}; }, obj) } function walkGetPropSave (obj, path) { // return path.split('.').reduce((target, key) => target[key] || {}, obj) var keys = ('' + path).split('.'); var key = keys.pop(); var target = keys.reduce(function (target, key) { return target[key] || {}; }, obj); return target[ key ] } /** * * @param {Record<string, any>} obj * @param {string} path * @param {object} data * @returns * * @exammple * let obj = { a: { b: { p1: 'A', p2: 'B', p3: { p31: 'C'}, _tasks: {} } } } * let data = { p1: 'A*', p3: { p31: 'C*', p32: 'D*' } } // p2 has been deleted, p32 was added * walkSetMerge( obj, 'a.b', data) * > obj = { a: { b: { p1: 'A*', p3: { p31: 'C*', p32: 'D*'}, _tasks: {} } } } * * let obj = { a: { b: { ... } } } * walkSetMerge( obj, 'a.c', data) * > obj = { a: { b: { ... }, c: data } } */ function walkSetVueProp (obj, path, data) { // TODO: What if path does not exist? option -p ? var keys = ('' + path).split('.'); // keys = 'a.b' => ['a', 'b'] (e.g a = 'goal', b = 'ASD1S4DA5S4D3') var key = keys.pop(); // key = 'b' // const target = keys.reduce((target, key) => target[key], obj) // object at location obj['a'] var target = keys.reduce(function (target, key) { if ( !( key in target ) ) { _Vue.set( target, key, {} ); } return target[key] }, obj); /* if ( !( key in target ) ) { target[ key ] = data; return } */ // TODO: Improve error message. Something better than: // Uncaught (in promise) TypeError: Cannot read property 'res' of undefined // at eval (utils.js?7e75:109) /* Backup everything that starts with '_' */ /* let backup = {}; Object.keys(target[ key ]) .filter( k => k.startsWith('_') ) .forEach( k => { backup[ k ] = target[ key ][ k ] } ) */ /* Merge data with backup */ // target[ key ] = Object.assign({}, data, backup) --> geht nicht!!! _Vue.set( target, key, data ); return target[ key ]; } /* function mergeDeep(target, source) { if (isObject(target) && isObject(source)) { for (const key in source) { if (isObject(source[key])) { if (!target[key]) Object.assign(target, { [key]: {} }); mergeDeep(target[key], source[key]); } else { Object.assign(target, { [key]: source[key] }); } } } return target; } */ /** * Deep merge two objects. * @param {Object} target - Target * @param {Object} data - Data to merge * @param {Boolean} delete_missing_fields - Delete fields that are missing in data? */ function deepMergeVue( target, data, delete_missing_fields ) { if ( delete_missing_fields === void 0 ) delete_missing_fields = true; var map = delete_missing_fields ? Object.assign({}, target) : {}; for ( var prop in data ) { var target_is_object = null; var source_is_object = null; if (target) { target_is_object = isObject$1(target[ prop ]); } if (data) { source_is_object = isObject$1(data[ prop ]); } if ( target_is_object && source_is_object ) { deepMergeVue( target[ prop ], data[ prop ], delete_missing_fields ); } else { /* All other cases we can safely overwrite the data in target */ _Vue.set( target, prop, data[ prop ] ); } delete map[ prop ]; } // trace( INFO_DEEPMERG, "Remaining fields", map, data); for ( var prop$1 in map ) { trace( INFO_DEEPMERGE, "Deleting <", prop$1, ">"); _Vue.delete( target, prop$1 ); } return map } function walkSetAndMerge (obj, path, data) { // TODO: What if path does not exist? option -p ? var keys = ('' + path).split('.'); // keys = 'a.b' => ['a', 'b'] (e.g a = 'goal', b = 'ASD1S4DA5S4D3') var key = keys.pop(); // key = 'b' var target = keys.reduce(function (target, key) { // object at location obj['a'] if ( !( key in target ) ) { _Vue.set( target, key, {} ); } return target[key] }, obj); if ( key in target ) { // INFO: Sollte nicht mehr auftreten - trozdem warning ausgeben // TODO: What about deleting items? trace( INFO_DEEPMERGE, "Existing data found -> Performing deep merge at '", key, "' of target", target, "with source", data); if ( '.value' in data && data['.value'] === null ) { trace( INFO_DEEPMERGE, "New data is null, deleting node at <", key, ">"); _Vue.delete( target, key ); return } /* for ( let prop in data ) { Vue.set( target[key], prop, data[ prop ] ) } */ deepMergeVue( target[key], data, true ); } else { _Vue.set( target, key, data ); } return target[ key ]; } var externalVMStore = new WeakMap(); // Exclude vm from instance, so it can be serialized var externalModelStore = new WeakMap(); // Stores generic store references var SERVER_TIMESTAMP_ALIASES = [ 'ServerTimestamp', 'CurrentTimestamp', 'InitialTimestamp' ]; var GenericModel = function GenericModel( schema, data, name ) { // TODO: Hide internal data from user this.$ready = false; /* This promise will resolve once the data is ready */ this.$promise = Promise.resolve(); this.$state = {}; this.$dirty = {}; this.$invalid = {}; this.$id = null; this.$idx = null; this.$noaccess = null; this._store_name= name; this._validation_behaviour = 'WARNING'; _Vue.observable( this.$state ); // TODO: Check if we get an error here // Vue.observable( this.$ready ); // this.$state = Vue.oberservable({}); }; var prototypeAccessors = { $isValid: { configurable: true },$key: { configurable: true },$vm: { configurable: true },$model: { configurable: true },$exists: { configurable: true } }; // --------------------------------------------------------------------------- GenericModel.prototype._update_data = function _update_data ( data, schema, make_dirty ) { if ( make_dirty === void 0 ) make_dirty = false; this.$state = data; // otherwise no reactivity if ( make_dirty ) { for ( var key in data ) { this.$dirty[ key ] = true; } } /*schema.forEach(field => { let propName = field.model; if ( propName in data ) { this.$state[ propName ] = data[ propName ]; } })*/ }; // --------------------------------------------------------------------------- GenericModel.prototype.clone = function clone () { var copy = Object.assign( Object.create( Object.getPrototypeOf(this)), this); copy.$state = lodash_clonedeep( copy.$state ); copy.$dirty = lodash_clonedeep( copy.$dirty ); copy.$invalid = lodash_clonedeep( copy.$invalid ); copy._autogenerate_props( this.$model.modelDefinition.schema.fields, copy.$state, false ); copy._set_generic_store( this.$model ); externalVMStore.set( copy, this.$vm ); return copy; }; // --------------------------------------------------------------------------- /* _write_field(key, value) { // TODO: We should not alter the state here!!! // Create a copy! this.$state[ key ] = value; this.$dirty[ key ] = true; } */ GenericModel.prototype.setValidationBehaviour = function setValidationBehaviour ( value ) { // TODO: Use enum if ( ['ERROR', 'WARNING', 'ELEMENT_VALIDATION', 'NONE'].includes( value ) ) { this._validation_behaviour = value; } }; GenericModel.prototype._update_field = function _update_field ( propName, value, field ) { var this$1 = this; var validation_behaviour = this._validation_behaviour || 'WARNING'; var prop_set = field.is_nested ? function () { return walkSetVueProp( this$1.$state, propName, value ); } : function () { return _Vue.set( this$1.$state, propName, value ); }; if ( moment.isMoment( value ) ) { /* Handle moment object as input */ if ( !moment.isValidDate( value ) ) { warn( WARNING_MODEL_INVALID_MOMENT, "Got invalid (enhanced) moment object", value, "for prop", propName); } value = value.toRealtimeDB(); /* convert to internal timestamp */ delete this.$invalid[ propName ]; this.$dirty[ propName ] = true; prop_set(); return } if ( !field.validator ) { /* No validate callback found */ /* Fixes bug where non existing fields are assigned */ // Vue.set( this.$state, propName, value ); prop_set(); // this.$state[ propName ] = value; this.$dirty[ propName ] = true; return } // TODO: bolt type validation if ( field.validator( value ) ) { // this._write_field( propName, value ); // this.$state[ propName ] = value; delete this.$invalid[ propName ]; this.$dirty[ propName ] = true; prop_set(); } else { // this._write_field( propName, value ); // this.$state[ propName ] = value; this.$invalid[ propName ] = true; this.$dirty[ propName ] = true; prop_set(); if ( validation_behaviour === 'ERROR' ) { throw new Error(("Validation failed for field '" + propName + "' with value " + value + ".")); } if ( validation_behaviour === 'WARNING' ) { warn(WARNING_CLIENT_VALIDATION, ("Validation failed for field '" + propName + "' with value " + value + ".")); } } }; // --------------------------------------------------------------------------- GenericModel.prototype._on_remove = function _on_remove () { this.$deleted = true; // TODO // This is called when the item is going to be removed //- maybe allow subscribers and call them here }; // --------------------------------------------------------------------------- prototypeAccessors.$isValid.get = function () { return Object.keys( this.$invalid ).length === 0; }; // --------------------------------------------------------------------------- prototypeAccessors.$key.get = function () { return 'KEY-' + this._store_name + '-' + this.$id; }; // --------------------------------------------------------------------------- prototypeAccessors.$vm.get = function () { return externalVMStore.get( this ) }; // --------------------------------------------------------------------------- prototypeAccessors.$model.get = function () { return externalModelStore.get( this ) }; // --------------------------------------------------------------------------- prototypeAccessors.$exists.get = function () { return this.$state[ '.exists' ] !== false; }; // --------------------------------------------------------------------------- GenericModel.prototype._autogenerate_props = function _autogenerate_props ( schema, data, is_dirty ) { var this$1 = this; if ( is_dirty === void 0 ) is_dirty = false; // TODO: move to util if ( !Array.isArray( schema ) ) { schema = Object.keys(schema).map(function (key) { return Object.assign({}, {model: key}, schema[key]) }); } schema.forEach(function (field) { var propName = field.model; if ( data && propName in data ) { this$1.$state[ propName ] = data[ propName ]; } /* else { this.$state[ propName ] = field.placeholder; } */ if ( is_dirty ) { this$1.$dirty[ propName ] = true; } if ( Object.prototype.hasOwnProperty.call(this$1, propName ) ) { warn(WARNING_NAME_CONFLICT, ("Name conflict: property \"" + propName + "\" has same name as global action/global getter \"" + propName + "\" in " + (this$1._store_name))); return } var prop_getter = function () {}; var prop_path = ''; if ( propName.includes('/') || propName.includes('.') ) { prop_path = propName.replace(/\//g, '.'); var prop_keys = prop_path.split('.'); var prop_last_key = prop_keys.pop(); prop_keys = prop_keys.join('.'); prop_getter = function () { // return walkGetPropSave( this.$state, prop_path ) var parent = walkGetObjectSave( this$1.$state, prop_keys ); return parent[ prop_last_key ] }; field.is_nested = true; } else { prop_path = propName; prop_getter = function () { return this$1.$state[ propName ]; }; field.is_nested = false; } if ( field.type ) { var validate_timestamp = function (value, moment_conversion_func, min_date, max_date) { if ( value === 0 || value === null ) { return value // TODO: Allow null instead of 0 } else if ( moment.isMoment( value ) ) { throw new Error("Assigning moment objects directly to property is not allowed."); } else if ( isFinite( value ) && value > min_date && value < max_date ) { return moment_conversion_func( value ); } else if ( value === undefined ) { // This is potentially dangerous, since it could return the current time // NaN should usually create an invalid moment object return moment_conversion_func( NaN ); } else { warn(WARNING_INVALID_TIMESTAMP_SERVER, "Schema defined", propName, "as Timestamp, but got invalid data:", value); // return value return moment(value) } }; var prop_getter_original = prop_getter; if ( field.type === 'Timestamp' ) { prop_getter = function () { var min_date = 200000000; // '1976-05-03' var max_date = 30000000000; // '2065-01-24' return validate_timestamp( prop_getter_original(), moment.fromRealtimeDB, min_date, max_date) }; } else if ( SERVER_TIMESTAMP_ALIASES.includes( field.type ) ) { prop_getter = function () { var min_date = 200000000 * 1000; // '1976-05-03' var max_date = 30000000000 * 1000; // '2065-01-24' return validate_timestamp( prop_getter_original(), moment.fromRealtimeServerTime, min_date, max_date) }; } else if ( field.type.includes( 'Timestamp' ) ) { warn( WARNING_UNKNOWN_TIMESTAMP_TYPE, "Found validation type that contains 'Timestamp' but is not recognized.", field.type ); } // TODO: Also validate other types } Object.defineProperty(this$1, prop_path, { set: function (value) { return this$1._update_field( prop_path, value, field ); }, get: prop_getter }); }); }; // --------------------------------------------------------------------------- GenericModel.prototype._decorate_actions = function _decorate_actions ( modelActions, context ) { if ( !modelActions ) { return } /* context.model = this; // HACK for ( let key in modelActions ) { let action = modelActions[ key ]; if ( Object.prototype.hasOwnProperty.call( this, key ) ) { warn(WARNING_NAME_CONFLICT, `Name conflict: action "${key}" has same name as property/global action/global getter "${key}" in ${this._store_name}`); continue } Object.defineProperty( this, key, { value: () => action(context) } ) // TODO: bind this? } */ var action_context = { $instance: this, $model: context.model, $models: context.models, }; add_custom_actions( action_context, this, modelActions, false ); }; // --------------------------------------------------------------------------- GenericModel.prototype._decorate_getters = function _decorate_getters ( modelGetters, context ) { // TODO: move to util if ( !modelGetters ) { return } for ( var key in modelGetters ) { if ( Object.prototype.hasOwnProperty.call( this, key ) ) { warn(WARNING_NAME_CONFLICT, ("Name conflict: getter \"" + key + "\" has same name as property/custom action/global action/global getter \"" + key + "\" in " + (this._store_name))); delete modelGetters[ key ]; // ? continue } } /* Embed getter in vue instance */ var getter_context = [ this, context.model, context.models ]; var vm = add_custom_getters( getter_context, this, modelGetters ); externalVMStore.set( this, vm ); }; // --------------------------------------------------------------------------- GenericModel.prototype._set_generic_store = function _set_generic_store ( store ) { externalModelStore.set( this, store ); }; // --------------------------------------------------------------------------- GenericModel.prototype.write = function write () { var this$1 = this; // TODO: Nested data // TODO: Also check if moment objects were changed! info( INFO_MODEL, "Writing $dirty fields", JSON.stringify(this.$dirty)); var payload = {}; for ( var prop in this.$dirty ) { var value = (void 0); var prop_path = (void 0); if ( prop.includes('.') ) { prop_path = prop.replace(/\./g, '/'); value = walkGetPropSave( this.$state, prop ); } else { prop_path = prop; value = this.$state[ prop ]; } if ( typeof value === 'undefined' ) { warn(WARNING_WRITING_UNDEFINED, "Trying to write undefined for prop", prop); continue } payload[ prop_path ] = value; } var model = this.$model; if ( !model ) { throw new Error('Model reference not set with _set_generic_store'); } var is_update = true; var temp_id = this.$id; if ( !temp_id ) { temp_id = model._get_uid(); is_update = false; } /* Check if all required fields are present */ if ( model.modelDefinition && model.modelDefinition.schema ) { model._validate_schema( payload, is_update ); // DOPPELT ? } else { warn(WARNING_NO_SCHEMA, "No schema found to validate input" ); } return model.update( temp_id, payload ).then(function () { this$1.$id = temp_id; this$1.$dirty = {}; return temp_id; }); /* 'store.add' would call 'create' - not what we want here */ // TODO: Alternative { directWrite: true } }; /* ------------------------------------------------------------------------ */ GenericModel.prototype._get_model_for_write = function _get_model_for_write () { if ( !this.$id ) { throw new Error('Write operations are not allowed for new models.'); } var model = this.$model; if ( !model ) { throw new Error('Model reference not set with _set_generic_store'); } return model }; /* ------------------------------------------------------------------------ */ GenericModel.prototype.update = function update ( payload ) { var this$1 = this; var model = this._get_model_for_write(); return model.update( this.$id, payload ).then(function () { for ( var propName in payload ) { delete this$1.$dirty[ propName ]; } return this$1.$id; }); }; /* ------------------------------------------------------------------------ */ GenericModel.prototype.remove = function remove ( soft_delete ) { var this$1 = this; if ( soft_delete === void 0 ) soft_delete = null; var model = this._get_model_for_write(); if ( soft_delete == null ) { soft_delete = model.defaultDeleteMode === DeleteMode.SOFT; } return model.remove( this.$id, soft_delete ).then(function () { if ( soft_delete ) { delete this$1.$dirty[ 'deleted' ]; // ? } // TODO Mark model as deleted? }) }; /* ------------------------------------------------------------------------ */ GenericModel.prototype.restore = function restore () { var this$1 = this; var model = this._get_model_for_write(); return model.restore( this.$id ).then(function () { delete this$1.$dirty[ 'deleted' ]; // ? }) }; // ----------------------------------------------------------------------------- GenericModel.prototype.reset = function reset () { // ... }; Object.defineProperties( GenericModel.prototype, prototypeAccessors ); function sortidx_sorter(a, b) { if (a.sortidx < b.sortidx) { return -1; } if (a.sortidx > b.sortidx) { return 1; } // if (a.$state.sortidx < b.$state.sortidx) return -1; // if (a.$state.sortidx > b.$state.sortidx) return 1; return 0; } function make_property_sorter(prop) { var sorter = null; if ( prop[0] === '-' ) { prop = prop.slice(1); sorter = function (a, b) { if (a[prop] < b[prop]) { return 1; } if (a[prop] > b[prop]) { return -1; } return 0; }; } else { sorter = function (a, b) { if (a[prop] < b[prop]) { return -1; } if (a[prop] > b[prop]) { return 1; } return 0; }; } return sorter; } var externalVMStore$1 = new WeakMap(); // Exclude vm from instance, so it can be serialized // TODO: Always save items as array, but keep index {id to idx} for quick access via id // This is rather an exception, since we would normally use getNode instead var GenericList = function GenericList( name ) { this.items = {}; // $items? this.$readyAll = false; this.$readySome = false; /* This promise will resolve once ALL the data is ready */ this.$promise = Promise.resolve(); this.$numReady = 0; // TODO this.$noaccess = null; this.$numChildren = 0; this._store_name= name; this._unwatch = null; // this.$lastUpdated = null; }; var prototypeAccessors$1 = { $vm: { configurable: true },itemsSorted: { configurable: true },$idList: { configurable: true } }; // ----------------------------------------------------------------------------- GenericList.prototype._clone = function _clone () { // --> this needs more work return Object.assign( Object.create( Object.getPrototypeOf(this)), this); }; // ----------------------------------------------------------------------------- GenericList.prototype._add_child = function _add_child ( id, child ) { // TODO: Check if this.items is an array this.$readySome = true; // this.$lastUpdated = Date.now(); _Vue.set( this.items, id, child ); this.$numChildren += 1; this.items[ id ].$idx = this.$numChildren; }; // ----------------------------------------------------------------------------- GenericList.prototype._rem_child = function _rem_child ( id ) { // TODO: Check if this.items is an array if ( id in this.items ) { this.items[ id ]._on_remove(); } _Vue.delete( this.items, id ); this.$numChildren -= 1; }; // --------------------------------------------------------------------------- prototypeAccessors$1.$vm.get = function () { return externalVMStore$1.get( this ) }; // ----------------------------------------------------------------------------- GenericList.prototype._decorate_actions = function _decorate_actions ( listActions, context ) { if ( !listActions ) { return } /* context.model = this; // HACK for ( let key in listActions ) { let action = listActions[ key ]; if ( Object.prototype.hasOwnProperty.call( this, key ) ) { warn(WARNING_NAME_CONFLICT, `Name conflict: list action "${key}" has same name as existing method "${key}" in ${this._store_name}`); continue } Object.defineProperty( this, key, { value: () => action(context) } ) // TODO: bind this? } */ var action_context = { $instance: this, $model: context.model, $models: context.models, }; add_custom_actions( action_context, this, listActions, false ); }; // ----------------------------------------------------------------------------- GenericList.prototype._decorate_getters = function _decorate_getters ( listGetters, context ) { // TODO: move to util if ( !listGetters ) { return } for ( var key in listGetters ) { if ( Object.prototype.hasOwnProperty.call( this, key ) ) { warn(WARNING_NAME_CONFLICT, ("Name conflict: list getter \"" + key + "\" has same name as existing property getter \"" + key + "\" in " + (this._store_name))); delete listGetters[ key ]; // ? continue } } /* Embed getter in vue instance */ var getter_context = [ this, context.model, context.models ]; var vm = add_custom_getters( getter_context, this, listGetters ); externalVMStore$1.set( this, vm ); // "Self destroy" }; // ----------------------------------------------------------------------------- GenericList.prototype.getItemByIdx = function getItemByIdx ( idx ) { for ( var id in this.items ) { if ( this.items[ id ].$idx === idx) { return this.items[ id ] } } return null; }; // ----------------------------------------------------------------------------- GenericList.prototype.asArraySorted = function asArraySorted () { // TODO: This should not mutate item!!! var new_this = this._clone(); new_this.items = this.itemsAsArray(); new_this.items.sort(sortidx_sorter); return new_this; // let items = this.asArray(); // return items.sort(sortidx_sorter); }; // ----------------------------------------------------------------------------- GenericList.prototype.asArraySortedBy = function asArraySortedBy (prop) { var new_this = this._clone(); new_this.items = this.itemsAsArray(); new_this.items.sort(make_property_sorter( prop )); return new_this; // let items = this.asArray(); // return items.sort(make_property_sorter( prop )); }; // ----------------------------------------------------------------------------- GenericList.prototype.asArrayFilteredBy = function asArrayFilteredBy (prop, value) { var new_this = this._clone(); new_this.items = this.itemsAsArray(); new_this.items = new_this.items.filter(function (item) { return ( item[ prop ] === value ) }); return new_this; // let items = this.asArray(); // return items.filter((item) => { // return ( item.prop === value ) // }); }; // ----------------------------------------------------------------------------- // Nicht sortiert!!, Why not a getter? GenericList.prototype.itemsAsArray = function itemsAsArray () { var this$1 = this; if ( Array.isArray( this.items ) ) { return this.items; } return Object.keys( this.items ).map( function (id) { return this$1.items[ id ]; }) }; // ----------------------------------------------------------------------------- prototypeAccessors$1.itemsSorted.get = function () { return this.itemsAsArray().sort(sortidx_sorter); }; // ----------------------------------------------------------------------------- GenericList.prototype.itemsAsArrayWithoutDeleted = function itemsAsArrayWithoutDeleted ( custom_sortidx ) { // otherwise no reactivity return this.itemsAsArray().filter(function (item) { return item.deleted === false || item.deleted === undefined }).sort( custom_sortidx ? make_property_sorter(custom_sortidx) : sortidx_sorter); }; // ----------------------------------------------------------------------------- GenericList.prototype.itemsAsArrayOnlyDeleted = function itemsAsArrayOnlyDeleted ( custom_sortidx ) { return this.itemsAsArray().filter(function (item) { return item.deleted === true }).sort( custom_sortidx ? make_property_sorter(custom_sortidx) : sortidx_sorter); }; // ----------------------------------------------------------------------------- prototypeAccessors$1.$idList.get = function () { // TODO: Here or static in $models.example? return Object.keys( this.items ); }; // ----------------------------------------------------------------------------- GenericList.prototype.reset = function reset () { if ( this._unwatch ) { info(INFO_COLLECTION, "Found local un-watcher in", this._store_name); this._unwatch(); } }; Object.defineProperties( GenericList.prototype, prototypeAccessors$1 ); /** * Joint for joining more than 2 functions. * Joins an array of functions together to return a single function * * Source: https://github.com/Dayjo/joint * * @param {array} a An array of functions * @return {function} Returns a function which is an accumilation of functions in 'a' */ function joint( a ) { var b = a[(a.length - 1)]; a.pop(); a = a.length > 1 ? joint( a ) : a[0]; return function() { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; // eslint-disable-next-line // b.apply( new a(...args), args ); /* // args is object var ra = a(args) var rb = b(args) return Object.assign(args, ra, rb) */ var ra = a.apply(void 0, args); var rb = b.apply(void 0, args); // can overwrite result from a return Object.assign(ra || {}, rb) }; } // types.js var HELIOSRX_INIT_VALUE = 'heliosrx/INIT_VALUE'; var HELIOSRX_UNSET_VALUE = 'heliosrx/UNSET_VALUE'; var HELIOSRX_ARRAY_SET = 'heliosrx/ARRAY_SET'; var HELIOSRX_ARRAY_ADD = 'heliosrx/ARRAY_ADD'; var HELIOSRX_ARRAY_REMOVE = 'heliosrx/ARRAY_REMOVE'; var HELIOSRX_SET = 'heliosrx/SET'; /* export const HELIOSRX_INIT_REGISTRY = 'heliosrx/INIT_REGISTRY' export const HELIOSRX_RESET_REGISTRY = 'heliosrx/RESET_REGISTRY' export const HELIOSRX_ADD_ENTRY = 'heliosrx/ADD_ENTRY' export const HELIOSRX_SET_ENTRY_STATUS = 'heliosrx/SET_ENTRY_STATUS' export const HELIOSRX_SET_GLOBAL_READY_STATE = 'heliosrx/SET_GLOBAL_READY_STATE' export const HELIOSRX_REM_GLOBAL_READY_STATE = 'heliosrx/REM_GLOBAL_READY_STATE' */ // ----------------------------------------------------------------------------- function rtdbFetchAsObject (ref) { var document = ref.document; var ops = ref.ops; var resolve = ref.resolve; var reject = ref.reject; var ref$1 = ops.init(); var target = ref$1.target; document.once('value', function (snapshot) { // INFO: This is not called, when the data does not exist var data = snapshot.val(); if ( !snapshot.exists() ) { data = { '.exists': false }; } ops.set( target, data ); resolve( data ); }, function (err) { if ( err ) { reject(err); } }); return function () {} } // ----------------------------------------------------------------------------- function rtdbFetchAsArray (ref) { var collection = ref.collection; var ops = ref.ops; var resolve = ref.resolve; var reject = ref.reject; var ref$1 = ops.init(); var target = ref$1.target; collection.once('value', function (snapshot) { var data = snapshot.val(); ops.once(target, data, snapshot.exists()); resolve(data); }, function (err) { if ( err ) { reject(err); } }); return function () {} } // ----------------------------------------------------------------------------- function rtdbBindAsObject (ref) { var document = ref.document; var ops = ref.ops; var resolve = ref.resolve; var reject = ref.reject; /* INFO: Single value is not supported */ // const target = {}; var ref$1 = ops.init(); var target = ref$1.target; var listener = document.on( 'value', function (snapshot) { // let target = snapshot.ref.path.toString(); var data = snapshot.val(); // TODO: Handle snapshot.exists if ( !snapshot.exists() ) { data = { '.exists': false }; } ops.set( target, data ); // TODO: Also pass { .exists } here? resolve( data ); // Only one argument allowed! }, function (err) { if ( err ) { reject(err); } } ); return function () { document.off('value', listener); } } // ----------------------------------------------------------------------------- function rtdbBindAsArray (ref) { var collection = ref.collection; var ops = ref.ops; var resolve = ref.resolve; var reject = ref.reject; // const target = {}; // [] var ref$1 = ops.init(); var target = ref$1.target; // TODO: Handle snapshot.exists collection.once('value', function (snapshot) { // INFO: This operation is currently unused! ops.once(target, snapshot.val(), snapshot.exists()); resolve(); }, function (err) { if ( err ) { reject(err); } }); var childAdded = collection.on( 'child_added', function (snapshot, prevKey) { // TWE: We're not really intersted in the order, since we ensure order via sortidx // TODO: Add sortidx for ordered queries ops.add(target, snapshot.key, snapshot.val()); }, reject ); var childRemoved = collection.on( 'child_removed', function (snapshot) { ops.remove(target, snapshot.key); }, reject ); var childChanged = collection.on( 'child_changed', function (snapshot) { ops.set( target, snapshot.key, snapshot.val() ); }, reject ); var childMoved = collection.on( // ATTENTION: This is also used for orderByChild 'child_moved', function (snapshot, prevKey) { // const index = indexForKey(target, snapshot.key) // const oldRecord = ops.remove(target, index)[0] // const newIndex = prevKey ? indexForKey(target, prevKey) + 1 : 0 // ops.add(target, newIndex, oldRecord) // TODO: Update target.sortidx // oldKey = prevKey // newKey = snapshot.key // ops.order( ) }, reject ); return function () { collection.off('child_added', childAdded); collection.off('child_changed', childChanged); collection.off('child_removed', childRemoved); collection.off('child_moved', childMoved); } } /* Defines a promise that can be resolved outside of it's scope * * Usage: * let d = defer() * d.then((x) => console.log('Hello World', x)) * d.resolve(123) * Output > Hello World 123 */ // See: http://lea.verou.me/2016/12/resolve-promises-externally-with-this-one-weird-trick/ function defer() { var res, rej; var promise = new Promise(function (resolve, reject) { res = resolve; rej = reject; }); promise.resolve = res; promise.reject = rej; return promise; } /* Extend native Array. Not best practive, but at least it's done the right way (prototype, non enumerable) */ // TODO: Do not extend native types var proto = Array.prototype; Object.defineProperty(proto, 'clone', { value: function() { return this.slice(0); }, enumerable: false, configurable: true, writable: true }); Object.defineProperty(proto, 'move', { value: function(from, to) { this.splice(to, 0, this.splice(from, 1)[0]); }, enumerable: false, configurable: true, writable: true }); function arrayDiff( array1, array2 ) { return array1.filter(function (i) { return array2.indexOf(i) < 0; } ); } function arrayDiffTwoWay( new_list, old_list ) { return { removed: arrayDiff( old_list, new_list ), added: arrayDiff( new_list, old_list ) } } /******************************************************************************* - xTODO: status should be stores in root.status or delete 'sync' / 'status' - xTODO: reg.*.data should be created "on-the-fly" without storing it in the db - xTODO: Return classes instead of object (tested - works with observable) - TODO: sharding support *******************************************************************************/ var LOCAL_PATH_PREFIX = 'res.'; var log0 = function (name) { var args = [], len = arguments.length - 1; while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ]; return trace.apply( void 0, [ INFO_SUBSCRIBE_QUERY, ("[" + name + "]") ].concat( args )); }; var log1 = function (name) { var args = [], len = arguments.length - 1; while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ]; return trace.apply( void 0, [ INFO_SUBSCRIBE, ("[" + name + "]") ].concat( args )); }; var log2 = function (name) { var args = [], len = arguments.length - 1; while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ]; return trace.apply( void 0, [ INFO_SUBSCRIBE_DETAILS, ("[" + name + "]") ].concat( args )); }; var log3 = function (name) { var args = [], len = arguments.length - 1; while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ]; return trace.apply( void 0, [ INFO_READ_INIT, ("[" + name + "]") ].concat( args )); }; var log4 = function (name) { var args = [], len = arguments.length - 1; while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ]; return trace.apply( void 0, [ INFO_READ_REMOVE, ("[" + name + "]") ].concat( args )); }; // const log_stringify = (v) => JSON.stringify(v) var log_stringify = function (v) { return null; }; var subscriptions = new WeakMap(); var _autoUnsubscribeMap = new Map(); var _resultInstanceCache = new Map(); var _resultListCache = new Map(); if ( String(process.env.VUE_APP_PRODUCTION) === 'false' ) { window.helioRxDev = window.helioRxDev || {}; window.helioRxDev._resultInstanceCache = _resultInstanceCache; window.helioRxDev._resultListCache = _resultListCache; window.helioRxDev._autoUnsubscribeMap = _autoUnsubscribeMap; } // ----------------------------------------------------------------------------- var ReadMixin = { // --------------------------------------------------------------------------- _read_mixin_init: function _read_mixin_init() { log2(this.name, "[GENS:LOADER] init"); if ( this.modelDefinition ) { if ( this.modelDefinition.staticGetters ) { // Careful: $store will point to the root instance not a with/clone-instance! // const context = [ this, _models, registry ]; // const context = this._create_context() var context = [ this, _models ]; this._vm = add_custom_getters( context, this, this.modelDefinition.staticGetters ); } } }, // --------------------------------------------------------------------------- /** * get subscriptions - Returns subscriptions that were create by this store * * @return {list} list of subscriptions */ get subscriptions() { // TODO: might not work return subscriptions.get( this ); }, // --------------------------------------------------------------------------- /** * _bind_rtdb - Firebase binding * * Adapted from: * see: https://github.com/vuejs/vuefire/blob/feat/rtdb/packages/vuexfire/src/rtdb/index.js * * @param {{ key, ref, ops, bindAsArray }} obj - config * @param {string} obj.key - Key where the data is stored locally * @param {firebase.database.ref} obj.ref - Firebase Realtime Database reference * @param {type} obj.ops - operations {init, add, remove, set, set_sync} * @param {boolean} obj.bindAsArray. - bind as list (true), bind as document (false) */ _bind_rtdb: function _bind_rtdb(ref$1) { var this$1 = this; var key = ref$1.key; var ref = ref$1.ref; var ops = ref$1.ops; var bindAsArray = ref$1.bindAsArray; // TODO check ref is valid // TODO check defined in vm // INFO: Why do we need subscriptions? Isn't that the same as the instance cache and the registry? // subscritions is a liittle bit more fundamental = real listeners // registry = reactive data (but used where?) // instance cache = cached subscriptions (real and 'simulated') as generic models // Keep track of of Vue components that subscribed to data and automatically // unsubscribe when the component is destroyed. var last_caller = this._last_caller || null; if ( this.autoUnsubscribe && last_caller ) { // Create or update an existing unsubscribe function nd save it to _autoUnsubscribeMap var unsubscribeFn = function () { var obj; this$1._unbind_rtdb(key); return ( obj = {}, obj[key] = true, obj ); }; var existingFn = _autoUnsubscribeMap.get( last_caller.uid ); if ( existingFn ) { unsubscribeFn = joint([ unsubscribeFn, existingFn ]); } _autoUnsubscribeMap.set( last_caller._uid, unsubscribeFn ); // Register beforeDestroy life-cycle hook on the vue component. // TODO: Maybe _autoUnsubscribeMap can be removed entirely last_caller.$once('hook:beforeDestroy', function () { this$1._clean_up_refs( last_caller ); }); } var sub = subscriptions.get(this); if (!sub) { sub = Object.create(null); subscriptions.set(this, sub); } // unbind if ref is already bound if (key in sub) { this._unbind_rtdb(key); } // if ( subscriptions.get(key) ) { } return new Promise(function (resolve, reject) { sub[ key ] = bindAsArray ? rtdbBindAsArray({ key: key, collection: ref, ops: ops, resolve: resolve, reject: reject }) : rtdbBindAsObject({ key: key, document: ref, ops: ops, resolve: resolve, reject: reject }); // subscriptions.set(key, unsubscribe) }) }, // --------------------------------------------------------------------------- /** * Will be called on hook:beforeDestroy for each VueComponent that accessed * this.$models and then made a subscription (via _bind_rtdb). * */ _clean_up_refs: function _clean_up_refs( caller ) { var unsubscribeFn = _autoUnsubscribeMap.get( caller._uid ); var name = caller.$options.name || caller.$options._componentTag; if ( unsubscribeFn ) { var keys = unsubscribeFn(); info(INFO_AUTO_UNSUBSCRIBE, "%cIt seems that the VueComponent \"" + name + "\" (" + (caller.$vnode.tag) + "), \n" + "accessed this.$models and created a subscriptions. The components \n" + "just got destroyed and so did it's subscription to " + (JSON.stringify(Object.keys(keys))) + ".", 'color: green'); } else { info(INFO_AUTO_UNSUBSCRIBE, "%cIt seems that the VueComponent \"" + name + "\" (" + (caller.$vnode.tag) + "), \n" + "accessed this.$models, but it either didn't create any subscriptions or \n" + "the subscription was already removed. The component just got destroyed \n" + "so there is nothing to clean up.", 'color: darkgoldenrod'); } _autoUnsubscribeMap.delete( caller._uid ); }, // --------------------------------------------------------------------------- /** * _fetch_rtdb - Firebase binding * */ _fetch_rtdb: function _fetch_rtdb(ref$1) { var key = ref$1.key; var ref = ref$1.ref; var ops = ref$1.ops; var bindAsArray = ref$1.bindAsArray; return new Promise(function (resolve, reject) { bindAsArray ? rtdbFetchAsArray({ key: key, collection: ref, ops: ops, resolve: resolve, reject: reject }) : rtdbFetchAsObject({ key: key, document: ref, ops: ops, resolve: resolve, reject: reject }); }) }, // --------------------------------------------------------------------------- /** * _unbind_rtdb - Unbind firebase from location * * @param {type} { key } description */ _unbind_rtdb: function _unbind_rtdb(ref) { var key = ref.key; var sub = subscriptions.get(this); if (!sub || !sub[key]) { return } // subscriptions.delete( key ); // const sub = subscriptions.get(key) sub[key](); delete sub[key]; }, // --------------------------------------------------------------------------- /** * _infer_local_path_from_ref - Converts a firebase ref into a "walkable" path * * @param {type} ref description * @return {type} description * * Converts * "/goal/{goalId}/user_list/{uid}/task_details/ * /task_subscription", * to * "goal.{goalId}.user_list.{uid}.task_details.{id}.task_subscription", * which refers to * state.res.goal[ goalId ].user_list[ uid ].task_details[ ].task_subscription * * TODO: * state.res.goal[ goalId ].children.user_list[ uid ].children.task_details[ ].task_subscription.data * */ _infer_local_path_from_ref: function _infer_local_path_from_ref( ref ) { var path = ref.path.toString(); // return path.replace(/\//g, '.') return path.split('/').filter(function (p) { return p; }).join('.'); }, // --------------------------------------------------------------------------- /** * unsync - Stop syncing. * * @param {type} id = null description * @param {type} { clean_up = false } = {} description */ unsync: function unsync( id, ref ) { if ( id === void 0 ) id = null; if ( ref === void 0 ) ref = {}; var clean_up = ref.clean_up; if ( clean_up === void 0 ) clean_up = false; log2(this.name, "[GENS] unsync", id, clean_up); // TODO: Document difference between unsync( without id ) and unsyncAll() var key = id !== null ? this.global_store_path_array[ id ] : this.global_store_path; if ( key ) { this._unbind_rtdb({ key: key }); } if ( id !== null && !( id in this.global_store_path_array ) ) { // This is the case, when we do unsync with id, even though // a data was synced with subscribeList(). if ( this.isSuffixed ) { throw new Error('Unsync with id for data retrieved via subscribeList() is not supported.') } key = this.global_store_path + '.' + id; } if ( clean_up ) { log4(this.name, "unsync: clean up state. id:", id, "path:", key); // Find entry in GenericList and delete model if ( id !== null && _resultListCache.has( this.path ) ) { var list = _resultListCache.get( this.path ); list._rem_child( id ); } /* // TODO: Use this._match_existing_synced_nodes? let existing_path = id !== null ? this.previewPath( id ) : this.path if ( _resultInstanceCache.has( existing_path ) ) { let model = _resultInstanceCache.get( existing_path ) model.reset(); model.$noaccess = true; } */ _registry.commit( HELIOSRX_UNSET_VALUE, { path: key }, { root: true } ); } }, // --------------------------------------------------------------------------- /** * unsyncAll - Stop sycning all subscriptions of this store. * * @param {type} { clean_up = false } = {} description */ unsyncAll: function unsyncAll(ref) { var this$1 = this; if ( ref === void 0 ) ref = {}; var clean_up = ref.clean_up; if ( clean_up === void 0 ) clean_up = false; log2(this.name, "[GENS] unsyncAll", clean_up); // Make sure there is only one sync per store // Currently it is possible to sync, then change prop, then sync again - but never unsync if (!subscriptions) { return } // TODO: Testen! if ( clean_up && _resultListCache.has( this.path ) ) { var list = _resultListCache.get( this.path ); list.$idList.forEach(function (id) { return list._rem_child( id ); }); list.reset(); // ?/ } Object.keys(subscriptions).forEach(function (key) { this$1._unbind_rtdb({ key: key }); // TODO: Testen! if ( clean_up ) { _registry.commit( HELIOSRX_UNSET_VALUE, { path: key }, { root: true } ); } }); }, // --------------------------------------------------------------------------- /** * _fetch_individual - fetch an individual item of the collection * * @param {type} id description * @param {type} { overwriteKey = false } = {} description */ _fetch_individual: function _fetch_individual( id, ref ) { if ( ref === void 0 ) ref = {}; var overwriteKey = ref.overwriteKey; if ( overwriteKey === void 0 ) overwriteKey = false; var customOps = ref.customOps; if ( customOps === void 0 ) customOps = {}; return this._sync_individual(id, { overwriteKey: overwriteKey, customOps: customOps, fetchOnce: true }) }, // --------------------------------------------------------------------------- /** * fetch - fetch all items in this collection * * @param {type} { overwriteKey = false } = {} description */ _fetch_list: function _fetch_list( ref ) { if ( ref === void 0 ) ref = {}; var overwriteKey = ref.overwriteKey; if ( overwriteKey === void 0 ) overwriteKey = false; var customOps = ref.customOps; if ( customOps === void 0 ) customOps = {}; var customRef = ref.customRef; if ( customRef === void 0 ) customRef = null; return this._sync_list({ overwriteKey: overwriteKey, customOps: customOps, customRef: customRef, fetchOnce: true }) }, // --------------------------------------------------------------------------- /** * _sync_individual - sync an individual item of the collection * * @param {type} id description * @param {type} { overwriteKey = false description * @param {type} fetchOnce = false } = {} description */ _sync_individual: function _sync_individual( id, ref$1 ) { var this$1 = this; if ( ref$1 === void 0 ) ref$1 = {}; var overwriteKey = ref$1.overwriteKey; if ( overwriteKey === void 0 ) overwriteKey = false; var fetchOnce = ref$1.fetchOnce; if ( fetchOnce === void 0 ) fetchOnce = false; var customOps = ref$1.customOps; if ( customOps === void 0 ) customOps = {}; if ( !this.isSuffixed && !fetchOnce ) { warn(WARNING_SYNCING_INDIVIDUAL, "Syncing individually in " + this.name + ", even though list would be supported"); } var ref = this.childRef( id ); var key_from_ref = this._infer_local_path_from_ref( ref ); var key = LOCAL_PATH_PREFIX + key_from_ref; this.global_store_path_array[ id ] = key; log1(this.name, "_sync_individual:", this.name, key, overwriteKey, fetchOnce); log2(this.name, "[GENS] - sync ref", ref.path.toString()); log2(this.name, "[GENS] - sync key", key); log2(this.name, "[GENS] - sync target", this.global_store_path_array[ id ]); var ops = { init: function () { /* We have to make sure, we don't trigger init here and 'set' of a list at the same time */ var data = {}; log2(this$1.name, '[OPS:INIT (individual)]', data); _registry.commit(HELIOSRX_INIT_VALUE, { path: this$1.global_store_path_array[ id ], data: data }, { root: true }); return { target: data } }, set: function ( target, data ) { /* When using Server.TIMESTAMP this will get triggered twice. * Throtteling this function by approx 100ms should avoid unnecessary updates. */ log2(this$1.name, '[OPS:SET (individual)]', target, log_stringify()); // Check if data[.exists] = false ? _registry.commit(HELIOSRX_SET, { target: target, data: data }, { root: true }); } }; if ( fetchOnce ) { ops = { init: function () { log3(this$1.name, '[OPS:INIT] (fetch, individial)'); var data = {}; return { target: data } }, set: function (target, data) { log3(this$1.name, '[OPS:SET] (fetch, individial)', target, log_stringify()); } }; } /* Join custom ops and regular ops together */ Object.keys(customOps).forEach(function (op) { ops[ op ] = joint([ ops[ op ], customOps[ op ] ]); }); return fetchOnce ? this._fetch_rtdb({ key: key, ref: ref, ops: ops, bindAsArray: false }) : this._bind_rtdb({ key: key, ref: ref, ops: ops, bindAsArray: false }) }, // --------------------------------------------------------------------------- /** * sync - sync entire collection (also track child added, child removed) * * @param {type} { overwriteKey = false description * @param {type} fetchOnce = false } = {} description * * Returns a promise, that will resolve, when all items are ready * */ _sync_list: function _sync_list( ref$1 ) { var this$1 = this; if ( ref$1 === void 0 ) ref$1 = {}; var overwriteKey = ref$1.overwriteKey; if ( overwriteKey === void 0 ) overwriteKey = false; var fetchOnce = ref$1.fetchOnce; if ( fetchOnce === void 0 ) fetchOnce = false; var customOps = ref$1.customOps; if ( customOps === void 0 ) customOps = {}; var customRef = ref$1.customRef; if ( customRef === void 0 ) customRef = null; if ( this.isSuffixed ) { throw new Error('Suffixed store does not support bind to array') } var ref = customRef || this.parentRef; var key_from_ref = overwriteKey || this._infer_local_path_from_ref( ref ); var key = LOCAL_PATH_PREFIX + key_from_ref; log1(this.name, "sync:", this.name, key, overwriteKey, fetchOnce); log2(this.name, "[GENS] - ref", this.parentRef); log2(this.name, "[GENS] - key", key); this.global_store_path = key; // ?? var commitOptions = { root: true }; // TODO: move to factory in vuefire var ops = { init: function () { /* This is ANNOTIATION#1, see subscribeNode for more information. */ // log2(this.name, "[GENS-ops] init", registry.commit, HELIOSRX_INIT_VALUE, { path: this.global_store_path, data }, commitOptions); log2(this$1.name, '[OPS:INIT]', this$1.global_store_path, _registry.state); var data = {}; /* Check if there is existing data, if yes it means _sync_individual already synced data, which we should keep. */ var existing_data = walkGetObjectSave( _registry.state, this$1.global_store_path ); if ( Object.keys(existing_data).length > 0 ) { log2(this$1.name, "[OPS:INIT] existing_data", existing_data); data = existing_data; } log2(this$1.name, "[OPS:INIT] data", log_stringify()); _registry.commit(HELIOSRX_INIT_VALUE, { path: this$1.global_store_path, data: data }, commitOptions); return { target: data } }, add: function (target, newId, data) { log2(this$1.name, '[OPS:ADD]', target, newId, data, log_stringify()); _registry.commit(HELIOSRX_ARRAY_ADD, { target: target, newId: newId, data: data }, commitOptions); }, remove: function (target, oldId) { var deleted_item = target[ oldId ]; // Check if this data is still needed by another query var synced_queries = this$1._match_all_existing_synced_queries( this$1.path ); log4(this$1.name, '[OPS:REMOVE]', target, oldId); log4(this$1.name, "entry_name", this$1.path ); log4(this$1.name, "deleted_item", deleted_item ); log4(this$1.name, "_match_existing_synced_nodes", synced_queries ); for ( var idx in synced_queries ) { var query = synced_queries[idx].query; if ( this$1._item_matches_query( query, deleted_item ) ) { log4(this$1.name, "ITEM STILL IN USE", oldId, deleted_item); return // Cancel deletion of entry } } _registry.commit(HELIOSRX_ARRAY_REMOVE, { target: target, oldId: oldId }, commitOptions); // return [ target[ oldId ] ] }, set: function (target, currentId, data) { log2(this$1.name, '[OPS:SET]', target, currentId, data); _registry.commit(HELIOSRX_ARRAY_SET, { target: target, currentId: currentId, data: data }, commitOptions); }, once: function (target, data, exists) { log2("[OPS:ONCE]", data, exists); } // set_sync: (target, path, value ) => { // registry.commit(HELIOSRX_SET_SYNC_STATE, { target, path, value }, commitOptions) // } }; if ( fetchOnce ) { ops = { init: function () { log3(this$1.name, '[OPS:INIT] (fetch)', key); var data = {}; return { target: data } }, once: function (target, data, exists) { log3(this$1.name, "[OPS:ONCE] (fetch)", data, exists); } }; } /* Join custom ops and regular ops together */ Object.keys(customOps).forEach(function (op) { ops[ op ] = joint([ ops[ op ], customOps[ op ] ]); }); log2(this.name, "[GENS] - ops", ops); log2(this.name, "[GENS] - payload", { key: key, ref: ref, ops: ops, bindAsArray: true }); return fetchOnce ? this._fetch_rtdb({ key: key, ref: ref, ops: ops, bindAsArray: true }) : this._bind_rtdb({ key: key, ref: ref, ops: ops, bindAsArray: true }) }, // --------------------------------------------------------------------------- _item_matches_query: function _item_matches_query(query, item) { // info(INFO_SUBSCRIBE_QUERY, "[_item_matches_query]", query, item) // TODO: Implement this function return true; }, // --------------------------------------------------------------------------- _create_context: function _create_context() { // move to generic store return { model: this, models: _models, // will return undefined, when called before setup } }, // --------------------------------------------------------------------------- _match_all_existing_synced_queries: function _match_all_existing_synced_queries( requested_path, only_active ) { if ( only_active === void 0 ) only_active = true; // INFO: Returns all nodes that if ( requested_path.includes('#') ) { requested_path = requested_path.split('#').shift(); } var match_list = []; for ( var existing_path in _registry.state.sync ) { var existing_path_without_query = existing_path.split('#').shift(); if ( requested_path.startsWith( existing_path_without_query ) ) { var existing_query = _registry.state.sync[ existing_path ]; if ( !( only_active && ( existing_query.status === 'Ready' || existing_query.status === 'Loading' ) ) ) { continue; } match_list.push(Object.assign({}, {path: existing_path, path_without_query: existing_path_without_query}, existing_query)); } } return match_list; }, // --------------------------------------------------------------------------- _match_existing_synced_nodes: function _match_existing_synced_nodes( requested_path, subnodes_can_match_lists) { if ( subnodes_can_match_lists === void 0 ) subnodes_can_match_lists = false; // INFO: This functions is not meant to match list paths, when requesting a // child node (e.g. /test/123 wont match for existing node /test/{id}). // Instead this case is covered by the GenericModel-Cache // and GenercList-Cache. /* Remove hash key, since subscribeList has a wider scope then subscribeQuery * ( e.g. /test/{id}#---2-- should therefor match /test/{id}) * * Example: * existing_path = /goal/BWpG75DcRs-kqVPPdRbxzg/meta#hashkey * requested_path = /goal/BWpG75DcRs-kqVPPdRbxzg/meta/commitment_meta/{id} */ if ( requested_path.includes('#') ) { requested_path = requested_path.split('#').shift(); } for ( var existing_path in _registry.state.sync ) { // if ( requested_path === existing_path ) { // /* This is fine, just means we found the same node */ // continue // } var existing_path_unmodified = existing_path; // Check if path is covered by query cache (e.g. id > limit) if ( existing_path.includes('#') ) { var existing_path_without_query = existing_path.split('#').shift(); if ( requested_path.startsWith( existing_path_without_query ) ) { warn(WARNING_SYNCING_EXISTING_QUERY_PATH, "You're trying to sync a path that has already been synced by a query. This is not supported.", "requested_path", requested_path, "existing_path", existing_path); } } if ( subnodes_can_match_lists && existing_path.includes('{id}') ) { existing_path = existing_path.replace('{id}', ''); // TODO: Does not work for suffixed stores // e.g. syncing: /goal/{id}/meta // lookup: /goal/18479723/meta/abc } if ( requested_path.startsWith( existing_path ) ) { if ( _registry.state.sync[ existing_path_unmodified ].status === 'Ready' || _registry.state.sync[ existing_path_unmodified ].status === 'Loading' ) { warn(WARNING_SYNCING_SUBSET_DATA, this.name, "Found node of higher hierarchy that is already syncing:", existing_path, "vs.", requested_path); return existing_path_unmodified } } } return false; }, // --------------------------------------------------------------------------- _get_sync_state: function _get_sync_state( path ) { return (_registry.state.sync[ path ] || {}).status || null }, // --------------------------------------------------------------------------- getList: function getList( idList, ref ) { if ( ref === void 0 ) ref = {}; var noReactiveGetter = ref.noReactiveGetter; if ( noReactiveGetter === void 0 ) noReactiveGetter = false; log1(this.name, "getList", idList || '*'); return this.subscribeList( idList, { noSync: true, createModelFromExistingCache: true, noReactiveGetter: noReactiveGetter }); }, // --------------------------------------------------------------------------- getNode: function getNode( id, ref ) { if ( ref === void 0 ) ref = {}; var noReactiveGetter = ref.noReactiveGetter; if ( noReactiveGetter === void 0 ) noReactiveGetter = false; log1(this.name, "getNode", id); if ( !id ) { throw new Error('getNode: got invalid id: ' + id ) } return this.subscribeNode( id, { noSync: true, createModelFromExistingCache: true, noReactiveGetter: noReactiveGetter }) }, /* --------------------------------------------------------- subscribe list */ subscribeList: function subscribeList(idList, ref) { var this$1 = this; if ( ref === void 0 ) ref = {}; var noSync = ref.noSync; if ( noSync === void 0 ) noSync = false; var noReactiveGetter = ref.noReactiveGetter; if ( noReactiveGetter === void 0 ) noReactiveGetter = false; var createModelFromExistingCache = ref.createModelFromExistingCache; if ( createModelFromExistingCache === void 0 ) createModelFromExistingCache = false; var queryParams = ref.queryParams; if ( queryParams === void 0 ) queryParams = null; // INFO: Different subscribeQuery's or mixing subscribeList with subscribeQuery // on the same node is currently not allowed!! // TODO: Cache instance somewhere // TODO: Save idlist internally! and call subscribeNode for each item - but still return a GenericList var customRef = null; var queryHash = ''; var entry_name = this.path; if ( queryParams ) { customRef = this.buildQueryRef( queryParams ); queryHash = this._query_hash( queryParams ); entry_name = entry_name + '#' + queryHash; log0(this.name, 'QUERYHASH:' + entry_name, "Using query hash in entry_name", entry_name); } log1(this.name, "subscribeList", entry_name); if ( _resultListCache.get(entry_name) ) { log1(this.name, "subscribeList - returning list cache"); return _resultListCache.get(entry_name); } var registry_entry = _registry.getters.get_registry_entry( entry_name ); // TODO: Check if data is in 'res' if ( registry_entry ) { log1(this.name, "subscribeList - WARN - found registry entry, but no local cache!"); } /* if ( registry_entry ) { if ( registry_entry.status === 'Loading' ) { return factory.make_reactive_list( this.modelDefinition, null ); } if ( registry_entry.status === 'Ready' ) { return factory.make_reactive_list( this.modelDefinition, this.getData(), this._create_context() ); } }*/ /* Check if parent path exists */ var existing_path = this._match_existing_synced_nodes( entry_name, true ); if ( existing_path ) { if ( createModelFromExistingCache ) { /* Maybe we don't have an instance in the cache, but still the data is * already here. We can use the data to create a model */ var existing_data = this.getData(); // Should automatically return the correct data node log1(this.name, "Found node in existing synced data making list model from existing data", existing_data); // TODO: This model is not reactive for some reason var list = factory.make_reactive_list( this.modelDefinition, existing_data, this._create_context(), noReactiveGetter ); /* This promise will get resolved as soon as everything is loaded */ list.$promise = defer(); // new Deferer() var sync_state = this._get_sync_state( existing_path ); log1(this.name, "checking sync state - is data already fully synced?", sync_state ); if ( sync_state === 'Ready' ) { list.$promise.resolve(true); } log4(this.name, "[Watcher] Registering Watcher"); var unwatch = _registry.watch( function (state) { log4(this$1.name, "[Watcher] -- asking for value"); // ONLY FOR TESTING: // log4(this.name, "[Watcher] -- existing_data", existing_data) // log4(this.name, "[Watcher] -- reference", state.res.goal["BWpG75DcRs-kqVPPdRbxzg"].meta.commitment_meta) // log4(this.name, "[Watcher] -- this.getData()", this.getData()) return this$1.getData(null, true) // should be safe, when unsyncing data of a higher hierachy node }, function (new_value, old_value) { log4(this$1.name, "[Watcher] -- watcher triggered", new_value, old_value); if ( new_value === undefined || new_value === null ) { /* This means the list was deleted */ list.$idList.forEach(function (old_id) { log4(this$1.name, "[Watcher] -- ELIMINATIING LIST", old_id); list._rem_child( old_id ); }); list.$numReady = false; list.$readyAll = false; list.$readySome = false; // list.$deleted = true; list.$promise.resolve(true); return } var ids_new = Object.keys( new_value ); var ids_old_via_watcher = old_value ? Object.keys( old_value ) : []; var ids_old = list.$idList; if ( ids_new.toString() === ids_old_via_watcher.toString() ) { log4(this$1.name, "[Watcher] Watcher values are the same? WHY? ", ids_new, ids_old_via_watcher); } var diff = arrayDiffTwoWay( ids_new, ids_old ); log4(this$1.name, "[Watcher] DIFF", diff, ids_new, ids_old); diff.removed.forEach(function (id) { log4(this$1.name, "[Watcher] -- REMOVED", id); list._rem_child( id ); list.$numReady--; }); diff.added.forEach(function (new_id) { log4(this$1.name, "[Watcher] -- ADDED", new_id); /* Check instance cache */ var child_entry_name = entry_name.split('#').shift().replace(/\{id\}/g, new_id); if ( _resultInstanceCache.has(child_entry_name) ) { warn(WARNING_COMMON, "A new item was added, but there already exists a model instance in the cache for this item. This means the subscription management failed."); } // todo: also check list cache? var data_reactive = this$1.getData( new_id ); var item = factory.make_reactive_model( this$1.modelDefinition, data_reactive, this$1._create_context(), false, noReactiveGetter ); item.$id = new_id; list._add_child( new_id, item ); list.$numReady++; _resultInstanceCache.set(child_entry_name, item); // ? }); list.$promise.resolve(true); } ); /* Save unwatch callback in generic list */ // this.list_watchers.push( unwatch ); list._unwatch = unwatch; _resultListCache.set(entry_name, list); return list; } else { // TODO: This warning should also show, when using subscribeList to return a cached node warn(WARNING_SYNCING_SUBSET_DATA, "You're trying to sync data, that is already synced by a node higher up in the hierarchy. This will result in undefined behaviour. Try using getList() or getNode() instead! Sync path:", entry_name); } } /* todo: remove if this never happens */ if ( this._match_existing_synced_nodes( entry_name ) === entry_name ) { // This will happen, when loading from persistent state trace(INFO_SUBSCRIBE, ">>>", entry_name, _resultListCache, _resultInstanceCache); throw new Error('Exact path found, but no cache hit. This should never happen') } if (noSync) { log1(this.name, "subscribeList - No Sync, returning"); warn(WARNING_ACCESSING_UNSYNCED_DATA, "You're trying to fetch data at " + entry_name + " that has not been synced yet."); return null; } log0(this.name, null, "*new* subscribeList", entry_name); // TODO: Move to sync? registry_entry = { query: queryParams, status: 'Loading', }; _registry.commit('ADD_ENTRY', { name: entry_name, data: registry_entry }); // TODO: registry.add_entry( registry_entry) var result = factory.make_reactive_list( this.modelDefinition, null, this._create_context() ); _resultListCache.set(entry_name, result); result.$promise = defer(); log1(this.name, "subscribeList - Created reactive list, made registry entry, started sync request for", registry_entry, result); var customOps = { add: function (target, newId, data) { _registry.commit('SET_ENTRY_STATUS', { name: entry_name, value: 'Ready' }); log1(this$1.name, "subscribeList:add - Child ready", this$1.name, entry_name, newId ); var child_entry_name = entry_name.split('#').shift().replace(/\{id\}/g, newId); if ( _resultInstanceCache.has(child_entry_name) ) { log1(this$1.name, "subscribeList:add - Reactive model already exists in instance cache"); } // INFO: Data was not updated here with item._update_data() -> Why did it work? // INFO: There is no need to theck _resultListCache, because we will only // get to this point, if there was not cache hit, meaning it would // be the same as 'result'. However checking result.items[ id ] // makes sense. if ( newId in result.items ) { warn(WARNING_COMMON, "An existing item was added twice. This means the subscription management failed."); } var item = _resultInstanceCache.has(child_entry_name) ? _resultInstanceCache.get(child_entry_name) : factory.make_reactive_model( this$1.modelDefinition, data, this$1._create_context(), false, noReactiveGetter ); item.$id = newId; result._add_child( newId, item ); if ( _resultInstanceCache.has(child_entry_name) ) { /* Update item */ log1("subscribeList:add - Updating existing item (previously synced with subscribeNode) with", data ); item._update_data( data ); /* It is possible, that the node was already synced and is now waiting for results (see ANNOTATION#1). This means, subscribeList is now responsible */ /* This will not happen! If a sub-node is already synced via _sync_individual, child_added for this node will NOT be called. */ /* item.$ready = true; registry.commit('SET_ENTRY_STATUS', { name: child_entry_name, value: 'Ready' }) item.$promise.resolve() */ // TODO: unsync individual node? sync() takes care of syncing now! Do we need to remove sync ops? } else { /* Also update instance cache! */ _resultInstanceCache.set(child_entry_name, item); } }, init: function () { log1(this$1.name, "subscribeList:init"); return {} }, remove: function (target, oldId) { log4(this$1.name, "subscribeList:remove", oldId); result._rem_child( oldId ); }, set: function (target, currentId, data) { log1(this$1.name, "subscribeList:set", currentId, data); /* Not 100% clear why we need to update here - for some reason dependencies are not triggered when HELIOSRX_ARRAY_SET is fired. */ /* if ( currentId in this._resultInstanceCache ) { let item = this._resultInstanceCache[ currentId ] let data_reactive = this.getData( currentId ); log1(this.name, "subscribeList:set [A] - updating model", data_reactive) item._update_data( data_reactive, this.modelDefinition.schema.fields ) } else */ if ( _resultListCache.get(entry_name) && currentId in _resultListCache.get(entry_name).items ) { var item = _resultListCache.get(entry_name).items[ currentId ]; var data_reactive = this$1.getData( currentId ); /* BUG: At this point data_reactive is outdated ! */ item._update_data( data_reactive, this$1.modelDefinition.schema.fields ); log1(this$1.name, "subscribeList:set [B] - updating model", data_reactive); /* log1(this.name, "subscribeList:set [B] - updating model", data) item._update_data( data, this.modelDefinition.schema.fields ) */ } else { log1(this$1.name, "subscribeList:set - WARNING - not found in cache!", currentId, _resultListCache.get(entry_name)); } }, }; this._sync_list({ customOps: customOps, customRef: customRef }).then(function () { /* This promise is resolved when data is first fetched */ result.$readyAll = true; result.$promise.resolve(true); }).catch(function (e) { if ( e.code === 'PERMISSION_DENIED' ) { warn(WARNING_PERMISSION_DENIED, e.message); info(INFO_PERMISSION, "======================================"); info(INFO_PERMISSION, ("PERMISSION_DENIED [" + (this$1.name) + ".subscribeList()]")); info(INFO_PERMISSION, "queryParams:", queryParams); info(INFO_PERMISSION, "======================================"); result.$readyAll = true; result.$readySome = true; result.$noaccess = true; /* TODO ? -> probably not result.$idList.forEach(old_id => { registry.commit('SET_ENTRY_STATUS', { name: entry_name_child, value: 'NoAccess' }) let data_reactive = this.getData( id ); data_reactive[ '.noaccess' ] = true; result._update_data( data_reactive, this.modelDefinition.schema.fields ) }) */ result.$promise.reject(e); } else { throw e; } }); return result; }, /* --------------------------------------------------------- subscribe node */ // noSync = Return from cache subscribeNode: function subscribeNode( id, ref ) { var this$1 = this; if ( ref === void 0 ) ref = {}; var noSync = ref.noSync; if ( noSync === void 0 ) noSync = false; var noReactiveGetter = ref.noReactiveGetter; if ( noReactiveGetter === void 0 ) noReactiveGetter = false; var createModelFromExistingCache = ref.createModelFromExistingCache; if ( createModelFromExistingCache === void 0 ) createModelFromExistingCache = false; if ( !id ) { throw new Error('subscribeNode: got invalid id: ') } // TODO: This might now always yield the expected result, when defined is used // TODO: Figure out if list is loading or item /* 1. Check if data already exists */ var entry_name_child = this.previewPath( id ); // HACK var entry_name_list = this.path; log1(this.name, "subscribeNode", entry_name_child); /* Check if item already exists in list cache. */ if ( _resultListCache.get(entry_name_list) ) { if ( id in _resultListCache.get(entry_name_list).items ) { log1(this.name, "subscribeNode - returning from list cache"); return _resultListCache.get(entry_name_list).items[ id ]; } } if ( _resultInstanceCache.has(entry_name_child) ) { log1(this.name, "subscribeNode - returning from instance cache"); return _resultInstanceCache.get(entry_name_child); } // TODO: This does not check if the parent path exists! It checks if this // particular child is already synced, which can happen if subscribeNode // is triggered while subscribeList is still waiting for OPS:ADD if ( this._match_existing_synced_nodes( entry_name_list ) ) { log0(this.name, "======================================= (FIXME)", { 'entry_name_child': entry_name_child }, { 'entry_name_list': entry_name_list }, { 'has:node': _resultInstanceCache.has(entry_name_child) }, { 'get:list': _resultInstanceCache.get(entry_name_list) } ); // TODO: For some reason this also get's called, when an instance should // already be in the instance cache // In this case we could do the following: // 1. check if list is "loading" // 2. create a GenericModel that is not $ready // 3. check if results are already at path // 4. if not, call OPS:INIT // 5. return generic model and write to instance cache // *6. when data is ready in subscribe list, get model from instance cache // *7. set model to Ready // *8. set data with commit() } /* Check if parent path exists */ if ( this._match_existing_synced_nodes( entry_name_child ) ) { if ( createModelFromExistingCache ) { var existing_data = this.getData( id ); // Should automatically return the correct data node log1(this.name, "Found node in existing synced data making model from existing data", existing_data); var model = factory.make_reactive_model( this.modelDefinition, existing_data, this._create_context(), false, noReactiveGetter ); model.$id = id; model.$ready = true; // model._update_data( existing_data, this.modelDefinition.schema.fields ) _resultInstanceCache.set( entry_name_child, model ); log1(this.name, "made model", model); return model; } else { warn(WARNING_SYNCING_SUBSET_DATA, "You're trying to sync data, that is already synced by a node higher up in the hierarchy. This will result in undefined behaviour. Try using getNode() instead! Sync path:", entry_name_child); } } /* todo: remove if this never happens */ if ( this._match_existing_synced_nodes( entry_name_child ) === entry_name_child ) { // This will happen, when loading from persistent state trace(INFO_SUBSCRIBE, ">>>", entry_name_child, _resultListCache, _resultInstanceCache); throw new Error('Exact path found, but no cache hit. This should never happen') } if (noSync) { // warn(WARNING_ACCESSING_UNSYNCED_DATA, "You're trying to fetch at " + entry_name_child + " that has not been synced yet."); return null; } log0(this.name, id, "*new* subscribeNode", entry_name_child); /* 2. Create empty model that is updated later when data is ready */ var load_result = factory.make_reactive_model( this.modelDefinition, null, this._create_context(), false, noReactiveGetter ); load_result.$id = id; load_result.$promise = defer(); _resultInstanceCache.set( entry_name_child, load_result ); /* 3. Create registry entry */ var registry_entry = { id: id, status: 'Loading', }; _registry.commit('ADD_ENTRY', { name: entry_name_child, data: registry_entry }); // TODO: registry.add_entry( registry_entry) log1(this.name, "subscribeNode - Made registry entry and started at", entry_name_child, registry_entry); var customOps = { init: function (data) { log1(this$1.name, "subscribeNode:init", data); return {} }, set: function (target, data) { log1(this$1.name, "subscribeNode:set", target, data); }, }; /* 4. Start syncing */ this._sync_individual( id, { customOps: customOps } ).then( function (data) { var data_reactive = this$1.getData( id ); log1(this$1.name, "subscribeNode - data ready", entry_name_child, data, data_reactive); if ( data_reactive === undefined ) { /* This case will not occur anymore /* In some cases, when a node is subscribing and while waiting for the results the list, that contains the node is synced as well, it can happen that the list is resetted in $registry.state.res (See. ANNOTIATION#1 ) */ warn(WARNING_COMMON, this$1.name, "subscribeNode - subscribeList took over, while waiting for _sync_individual. subscribeList will handle instance now."); /* We need to wait now, until the list is synced, so we can return reactive data. This is (hopefully) handled by subscribe List, when picking up 'load_result' from the instance cache */ /* ...but this only works if the node really exists in the list */ return /* if ( _resultInstanceCache.has(child_entry_name) ) { return _resultInstanceCache.get(child_entry_name) } else { throw new Error('THIS IS BAD'); } */ } load_result._update_data( data_reactive, this$1.modelDefinition.schema.fields ); load_result.$ready = true; load_result.$noaccess = false; // INFO: this is only called once, maybe thats why we have problem here // Vue.observable( registry.state.res.goal[ id ].meta ) // load_result.$state = registry.state.res.goal[ id ].meta // Vue.observable( load_result.$state ) _registry.commit('SET_ENTRY_STATUS', { name: entry_name_child, value: 'Ready' }); // TODO: registry.set_entry_status( entry_name, 'Ready' ) log1(this$1.name, "subscribeNode - created reactive model", load_result); load_result.$promise.resolve(true); }).catch(function (e) { if ( e.code === 'PERMISSION_DENIED' ) { // !!! TODO: Also implement for fetchNode, fetchList !!! warn(WARNING_PERMISSION_DENIED, e.message); info(INFO_PERMISSION, "======================================"); info(INFO_PERMISSION, ("PERMISSION_DENIED [" + (this$1.name) + ".subscribeNode( " + id + " )]")); // Query parameter for *List info(INFO_PERMISSION, "======================================"); _registry.commit('SET_ENTRY_STATUS', { name: entry_name_child, value: 'NoAccess' }); var data_reactive = this$1.getData( id ); // maybe we should remove everything... data_reactive[ '.noaccess' ] = true; load_result._update_data( data_reactive, this$1.modelDefinition.schema.fields ); load_result.$ready = true; load_result.$noaccess = true; load_result.$promise.reject(e); } else { throw e; } }); return load_result }, // --------------------------------------------------------------------------- buildQueryRef: function buildQueryRef(ref) { var key = ref.key; if ( key === void 0 ) key = undefined; var value = ref.value; if ( value === void 0 ) value = undefined; var limit = ref.limit; if ( limit === void 0 ) limit = undefined; var startAt = ref.startAt; if ( startAt === void 0 ) startAt = undefined; var endAt = ref.endAt; if ( endAt === void 0 ) endAt = undefined; var customRef = this.parentRef; if ( key === '*' ) { // Don't forget to add indexOn( [ '.value' ] ) customRef = customRef.orderByValue(); } else if ( key === undefined ) { // No index needed. Key is always indexed customRef = customRef.orderByKey(); } else { // Don't forget to add indexOn( [ key ] ) customRef = customRef.orderByChild(key); } if ( value !== undefined ) { customRef = customRef.equalTo(value); } if ( startAt !== undefined ) { customRef = customRef.startAt(startAt); } if ( endAt !== undefined ) { customRef = customRef.endAt(endAt); } if ( limit !== undefined ) { if ( limit > 0 ) { customRef = customRef.limitToFirst(limit); } else { customRef = customRef.limitToLast(-limit); } } return customRef }, // --------------------------------------------------------------------------- _query_hash: function _query_hash( query ) { var queryHash = [ query.key, query.value, query.limit, query.startAt, query.endAt ].join('_'); return queryHash; }, // --------------------------------------------------------------------------- /* query: - key = key, '*' or undefined - value - limit - startAt - endAt options: - noSync = false - noReactiveGetter = false - createModelFromExistingCache = false @example this.$models.example.subscribeQuery({ key: 'createdAt', startAt: 123456789, limit: 100 }); */ subscribeQuery: function subscribeQuery(query, options) { if ( options === void 0 ) options = {}; // TODO: alternative syntax subscribeQuery({ key: value }, 100) return this.subscribeList( null, Object.assign({}, options, {queryParams: query}) ) }, // --------------------------------------------------------------------------- fetchNode: function fetchNode(id, ref) { var this$1 = this; if ( ref === void 0 ) ref = {}; var noReactiveGetter = ref.noReactiveGetter; if ( noReactiveGetter === void 0 ) noReactiveGetter = false; // TODO: in state schreiben? // TODO: Simplify by using ref directly // TODO: ['.exists'] wird nicht gesetzt! -> Actually not possible, once('value') won't trigger /* 2. Create empty model that is updated later when data is ready */ var load_result = factory.make_reactive_model( this.modelDefinition, null, this._create_context(), false, noReactiveGetter ); load_result.$id = id; load_result.$promise = defer(); /* 3. Create registry entry */ /* let registry_entry = { name: entry_name_child, status: 'Loading', fetch: true }; registry.commit('ADD_ENTRY', {...}) */ var customOps = { init: function () { log3(this$1.name, "fetchNode:init"); return {} }, set: function (target, data) { log3(this$1.name, "fetchNode:set", target, data); }, }; this._fetch_individual( id, { customOps: customOps } ).then( function (data) { log3(this$1.name, "fetchNode - data ready", data); // TODO: make data reactive load_result._update_data( data, this$1.modelDefinition.schema.fields ); load_result.$ready = true; /* registry_entry.status = 'Ready' registry.commit('SET_ENTRY_STATUS', registry_entry) */ load_result.$promise.resolve(true); }); return load_result }, // --------------------------------------------------------------------------- fetchList: function fetchList(ref) { var this$1 = this; if ( ref === void 0 ) ref = {}; var noReactiveGetter = ref.noReactiveGetter; if ( noReactiveGetter === void 0 ) noReactiveGetter = false; var queryParams = ref.queryParams; if ( queryParams === void 0 ) queryParams = null; // TODO: Simplify by using ref directly var customRef = queryParams ? this.buildQueryRef( queryParams ) : null; /* 1. Create empty model list */ var list = factory.make_reactive_list( this.modelDefinition, null, this._create_context(), noReactiveGetter ); /* This promise will get resolved as soon as everything is loaded */ list.$promise = defer(); var customOps = { init: function () { log3(this$1.name, "fetchList:init"); return {} }, once: function (target, data, exists) { log3(this$1.name, "fetchList:once", data); } }; /* 2. Start fetching and update list when data is ready */ this._fetch_list({ customOps: customOps, customRef: customRef }).then(function (data) { log3(this$1.name, "fetchList:resolve", data); var id_list = Object.keys( data || [] ); id_list.forEach(function (new_id) { var item_data = data[ new_id ]; var item = factory.make_reactive_model( this$1.modelDefinition, item_data, this$1._create_context(), false, noReactiveGetter ); item.$id = new_id; list._add_child( new_id, item ); list.$numReady++; }); list.$readyAll = true; list.$promise.resolve(true); }); return list; }, // --------------------------------------------------------------------------- fetchQuery: function fetchQuery(query, options) { // let customRef = this.buildQueryRef(query) return this.fetchList(Object.assign({}, options, {queryParams: query})) }, /* ------------------------------------------------------------------------ */ getRegistryState: function getRegistryState() { return _registry.state; }, /* ------------------------------------------------------------------------ */ getAllSyncedPaths: function getAllSyncedPaths() { var list = {}; Object.keys( _registry.state.sync ).forEach(function (path) { list[ path ] = _registry.state.sync[ path ].status; }); return list; }, // --------------------------------------------------------------------------- /* Syntax: * getData() -> get reference to list of data * getData(child_id) -> get reference to an item in the list * * TODO: Move redudant? * * */ getData: function getData(id, safe) { if ( id === void 0 ) id = null; if ( safe === void 0 ) safe = false; var item_path = ''; if ( this.isSuffixed || id ) { if ( !id ) { throw new Error('getData: id required for suffixed stores') } item_path = this.path.replace(/\{id\}/g, id); } else { item_path = this.path.split('{id}').shift(); } var data_path = LOCAL_PATH_PREFIX + item_path.split('/').filter(function (p) { return p; }).join('.'); if ( !_registry.state.initialized ) { return null } // info(INFO_SUBSCRIBE, "getData data_path", data_path); { return safe ? walkGetObjectSave( _registry.state, data_path ) : walkGet( _registry.state, data_path ) } }, // --------------------------------------------------------------------------- /* INFO: Currently not use, there is better methods exists(id = null) { // Only for the following use case: // - Data has been synced at /path/* // - We want to know if /path/{id}/bla/bla exists // Example: // $models.timeslotWeekdayPref.with({ timeslotCollectionId: tscId }).exists() let existing_path = id ? this._match_existing_synced_nodes( this.previewPath( id ), true ) : this._match_existing_synced_nodes( this.path, true ) // This does not work in all cases! if ( existing_path ) { return !!this.getData(id) } return false; }, */ // --------------------------------------------------------------------------- // TODO: make static // (would be a little bit of work, since this is an object not a class) resetGlobalInstanceCache: function resetGlobalInstanceCache() { try { _resultInstanceCache.forEach(function (instance) { instance.reset(); }); _resultListCache.forEach(function (instance) { instance.reset(); }); } catch ( e ) { warn(WARNING_COMMON, "Reseting instances failed", e); } _resultInstanceCache.clear(); _resultListCache.clear(); }, // --------------------------------------------------------------------------- }; var lodash_isequal = createCommonjsModule(function (module, exports) { /** * Lodash (Custom Build) <https://lodash.com/> * Build: `lodash modularize exports="npm" -o ./` * Copyright JS Foundation and other contributors <https://js.foundation/> * Released under MIT license <https://lodash.com/license> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright <NAME>, DocumentCloud and Investigative Reporters & Editors */ /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', asyncTag = '[object AsyncFunction]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', mapTag = '[object Map]', numberTag = '[object Number]', nullTag = '[object Null]', objectTag = '[object Object]', promiseTag = '[object Promise]', proxyTag = '[object Proxy]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', symbolTag = '[object Symbol]', undefinedTag = '[object Undefined]', weakMapTag = '[object WeakMap]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** * Used to match `RegExp` * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). */ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; /** Used to detect host constructors (Safari). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/; /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal; /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); /** Detect free variable `exports`. */ var freeExports = exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Detect free variable `process` from Node.js. */ var freeProcess = moduleExports && freeGlobal.process; /** Used to access faster Node.js helpers. */ var nodeUtil = (function() { try { return freeProcess && freeProcess.binding && freeProcess.binding('util'); } catch (e) {} }()); /* Node.js helper references. */ var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; /** * A specialized version of `_.filter` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function arrayFilter(array, predicate) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[resIndex++] = value; } } return result; } /** * Appends the elements of `values` to `array`. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to append. * @returns {Array} Returns `array`. */ function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index]; } return array; } /** * A specialized version of `_.some` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function arraySome(array, predicate) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } /** * The base implementation of `_.times` without support for iteratee shorthands * or max array length checks. * * @private * @param {number} n The number of times to invoke `iteratee`. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the array of results. */ function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) { result[index] = iteratee(index); } return result; } /** * The base implementation of `_.unary` without support for storing metadata. * * @private * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. */ function baseUnary(func) { return function(value) { return func(value); }; } /** * Checks if a `cache` value for `key` exists. * * @private * @param {Object} cache The cache to query. * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function cacheHas(cache, key) { return cache.has(key); } /** * Gets the value at `key` of `object`. * * @private * @param {Object} [object] The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function getValue(object, key) { return object == null ? undefined : object[key]; } /** * Converts `map` to its key-value pairs. * * @private * @param {Object} map The map to convert. * @returns {Array} Returns the key-value pairs. */ function mapToArray(map) { var index = -1, result = Array(map.size); map.forEach(function(value, key) { result[++index] = [key, value]; }); return result; } /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } /** * Converts `set` to an array of its values. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the values. */ function setToArray(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = value; }); return result; } /** Used for built-in method references. */ var arrayProto = Array.prototype, funcProto = Function.prototype, objectProto = Object.prototype; /** Used to detect overreaching core-js shims. */ var coreJsData = root['__core-js_shared__']; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to detect methods masquerading as native. */ var maskSrcKey = (function() { var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); return uid ? ('Symbol(src)_1.' + uid) : ''; }()); /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** Built-in value references. */ var Buffer = moduleExports ? root.Buffer : undefined, Symbol = root.Symbol, Uint8Array = root.Uint8Array, propertyIsEnumerable = objectProto.propertyIsEnumerable, splice = arrayProto.splice, symToStringTag = Symbol ? Symbol.toStringTag : undefined; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeGetSymbols = Object.getOwnPropertySymbols, nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, nativeKeys = overArg(Object.keys, Object); /* Built-in method references that are verified to be native. */ var DataView = getNative(root, 'DataView'), Map = getNative(root, 'Map'), Promise = getNative(root, 'Promise'), Set = getNative(root, 'Set'), WeakMap = getNative(root, 'WeakMap'), nativeCreate = getNative(Object, 'create'); /** Used to detect maps, sets, and weakmaps. */ var dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map), promiseCtorString = toSource(Promise), setCtorString = toSource(Set), weakMapCtorString = toSource(WeakMap); /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; /** * Creates a hash object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Hash(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the hash. * * @private * @name clear * @memberOf Hash */ function hashClear() { this.__data__ = nativeCreate ? nativeCreate(null) : {}; this.size = 0; } /** * Removes `key` and its value from the hash. * * @private * @name delete * @memberOf Hash * @param {Object} hash The hash to modify. * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function hashDelete(key) { var result = this.has(key) && delete this.__data__[key]; this.size -= result ? 1 : 0; return result; } /** * Gets the hash value for `key`. * * @private * @name get * @memberOf Hash * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function hashGet(key) { var data = this.__data__; if (nativeCreate) { var result = data[key]; return result === HASH_UNDEFINED ? undefined : result; } return hasOwnProperty.call(data, key) ? data[key] : undefined; } /** * Checks if a hash value for `key` exists. * * @private * @name has * @memberOf Hash * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function hashHas(key) { var data = this.__data__; return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); } /** * Sets the hash `key` to `value`. * * @private * @name set * @memberOf Hash * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the hash instance. */ function hashSet(key, value) { var data = this.__data__; this.size += this.has(key) ? 0 : 1; data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; return this; } // Add methods to `Hash`. Hash.prototype.clear = hashClear; Hash.prototype['delete'] = hashDelete; Hash.prototype.get = hashGet; Hash.prototype.has = hashHas; Hash.prototype.set = hashSet; /** * Creates an list cache object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function ListCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the list cache. * * @private * @name clear * @memberOf ListCache */ function listCacheClear() { this.__data__ = []; this.size = 0; } /** * Removes `key` and its value from the list cache. * * @private * @name delete * @memberOf ListCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function listCacheDelete(key) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { return false; } var lastIndex = data.length - 1; if (index == lastIndex) { data.pop(); } else { splice.call(data, index, 1); } --this.size; return true; } /** * Gets the list cache value for `key`. * * @private * @name get * @memberOf ListCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function listCacheGet(key) { var data = this.__data__, index = assocIndexOf(data, key); return index < 0 ? undefined : data[index][1]; } /** * Checks if a list cache value for `key` exists. * * @private * @name has * @memberOf ListCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function listCacheHas(key) { return assocIndexOf(this.__data__, key) > -1; } /** * Sets the list cache `key` to `value`. * * @private * @name set * @memberOf ListCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the list cache instance. */ function listCacheSet(key, value) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { ++this.size; data.push([key, value]); } else { data[index][1] = value; } return this; } // Add methods to `ListCache`. ListCache.prototype.clear = listCacheClear; ListCache.prototype['delete'] = listCacheDelete; ListCache.prototype.get = listCacheGet; ListCache.prototype.has = listCacheHas; ListCache.prototype.set = listCacheSet; /** * Creates a map cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function MapCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the map. * * @private * @name clear * @memberOf MapCache */ function mapCacheClear() { this.size = 0; this.__data__ = { 'hash': new Hash, 'map': new (Map || ListCache), 'string': new Hash }; } /** * Removes `key` and its value from the map. * * @private * @name delete * @memberOf MapCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function mapCacheDelete(key) { var result = getMapData(this, key)['delete'](key); this.size -= result ? 1 : 0; return result; } /** * Gets the map value for `key`. * * @private * @name get * @memberOf MapCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function mapCacheGet(key) { return getMapData(this, key).get(key); } /** * Checks if a map value for `key` exists. * * @private * @name has * @memberOf MapCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function mapCacheHas(key) { return getMapData(this, key).has(key); } /** * Sets the map `key` to `value`. * * @private * @name set * @memberOf MapCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the map cache instance. */ function mapCacheSet(key, value) { var data = getMapData(this, key), size = data.size; data.set(key, value); this.size += data.size == size ? 0 : 1; return this; } // Add methods to `MapCache`. MapCache.prototype.clear = mapCacheClear; MapCache.prototype['delete'] = mapCacheDelete; MapCache.prototype.get = mapCacheGet; MapCache.prototype.has = mapCacheHas; MapCache.prototype.set = mapCacheSet; /** * * Creates an array cache object to store unique values. * * @private * @constructor * @param {Array} [values] The values to cache. */ function SetCache(values) { var index = -1, length = values == null ? 0 : values.length; this.__data__ = new MapCache; while (++index < length) { this.add(values[index]); } } /** * Adds `value` to the array cache. * * @private * @name add * @memberOf SetCache * @alias push * @param {*} value The value to cache. * @returns {Object} Returns the cache instance. */ function setCacheAdd(value) { this.__data__.set(value, HASH_UNDEFINED); return this; } /** * Checks if `value` is in the array cache. * * @private * @name has * @memberOf SetCache * @param {*} value The value to search for. * @returns {number} Returns `true` if `value` is found, else `false`. */ function setCacheHas(value) { return this.__data__.has(value); } // Add methods to `SetCache`. SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; SetCache.prototype.has = setCacheHas; /** * Creates a stack cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Stack(entries) { var data = this.__data__ = new ListCache(entries); this.size = data.size; } /** * Removes all key-value entries from the stack. * * @private * @name clear * @memberOf Stack */ function stackClear() { this.__data__ = new ListCache; this.size = 0; } /** * Removes `key` and its value from the stack. * * @private * @name delete * @memberOf Stack * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function stackDelete(key) { var data = this.__data__, result = data['delete'](key); this.size = data.size; return result; } /** * Gets the stack value for `key`. * * @private * @name get * @memberOf Stack * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function stackGet(key) { return this.__data__.get(key); } /** * Checks if a stack value for `key` exists. * * @private * @name has * @memberOf Stack * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function stackHas(key) { return this.__data__.has(key); } /** * Sets the stack `key` to `value`. * * @private * @name set * @memberOf Stack * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the stack cache instance. */ function stackSet(key, value) { var data = this.__data__; if (data instanceof ListCache) { var pairs = data.__data__; if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { pairs.push([key, value]); this.size = ++data.size; return this; } data = this.__data__ = new MapCache(pairs); } data.set(key, value); this.size = data.size; return this; } // Add methods to `Stack`. Stack.prototype.clear = stackClear; Stack.prototype['delete'] = stackDelete; Stack.prototype.get = stackGet; Stack.prototype.has = stackHas; Stack.prototype.set = stackSet; /** * Creates an array of the enumerable property names of the array-like `value`. * * @private * @param {*} value The value to query. * @param {boolean} inherited Specify returning inherited property names. * @returns {Array} Returns the array of property names. */ function arrayLikeKeys(value, inherited) { var isArr = isArray(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer(value), isType = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes(value.length, String) : [], length = result.length; for (var key in value) { if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode. key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers. (isBuff && (key == 'offset' || key == 'parent')) || // PhantomJS 2 has enumerable non-index properties on typed arrays. (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || // Skip index properties. isIndex(key, length) ))) { result.push(key); } } return result; } /** * Gets the index at which the `key` is found in `array` of key-value pairs. * * @private * @param {Array} array The array to inspect. * @param {*} key The key to search for. * @returns {number} Returns the index of the matched value, else `-1`. */ function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq(array[length][0], key)) { return length; } } return -1; } /** * The base implementation of `getAllKeys` and `getAllKeysIn` which uses * `keysFunc` and `symbolsFunc` to get the enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @param {Function} keysFunc The function to get the keys of `object`. * @param {Function} symbolsFunc The function to get the symbols of `object`. * @returns {Array} Returns the array of property names and symbols. */ function baseGetAllKeys(object, keysFunc, symbolsFunc) { var result = keysFunc(object); return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); } /** * The base implementation of `getTag` without fallbacks for buggy environments. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { if (value == null) { return value === undefined ? undefinedTag : nullTag; } return (symToStringTag && symToStringTag in Object(value)) ? getRawTag(value) : objectToString(value); } /** * The base implementation of `_.isArguments`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, */ function baseIsArguments(value) { return isObjectLike(value) && baseGetTag(value) == argsTag; } /** * The base implementation of `_.isEqual` which supports partial comparisons * and tracks traversed objects. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {boolean} bitmask The bitmask flags. * 1 - Unordered comparison * 2 - Partial comparison * @param {Function} [customizer] The function to customize comparisons. * @param {Object} [stack] Tracks traversed `value` and `other` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(value, other, bitmask, customizer, stack) { if (value === other) { return true; } if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { return value !== value && other !== other; } return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); } /** * A specialized version of `baseIsEqual` for arrays and objects which performs * deep comparisons and tracks traversed objects enabling objects with circular * references to be compared. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} [stack] Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { var objIsArr = isArray(object), othIsArr = isArray(other), objTag = objIsArr ? arrayTag : getTag(object), othTag = othIsArr ? arrayTag : getTag(other); objTag = objTag == argsTag ? objectTag : objTag; othTag = othTag == argsTag ? objectTag : othTag; var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag; if (isSameTag && isBuffer(object)) { if (!isBuffer(other)) { return false; } objIsArr = true; objIsObj = false; } if (isSameTag && !objIsObj) { stack || (stack = new Stack); return (objIsArr || isTypedArray(object)) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); } if (!(bitmask & COMPARE_PARTIAL_FLAG)) { var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); if (objIsWrapped || othIsWrapped) { var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; stack || (stack = new Stack); return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); } } if (!isSameTag) { return false; } stack || (stack = new Stack); return equalObjects(object, other, bitmask, customizer, equalFunc, stack); } /** * The base implementation of `_.isNative` without bad shim checks. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. */ function baseIsNative(value) { if (!isObject(value) || isMasked(value)) { return false; } var pattern = isFunction(value) ? reIsNative : reIsHostCtor; return pattern.test(toSource(value)); } /** * The base implementation of `_.isTypedArray` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. */ function baseIsTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; } /** * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeys(object) { if (!isPrototype(object)) { return nativeKeys(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty.call(object, key) && key != 'constructor') { result.push(key); } } return result; } /** * A specialized version of `baseIsEqualDeep` for arrays with support for * partial deep comparisons. * * @private * @param {Array} array The array to compare. * @param {Array} other The other array to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `array` and `other` objects. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length; if (arrLength != othLength && !(isPartial && othLength > arrLength)) { return false; } // Assume cyclic values are equal. var stacked = stack.get(array); if (stacked && stack.get(other)) { return stacked == other; } var index = -1, result = true, seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; stack.set(array, other); stack.set(other, array); // Ignore non-index properties. while (++index < arrLength) { var arrValue = array[index], othValue = other[index]; if (customizer) { var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); } if (compared !== undefined) { if (compared) { continue; } result = false; break; } // Recursively compare arrays (susceptible to call stack limits). if (seen) { if (!arraySome(other, function(othValue, othIndex) { if (!cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { return seen.push(othIndex); } })) { result = false; break; } } else if (!( arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack) )) { result = false; break; } } stack['delete'](array); stack['delete'](other); return result; } /** * A specialized version of `baseIsEqualDeep` for comparing objects of * the same `toStringTag`. * * **Note:** This function only supports comparing values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {string} tag The `toStringTag` of the objects to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { switch (tag) { case dataViewTag: if ((object.byteLength != other.byteLength) || (object.byteOffset != other.byteOffset)) { return false; } object = object.buffer; other = other.buffer; case arrayBufferTag: if ((object.byteLength != other.byteLength) || !equalFunc(new Uint8Array(object), new Uint8Array(other))) { return false; } return true; case boolTag: case dateTag: case numberTag: // Coerce booleans to `1` or `0` and dates to milliseconds. // Invalid dates are coerced to `NaN`. return eq(+object, +other); case errorTag: return object.name == other.name && object.message == other.message; case regexpTag: case stringTag: // Coerce regexes to strings and treat strings, primitives and objects, // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring // for more details. return object == (other + ''); case mapTag: var convert = mapToArray; case setTag: var isPartial = bitmask & COMPARE_PARTIAL_FLAG; convert || (convert = setToArray); if (object.size != other.size && !isPartial) { return false; } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked) { return stacked == other; } bitmask |= COMPARE_UNORDERED_FLAG; // Recursively compare objects (susceptible to call stack limits). stack.set(object, other); var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); stack['delete'](object); return result; case symbolTag: if (symbolValueOf) { return symbolValueOf.call(object) == symbolValueOf.call(other); } } return false; } /** * A specialized version of `baseIsEqualDeep` for objects with support for * partial deep comparisons. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, objProps = getAllKeys(object), objLength = objProps.length, othProps = getAllKeys(other), othLength = othProps.length; if (objLength != othLength && !isPartial) { return false; } var index = objLength; while (index--) { var key = objProps[index]; if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { return false; } } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked && stack.get(other)) { return stacked == other; } var result = true; stack.set(object, other); stack.set(other, object); var skipCtor = isPartial; while (++index < objLength) { key = objProps[index]; var objValue = object[key], othValue = other[key]; if (customizer) { var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); } // Recursively compare objects (susceptible to call stack limits). if (!(compared === undefined ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) : compared )) { result = false; break; } skipCtor || (skipCtor = key == 'constructor'); } if (result && !skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal. if (objCtor != othCtor && ('constructor' in object && 'constructor' in other) && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { result = false; } } stack['delete'](object); stack['delete'](other); return result; } /** * Creates an array of own enumerable property names and symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeys(object) { return baseGetAllKeys(object, keys, getSymbols); } /** * Gets the data for `map`. * * @private * @param {Object} map The map to query. * @param {string} key The reference key. * @returns {*} Returns the map data. */ function getMapData(map, key) { var data = map.__data__; return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map; } /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = getValue(object, key); return baseIsNative(value) ? value : undefined; } /** * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * * @private * @param {*} value The value to query. * @returns {string} Returns the raw `toStringTag`. */ function getRawTag(value) { var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; try { value[symToStringTag] = undefined; var unmasked = true; } catch (e) {} var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag] = tag; } else { delete value[symToStringTag]; } } return result; } /** * Creates an array of the own enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbols = !nativeGetSymbols ? stubArray : function(object) { if (object == null) { return []; } object = Object(object); return arrayFilter(nativeGetSymbols(object), function(symbol) { return propertyIsEnumerable.call(object, symbol); }); }; /** * Gets the `toStringTag` of `value`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ var getTag = baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || (Map && getTag(new Map) != mapTag) || (Promise && getTag(Promise.resolve()) != promiseTag) || (Set && getTag(new Set) != setTag) || (WeakMap && getTag(new WeakMap) != weakMapTag)) { getTag = function(value) { var result = baseGetTag(value), Ctor = result == objectTag ? value.constructor : undefined, ctorString = Ctor ? toSource(Ctor) : ''; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag; case mapCtorString: return mapTag; case promiseCtorString: return promiseTag; case setCtorString: return setTag; case weakMapCtorString: return weakMapTag; } } return result; }; } /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { length = length == null ? MAX_SAFE_INTEGER : length; return !!length && (typeof value == 'number' || reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length); } /** * Checks if `value` is suitable for use as unique object key. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is suitable, else `false`. */ function isKeyable(value) { var type = typeof value; return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') ? (value !== '__proto__') : (value === null); } /** * Checks if `func` has its source masked. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` is masked, else `false`. */ function isMasked(func) { return !!maskSrcKey && (maskSrcKey in func); } /** * Checks if `value` is likely a prototype object. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ function isPrototype(value) { var Ctor = value && value.constructor, proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; return value === proto; } /** * Converts `value` to a string using `Object.prototype.toString`. * * @private * @param {*} value The value to convert. * @returns {string} Returns the converted string. */ function objectToString(value) { return nativeObjectToString.call(value); } /** * Converts `func` to its source code. * * @private * @param {Function} func The function to convert. * @returns {string} Returns the source code. */ function toSource(func) { if (func != null) { try { return funcToString.call(func); } catch (e) {} try { return (func + ''); } catch (e) {} } return ''; } /** * Performs a * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ function eq(value, other) { return value === other || (value !== value && other !== other); } /** * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, * else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); }; /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ function isArrayLike(value) { return value != null && isLength(value.length) && !isFunction(value); } /** * Checks if `value` is a buffer. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. * @example * * _.isBuffer(new Buffer(2)); * // => true * * _.isBuffer(new Uint8Array(2)); * // => false */ var isBuffer = nativeIsBuffer || stubFalse; /** * Performs a deep comparison between two values to determine if they are * equivalent. * * **Note:** This method supports comparing arrays, array buffers, booleans, * date objects, error objects, maps, numbers, `Object` objects, regexes, * sets, strings, symbols, and typed arrays. `Object` objects are compared * by their own, not inherited, enumerable properties. Functions and DOM * nodes are compared by strict equality, i.e. `===`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.isEqual(object, other); * // => true * * object === other; * // => false */ function isEqual(value, other) { return baseIsEqual(value, other); } /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { if (!isObject(value)) { return false; } // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 9 which returns 'object' for typed arrays and other constructors. var tag = baseGetTag(value); return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; } /** * Checks if `value` is a valid array-like length. * * **Note:** This method is loosely based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return value != null && (type == 'object' || type == 'function'); } /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return value != null && typeof value == 'object'; } /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * for more details. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ function keys(object) { return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); } /** * This method returns a new empty array. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {Array} Returns the new empty array. * @example * * var arrays = _.times(2, _.stubArray); * * console.log(arrays); * // => [[], []] * * console.log(arrays[0] === arrays[1]); * // => false */ function stubArray() { return []; } /** * This method returns `false`. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {boolean} Returns `false`. * @example * * _.times(2, _.stubFalse); * // => [false, false] */ function stubFalse() { return false; } module.exports = isEqual; }); /******************************************************************************* - TODO: [ ] ... *******************************************************************************/ var BACKEND = 'REALTIMEDB'; // ----------------------------------------------------------------------------- var WriteMixin = { // --------------------------------------------------------------------------- _write_mixin_init: function _write_mixin_init( reset ) { if ( reset === void 0 ) reset = false; if ( this.modelDefinition ) { if ( this.modelDefinition.staticActions ) { var context = { $model: this, $modelsGetter: function () { return _models; }, // $models: _models, // must be injected later // $registry: registry, // $state: registry.state, }; // const context = this._create_context(); add_custom_actions( context, this, this.modelDefinition.staticActions, reset ); } } }, // --------------------------------------------------------------------------- /** * @example <caption>Add a new item</caption> * challenge.add({ title: 'Name' }) * * @returns {Promise} - Promise that returns the new id when resolved */ add: function add( overwrite_data, new_id, options ) { var obj; /* if ( this.isSuffixed ) { warn(WARNING_DEPRECATED, 'Suffixed stores can not create new items, use unsuffixed' + ' store instead (e.g. goal instead of goalMeta).') } */ var payload = null; if ( !new_id ) { new_id = this._get_uid(); } if ( !new_id['.sv'] && !this._validate_id( new_id ) ) { // only validate if not a server variable throw new Error('Got invalid id:' + new_id) } var useTemplateFunction = true; if ( options && options.directWrite ) { useTemplateFunction = false; } if ( this.modelDefinition ) { if ( useTemplateFunction ) { if ( this.modelDefinition.schema && this.modelDefinition.schema.create ) { /* Check if required input args are present */ this._check_required_create_arg( overwrite_data ); /* Execute create function */ payload = this.modelDefinition.schema.create( overwrite_data, overwrite_data, BACKEND ); } else { warn(WARNING_NO_CREATE_FUNCTION, "No create function found in type definition, using overwrite data as payload."); payload = overwrite_data; } } else { payload = overwrite_data; } /* Validate created data against it's schema. This is not 100% necessary, but just checks if the data coming from create() is consistent with the schema. */ if ( this.modelDefinition.schema ) { this._validate_schema( payload, false ); } else { warn(WARNING_NO_SCHEMA, "No schema found to validate input"); } } else { warn(WARNING_NO_SCHEMA, "No type definition found, using UNVALIDATED overwrite data as payload."); payload = overwrite_data; } this._convert_moment_objects( payload ); info(INFO_STORE_WRITE, "Creating at", this.previewPath(new_id), "with payload", payload); /* if ('.sv' in new_id) { // server value in key warn(WARNING_CLIENT_VALIDATION, 'server value in id detected') return this.parentRef.update({ [newPostKey]: payload }).then(() => new_id); } */ if ( this.isSuffixed ) { return this.childRef( new_id ).update(payload).then(function () { return new_id; }); } else { return this.parentRef.update(( obj = {}, obj[new_id] = payload, obj )).then(function () { return new_id; }); } }, // --------------------------------------------------------------------------- /** * @example <caption>Update single field</caption> * challenge.update(id, { key: value }) * goal_user_settings.update({ 'kanbanSettings/showFinishedTasks': 1 }) * * @example <caption>Update multiple fields</caption> * challenge.update(id, { key1: value1, key2: value2 }) * challenge.update([{ key1: value1 }, { key2: value2 }, ...]) -- ???? * */ update: function update(id, data) { // if ( !util.isArray( data ) ) { // data = [ data ]; // } // data.forEach((value, key) => { // payload // }); if ( !id || !data ) { throw new Error('Either id or data is missing.') } if ( !this._validate_id(id) ) { if ( (this.modelDefinition.schema || {}).unsafe_disable_validation ) { warn(WARNING_INVALID_ID, "Got invalid id <" + id + ">, but validation is disabled."); } else { throw new Error('Got invalid id in update') } } // TODO: Replace '/' with '.' to be consistent with schema --> .replace(/\//g, '.') if ( this.modelDefinition.schema ) { this._validate_schema( data, true ); } else { warn(WARNING_NO_SCHEMA, "No schema found to validate input"); } // let path = this.interpolatedPath; var payload = data; this._convert_moment_objects( payload ); info(INFO_STORE_WRITE, "Updating at", this.previewPath(id), "with payload", payload); return this.childRef( id ).update(payload); }, // --------------------------------------------------------------------------- /** * * @param {object/array} sortidxList - Batch should be an array or array of objects * @example * store.reorder([id1, id2, ...]) * store.reoder([{ id: id1, sortidx: 1 }, { id: id2 sortidx: 2 }, ...]) * * The second version can also be used to pass the entire collection * store.reoder(updated_commitment_list) */ reorder: function reorder(sortidxList, options) { var this$1 = this; if ( options === void 0 ) options = {}; if ( this.isSuffixed ) { throw new Error('Suffixed store does not support reorder') } var sortkey = options.overwriteSortIdxKey || 'sortidx'; if ( sortidxList.length > 0 ) { var first_item = sortidxList[0]; var sortidx = 0; if ( isString( first_item ) || isNumeric( first_item ) ) { sortidxList = sortidxList.map(function (id) { sortidx = sortidx + 100; return { id: id, sortidx: sortidx } }); } if ( '$id' in first_item || first_item.constructor.name === 'GenericModel' ) { sortidxList = sortidxList.map(function (model) { sortidx = sortidx + 100; return { id: model.$id, sortidx: sortidx } }); } } var batchData = {}; sortidxList.forEach(function (item) { var obj; var sortidx = item.sortidx; // Support 'id' and '$id' as key item.id = item.id || item.$id; if (typeof sortidx !== "number") { sortidx = parseFloat(sortidx); } if (isNaN(sortidx)) { throw new Error("Got invalid sortidx", sortidx); } if (!this$1._validate_id(item.id)) { throw new Error("Got invalid id", item.id); } // payload[`tasks.${item.id}.sortidx`] = sortidx; batchData[item.id] = ( obj = {}, obj[sortkey] = sortidx, obj ); }); var payload = {}; Object.keys(batchData).forEach(function (id) { var data = batchData[id]; Object.keys(data).forEach( function (prop) { /* Allow to update multiple fields. This is not required here, but maybe in the future */ // data[path + '/' + subset_name + '/' + id + '/' + prop] = data[prop]; // "/goal/{goalId}/user_list/{uid}/task_names/" payload[ this$1.previewPath(id) + '/' + prop ] = data[prop]; }); }); // TODO: Check schema if sortidx is allowed info(INFO_STORE_WRITE, "Updating at", this.previewPath(), "with payload", payload); return this.rootRef.update(payload) }, // --------------------------------------------------------------------------- /** * Deletes one or many an entry at the data location * @param {UUID} id - id the item or arrary of ids of items that should be deleted * @param {bool=} soft_delete - optional: Overwrite default behaviour for delete mode * @example * challenge.remove(id) * challenge.remove(id, true) // Soft delete * challenge.remove([id1, id2, id3], true) // List mode */ remove: function remove(id, soft_delete) { var this$1 = this; // TODO: Check in schema if soft delete is supported soft_delete = soft_delete === undefined ? this.defaultDeleteMode === DeleteMode.SOFT : soft_delete; if ( Array.isArray( id ) ) { var id_list = id; var payload = {}; id_list.forEach(function (id) { if ( !this$1._validate_id(id) ) { throw new Error('Got invalid id in remove') } if ( soft_delete ) { payload[ id + '/deleted' ] = true; } else { payload[ id ] = null; } }); info(INFO_STORE_WRITE, "Batch deleting at", this.path, "with payload", payload); return this.parentRef.update(payload); } if ( !this._validate_id(id) ) { throw new Error('Got invalid id in remove') } // TODO: Check in schema if soft delete is supported if ( soft_delete ) { info(INFO_STORE_WRITE, "Soft deleting at", this.path, "with", { deleted: true }); return this.update(id, { deleted: true }) // return this.childRef( id ).update({ deleted: true }); } // TODO: automatically remove listener !!! info(INFO_STORE_WRITE, "Hard deleting at", this.path); return this.childRef( id ).remove(); }, // --------------------------------------------------------------------------- /** * Restores a deleted entry at the data location */ restore: function restore( id ) { return this.update(id, { deleted: false }) // ... or null }, // --------------------------------------------------------------------------- /** * copy - Copy data between nodes (same as move, but keeps original * and generates new id) * @param {id} id - id of source object * @param {object} contextA - props of the source path * @param {object} contextB - props of the destination path * */ copy: function copy(id, contextA, contextB) { return this.move(id, contextA, contextB, { keepOriginal: true, keepId: false }); }, // --------------------------------------------------------------------------- /** * Move data between nodes * @params {UUID} id - Id of the object that should be moved * @param {object} contextA - props of the source path * @param {object} contextB - props of the destination path * * @example * store.move(234, { uid: 'A' }, { uid: 'B' }) * * store.move(id, { uid: 'A', taskId: 234 }, { uid: 'B', taskId: 234 }) * * @todo support batch move (as transaction!): * storeA = GenericStore('/goal/{goalId}/user_list/{uid}/task_names/*') * storeB = GenericStore('/goal/{goalId}/user_list/{uid}/task_details/*') * storeC = GenericStore('/goal/{goalId}/user_list/{uid}/task_end_dates/*') * let superStore = SuperStore([storeA, storeB, storeC]) * superStore.batchMove( id, contextA, contextB ) * */ move: function move(id, contextA, contextB, ref) { var this$1 = this; if ( ref === void 0 ) ref = {}; var keepOriginal = ref.keepOriginal; if ( keepOriginal === void 0 ) keepOriginal = false; var keepId = ref.keepId; if ( keepId === void 0 ) keepId = true; if ( this.isSuffixed ) { throw new Error('Suffixed store does not support move') // TODO: It probably does - test and remove this check } if ( !this._validate_id(id) ) { throw new Error('Got invalid id in remove') } var keysContextA = Object.keys( contextA ).sort(); var keysContextB = Object.keys( contextB ).sort(); if ( !lodash_isequal(keysContextA, keysContextB) ) { throw new Error('Context A and context B do not have equal keys') } // TODO: Validate each id in keys /* Example path = '/goal/{goalId}/user_list/{uid}/task_session_list/{taskId}/*' define({ goalId: 'KrZPg8N6THOisFz_T992Zg', uid: 'l1X8FPc7YtbftlC31frciInV3PU2' }) path = '/goal/KrZPg8N6THOisFz_T992Zg/user_list/l1X8FPc7YtbftlC31frciInV3PU2/task_session_list/{taskId}/{id}' move(123, { uid: 'A', taskId: 234 }, { uid: 'B', taskId: 234 }) pathA = '/goal/KrZPg8N6THOisFz_T992Zg/user_list/A/task_session_list/234/123' pathB = '/goal/KrZPg8N6THOisFz_T992Zg/user_list/B/task_session_list/234/123' */ var propsA = Object.assign({}, this.definedProps, contextA, { id: id }); var propsB = Object.assign({}, this.definedProps, contextB, { id: id }); if ( !keepId ) { propsB['id'] = this._get_uid(); // TODO: allow to set new id ? } /* Replace * with {id} in template string (see interpolatedPath)*/ var templatePath = this.templatePath.replace(/\*/, '{id}'); var pathA = parseTpl(templatePath, propsA); var pathB = parseTpl(templatePath, propsB); // if( !this.isSuffixed ) { // pathA = pathA.slice(0, -1) // pathB = pathB.slice(0, -1) // } /* No need to check pathB, since we ensure that they have the same keys */ var undefinedFields = analyzeTpl( pathA ); if ( undefinedFields.length > 0 ) { throw new Error('Not all template id\'s are defined. Required fields are ' + undefinedFields.join(', ')) } // 1. Read at A return this._db.ref(pathA).once('value').then(function (snapshot) { var objectA = snapshot.val(); // TODO: check if we got data return objectA }).then(function (objectA) { // 2. Write A to B // 3. Delete A (as a transaction with 2.) var payload = {}; payload[pathA] = null; payload[pathB] = objectA; if ( keepOriginal ) { payload = {}; payload[pathB] = objectA; } info(INFO_STORE_WRITE, "Moving data from ", pathA, "to", pathB, "with payload", payload); return this$1.rootRef.update(payload).then(function () { return propsB['id']; }) }); }, /** * transaction - perform transaction on RTDB * * @example: * $models.example.transaction( <childId>, <prop>, <transaction> ) * $models.example.transaction( id, 'coins', coins => coins * 2 ) * $models.example.transaction( id, 'coins', 'inc', 100 ) * $models.example.transaction( id, 'coins', 'inc' ) // defaul: increment by 1 * */ transaction: function transaction( id, prop, transaction$1, value ) { var obj; if ( value === void 0 ) value = 1; if ( !this._validate_id(id) ) { throw new Error('Got invalid id in remove') } var targetRef = this.childRef( id ); if ( prop ) { this._validate_schema(( obj = {}, obj[prop] = 1, obj )); // HACK: Using numeric dummy value to check schema targetRef = targetRef.ref.child(prop); } if ( typeof transaction$1 === 'string' ) { switch ( transaction$1 ) { case 'inc': transaction$1 = function (v) { return ( v || 0 ) + value; }; break; case 'dec': transaction$1 = function (v) { return ( v || 0 ) - value; }; break; } } if ( typeof transaction$1 !== 'function' ) { throw new Error('Transacton must be a function') } info(INFO_STORE_WRITE, "Tranaction on", targetRef.path.toString() /*, "with", transaction*/); return targetRef.transaction(transaction$1).then(function (result) { if ( result.committed ) { info(INFO_STORE_WRITE, "Transacton successfully committed"); return true } info(INFO_STORE_WRITE, "Transacton aborted"); // To abort transaction return undefined return false }); }, // --------------------------------------------------------------------------- /** * new - Create empty model from schema (without calling create function) * * new + write = new_id + update * * @return {type} description */ new: function new$1() { var model = factory.make_reactive_model( this.modelDefinition, null, this._create_context(), false ); return model; }, /** * newFromTemplate - Create empty model from create function * * newFromTemplate + write = add * * @return {type} description */ newFromTemplate: function newFromTemplate( data, optional_data ) { if ( data === void 0 ) data = {}; if ( optional_data === void 0 ) optional_data = null; var generated_data = this.empty( data, optional_data ); var model = factory.make_reactive_model( this.modelDefinition, data, this._create_context(), false ); model._update_data( generated_data, null, true ); // doppelt return model }, /** * newFromData - Create empty model from create function * * newFromData + write = add */ newFromData: function newFromData( data, make_dirty ) { if ( data === void 0 ) data = {}; var model = factory.make_reactive_model( this.modelDefinition, data, this._create_context(), false ); // model._update_data( generated_data, null, true ); return model }, /** * empty - Create empty payload from schema.create() * This method WILL only create an JS-Object, not a GenericModel * In most cases, you want to use newFromTemplate instead */ empty: function empty( data, optional_data ) { if ( data === void 0 ) data = {}; if ( optional_data === void 0 ) optional_data = null; if ( !this.modelDefinition ) { return null } if ( !( this.modelDefinition.schema && this.modelDefinition.schema.create ) ) { return null } this._check_required_create_arg( data ); var payload = this.modelDefinition.schema.create( data, optional_data || data /*HACK*/, BACKEND ); /* Validate created data against it's schema. */ if ( this.modelDefinition.schema ) { this._validate_schema( payload, false ); } else { warn(WARNING_NO_SCHEMA, "No schema found to validate input"); } return payload; }, /** * _convert_moment_objects - Convert all moment objects * */ _convert_moment_objects: function _convert_moment_objects( payload ) { if ( typeof payload !== 'object' ) { trace(INFO_MOMENT, "Got invalid payload in _convert_moment_objects", payload, typeof payload); throw new Error('Expected object, got ' + payload); } /* payload can either be array or object */ for ( var prop in payload ) { if ( moment.isMoment( payload[ prop ] ) ) { if ( payload[ prop ].toRealtimeDB ) { payload[ prop ] = payload[ prop ].toRealtimeDB(); } else { throw new Error('Moment object passed to add/update must be enhanced moment objects.') } } else if ( Array.isArray( payload[ prop ] ) ) { this._convert_moment_objects( payload[ prop ] ); } else if ( typeof payload[ prop ] === 'object' ) { // TODO: Detect circular structures this._convert_moment_objects( payload[ prop ] ); } } } }; // import { _Vue as Vue } from '../external-deps' var slugid = require('slugid'); var defaultDB = null; var recentModelCallerComponent = null; // Component, that last called $models var _Vue$1; var _firebase = null; // TODO: Getter with not init warn // let _userId = null; // This is not stateless !!! also this is NOT reactive !!! // let genericStoreGlobalState = _Vue.observable({ userId: null }) var genericStoreGlobalState = { userId: null }; function setup$1(ref) { var Vue = ref.Vue; var firebase = ref.firebase; _Vue$1 = Vue; genericStoreGlobalState = _Vue$1.observable(genericStoreGlobalState); /* In Vue 2.x, _Vue.observable directly mutates the object passed to it, so that it is equivalent to the object returned, as demonstrated here. In Vue 3.x, a reactive proxy will be returned instead, leaving the original object non-reactive if mutated directly. Therefore, for future compatibility, we recommend always working with the object returned by _Vue.observable, rather than the object originally passed to it. */ factory.configure({ GenericModel: GenericModel, GenericList: GenericList }); _firebase = firebase; } var defaultStoreOptions = { isAbstract: false, uidMethod: UIDMethod.PUSHID, additionalProps: [], defaultDeleteMode: DeleteMode.HARD, enableTypeValidation: true, autoUnsubscribe: true, isReadonly: false, allowEmptySchema: true, }; /** * Sync-Implementation is bashed on: * https://github.com/vuejs/vuefire/blob/master/packages/vuexfire/src/index.js * */ var GenericStore = function GenericStore( templatePath, modelDefinition, options ) { if ( options === void 0 ) options = {}; // TODO: Parse templatePath for "[DBName]:", set LOCAL_PATH_PREFIX options = Object.assign( {}, defaultStoreOptions, options ); if ( modelDefinition && ( modelDefinition.abstract_store || options.isAbstract ) ) { this.isAbstract = true; this.templatePath = templatePath; this.modelDefinition = modelDefinition; this.definedProps = {}; this.name = 'unnamed abstract'; } else { this.isAbstract = false; this.name = 'unnamed'; if ( !templatePath || templatePath.length < 2 ) { throw new Error('Invalid template path:' + templatePath ) } if ( templatePath[0] !== '/' ) { throw new Error('Template path has to start with /, got: ' + templatePath ) } if ( (templatePath.match(/\*/g) || []).length !== 1 ) { throw new Error('Template path must contain exactly one *, got:' + templatePath ) } /* let strIsInvalid = !str.match(/^(\/[a-zA-Z_0-9-_$]+)+$/); if ( strIsInvalid ) { throw new Error('Invalid template string ' + this.PREFIX + ' with options ' + JSON.stringify(options)) } */ this.isSuffixed = ( templatePath.indexOf('*') !== templatePath.length - 1 ); // this.isSuffixed = this.path.substr(-1) !== '*'; if ( isFunction( options.uidMethod ) ) { this.uidMethod = UIDMethod.CUSTOM; this.uidMethodCallback = options.uidMethod; } else { this.uidMethod = options.uidMethod || UIDMethod.PUSHID; } this.additionalProps = options.additionalProps || []; this.defaultDeleteMode = options.defaultDeleteMode; } this.enableTypeValidation = options.enableTypeValidation; this.autoUnsubscribe = options.autoUnsubscribe; this.allowEmptySchema = options.allowEmptySchema; this.isReadonly = options.isReadonly; this.templatePath = templatePath; this.modelDefinition = modelDefinition; // this.path = templatePath; this.definedProps = {}; this._localDB = null; this._clones = []; this.global_store_path_array = []; if ( !this.isSuffixed ) { this.global_store_path = ''; } if ( this.isAbstract) { // Only execute mixin inits, but don't attach methods Object.assign(this, { _read_mixin_init: ReadMixin._read_mixin_init, _write_mixin_init: WriteMixin._write_mixin_init }); this._read_mixin_init(); this._write_mixin_init(); } else { { Object.assign(this, ReadMixin); this._read_mixin_init(); } if ( !this.isReadonly ) { Object.assign(this, WriteMixin); this._write_mixin_init(); } } // delete this._read_mixin_init // delete this._write_mixin_init }; var prototypeAccessors$2 = { _db: { configurable: true },defaultUserId: { configurable: true },path: { configurable: true },parentRef: { configurable: true },rootRef: { configurable: true },_template_path_field_names: { configurable: true },schemaFields: { configurable: true },schemaRequiredFields: { configurable: true },schemaOptionalFields: { configurable: true },schemaAllFields: { configurable: true },_last_caller: { configurable: true },rules: { configurable: true } }; var staticAccessors = { defaultUserId: { configurable: true } }; /** * _clone - */ GenericStore.prototype._clone = function _clone () { // INFO: Here we could easly make a copy of items that are meant to be // singletons (like caches) // INFO: This will evaluate all getters! // (all static getters from model definition -> fixed) // - Only because they are not in the prototype // get _db // get _template_path_field_names // get schemaFields // get path // get parentRef // get rootRef // get schemaRequiredFields // get schemaOptionalFields // get schemaAllFields // get subscriptions // get rules // CAREFUL: $store inside getters will still point to old instance! var prototype = Object.getPrototypeOf( this ); var instance = Object.create( prototype ); var clone = Object.assign( instance, this ); var REDEFINE_ACTIONS_AFTER_CLONE = true; { delete clone.getters; delete clone._vm; // !!! clone._read_mixin_init(); } if ( !this.isReadonly && REDEFINE_ACTIONS_AFTER_CLONE ) { clone._write_mixin_init(true); } // Keep track of clones clone._clones = []; this._clones.push(clone); return clone }; /** * setName - Set stores name */ GenericStore.prototype.setName = function setName ( name ) { this.name = name; }; /** * _get_uid - Generates a new unique identifier based on the selected method in the constructor * @returns Unique ID */ // TODO: Public, uid -> id GenericStore.prototype.generateId = function generateId () { return this._get_uid() }; GenericStore.prototype._get_uid = function _get_uid () { switch ( this.uidMethod ) { case UIDMethod.SLUGID: return slugid.nice(); case UIDMethod.PUSHID: // var ref = this.parentRef; var ref = this.rootRef; // Generate a reference to a new location and add some data using push() var newItemRef = ref.push(); // Get the unique key generated by push() return newItemRef.key; // return this.ref.push().key; case UIDMethod.TIMESTAMP: return _firebase.database.ServerValue.TIMESTAMP; case UIDMethod.LOCAL_TIMESTAMP: return moment.currentTime().unix(); case UIDMethod.DATE: /* !!! This is the local time, not the server time !!! */ return moment.currentDate().format('DD-MM-YYYY'); case UIDMethod.OTHER_USER_ID: throw new Error('Please provide id through id override') case UIDMethod.MY_USER_ID: if ( !GenericStore.defaultUserId ) { throw new Error('User ID is not set, but a store uses USER_ID as key') } return GenericStore.defaultUserId; case UIDMethod.ARRAY: return 0; // TODO case UIDMethod.EMAIL: // TODO: let email = atob(key) // TODO: let key = btoa(email) throw new Error('Only email addresses allowed as key') case UIDMethod.CUSTOM: { var customId = this.uidMethodCallback( this.definedProps ); if ( !customId ) { throw new Error( 'An ID was not defined. Check custom UID Callback.' ); } return customId } default: throw new Error('Unknown UID Method: ' + this.uidMethod) } }; /** * Set defaults */ GenericStore.setDefault = function setDefault (key, value) { defaultStoreOptions[ key ] = value; }; /** * @static setDefaultDB - Sets the default DB * * @param{type} db description */ GenericStore.setDefaultDB = function setDefaultDB ( db ) { defaultDB = db; }; /** * get _db - Get reference to db (this will allow other then default databases in the future) * * @return {type}Firebase.db */ prototypeAccessors$2._db.get = function () { return this._localDB || defaultDB; }; /** * _validate_id - Checks if a given id is valid * * @return {type} true or false */ GenericStore.prototype._validate_id = function _validate_id ( id ) { if ( this.uidMethod === UIDMethod.SLUGID ) { if ( !isValidId(id) ) { return false; } } if ( id === -1 || !id ) { return false; } return true; }; /** * _define_user - Define user (userId/uid) based on default value */ GenericStore.prototype._define_user = function _define_user () { if ( GenericStore.defaultUserId ) { this.definedProps[ 'uid' ] = GenericStore.defaultUserId; } }; /** * @static get - Returns the default default UserId for all stores * * @return {type}description */ staticAccessors.defaultUserId.get = function () { return genericStoreGlobalState.userId; }; /* Non static version */ prototypeAccessors$2.defaultUserId.get = function () { return genericStoreGlobalState.userId; }; /** * @static set - Set the default default UserId for all all stores * * @param{type} id description * @return {type} description */ staticAccessors.defaultUserId.set = function (id) { // TODO: Throw error if called before Vue.use(heliosRX) /* When changing the user id we have to DELETE the 'uid' prop, otherwise the user uid will be stored in definedProps, and is still used. This is especially dangerous in Cloud Functions, since a call of most GenericStore methods will define uid. The next call of the CF will then still remember the old user, even when setting a new user with setDefaultUser(). This will happen for all paths that look like /user/{uid}/etc */ /* INFO: In the future this should be refactored to be completly stateless! */ info(INFO_STORE, "settings default user id to: uid =", id); _Vue$1.set( genericStoreGlobalState, 'userId', id); // _userId = id; }; /** * * */ GenericStore.resetState = function resetState () { // genericStoreGlobalState.reset(); info(INFO_STORE, "reset state"); _Vue$1.set( genericStoreGlobalState, 'userId', null); }; /** * get path - Returns a firebase reference based on the template string * Automatically sets user if not defined */ prototypeAccessors$2.path.get = function () { // TODO: rename this to path and this.path to this.uninterpolatedPath if ( !( 'uid' in this.definedProps ) ) { this._define_user(); } var path = parseTpl(this.templatePath, this.definedProps); var undefinedFields = analyzeTpl( path ); if ( undefinedFields.length > 0 ) { // this might be ok in some cases? throw new Error('Not all template id\'s are defined. Required fields are ' + undefinedFields.join(', ')) } /* remove * if it is the last character, otherwise replace * by {id} so it can be interpolated by this.define. */ /* if ( !this.isSuffixed) { return path.slice(0, -1) } else { return path.replace(/\*----/, '{id}') }*/ return path.replace(/\*/g, '{id}') }; /** * previewPath - Generate a path preview for a given it * * @param{type} id description */ GenericStore.prototype.previewPath = function previewPath ( id ) { // TODO: Should this be called during preview? if ( !( 'uid' in this.definedProps ) ) { this._define_user(); } var path = parseTpl(this.templatePath, this.definedProps); if ( id ) { path = path.replace(/\*/g, id); } else { path = path.replace(/\*/, '{id}'); } return path; }; /** * childRef(id) - Returns reference to a specific child of the collection */ GenericStore.prototype.childRef = function childRef (id) { /* replace {id} with id */ return this._db.ref( this.path.replace(/\{id\}/g, id) ); }; /** * get parentRef - Returns reference to collection that contains all items */ prototypeAccessors$2.parentRef.get = function () { /* get string before {id} */ return this._db.ref( this.path.split('{id}').shift() ); // return this._db.ref( this.path ).parent < should work too? }; /** * get rootRef - Return reference to root of database */ prototypeAccessors$2.rootRef.get = function () { return this._db.ref(); }; /** * _define - Defines id's in the template string (INTERNAL) * * @param {GenericStore} target - Target of replacement (usually this) * @param {object} props - Id's that should be replaced. * @example <caption>Example usage of method1.</caption> * task_session_list = new GenericStore('/goal/{goalId}/user_list/{uid}/task_session_list/{taskId}/*', TaskSessionTypeDefinition) * * task_session_list.define({ * goalId: 'KrZPg8N6THOisFz_T992Zg', * uid: 'l1X8FPc7YtbftlC31frciInV3PU2' * }) * * @returns {nothing} */ GenericStore.prototype.define = function define ( target, props ) { /* Merge new props with previous props */ target.definedProps = Object.assign({}, this.definedProps, props); var known_field_names = [].concat( this._template_path_field_names, this.additionalProps ); for ( var prop in props ) { if ( !known_field_names.includes( prop ) ) { warn(WARNING_DEFINE_UNKNOWN_PROP, "Prop", prop, "not found in template path. Known fields are", known_field_names); } } return target; // Allow chaining }; GenericStore.prototype.with = function with$1 ( props ) { // Synax: store.with({ prop1: 'value' }).add({...}) - store is not mutated var new_this = this._clone(); return this.define( new_this, props ); }; /** * get _template_path_field_names - Returns all fields in the template path that need to be defined * * @return {type}description */ prototypeAccessors$2._template_path_field_names.get = function () { var known_field_names = analyzeTpl( this.templatePath ); return known_field_names; }; /** * Resets the template path to it's initial state, without substitutions. */ GenericStore.prototype.reset = function reset (level) { if ( level === void 0 ) level = 1; if ( level === 1 ) { trace(INFO_STORE, "resetting", this.name, "with", this._clones.length, "clones"); } // info(INFO_STORE, "RESET ", level, ":", this.name, " -> Found", this._clones.length, "clones") this.definedProps = {}; if ( level > 3 ) { warn(WARNING_RESET_MAX_DEPTH, "RESET - Stop at recursion level 3", this._clones); return } this._clones.forEach(function (clone) { clone.reset( level + 1 ); }); }; /** * */ prototypeAccessors$2.schemaFields.get = function () { var schema = ( ( this.modelDefinition || {} ).schema || {} ).fields; if ( typeof schema === 'undefined' ) { return []; } if ( !Array.isArray( schema ) ) { schema = Object.keys(schema).map(function (key) { return Object.assign({}, {model: key}, schema[key]) }); } return schema; }; /** * get schemaOptionalFields - Returns all required fields defined in the schema * * @return {type}description */ prototypeAccessors$2.schemaRequiredFields.get = function () { return this.schemaFields .filter( function (field) { return field.required; } ) .map( function (field) { return field.model; } ); }; /** * get schemaOptionalFields - Returns all optional fields defined in the schema * * @return {type}description */ prototypeAccessors$2.schemaOptionalFields.get = function () { return this.schemaFields .filter( function (field) { return !( field.required || false ); }) .map( function (field) { return field.model; } ); }; /** * get schemaAllFields - Returns all fields that are defined in the schema * * @return {type}description */ prototypeAccessors$2.schemaAllFields.get = function () { return this.schemaFields.map( function (field) { return field.model; } ); }; /** * _check_required_fields - Check if all required fields exists according to schema * * @param{type} data data to check */ GenericStore.prototype._check_required_fields = function _check_required_fields ( data ) { this.schemaRequiredFields.forEach(function (required_field) { if ( !( required_field in data ) ) { throw new Error('Required field <' + required_field + '> not present.') } }); }; /** * _check_required_fields - Check if create inputs are present * Required by user is not the same a required by DB! * * @param{type} data data to check */ GenericStore.prototype._check_required_create_arg = function _check_required_create_arg ( data ) { // TODO: Convert object to array var schema = ( ( this.modelDefinition || {} ).schema || {} ); (schema.create_required || []).forEach(function (required_create_arg) { if ( !( required_create_arg in data )) { throw new Error('Required create argument <' + required_create_arg + '> not present.') } }); }; /** * _validate_schema - Validates against the current schema * * @param{type} data data to validate * @param{type} is_update is the data used for updating and existing item? */ GenericStore.prototype._validate_schema = function _validate_schema ( data, is_update ) { var this$1 = this; if ( this.modelDefinition && this.modelDefinition.schema && this.modelDefinition.schema.unsafe_disable_validation ) { return; } var schema = this.schemaFields; if ( !this.allowEmptySchema ) { if ( !schema || schema.length === 0 ) { throw new Error('No schema found for "' + this.name + '", please provide one.') } } /* Check 1: Are required fields present (Disabled for updates) */ if ( !is_update ) { this._check_required_fields( data ); /* schema.fields.forEach(required_field => { if ( ( required_field.required || false ) && !( required_field.model in data ) ) { throw new Error('Required field <' + required_field.model + '> not present.') } }); */ } // This is a ES2018 feature that buble won't compile // const mapRegex = /Map\s*<(?<key>\w+),\s*(?<val>\w+)>/i; // const typeRegex = /(?<val>\w+)\s*\[\]/; // Regexes to match special bolt types var mapRegex = /Map\s*<(\w+),\s*(\w+)>/i; var typeRegex = /(\w+)\s*\[\]/; /* Check 2: Are provided fields within schema? */ var allowed_field_names = this.schemaAllFields; var allowed_field_regex = []; var allowed_field_map = {}; if ( schema.length === 0 ) { warn(WARNING_EMPTY_SCHEMA, 'Schema for "' + this.name + '" is empty.'); } else { allowed_field_map = Object.assign.apply(Object, allowed_field_names.map(function (k, i) { var obj; if ( k.startsWith('/') && k.endsWith('/') ) { allowed_field_regex.push( k ); } return ( obj = {}, obj[k] = this$1.schemaFields[i], obj ) })); Object.keys(allowed_field_map).forEach(function (key, i) { var type = allowed_field_map[ key ].type || ''; if ( mapRegex.test( type ) ) { // See: https://github.com/firebase/firebase-js-sdk/blob/master/packages/database/src/core/util/validation.ts var regex = "/^" + key + "\\/((?![\\/\\[\\]\\.\\#\\$\\/\\u0000-\\u001F\\u007F]).)*$/"; allowed_field_regex.push( regex ); allowed_field_map[ regex ] = this$1.schemaFields[i]; } }); } // TODO: Cache everything above this point Object.keys( data ).forEach(function (key) { var matchedRegex = allowed_field_regex.find(function (regex) { var flags = regex.includes('\\u00') ? '' : 'u'; // Unicode var rx = new RegExp( regex.substring( 1, regex.length - 1 ), flags ); return rx.test( key ) }); if ( !matchedRegex && !allowed_field_names.includes(key) ) { throw new Error('Field <' + key + '> is not allowed by schema.') } /* Check 3: Execute validator if present */ var field = allowed_field_map[ matchedRegex || key ]; // Remove "|| key" ? if ( field.validator ) { // TODO: Try-catch // TODO: see https://vue-generators.gitbook.io/vue-generators/validation/custom-validators var result = field.validator( /* value */ data[ key ], /* field */ field, /* model */ null ); if ( !result || ( result.length && result.length === 0 ) ) { throw new Error('User-defined schema validation failed for key "' + key + '" with error: ' + result) } } if ( this$1.enableTypeValidation ) { // TODO: Also support Generic types (MyTime<A,B>) var type_list = (field.type || "").split("|"); var check = type_list.some(function (typeRaw) { var type = typeRaw.trim(); var typeInfo = {}; if ( typeRegex.test( type ) ) { // typeInfo = typeRegex.exec( type ).groups; var match = typeRegex.exec( type ); typeInfo = { val: match[1] }; type = 'Array'; } if ( mapRegex.test( type ) ) { // typeInfo = mapRegex.exec( type ).groups; var match$1 = mapRegex.exec( type ); typeInfo = { key: match$1[1], val: match$1[2] }; type = 'Map'; } // For non required fields also allow 'null' as a valid input if ( !field.required ) { if ( data[ key ] === null ) { return true; } } return this$1._validate_bolt_type( data[ key ], type, typeInfo ); }); if ( !check ) { throw new Error('Type-based schema validation failed for key "' + key + '" with error.') } } }); }; /** * _validate_bolt_type - Returns true if the value is a valid type of a give type * * @return {boolean} is value of type 'type'? */ GenericStore.prototype._validate_bolt_type = function _validate_bolt_type ( value, type, typeInfo ) { var this$1 = this; if ( typeInfo === void 0 ) typeInfo = {}; switch ( type.toLowerCase() ) { case 'string':return isString( value ); case 'number':return isNumeric( value ); case 'boolean': return isBoolean( value ); case 'object':return isValue( value ) && isObject( value ) && !isArray( value ); case 'any': return isValue( value ); case 'null': return value === null; case 'map': // Map<Key, Value> -> Map + { key, val } return isObject( value ) && !isArray( value ) && Object.entries( value ).every(function (ref) { var k = ref[0]; var v = ref[1]; // JS-Array keys are always strings! var hasValidKey = isString( k ); var hasValidValue = this$1._validate_bolt_type( v, typeInfo.val ); // let hasValidKey = this._validate_bolt_type( k, typeInfo.key ); return hasValidKey && hasValidValue; }); case 'array': { // Type[] = Map<Number, Type> var entries = []; if ( isArray( value ) ) { entries = value; } else if ( isObject( value ) ) { entries = Object.values( value ); } else { return false; } return entries.every( function (v) { var hasValidType = this$1._validate_bolt_type( v, typeInfo.val ); return hasValidType; }); } default: warn(WARNING_UKNONWN_VALIDATION_TYPE, "Can not validate type '" + type + "'"); return true; } }; /** * Set the recent caller, this is trigger by the getter that returns $models. * Which means this is called before subscribeList(), when calling it like this: * this.$models.myexample.subscribeList() * ^ ^ * | | * +- _set_caller +- subscribeList is called * is called and can access this._last_caller * */ GenericStore._set_caller = function _set_caller ( caller ) { // Check, if we got a VueComponent instance if ( caller._isVue !== true ) { return false; } recentModelCallerComponent = caller; }; /** * Returns last VueCompoennt that accessed this.$models (see above). * */ prototypeAccessors$2._last_caller.get = function () { return recentModelCallerComponent }; // --------------------------------------------------------------------------- /** * rules - Return custom validation rules for elements * See: https://element.eleme.io/#/en-US/component/form#custom-validation-rules */ prototypeAccessors$2.rules.get = function () { var schema = this.modelDefinition.schema.fields; if ( !Array.isArray( schema ) ) { schema = Object.keys(schema).map(function (key) { return Object.assign({}, {model: key}, schema[key]) }); } var rules = {}; schema.forEach(function (field) { // TODO: Allow multiple rules // TODO: Allow UI-rules AND DB-rules // TODO: Allow custom message // TODO: Allow to set blur rules[ field.model ] = [{ validator: function (rule, value, callback) { if ( field.validator( value ) ) { callback(); } else { callback(new Error('Invalid input')); } }, trigger: 'blur' }]; }); return rules; }; Object.defineProperties( GenericStore.prototype, prototypeAccessors$2 ); Object.defineProperties( GenericStore, staticAccessors ); // export default from './GenericStore'; // export const UIDMethod = xUIDMethod; var obj; var genericStoreMutations = ( obj = {}, obj[HELIOSRX_INIT_VALUE] = function (state, ref) { var path = ref.path; var data = ref.data; trace(INFO_REGISTRY, '[HELIOSRX_INIT_VALUE]', { path: path, data: data }); // TODO: will this delete children? return walkSetAndMerge( state, path, data ) }, obj[HELIOSRX_UNSET_VALUE] = function (state, ref) { var path = ref.path; trace(INFO_REGISTRY, '[HELIOSRX_UNSET_VALUE]', { path: path }); return walkSetAndMerge( state, path, { '.value': null } ) }, obj[HELIOSRX_ARRAY_ADD] = function (state, ref) { var target = ref.target; var newId = ref.newId; var data = ref.data; trace(INFO_REGISTRY, '[HELIOSRX_ARRAY_ADD]', { target: target, newId: newId, data: data }); _Vue.set( target, newId, data ); }, obj[HELIOSRX_ARRAY_REMOVE] = function (state, ref) { var target = ref.target; var oldId = ref.oldId; trace(INFO_REGISTRY, '[HELIOSRX_ARRAY_REMOVE]', { target: target, oldId: oldId }); _Vue.delete( target, oldId ); }, obj[HELIOSRX_ARRAY_SET] = function (state, ref) { var target = ref.target; var currentId = ref.currentId; var data = ref.data; var performMerge = ref.performMerge; if ( performMerge === void 0 ) performMerge = false; if (target[ currentId ]) { deepMergeVue( target[ currentId ], data, !performMerge ); } else { target[ currentId ] = data; } }, obj[HELIOSRX_SET] = function (state, ref) { var target = ref.target; var data = ref.data; var performMerge = ref.performMerge; if ( performMerge === void 0 ) performMerge = false; trace(INFO_REGISTRY, '[HELIOSRX_SET]', { target: target, data: data, performMerge: performMerge }); deepMergeVue( target, data, !performMerge ); }, obj ); // import createPersistedState from 'vuex-persistedstate' // import { ENABLE_PERSISTENT_REGISTRY } from '@/features' // TODO: Replace vuex store with vue instance - maybe var registryModule = { strict: true, // plugins: /* ENABLE_PERSISTENT_REGISTRY ? [ createPersistedState() ] : */ [], state: { initialized: false, res: {}, sync: {}, ready: {} // index: {}, }, getters: { get_registry_entry: function (state) { return function (name) { return state.sync[ name ]; }; }, is_ready: function (state) { return function (name) { return state.ready[ name ] || false; }; }, }, mutations: Object.assign({}, genericStoreMutations, // TODO: Refactor (ready mutations) {INIT_REGISTRY: function INIT_REGISTRY(state) { state.initialized = true; }, RESET_REGISTRY: function RESET_REGISTRY(state) { trace(INFO_REGISTRY, 'RESET_REGISTRY'); // Callend on logout _Vue.set( state, 'sync', {}); _Vue.set( state, 'res', {}); _Vue.set( state, 'ready', {}); state.initialized = false; }, ADD_ENTRY: function ADD_ENTRY(state, ref) { var name = ref.name; var data = ref.data; trace(INFO_REGISTRY, 'ADD_ENTRY'); if (!state.sync[name] || state.sync[name] !== data) { _Vue.set( state.sync, name, data ); } }, SET_ENTRY_STATUS: function SET_ENTRY_STATUS( state, ref ) { var name = ref.name; var value = ref.value; trace(INFO_REGISTRY, 'SET_ENTRY_STATUS'); if (!state.sync[ name ][status] || state.sync[ name ][status] !== value) { _Vue.set(state.sync[ name ], 'status', value); } }, SET_GLOBAL_READY_STATE: function SET_GLOBAL_READY_STATE( state, ref ) { var name = ref.name; var value = ref.value; trace(INFO_REGISTRY, 'SET_GLOBAL_READY_STATE'); if (!state.ready[name] || state.ready[name] !== !!value) { _Vue.set(state.ready, name, !!value); } }, REM_GLOBAL_READY_STATE: function REM_GLOBAL_READY_STATE( state, ref ) { var name = ref.name; trace(INFO_REGISTRY, 'REM_GLOBAL_READY_STATE'); _Vue.delete(state.ready, name); }}), }; function setup$2( name ) { registryModule.name = name; registryModule.namespaced = true; // TODO: state as function return registryModule; } // import registrySetup from './registry/setup.js' // import api from './api/index.js' var _Vue$2; // bind on install ( --> MOVE) function install (Vue, options) { if (install.installed && _Vue$2 === Vue) { return } install.installed = true; info(INFO_COMMON, "Installing Generic API plugin"); if ( !options ) { throw new Error('heliosRX: Missing configuration. Did you supply config with Vue.use("heliosRx", {...})?') } if ( !options.db ) { throw new Error('heliosRX: Missing configuration "db".') } if ( !options.models ) { throw new Error('heliosRX: Missing configuration "models".') } _Vue$2 = Vue; setup({ Vue: Vue, models: options.models, db: options.db, }); // Configure database var dbConfig = options.db; // Checking dbConfig.constructor.name === 'Database' won't work in production // Setup generic store setup$1({ Vue: Vue, firebase: options.firebase || options.db.app.firebase_ // HACK: Figure out from rtdb }); if ( dbConfig.app && dbConfig.app.database ) { GenericStore.setDefaultDB( options.db ); // TODO: Move to 'storeSetup'? } else if ( typeof dbConfig === 'object' ) { throw new Error('heliosRX: Multi-DB configuration not implemented yet.') } else { throw new Error('heliosRX: Invalid configuration for db.') } // Setup registry var _registry; if ( !options.useExistingStore ) { // TODO: Get vue from option or from vue instance? (Vue._installedPlugins || []).forEach(function (plugin) { if ( plugin.Store && plugin.mapActions ) { warn(WARNING_COMMON, "Existing Vuex detected. Consider using 'useExistingStore'. See heliosRX documentation."); } }); Vue.use( _Vuex ); _registry = new _Vuex.Store( setup$2( 'heliosRX' ) ); setup({ Vuex: _Vuex, registry: _registry }); // Initialize registry _registry.commit('INIT_REGISTRY'); // TODO: module/INIT_REGISTRY } else { var store = options.useExistingStore; store.registerModule('heliosrx', setup$2( 'heliosRX' )); setup({ Vuex: _Vuex, registry: store }); throw new Error('heliosRX: Custom state management not fully implemented.') // TODO: Fix mutations } // Define $models Object.defineProperty(Vue.prototype, '$models', { get: function get () { GenericStore._set_caller( this ); return options.models } }); // Merge user api with helios API // let mergedApi = api; var mergedApi = {}; if ( options.userApi ) { // mergedApi = Object.assign({}, api, options.userApi); mergedApi = options.userApi; } // Define $api Object.defineProperty(Vue.prototype, '$api', { get: function get () { return mergedApi } }); // TODO: Also allow to set trace / warnings if ( options.devMode ) { loglevel.setDefaultLevel('info'); loglevel.setLevel('info'); loglevel.getLogger( INFO_STORE_WRITE ).setLevel('trace'); } else { loglevel.setDefaultLevel('warn'); loglevel.setLevel('warn'); } // Expose everything to developer console var isDevEnvironment = process.env.VUE_APP_PRODUCTION === 'false' && process.browser; if ( options.devMode === true || ( options.devMode === undefined && isDevEnvironment ) ) { window.$models = options.models; window.$db = options.db; window.$api = mergedApi; window.$registry = _registry; } } function setDefaultDB(db) { GenericStore.setDefaultDB(db); } function setDefaultUser(id) { if ( GenericStore.defaultUserId !== null ) { throw new Error('Call resetGenericStores before setting the default user id') } GenericStore.defaultUserId = id; } function resetGenericStores( unsubscribe ) { if ( unsubscribe === void 0 ) unsubscribe = true; GenericStore.resetState(); // GenericStore.defaultUserId = null; // const stores = ModelRegistry.getAllStores(); var stores = _models; var loop = function ( key ) { // if ( key === '_prototype' ) { // continue // } var model = stores[ key ]; var sublist = model.subscriptions; /* reset models */ model.reset(); /* unsubscribe */ if ( unsubscribe && sublist ) { Object.keys(sublist).forEach(function (sub) { var callback = sublist[ sub ]; info(INFO_COMMON, "Calling unsubscribe for", key, ":", sub); callback(); }); } }; for ( var key in stores ) loop( key ); } /* Usage: let client_env = functions.config().client_env; let config = { apiKey: client_env.firebase_api_key, authDomain: client_env.firebase_auth_domain, databaseURL: client_env.firebase_database_url, projectId: client_env.firebase_project_id, storageBucket: client_env.firebase_storage_bucket, messagingSenderId: client_env.firebase_messaging_sender_id } heliosRX.setup({ firebaseConfig: config, runAsUser: false, models: { ... }, }) */ function setupNode( options ) { /* options.runAsUser: false | null | <String>, options.firebaseConfig: null | <FirebaseApp>, options.firebase options.devMode */ // eslint-disable-next-line import/no-unresolved var admin = options.firebaseAdmin; // require('firebase-admin'); // eslint-disable-next-line import/no-unresolved var Vue = options.Vue || _Vue; // eslint-disable-next-line import/no-unresolved var Vuex = options.Vuex || _Vuex; var usingLocalEmulator = process.env.FUNCTIONS_EMULATOR === 'true'; if ( options.runAsUser ) { if ( usingLocalEmulator ) { info(INFO_COMMON, "[initializeApp]", "with default config", process.env.FIREBASE_CONFIG); admin.initializeApp({ credential: admin.credential.applicationDefault(), }); } else { // Test config with: admin.initializeApp(); } } else { // TODO: Scope admin user to regular service user -> "support user" // https://firebase.googleblog.com/2019/03/firebase-security-rules-admin-sdk-tips.html // INFO: This is the same as the env variable CLOUD_RUNTIME_CONFIG, // which is only configured on host machine, not in local emulator! var config = options.firebaseConfig; info(INFO_COMMON, "[initializeApp]", "config", config); admin.initializeApp(config); } // Set default DB for generic API var defaultDb = admin.database(); setDefaultDB( defaultDb ); setup({ Vue: Vue, models: options.models, db: defaultDb, }); setup$1({ Vue: Vue, firebase: admin }); if ( Vue && Vuex ) { Vue.use( Vuex ); var _registry = new Vuex.Store( setup$2( 'heliosRX' ) ); setup({ Vuex: Vuex, registry: _registry }); // Initialize registry _registry.commit('INIT_REGISTRY'); } /* // Merge user api with helios API let mergedApi = {}; if ( options.userApi ) { mergedApi = options.userApi; } // Define $api Object.defineProperty(Vue.prototype, '$api', { get () { return mergedApi } }) */ // Setup heliosRX without Vue? // install( options.Vue, options ) } var version = '0.2.4'; var heliosRX = function heliosRX () {}; heliosRX.install = function install () {}; heliosRX.setup = function setup ( options ) { setupNode(options); return heliosRX; }; heliosRX.version = version; heliosRX.install = install; heliosRX.getRegistry = getRegistry; heliosRX.registryModule = setup$2; heliosRX.moment = moment; heliosRX.GenericStore = GenericStore; heliosRX.UIDMethod = UIDMethod; heliosRX.DeleteMode = DeleteMode; heliosRX.setDefaultDB = setDefaultDB; heliosRX.setDefaultUser = setDefaultUser; heliosRX.resetGenericStores = resetGenericStores; heliosRX.heliosLogger = loglevel; heliosRX.heliosLogger.channels = loggerChannel; module.exports = heliosRX;
diatum-org/dikota
src/app/profileimage/profileimage.component.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var router_1 = require("nativescript-angular/router"); var page_1 = require("tns-core-modules/ui/page"); var image_source_1 = require("tns-core-modules/image-source"); var camera_service_1 = require("../service/camera.service"); var gallery_service_1 = require("../service/gallery.service"); var bitmap_service_1 = require("../service/bitmap.service"); var amigo_service_1 = require("../appdb/amigo.service"); var dialogs = require("tns-core-modules/ui/dialogs"); var utils = require("tns-core-modules/utils/utils"); var application = require("tns-core-modules/application"); var platform_1 = require("tns-core-modules/platform"); var ProfileImageComponent = /** @class */ (function () { function ProfileImageComponent(router, bitmapService, galleryService, cameraService, amigoService, page) { this.router = router; this.bitmapService = bitmapService; this.galleryService = galleryService; this.cameraService = cameraService; this.amigoService = amigoService; this.page = page; this.source = null; this.avatarSrc = null; this.timeout = null; this.sub = []; this.msg = "---"; this.dirty = false; this.iOS = (platform_1.device.os == "iOS"); this.clearVisible = "hidden"; this.moveVisible = "hidden"; this.stretchVisible = "hidden"; this.applyText = ""; this.applyCrop = false; this.applySave = false; this.applyReset = false; } ProfileImageComponent.prototype.ngOnInit = function () { var _this = this; // load default logo this.avatarSrc = image_source_1.ImageSource.fromFileSync("~/assets/avatar.png"); // check if we are discarding changes if (application.android != null) { this.discard = function (args) { args.cancel = true; if (_this.isDirty()) { dialogs.confirm({ message: "Are you sure you want to discard your changes?", okButtonText: "Yes, Discard", cancelButtonText: "No, Cancel" }).then(function (flag) { if (flag) { _this.goBack(); } }); } else { _this.goBack(); } }; application.android.on(application.AndroidApplication.activityBackPressedEvent, this.discard); } // setup orientation callback //this.application = require('application'); //this.orientationEvent = (args) => { this.onOrientation(); }; //this.application.on(this.application.orientationChangedEvent, this.orientationEvent); //this.application.off(this.application.orientationChangedEvent, this.orientationEvent); }; ProfileImageComponent.prototype.ngAfterViewInit = function () { var _this = this; // store reference to objects this.profile = this.img.nativeElement; this.move = this.mov.nativeElement; this.clear = this.clr.nativeElement; this.stretch = this.sth.nativeElement; this.bound = this.box.nativeElement; this.frame = this.frm.nativeElement; this.sub.push(this.amigoService.identity.subscribe(function (i) { if (i == null || i.logo == null) { _this.profile.imageSource = _this.avatarSrc; } else { var src = image_source_1.ImageSource.fromBase64Sync(i.logo); _this.clearOverlay(); _this.setImageSource(src); } })); }; ProfileImageComponent.prototype.ngOnDestroy = function () { if (this.timeout != null) { clearTimeout(this.timeout); } for (var i = 0; i < this.sub.length; i++) { this.sub[i].unsubscribe(); } this.profile.imageSource = null; utils.GC(); }; ProfileImageComponent.prototype.goBack = function () { if (application.android != null) { application.android.off(application.AndroidApplication.activityBackPressedEvent, this.discard); } this.router.back(); }; ProfileImageComponent.prototype.onOrientation = function () { if (this.profile != null && this.profile.imageSource != null) { //this.clearOverlay(); this.applyCrop = false; this.applySave = false; this.applyText = ""; this.clearVisible = "visible"; this.moveVisible = "hidden"; this.stretchVisible = "hidden"; this.setImageSource(this.profile.imageSource); } }; ProfileImageComponent.prototype.isDirty = function () { return this.applySave || this.applyCrop || this.applyReset; }; ProfileImageComponent.prototype.onBack = function () { var _this = this; if (this.isDirty()) { dialogs.confirm({ message: "Are you sure you want to discard your changes?", okButtonText: "Yes, Discard", cancelButtonText: "No, Cancel" }).then(function (flag) { if (flag) { _this.goBack(); } }); } else { this.goBack(); } }; ProfileImageComponent.prototype.onPan = function (args) { if (platform_1.isIOS) { args.deltaX *= this.scale; args.deltaY *= this.scale; } // correct for left var left = (this.scale * this.overlayWidth / 2) - (this.deltaX + args.deltaX); if (left > this.profileWidth / 2) { args.deltaX = (this.scale * this.overlayWidth / 2) - (this.deltaX + this.profileWidth / 2); } // correct for right var right = (this.scale * this.overlayWidth / 2) + (this.deltaX + args.deltaX); if (right > this.profileWidth / 2) { args.deltaX = (this.profileWidth / 2) - (this.scale * this.overlayWidth / 2) - this.deltaX; } // correct for top var top = (this.scale * this.overlayHeight / 2) - (this.deltaY + args.deltaY); if (top > this.profileHeight / 2) { args.deltaY = (this.scale * this.overlayHeight / 2) - (this.deltaY + this.profileHeight / 2); } // correct for bottom var bottom = (this.scale * this.overlayHeight / 2) + (this.deltaY + args.deltaY); if (bottom > this.profileHeight / 2) { args.deltaY = (this.profileHeight / 2) - (this.scale * this.overlayHeight / 2) - this.deltaY; } // reposition image if (args.state == 2) { this.move.translateX = this.deltaX + args.deltaX; this.move.translateY = this.deltaY + args.deltaY; } if (args.state == 3) { this.deltaX += args.deltaX; this.deltaY += args.deltaY; this.move.translateX = this.deltaX; this.move.translateY = this.deltaY; } }; ProfileImageComponent.prototype.onPinch = function (args) { // correct for left var left = (this.scale * args.scale * this.overlayWidth / 2) - this.deltaX; if (left > this.profileWidth / 2) { args.scale = ((this.profileWidth / 2) + this.deltaX) / (this.scale * this.overlayWidth / 2); } // correct for right var right = (this.scale * args.scale * this.overlayWidth / 2) + this.deltaX; if (right > this.profileWidth / 2) { args.scale = ((this.profileWidth / 2) - this.deltaX) / (this.scale * this.overlayWidth / 2); } // correct for top var top = (this.scale * args.scale * this.overlayHeight / 2) - this.deltaY; if (top > this.profileHeight / 2) { args.scale = ((this.profileHeight / 2) + this.deltaY) / (this.scale * this.overlayHeight / 2); } // correct for bottom var bottom = (this.scale * args.scale * this.overlayHeight / 2) + this.deltaY; if (bottom > this.profileHeight / 2) { args.scale = ((this.profileHeight / 2) - this.deltaY) / (this.scale * this.overlayHeight / 2); } // scale image if (args.state == 2) { this.stretch.scaleX = this.scale * args.scale; this.stretch.scaleY = this.scale * args.scale; } if (args.state == 3) { this.scale *= args.scale; this.stretch.scaleX = this.scale; this.stretch.scaleY = this.scale; } if (this.stretch.scaleX > 1) { this.stretch.scaleX = 1; } if (this.stretch.scaleY > 1) { this.stretch.scaleY = 1; } }; ProfileImageComponent.prototype.setScale = function () { var boxRatio = this.boxWidth / this.boxHeight; var imgRatio = this.imgWidth / this.imgHeight; if (imgRatio > boxRatio) { // image will span horizontally this.profileHeight = this.boxWidth * this.imgHeight / this.imgWidth; this.profileWidth = this.boxWidth; } else { // image will span vertically this.profileWidth = this.boxHeight * this.imgWidth / this.imgHeight; this.profileHeight = this.boxHeight; } if (this.boxWidth > this.boxHeight) { this.overlayWidth = this.boxHeight; this.overlayHeight = this.boxHeight; } else { this.overlayWidth = this.boxWidth; this.overlayHeight = this.boxWidth; } var widthRatio = this.profileWidth / this.overlayWidth; var heightRatio = this.profileHeight / this.overlayHeight; if (widthRatio < heightRatio) { this.scale = widthRatio; } else { this.scale = heightRatio; } }; ProfileImageComponent.prototype.syncOverlay = function () { this.move.scaleX = this.scale; this.move.scaleY = this.scale; this.move.translateX = this.deltaX; this.move.translateY = this.deltaY; this.stretch.scaleX = this.scale; this.stretch.scaleY = this.scale; this.stretch.translateX = this.deltaX; this.stretch.translateY = this.deltaY; }; ProfileImageComponent.prototype.onClear = function () { this.applySave = false; this.applyCrop = true; this.applyText = "CROP"; this.clearVisible = "hidden"; this.moveVisible = "hidden"; this.stretchVisible = "visible"; this.syncOverlay(); }; ProfileImageComponent.prototype.onStretch = function () { this.applySave = false; this.applyCrop = true; this.applyText = "CROP"; this.clearVisible = "hidden"; this.moveVisible = "visible"; this.stretchVisible = "hidden"; this.syncOverlay(); }; ProfileImageComponent.prototype.onMove = function () { if (this.imgWidth == this.imgHeight) { this.applySave = true; this.applyText = "SAVE"; } else { this.applySave = false; this.applyText = ""; } this.applyCrop = false; this.clearVisible = "visible"; this.moveVisible = "hidden"; this.stretchVisible = "hidden"; this.syncOverlay(); }; ProfileImageComponent.prototype.clearOverlay = function () { // reset overlay this.applyText = ""; this.applySave = false; this.applyCrop = false; this.applyReset = false; this.moveVisible = "hidden"; this.stretchVisible = "hidden"; this.clearVisible = "hidden"; this.deltaX = 0; this.deltaY = 0; this.scale = 1; this.syncOverlay(); }; ProfileImageComponent.prototype.onApply = function () { var _this = this; if (this.applyCrop) { // mark change has been made this.dirty = true; var left = (this.profileWidth / 2) - ((this.scale * this.overlayWidth / 2) - this.deltaX); left *= (this.imgWidth / this.profileWidth); left = Math.round(left); if (left < 0) { left = 0; } if (left > this.imgWidth) { left = this.imgWidth; } var right = (this.profileWidth / 2) + ((this.scale * this.overlayWidth / 2) + this.deltaX); right *= (this.imgWidth / this.profileWidth); right = Math.round(right); if (right < 0) { right = 0; } if (right > this.imgWidth) { right = this.imgWidth; } var top_1 = (this.profileHeight / 2) - ((this.scale * this.overlayHeight / 2) - this.deltaY); top_1 *= (this.imgHeight / this.profileHeight); top_1 = Math.round(top_1); if (top_1 < 0) { top_1 = 0; } if (top_1 > this.imgHeight) { top_1 = this.imgHeight; } var bottom = (this.profileHeight / 2) + ((this.scale * this.overlayHeight / 2) + this.deltaY); bottom *= (this.imgHeight / this.profileHeight); bottom = Math.round(bottom); if (bottom < 0) { bottom = 0; } if (bottom > this.imgHeight) { bottom = this.imgHeight; } // make square crop if ((right - left) > (bottom - top_1)) { right = (bottom - top_1) + left; } if ((bottom - top_1) > (right - left)) { bottom = (right - left) + top_1; } this.clearOverlay(); utils.GC(); this.bitmapService.crop(this.profile.imageSource, left, right, top_1, bottom).then(function (s) { _this.setImageSource(s); }).catch(function (err) { dialogs.alert({ message: err, okButtonText: "ok" }); }); } else if (this.applySave) { this.dirty = false; this.clearOverlay(); this.bitmapService.resize(this.profile.imageSource, 1024, 1024).then(function (s) { var data = s.toBase64String("jpg", 25); _this.amigoService.setImage(data); _this.profile.imageSource = s; }).catch(function (err) { dialogs.alert({ message: err, okButtonText: "ok" }); }); } else if (this.applyReset) { this.amigoService.setImage(null); this.applyReset = false; this.applyText = ""; } }; ProfileImageComponent.prototype.setImageSource = function (s) { var _this = this; // remove previous layers this.bound.removeChild(this.profile); this.bound.removeChild(this.move); this.bound.removeChild(this.stretch); this.bound.removeChild(this.clear); // store actual image dimensiosn this.imgWidth = s.width; this.imgHeight = s.height; // set profile layer this.profile.imageSource = s; // place layers this.bound.addChildAtCell(this.profile, 0, 0); this.bound.addChildAtCell(this.move, 0, 0); this.bound.addChildAtCell(this.stretch, 0, 0); this.bound.addChildAtCell(this.clear, 0, 0); // ugly, isn't there an event to wait on?? if (this.timeout != null) { clearTimeout(this.timeout); } this.timeout = setTimeout(function () { _this.timeout = null; var size = _this.frame.getActualSize(); if (size.width == 0 || size.height == 0) { dialogs.alert({ message: "Invalid grid dimensions", okButtonText: "ok" }); } else { _this.boxWidth = size.width; _this.boxHeight = size.height; if (_this.dirty) { if (_this.imgWidth == _this.imgHeight) { _this.applyCrop = false; _this.applySave = true; _this.applyText = "SAVE"; _this.clearVisible = "visible"; } else { _this.applyCrop = true; _this.applySave = false; _this.applyText = "CROP"; _this.stretchVisible = "visible"; } } else { _this.clearVisible = "visible"; } _this.setScale(); _this.syncOverlay(); } }, 500); }; ProfileImageComponent.prototype.isEdit = function () { if (this.clearVisible == "visible") { return true; } if (this.moveVisible == "visible") { return true; } if (this.stretchVisible == "visible") { return true; } return false; }; ProfileImageComponent.prototype.onCamera = function () { var _this = this; this.clearOverlay(); utils.GC(); this.cameraService.snap().then(function (s) { _this.dirty = true; _this.setImageSource(s); }).catch(function (err) { if (err == null) { dialogs.alert({ message: "unknown camera error", okButtonText: "ok" }); } else { dialogs.alert({ message: err.toString(), okButtonText: "ok" }); } }); }; ProfileImageComponent.prototype.onGallery = function () { var _this = this; this.clearOverlay(); utils.GC(); this.galleryService.snag().then(function (s) { _this.dirty = true; _this.setImageSource(s); }).catch(function (err) { if (err == null) { dialogs.alert({ message: "unknown gallery error", okButtonText: "ok" }); } else { dialogs.alert({ message: err.toString(), okButtonText: "ok" }); } }); }; ProfileImageComponent.prototype.onReset = function () { this.dirty = true; this.clearOverlay(); this.profile.imageSource = this.avatarSrc; this.applyReset = true; this.applyText = "SAVE"; }; __decorate([ core_1.ViewChild("box", { static: false }), __metadata("design:type", core_1.ElementRef) ], ProfileImageComponent.prototype, "box", void 0); __decorate([ core_1.ViewChild("frm", { static: false }), __metadata("design:type", core_1.ElementRef) ], ProfileImageComponent.prototype, "frm", void 0); __decorate([ core_1.ViewChild("img", { static: false }), __metadata("design:type", core_1.ElementRef) ], ProfileImageComponent.prototype, "img", void 0); __decorate([ core_1.ViewChild("mov", { static: false }), __metadata("design:type", core_1.ElementRef) ], ProfileImageComponent.prototype, "mov", void 0); __decorate([ core_1.ViewChild("sth", { static: false }), __metadata("design:type", core_1.ElementRef) ], ProfileImageComponent.prototype, "sth", void 0); __decorate([ core_1.ViewChild("clr", { static: false }), __metadata("design:type", core_1.ElementRef) ], ProfileImageComponent.prototype, "clr", void 0); ProfileImageComponent = __decorate([ core_1.Component({ selector: "profileimage", moduleId: module.id, templateUrl: "./profileimage.component.xml" }), __metadata("design:paramtypes", [router_1.RouterExtensions, bitmap_service_1.BitmapService, gallery_service_1.GalleryService, camera_service_1.CameraService, amigo_service_1.AmigoService, page_1.Page]) ], ProfileImageComponent); return ProfileImageComponent; }()); exports.ProfileImageComponent = ProfileImageComponent;
cerberus707/lab-python
Conteudo das Aulas/140/pop.py
<filename>Conteudo das Aulas/140/pop.py import poplib import getpass import sys import mailconfig # Configuramos o servidor mailserver = mailconfig.servidor_pop # O nome do usuário mailuser = mailconfig.usuário_pop # Pedimos por uma senha mailpasswd = getpass.getpass('Senha para %s?' % mailserver) # Iniciamos o processo de conexão com o servidor print('Conectando...') # Por falta de exemplos práticos estaremos conectando no servidor # do gmail. Para tanto utilizaremos um objeto especial o POP3_SSL # ao invés do objeto clássico POP3. Esta diferença ocorre porque # o servidor do google é implementado por cima de um socket # criptografado com SSL. É preciso notar que o port para servidores # desse tipo é, por default, 995, ao invés de 110 do POP3. O port # pode ser configurado especialmente para cada servidor passando # o parâmetro como uma string para a construção do objeto server = poplib.POP3_SSL(mailserver) server.user(mailuser) server.pass_(mailpasswd) # Uma vez conectado iniciamos o processo de recebimento de dados try: # Se o servidor tiver alguma mensagem de boas vindas nós o # recebemos a partir do método "getwelcome" print(server.getwelcome()) # Podemos obter dados do servidor utilizando o método stat msgCount, msgBytes = server.stat() # Imprimimos as informações recebidas print('Existem ', msgCount, 'mensagens de email em', msgBytes, 'bytes') # Aqui imprimimos as listas de mensagens com os bytes correspondentes # a cada uma delas print(server.list()) # Esperamos o usuário querer prosseguir para ler o conteúdo das mensagens print('-' * 80) input('[Pressione Enter para Prosseguir]') # Iremos percorrer cada uma das mensagens contidas na caixa de email for i in range(msgCount): # Podemos ler o conteúdo das mensagens utilizando o método # retr e passando o número da mensagem que nós desejamos # obter hdr, mensagem, octets = server.retr(i+1) # Imprimimos todo o conteúdo da mensagem que acabamos de ler # só que temos que decodifica-la, uma vez que todo o texto de # email está em Bytes para o python 3.x for linha in mensagem: print(linha.decode()) # Imprimimos um separador de conteúdo print('-' * 80) # Se nós não tivermos lido todas as mensagens ainda podemos if i < msgCount - 1: # Esperar o usuário pressionar enter para prosseguir com a # leitura de mensagens input('[Pressione Enter para Prosseguir]') finally: # Nós fechamos a conexão com o email a partir # do método quit server.quit()
qiuxnlin/workflow
src/main/java/com/scxys/activiti/controller/ActDelegationCtl.java
package com.scxys.activiti.controller; import com.scxys.activiti.bean.ActDelegation; import com.scxys.activiti.service.ActDelegationService; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author 作者:qiuxinlin * @version 创建时间:2017年7月17日 下午2:32:57 * @description 说明: */ @RestController public class ActDelegationCtl { private ActDelegationService delegationService; @RequestMapping(value="/actDelegation", method = RequestMethod.POST, produces = "application/json") public void add(@RequestBody ActDelegation delegation, HttpServletRequest request, HttpServletResponse response){ delegationService.add(delegation); } @RequestMapping(value="/actDelegation", method=RequestMethod.GET) public Map findAll(){ List<ActDelegation> list=delegationService.findAll(); Map map=new HashMap(); map.put("data",list); map.put("total",list.size()); return map; } @RequestMapping(value = "/actDelegationDel",method = RequestMethod.POST) public String delete(@RequestParam("selectStr") String selectStr){ String[] array=selectStr.split("-"); if(array.length>0){ for (String anArray : array) { delegationService.deleteById(Long.parseLong(anArray)); } return "删除成功"; } return "删除失败"; } }
jackie-h/legend-engine
legend-engine-xt-json-model/src/main/java/org/finos/legend/engine/external/format/json/JsonExternalFormatExtension.java
<gh_stars>0 // Copyright 2022 <NAME> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.finos.legend.engine.external.format.json; import org.eclipse.collections.api.list.ImmutableList; import org.finos.legend.engine.external.format.json.compile.JsonSchemaCompiler; import org.finos.legend.engine.external.format.json.fromModel.ModelToJsonSchemaConfiguration; import org.finos.legend.engine.external.format.json.toModel.JsonSchemaToModelConfiguration; import org.finos.legend.engine.external.shared.format.model.ExternalFormatExtension; import org.finos.legend.engine.external.shared.format.model.ExternalSchemaCompileContext; import org.finos.legend.engine.language.pure.compiler.toPureGraph.CompileContext; import org.finos.legend.engine.language.pure.compiler.toPureGraph.PureModel; import org.finos.legend.engine.protocol.pure.PureClientVersions; import org.finos.legend.pure.generated.core_external_format_json_binding_validation; import org.finos.legend.pure.generated.core_external_format_json_binding_jsonSchemaToPure; import org.finos.legend.pure.generated.core_external_format_json_binding_pureToJsonSchema; import org.finos.legend.pure.generated.Root_meta_external_format_json_binding_fromPure_ModelToJsonSchemaConfiguration; import org.finos.legend.pure.generated.Root_meta_external_format_json_binding_fromPure_ModelToJsonSchemaConfiguration_Impl; import org.finos.legend.pure.generated.Root_meta_external_format_json_binding_toPure_JsonSchemaToModelConfiguration; import org.finos.legend.pure.generated.Root_meta_external_format_json_binding_toPure_JsonSchemaToModelConfiguration_Impl; import org.finos.legend.pure.generated.Root_meta_external_format_json_metamodel_JsonSchema; import org.finos.legend.pure.generated.Root_meta_external_shared_format_binding_Binding; import org.finos.legend.pure.generated.Root_meta_external_shared_format_binding_validation_BindingDetail; import org.finos.legend.pure.generated.Root_meta_external_shared_format_metamodel_SchemaSet; import java.lang.management.ManagementFactory; import java.util.Collections; import java.util.List; public class JsonExternalFormatExtension implements ExternalFormatExtension<Root_meta_external_format_json_metamodel_JsonSchema, JsonSchemaToModelConfiguration, ModelToJsonSchemaConfiguration> { public static final String TYPE = "JSON"; private static final boolean IN_DEBUG = ManagementFactory.getRuntimeMXBean().getInputArguments().toString().contains(":jdwp"); @Override public String getFormat() { return TYPE; } @Override public List<String> getContentTypes() { return Collections.singletonList(JsonExternalFormatPureExtension.CONTENT_TYPE); } @Override public Root_meta_external_format_json_metamodel_JsonSchema compileSchema(ExternalSchemaCompileContext context) { return new JsonSchemaCompiler(context).compile(); } @Override public Root_meta_external_shared_format_binding_validation_BindingDetail bindDetails(Root_meta_external_shared_format_binding_Binding binding, CompileContext context) { return core_external_format_json_binding_validation.Root_meta_external_format_json_binding_validation_bindDetails_Binding_1__BindingDetail_1_(binding, context.getExecutionSupport()); } @Override public String metamodelToText(Root_meta_external_format_json_metamodel_JsonSchema schemaDetail, PureModel pureModel) { return schemaDetail._content(); } @Override public Root_meta_external_shared_format_binding_Binding generateModel(Root_meta_external_shared_format_metamodel_SchemaSet schemaSet, JsonSchemaToModelConfiguration config, PureModel pureModel) { Root_meta_external_format_json_binding_toPure_JsonSchemaToModelConfiguration configuration = new Root_meta_external_format_json_binding_toPure_JsonSchemaToModelConfiguration_Impl("") ._sourceSchemaId(config.sourceSchemaId) ._targetBinding(config.targetBinding) ._targetPackage(config.targetPackage); return IN_DEBUG ? core_external_format_json_binding_jsonSchemaToPure.Root_meta_external_format_json_binding_toPure_jsonSchemaToPureWithDebug_SchemaSet_1__JsonSchemaToModelConfiguration_1__Binding_1_(schemaSet, configuration, pureModel.getExecutionSupport()) : core_external_format_json_binding_jsonSchemaToPure.Root_meta_external_format_json_binding_toPure_jsonSchemaToPure_SchemaSet_1__JsonSchemaToModelConfiguration_1__Binding_1_(schemaSet, configuration, pureModel.getExecutionSupport()); } @Override public Root_meta_external_shared_format_binding_Binding generateSchema(ModelToJsonSchemaConfiguration config, PureModel pureModel) { Root_meta_external_format_json_binding_fromPure_ModelToJsonSchemaConfiguration configuration = new Root_meta_external_format_json_binding_fromPure_ModelToJsonSchemaConfiguration_Impl("") ._targetBinding(config.targetBinding) ._targetSchemaSet(config.targetSchemaSet); config.sourceModel.forEach(pe -> configuration._sourceModelAdd(pureModel.getPackageableElement(pe))); return IN_DEBUG ? core_external_format_json_binding_pureToJsonSchema.Root_meta_external_format_json_binding_fromPure_pureToJsonSchemaWithDebug_ModelToJsonSchemaConfiguration_1__Binding_1_(configuration, pureModel.getExecutionSupport()) : core_external_format_json_binding_pureToJsonSchema.Root_meta_external_format_json_binding_fromPure_pureToJsonSchema_ModelToJsonSchemaConfiguration_1__Binding_1_(configuration, pureModel.getExecutionSupport()); } @Override public List<String> getRegisterablePackageableElementNames() { ImmutableList<String> versions = PureClientVersions.versionsSince("v1_23_0"); return versions.collect(v -> "meta::protocols::pure::" + v + "::external::format::json::serializerExtension_String_1__SerializerExtension_1_").toList(); } }
jinroq/msgraph
lib/msgraph/odata/types/primitive_types.rb
require 'msgraph/odata/types/primitive_types/binary_type' require 'msgraph/odata/types/primitive_types/date_type' require 'msgraph/odata/types/primitive_types/double_type' require 'msgraph/odata/types/primitive_types/guid_type' require 'msgraph/odata/types/primitive_types/int_16_type' require 'msgraph/odata/types/primitive_types/int_32_type' require 'msgraph/odata/types/primitive_types/int_64_type' require 'msgraph/odata/types/primitive_types/stream_type' require 'msgraph/odata/types/primitive_types/string_type' require 'msgraph/odata/types/primitive_types/boolean_type' require 'msgraph/odata/types/primitive_types/date_time_offset_type'
andrew-edgar/cloud_controller_ng
app/messages/base_message.rb
<reponame>andrew-edgar/cloud_controller_ng require 'active_model' require 'messages/validators' module VCAP::CloudController class BaseMessage include ActiveModel::Model include Validators attr_accessor :requested_keys, :extra_keys def self.register_allowed_keys(allowed_keys) current_keys = const_defined?(:ALLOWED_KEYS) ? self.const_get(:ALLOWED_KEYS) : [] keys = current_keys + allowed_keys self.const_set(:ALLOWED_KEYS, keys.freeze) attr_accessor(*allowed_keys) end def initialize(params) params = params ? params.deep_symbolize_keys : {} @requested_keys = params.keys disallowed_params = params.slice!(*allowed_keys) @extra_keys = disallowed_params.keys super(params) end def requested?(key) requested_keys.include?(key) end def audit_hash(exclude: []) request = {} requested_keys.each_with_object(request) do |key, memo| memo[key] = self.try(key) unless exclude.include?(key) end request.deep_stringify_keys end def to_param_hash(opts={ exclude: [] }) params = {} (requested_keys - opts[:exclude]).each do |key| val = self.try(key) params[key] = val.is_a?(Array) ? val.map { |v| v.gsub(',', CGI.escape(',')) }.join(',') : val end params end def self.from_params(params, to_array_keys) opts = params.dup to_array_keys.each do |attribute| to_array! opts, attribute end message = new(opts.symbolize_keys) message end def self.to_array!(params, key) return if params[key].nil? params[key] = if params[key] == '' [''] else params[key].to_s.split(/,\s*/, -1).map do |val| Addressable::URI.unescape(val) end end end class NoAdditionalKeysValidator < ActiveModel::Validator def validate(record) if record.extra_keys.any? record.errors[:base] << "Unknown field(s): '#{record.extra_keys.join("', '")}'" end end end class NoAdditionalParamsValidator < ActiveModel::Validator def validate(record) if record.extra_keys.any? record.errors[:base] << "Unknown query parameter(s): '#{record.extra_keys.join("', '")}'" end end end class IncludeParamValidator < ActiveModel::Validator def validate(record) if record.requested?(:include) key_counts = Hash.new(0) record.include.each do |include_candidate| if !options[:valid_values].member?(include_candidate) record.errors[:base] << "Invalid included resource: '#{include_candidate}'" else key_counts[include_candidate] += 1 if key_counts[include_candidate] == 2 record.errors[:base] << "Duplicate included resource: '#{include_candidate}'" end end end end end end class LifecycleTypeParamValidator < ActiveModel::Validator def validate(record) if record.requested?(:lifecycle_type) valid_lifecycle_types = [BuildpackLifecycleDataModel::LIFECYCLE_TYPE, DockerLifecycleDataModel::LIFECYCLE_TYPE] unless valid_lifecycle_types.include?(record.lifecycle_type) record.errors[:base] << "Invalid lifecycle_type: '#{record.lifecycle_type}'" end end end end private def allowed_keys self.class::ALLOWED_KEYS end end end
simonct/CoreAstro
External/astrometry.net/astrometry/include/2mass-fits.h
/* This file is part of the Astrometry.net suite. Copyright 2006-2008 <NAME>, <NAME> and <NAME>. The Astrometry.net suite 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, version 2. The Astrometry.net suite 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 the Astrometry.net suite ; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef TWOMASS_FITS_H #define TWOMASS_FITS_H #include "qfits.h" #include "2mass.h" #include "fitstable.h" #include "ioutils.h" #define AN_FILETYPE_2MASS "2MASS" typedef fitstable_t twomass_fits; twomass_fits* twomass_fits_open(char* fn); twomass_fits* twomass_fits_open_for_writing(char* fn); int twomass_fits_write_headers(twomass_fits* cat); int twomass_fits_fix_headers(twomass_fits* cat); int twomass_fits_read_entries(twomass_fits* cat, int offset, int count, twomass_entry* entries); twomass_entry* twomass_fits_read_entry(twomass_fits* cat); int twomass_fits_count_entries(twomass_fits* cat); int twomass_fits_close(twomass_fits* cat); int twomass_fits_write_entry(twomass_fits* cat, twomass_entry* entry); qfits_header* twomass_fits_get_primary_header(const twomass_fits* cat); #endif
erickhouse1/scala-blog
client/node_modules/marky-markdown/lib/plugin/github.js
<filename>client/node_modules/marky-markdown/lib/plugin/github.js<gh_stars>0 // markdown-it plugin to rewrite image and link URLs to be static github URLs // when the calling code provides github repository information // var gh = require('github-url-to-object') var URL = require('url') var path = require('path') module.exports = function (md, opts) { if (!opts) return if (!opts.package) return if (!opts.package.repository) return var repo = gh(opts.package.repository.url) if (!repo) return // rewrite image locations to be fully qualified github URLs var originalImageRule = md.renderer.rules.image md.renderer.rules.image = function (tokens, idx, options, env, self) { var src = tokens[idx].attrGet('src') if (src && src.length) { var url = URL.parse(src) // Skip fully-qualified URLs, #hash fragments, and protocol-relative URLs if (!url.host && url.path && !url.path.match(/^\/\//)) { tokens[idx].attrSet('src', 'https://raw.githubusercontent.com/' + path.join( repo.user, repo.repo, 'master', url.href) ) } } return originalImageRule.call(this, tokens, idx, options, env, self) } // rewrite link hrefs to be fully qualified github URLs var originalLinkRule = md.renderer.rules.link_open md.renderer.rules.link_open = function (tokens, idx, options, env, self) { var href = tokens[idx].attrGet('href') if (href && href.length) { var url = URL.parse(href) // Skip fully-qualified URLs, #hash fragments, and protocol-relative URLs if (!url.host && url.path && !url.path.match(/^\/\//)) { tokens[idx].attrSet('href', repo.https_url + path.join('/blob/master/', url.href)) } } if (originalLinkRule) { return originalLinkRule.call(this, tokens, idx, options, env, self) } else { return md.renderer.renderToken(tokens, idx, options) } } }
TotteKarlsson/atapi
source/vcl/frames/THDMIStreamerFrame.cpp
<reponame>TotteKarlsson/atapi #include <vcl.h> #pragma hdrstop #include "THDMIStreamerFrame.h" #include "dslLogger.h" #include "dslVCLUtils.h" #include "dslFileUtils.h" //#include "ArrayCamUtils.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma link "TArrayBotBtn" #pragma link "dslTIntegerLabeledEdit" #pragma link "dslTPropertyCheckBox" #pragma link "dslTStdStringLabeledEdit" #pragma link "dslTIntegerLabeledEdit" #pragma link "dslTSTDStringLabeledEdit" #pragma resource "*.dfm" THDMIStreamerFrame *HDMIStreamerFrame; using namespace dsl; using namespace Poco; //--------------------------------------------------------------------------- __fastcall THDMIStreamerFrame::THDMIStreamerFrame(TComponent* Owner) : TFrame(Owner), mStreamer("bm.exe") { mStreamer.assignCallBacks( boost::bind(&THDMIStreamerFrame::onEnter, this, _1, _1), boost::bind(&THDMIStreamerFrame::onProgress, this, _1, _1), boost::bind(&THDMIStreamerFrame::onExit, this, _1, _1) ); } __fastcall THDMIStreamerFrame::~THDMIStreamerFrame() { //Make sure bm process is ended if(mStreamer.isRunning()) { mStreamer.exit(); } } HDMIStreamerProcess& THDMIStreamerFrame::getStreamer() { return mStreamer; } void THDMIStreamerFrame::enableSettings() { enableDisableGroupBox(SettingsGB, true); } void THDMIStreamerFrame::disableSettings() { enableDisableGroupBox(SettingsGB, false); } bool THDMIStreamerFrame::isStreamerAlive() { return mStreamer.isRunning(); } bool THDMIStreamerFrame::shutDownStreamer() { mStreamer.exit(); return true; } void THDMIStreamerFrame::setPathPostFix(const string& f) { mPathPostFix = f; } //--------------------------------------------------------------------------- void __fastcall THDMIStreamerFrame::StartStreamerBtnClick(TObject *Sender) { if(StartRecordingBtn->Caption == "Start Recording") { mStreamer.startRecording(joinPath(OutputFileFolderE->getValue(), mPathPostFix, OutputFileNameE->getValue()), BitrateE->getValue()); } else { mStreamer.stopRecording(); } } void THDMIStreamerFrame::onEnter(int i, int j) { struct lclS { int i, j; THDMIStreamerFrame* f; void __fastcall fn() { Log(lInfo) << "HDMI Streamer Thread was entered.."; f->StartRecordingBtn->Caption = "Stop Recording"; f->disableSettings(); } }; lclS lcl; lcl.i = i; lcl.j = j; lcl.f = this; TThread::Synchronize(0, &lcl.fn); } void THDMIStreamerFrame::onProgress(int i, int j) { struct lclS { int i, j; THDMIStreamerFrame* f; void __fastcall fn() { //Check current file size f->StartRecordingBtn->Caption = "Stop Recording\n" + vclstr(getHumanReadableFileSize(i)); } }; lclS lcl; lcl.i = i; lcl.j = j; lcl.f = this; TThread::Synchronize(0, &lcl.fn); } void THDMIStreamerFrame::onExit(int i, int j) { struct lclS { int i, j; THDMIStreamerFrame* f; void __fastcall fn() { Log(lInfo) << "HDMI Streamer Thread exited.."; f->StartRecordingBtn->Caption = "Start Recording"; f->enableSettings(); } }; lclS lcl; lcl.i = i; lcl.j = j; lcl.f = this; TThread::Synchronize(0, &lcl.fn); }
dshook/robo
mixins/withDeferredClose.js
define(function(require, exports, module) { var compose = require('robo/compose'); var _ = require('underscore'); // modify the render and close behavior to delay the removal from the DOM // long enough to potentially animate it var withDeferredClose = compose.defineMixin( { // once we render, add the opened class __before__render: function() { _(function() { this.addClass('open').addClass('opened'); }.bind(this)).defer(); }, // close after a short period of time __wrapped__close: function(close) { this.addClass('closed').removeClass('open'); this.trigger('close'); setTimeout(function() { close({silent: true }); }, 1000); return this; } }); return withDeferredClose; });
Tamookk/Basil
Basil/src/Core/Window.cpp
#include "pch.h" #include "Core/Window.h" #ifdef PLATFORM_WINDOWS #include "Platform/Windows/WindowsWindow.h" #endif namespace Basil { Unique<Window> Window::create(const WindowProps& props) { #ifdef PLATFORM_WINDOWS return makeUnique<WindowsWindow>(props); #else ASSERT(false, "Unknown platform."); return nullptr; #endif } }
StephanBusch/7-Zip
EcoZipFM/BenchmarkDialog.cpp
<gh_stars>10-100 // BenchmarkDialog.cpp : implementation file // #include "stdafx.h" #include "C/CpuArch.h" #include "CPP/Common/Defs.h" #include "CPP/Common/IntToString.h" #include "CPP/Common/MyException.h" #include "CPP/Common/StringConvert.h" #include "CPP/Common/StringToInt.h" #include "CPP/Windows/System.h" #include "CPP/7zip/Common/MethodProps.h" #include "CPP/7zip/UI/FileManager/HelpUtils.h" #include "CPP/7zip/MyVersion.h" #include "EcoZipFM.h" #include "BenchmarkDialog.h" #include "FMUtils.h" #include "ImageUtils.h" static LPCWSTR kHelpTopic = L"fm/benchmark.htm"; static const UINT_PTR kTimerID = 4; static const UINT kTimerElapse = 1000; #ifdef LANG #include "CPP/7zip/UI/FileManager/LangUtils.h" #endif using namespace NWindows; void GetCpuName(AString &s); UString HResultToMessage(HRESULT errorCode); #ifdef LANG static const UInt32 kLangIDs[] = { IDT_BENCH_TOTAL, IDX_BENCH_MULTITHREAD, }; static const UInt32 kLangIDs_Colon[] = { IDT_BENCH_SYSTEM }; #endif static const LPCTSTR kProcessingString = TEXT("..."); static const LPCTSTR kMB = TEXT(" MB"); static const LPCTSTR kMIPS = TEXT(" MIPS"); static const LPCTSTR kKBs = TEXT(" KB/s"); static const unsigned kMinDicLogSize = #ifdef UNDER_CE 20; #else 21; #endif static const UInt32 kMinDicSize = (1 << kMinDicLogSize); static const UInt32 kMaxDicSize = #ifdef MY_CPU_64BIT (1 << 30); #else (1 << 27); #endif // CBenchmarkDialog dialog IMPLEMENT_DYNAMIC(CBenchmarkDialog, CDialogEx) CBenchmarkDialog::CBenchmarkDialog(CWnd* pParent /*=NULL*/) : CDialogEx(CBenchmarkDialog::IDD, pParent) , _timer(0) , m_strAverage(_T("")) , m_strSystemInfo(_T("")) , m_strModules(_T("")) , m_strTotalComp(_T("")) , m_strTotalDecomp(_T("")) { } CBenchmarkDialog::~CBenchmarkDialog() { } void CBenchmarkDialog::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Control(pDX, IDL_BENCH, m_lstBench); DDX_Text(pDX, IDT_BENCH_SYSTEM_VAL, m_strSystemInfo); DDX_Text(pDX, IDE_BENCH_MODULES, m_strModules); DDX_Text(pDX, IDT_BENCH_TOTAL_COMP, m_strTotalComp); DDX_Text(pDX, IDT_BENCH_TOTAL_DECOMP, m_strTotalDecomp); } BEGIN_MESSAGE_MAP(CBenchmarkDialog, CDialogEx) ON_WM_DESTROY() ON_WM_TIMER() ON_NOTIFY(NM_CUSTOMDRAW, IDL_BENCH, &CBenchmarkDialog::OnNMCustomdrawBench) ON_WM_SIZE() END_MESSAGE_MAP() // CBenchmarkDialog message handlers static FString GetProcessorName() { int CPUInfo[4] = { -1 }; char CPUBrandString[0x40]; __cpuid(CPUInfo, 0x80000000); unsigned int nExIds = CPUInfo[0]; memset(CPUBrandString, 0, sizeof(CPUBrandString)); // Get the information associated with each extended ID. for (unsigned i = 0x80000000; i <= nExIds; ++i) { __cpuid(CPUInfo, i); // Interpret CPU brand string. if (i == 0x80000002) memcpy(CPUBrandString, CPUInfo, sizeof(CPUInfo)); else if (i == 0x80000003) memcpy(CPUBrandString + 16, CPUInfo, sizeof(CPUInfo)); else if (i == 0x80000004) memcpy(CPUBrandString + 32, CPUInfo, sizeof(CPUInfo)); } return GetSystemString(CPUBrandString); } #pragma pack(push) #pragma pack(1) typedef struct _RawSMBIOSData { BYTE Used20CallingMethod; BYTE SMBIOSMajorVersion; BYTE SMBIOSMinorVersion; BYTE DmiRevision; DWORD Length; PBYTE SMBIOSTableData; } RawSMBIOSData, *PRawSMBIOSData; typedef struct _SMBIOSHEADER_ { BYTE Type; BYTE Length; WORD Handle; } SMBIOSHEADER, *PSMBIOSHEADER; typedef struct _TYPE_17_ { SMBIOSHEADER Header; UINT16 PhysicalArrayHandle; UINT16 ErrorInformationHandle; UINT16 TotalWidth; UINT16 DataWidth; UINT16 Size; UCHAR FormFactor; UCHAR DeviceSet; UCHAR DeviceLocator; UCHAR BankLocator; UCHAR MemoryType; UINT16 TypeDetail; UINT16 Speed; UCHAR Manufacturer; UCHAR SN; UCHAR AssetTag; UCHAR PN; UCHAR Attributes; } MemoryDevice, *PMemoryDevice; #pragma pack(push) #ifdef UNICODE #define getHeaderString getHeaderStringW #define LocateString LocateStringW #else #define getHeaderString getHeaderStringA #define LocateString LocateStringA #endif static const char* LocateStringA(const char* str, UINT i) { static const char strNull[] = "Null String"; if (0 == i || 0 == *str) return strNull; while (--i) { str += strlen((char*)str) + 1; } return str; } static const wchar_t* LocateStringW(const char* str, UINT i) { static wchar_t buff[2048]; const char *pStr = LocateStringA(str, i); SecureZeroMemory(buff, sizeof(buff)); MultiByteToWideChar(CP_OEMCP, 0, pStr, (int)strlen(pStr), buff, sizeof(buff)); return buff; } static const char* toPointString(void* p) { return (char*)p + ((PSMBIOSHEADER)p)->Length; } static FString GetRamType() { FString strRamType; Byte *pBuffer = NULL; UINT retVal = GetSystemFirmwareTable('RSMB', 'PCAF', NULL, 0); pBuffer = (Byte *)malloc(retVal); retVal = GetSystemFirmwareTable('RSMB', 'PCAF', pBuffer, retVal); unsigned pos = sizeof(RawSMBIOSData); while (pos < retVal) { SMBIOSHEADER *hdr = (SMBIOSHEADER *)(pBuffer + pos); unsigned end = hdr->Length; while (pos + end < retVal) { if (*(WORD *)(pBuffer + pos + end) == 0) break; end++; } if (pos + end >= retVal || *(WORD *)(pBuffer + pos + end) != 0) break; if (hdr->Type == 17) { PMemoryDevice pMD = (PMemoryDevice)(pBuffer + pos); const char *str = toPointString(pBuffer + pos); strRamType = LocateString(str, pMD->DeviceLocator); if (!strRamType.IsEmpty()) { TCHAR chLast = strRamType.Ptr()[strRamType.Len() - 1]; if (chLast >= _T('0') && chLast <= _T('9')) strRamType.DeleteBack(); } return strRamType; } pos += end + sizeof(WORD); } free(pBuffer); return strRamType; } static FString GetRamSizeString() { TCHAR szRam[32]; UInt64 numRam; bool got = NSystem::GetRamSize(numRam); numRam = (numRam + 1023) / 1024; if (numRam > 1024) { numRam = (numRam + 1023) / 1024; if (numRam > 1024) { numRam = (numRam + 1023) / 1024; ConvertUInt64ToString(numRam, szRam); lstrcat(szRam, _T(" GB")); } else { ConvertUInt64ToString(numRam, szRam); lstrcat(szRam, _T(" MB")); } } else { ConvertUInt64ToString(numRam, szRam); lstrcat(szRam, _T(" KB")); } return szRam; } BOOL CBenchmarkDialog::OnInitDialog() { CDialogEx::OnInitDialog(); #ifdef LANG LangSetWindowText(*this, IDD_BENCH); LangSetDlgItems(*this, kLangIDs, ARRAY_SIZE(kLangIDs)); LangSetDlgItems_Colon(*this, kLangIDs_Colon, ARRAY_SIZE(kLangIDs_Colon)); #endif const int count = 5; const wchar_t *names[] = { _T("Name"), _T("Compression"), _T("Unit"), _T("Decompression"), _T("Unit"), }; const int width[] = { 150, 200, 70, 200, 70 }; for (int i = 0; i < count; i++) { m_lstBench.InsertColumn(i, names[i], LVCFMT_LEFT, -1, -1); m_lstBench.SetColumnWidth(i, width[i]); } // m_lstBench.InsertColumn(1, _T("Compression"), LVCFMT_LEFT, -1, 1); // m_lstBench.InsertColumn(2, _T("Unit"), LVCFMT_LEFT, -1, 2); // m_lstBench.InsertColumn(3, _T("Decompression"), LVCFMT_LEFT, -1, 3); // m_lstBench.InsertColumn(4, _T("Unit"), LVCFMT_LEFT, -1, 4); AdjustWidth(); m_lstBench.SetExtendedStyle(m_lstBench.GetExtendedStyle() | LVS_EX_FULLROWSELECT); CImageUtils::LoadBitmapFromPNG(IDB_LEVEL1, m_bmpLevel1); CImageUtils::LoadBitmapFromPNG(IDB_LEVEL2, m_bmpLevel2); CDC *pDC = GetDC(); // CImageUtils::PremultiplyBitmapAlpha(pDC->m_hDC, m_bmpLevel1); // CImageUtils::PremultiplyBitmapAlpha(pDC->m_hDC, m_bmpLevel2); ReleaseDC(pDC); m_nEncMax = 0; m_nDecMax = 0; Sync.Init(); /************************************************************************/ /* Get System Info */ /************************************************************************/ m_strSystemInfo = GetProcessorName(); { TCHAR s[40]; s[0] = '/'; s[1] = ' '; ConvertUInt32ToString(NSystem::GetNumberOfProcessors(), s + 2); //SetDlgItemText(IDT_BENCH_HARDWARE_THREADS, s); } { UString s; { AString cpuName; GetCpuName(cpuName); s.SetFromAscii(cpuName); //SetDlgItemText(IDT_BENCH_CPU, s); } s.SetFromAscii("EcoZip " MY_VERSION " [" #ifdef MY_CPU_64BIT "64-bit" #elif defined MY_CPU_32BIT "32-bit" #endif "]"); //SetDlgItemText(IDT_BENCH_VER, s); } UInt32 numCPUs = NSystem::GetNumberOfProcessors(); if (numCPUs < 1) numCPUs = 1; numCPUs = MyMin(numCPUs, (UInt32)(1 << 8)); TCHAR szCPUs[8]; ConvertUInt32ToString(numCPUs, szCPUs); m_strSystemInfo += _T(" ("); m_strSystemInfo += szCPUs; m_strSystemInfo += _T(" CPUs)"); m_strSystemInfo += _T(", "); m_strSystemInfo += GetRamSizeString(); m_strSystemInfo += _T(' '); m_strSystemInfo += GetRamType(); if (Sync.NumThreads == (UInt32)(Int32)-1) { Sync.NumThreads = numCPUs; if (Sync.NumThreads > 1) Sync.NumThreads &= ~1; } // m_NumThreads.Attach(GetItem(IDC_BENCH_NUM_THREADS)); // int cur = 0; // for (UInt32 num = 1; num <= numCPUs * 2;) // { // TCHAR s[16]; // ConvertUInt32ToString(num, s); // int index = (int)m_NumThreads.AddString(s); // m_NumThreads.SetItemData(index, num); // if (num <= Sync.NumThreads) // cur = index; // if (num > 1) // num++; // num++; // } // m_NumThreads.SetCurSel(cur); // Sync.NumThreads = GetNumberOfThreads(); // cur = 0; UInt64 ramSize = (UInt64)(sizeof(size_t)) << 29; bool ramSize_Defined = NSystem::GetRamSize(ramSize); #ifdef UNDER_CE const UInt32 kNormalizedCeSize = (16 << 20); if (ramSize > kNormalizedCeSize && ramSize < (33 << 20)) ramSize = kNormalizedCeSize; #endif if (Sync.DictionarySize == (UInt32)(Int32)-1) { unsigned dicSizeLog = 25; #ifdef UNDER_CE dicSizeLog = 20; #endif if (ramSize_Defined) for (; dicSizeLog > kBenchMinDicLogSize; dicSizeLog--) if (GetBenchMemoryUsage(Sync.NumThreads, ((UInt32)1 << dicSizeLog)) + (8 << 20) <= ramSize) break; Sync.DictionarySize = (1 << dicSizeLog); } if (Sync.DictionarySize < kMinDicSize) Sync.DictionarySize = kMinDicSize; if (Sync.DictionarySize > kMaxDicSize) Sync.DictionarySize = kMaxDicSize; // for (unsigned i = kMinDicLogSize; i <= 30; i++) // for (unsigned j = 0; j < 2; j++) // { // UInt32 dict = (1 << i) + (j << (i - 1)); // if (dict > kMaxDicSize) // continue; // TCHAR s[16]; // ConvertUInt32ToString((dict >> 20), s); // lstrcat(s, kMB); // int index = (int)m_Dictionary.AddString(s); // m_Dictionary.SetItemData(index, dictionary); // if (dictionary <= Sync.DictionarySize) // cur = index; // } // m_Dictionary.SetCurSel(cur); OnChangeSettings(); Sync._startEvent.Set(); _timer = SetTimer(kTimerID, kTimerElapse, NULL); UpdateData(FALSE); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } static const UInt32 g_IDs[] = { IDT_BENCH_SYSTEM_VAL, IDE_BENCH_MODULES, IDT_BENCH_TOTAL_COMP, IDT_BENCH_TOTAL_DECOMP, }; void CBenchmarkDialog::OnChangeSettings() { // EnableItem(IDB_STOP, true); // UInt32 dict = OnChangeDictionary(); for (int i = 0; i < ARRAY_SIZE(g_IDs); i++) SetDlgItemText(g_IDs[i], kProcessingString); _startTime = GetTickCount(); PrintTime(); CSingleLock lock(&Sync.CS, TRUE); Sync.Init(); // Sync.DictionarySize = dict; // Sync.Changed = true; // Sync.NumThreads = GetNumberOfThreads(); } void CBenchmarkDialog::OnHelp() { ShowHelpWindow(NULL, kHelpTopic); CDialogEx::OnHelp(); } void CBenchmarkDialog::OnDestroy() { CDialogEx::OnDestroy(); Sync.Stop(); KillTimer(_timer); } void CBenchmarkDialog::PrintTime() { UInt32 curTime = ::GetTickCount(); UInt32 elapsedTime = (curTime - _startTime); UInt32 elapsedSec = elapsedTime / 1000; if (elapsedSec != 0 && Sync.WasPaused()) return; WCHAR s[40]; GetTimeString(elapsedSec, s); // SetDlgItemText(IDT_BENCH_ELAPSED_VAL, s); } void CBenchmarkDialog::PrintRating(UInt64 rating, UINT controlID) { TCHAR s[40]; ConvertUInt64ToString(rating / 1000000, s); lstrcat(s, kMIPS); SetDlgItemText(controlID, s); } void CBenchmarkDialog::PrintUsage(UInt64 usage, UINT controlID) { TCHAR s[40]; ConvertUInt64ToString((usage + 5000) / 10000, s); lstrcat(s, TEXT("%")); SetDlgItemText(controlID, s); } void CBenchmarkDialog::PrintResults( UInt32 dictionarySize, const CBenchInfo2 &info, UINT usageID, UINT speedID, UINT rpuID, UINT ratingID, bool decompressMode) { if (info.GlobalTime == 0) return; TCHAR s[40]; { UInt64 speed = info.UnpackSize * info.NumIterations * info.GlobalFreq / info.GlobalTime; ConvertUInt64ToString(speed / 1024, s); lstrcat(s, kKBs); SetDlgItemText(speedID, s); } UInt64 rating; if (decompressMode) rating = info.GetDecompressRating(); else rating = info.GetCompressRating(dictionarySize); PrintRating(rating, ratingID); PrintRating(info.GetRatingPerUsage(rating), rpuID); PrintUsage(info.GetUsage(), usageID); } void CBenchmarkDialog::OnTimer(UINT_PTR nIDEvent) { // Update changed info UpdateData(FALSE); bool printTime = true; if (Sync.WasStopped()) printTime = false; if (printTime) PrintTime(); CSingleLock lock(&Sync.CS, TRUE); // if (TotalMode) // { if (Sync.TextWasChanged) { // _consoleEdit.SetText(GetSystemString(Sync.Text)); Sync.TextWasChanged = false; } return; // } TCHAR s[40]; ConvertUInt64ToString((Sync.ProcessedSize >> 20), s); lstrcat(s, kMB); // SetItemText(IDT_BENCH_SIZE_VAL, s); ConvertUInt64ToString(Sync.NumPasses, s); // SetItemText(IDT_BENCH_PASSES_VAL, s); /* if (Sync.FreqWasChanged) { SetItemText(IDT_BENCH_FREQ, Sync.Freq); Sync.FreqWasChanged = false; } */ { // UInt32 dicSizeTemp = (UInt32)MyMax(Sync.ProcessedSize, UInt64(1) << 20); // dicSizeTemp = MyMin(dicSizeTemp, Sync.DictionarySize), // PrintResults(dicSizeTemp, // Sync.CompressingInfoTemp, // IDT_BENCH_COMPRESS_USAGE1, // IDT_BENCH_COMPRESS_SPEED1, // IDT_BENCH_COMPRESS_RPU1, // IDT_BENCH_COMPRESS_RATING1); } { // PrintResults( // Sync.DictionarySize, // Sync.CompressingInfo, // IDT_BENCH_COMPRESS_USAGE2, // IDT_BENCH_COMPRESS_SPEED2, // IDT_BENCH_COMPRESS_RPU2, // IDT_BENCH_COMPRESS_RATING2); } // { // PrintResults( // Sync.DictionarySize, // Sync.DecompressingInfoTemp, // IDT_BENCH_DECOMPR_USAGE1, // IDT_BENCH_DECOMPR_SPEED1, // IDT_BENCH_DECOMPR_RPU1, // IDT_BENCH_DECOMPR_RATING1, // true); // } // { // PrintResults( // Sync.DictionarySize, // Sync.DecompressingInfo, // IDT_BENCH_DECOMPR_USAGE2, // IDT_BENCH_DECOMPR_SPEED2, // IDT_BENCH_DECOMPR_RPU2, // IDT_BENCH_DECOMPR_RATING2, // true); // if (Sync.DecompressingInfo.GlobalTime > 0 && // Sync.CompressingInfo.GlobalTime > 0) // { // UInt64 comprRating = Sync.CompressingInfo.GetCompressRating(Sync.DictionarySize); // UInt64 decomprRating = Sync.DecompressingInfo.GetDecompressRating(); // PrintRating((comprRating + decomprRating) / 2, IDT_BENCH_TOTAL_RATING_VAL); // PrintRating(( // Sync.CompressingInfo.GetRatingPerUsage(comprRating) + // Sync.DecompressingInfo.GetRatingPerUsage(decomprRating)) / 2, IDT_BENCH_TOTAL_RPU_VAL); // PrintUsage( // (Sync.CompressingInfo.GetUsage() + // Sync.DecompressingInfo.GetUsage()) / 2, IDT_BENCH_TOTAL_USAGE_VAL); // } // } CDialogEx::OnTimer(nIDEvent); } struct CThreadBenchmark { CBenchmarkDialog *BenchmarkDialog; DECL_EXTERNAL_CODECS_LOC_VARS2; // UInt32 dictionarySize; // UInt32 numThreads; HRESULT Process(); HRESULT Result; static THREAD_FUNC_DECL MyThreadFunction(void *param) { ((CThreadBenchmark *)param)->Result = ((CThreadBenchmark *)param)->Process(); return 0; } }; struct CBenchCallback: public IBenchCallback { UInt32 dictionarySize; CProgressSyncInfo *Sync; // void AddCpuFreq(UInt64 cpuFreq); HRESULT SetFreq(bool showFreq, UInt64 cpuFreq); HRESULT SetEncodeResult(const CBenchInfo &info, bool final); HRESULT SetDecodeResult(const CBenchInfo &info, bool final); }; /* void CBenchCallback::AddCpuFreq(UInt64 cpuFreq) { NSynchronization::CCriticalSectionLock lock(Sync->CS); { wchar_t s[32]; ConvertUInt64ToString(cpuFreq, s); Sync->Freq.Add_Space_if_NotEmpty(); Sync->Freq += s; Sync->FreqWasChanged = true; } } */ HRESULT CBenchCallback::SetFreq(bool /* showFreq */, UInt64 /* cpuFreq */) { return S_OK; } HRESULT CBenchCallback::SetEncodeResult(const CBenchInfo &info, bool final) { CSingleLock lock(&Sync->CS, TRUE); if (Sync->Changed || Sync->Paused || Sync->Stopped) return E_ABORT; Sync->ProcessedSize = info.UnpackSize * info.NumIterations; if (final && Sync->CompressingInfo.GlobalTime == 0) { (CBenchInfo&)Sync->CompressingInfo = info; if (Sync->CompressingInfo.GlobalTime == 0) Sync->CompressingInfo.GlobalTime = 1; } else (CBenchInfo&)Sync->CompressingInfoTemp = info; return S_OK; } HRESULT CBenchCallback::SetDecodeResult(const CBenchInfo &info, bool final) { CSingleLock lock(&Sync->CS, TRUE); if (Sync->Changed || Sync->Paused || Sync->Stopped) return E_ABORT; CBenchInfo info2 = info; if (final && Sync->DecompressingInfo.GlobalTime == 0) { info2.UnpackSize *= info2.NumIterations; info2.PackSize *= info2.NumIterations; info2.NumIterations = 1; (CBenchInfo&)Sync->DecompressingInfo = info2; if (Sync->DecompressingInfo.GlobalTime == 0) Sync->DecompressingInfo.GlobalTime = 1; } else (CBenchInfo&)Sync->DecompressingInfoTemp = info2; return S_OK; } struct CBenchCallback2: public IBenchPrintCallback { CProgressSyncInfo *Sync; void Print(const char *s); void NewLine(); HRESULT CheckBreak(); }; void CBenchCallback2::Print(const char *s) { CSingleLock lock(&Sync->CS, TRUE); Sync->Text += s; Sync->TextWasChanged = true; } void CBenchCallback2::NewLine() { Print("\xD\n"); } HRESULT CBenchCallback2::CheckBreak() { if (Sync->Changed || Sync->Paused || Sync->Stopped) return E_ABORT; return S_OK; } HRESULT CThreadBenchmark::Process() { CProgressSyncInfo &sync = BenchmarkDialog->Sync; sync.WaitCreating(); UInt32 numCPUs = 1; UInt64 ramSize = (UInt64)512 << 20; #ifndef _7ZIP_ST numCPUs = NSystem::GetNumberOfProcessors(); #endif #if !defined(_7ZIP_ST) || defined(_WIN32) bool got = NSystem::GetRamSize(ramSize); #endif UInt32 numThreads = 1;// numCPUs; UInt32 testTime = (UInt32)kComplexInSeconds; UInt64 complexInCommands = kComplexInCommands; { UInt64 numMilCommands = (1 << 6); for (int jj = 0;; jj++) { UInt64 start = ::GetTimeCount(); UInt32 sum = (UInt32)start; sum = CountCpuFreq(sum, (UInt32)(numMilCommands * 1000000 / kNumFreqCommands), g_BenchCpuFreqTemp); start = ::GetTimeCount() - start; if (start == 0) start = 1; UInt64 freq = GetFreq(); UInt64 mipsVal = numMilCommands * freq / start; if (jj >= 3) { SetComplexCommands(testTime, mipsVal * 1000000, complexInCommands); if (jj >= 8 || start >= freq) break; // break; // change it numMilCommands <<= 1; } } } UInt32 dict; int dicSizeLog; for (dicSizeLog = 25; dicSizeLog > kBenchMinDicLogSize; dicSizeLog--) if (GetBenchMemoryUsage(numThreads, ((UInt32)1 << dicSizeLog)) + (8 << 20) <= ramSize) break; dict = (1 << dicSizeLog); // IBenchPrintCallback &f = *printCallback; // PrintRequirements(f, "usage:", GetBenchMemoryUsage(numThreads, dict), "Benchmark threads: ", numThreads); bool totalBenchMode = true; bool showFreq = totalBenchMode; UInt64 cpuFreq = 0; dict = #ifdef UNDER_CE (UInt64)1 << 20; #else (UInt64)1 << 24; #endif CBenchCallback2 printCallback; printCallback.Sync = &sync; try { int freqTest; const int kNumCpuTests = 3; for (freqTest = 0; freqTest < kNumCpuTests; freqTest++) { UInt32 resVal; RINOK(FreqBench(complexInCommands, numThreads, &printCallback, freqTest == kNumCpuTests - 1, cpuFreq, resVal)); if (freqTest == kNumCpuTests - 1) SetComplexCommands(testTime, cpuFreq, complexInCommands); } // callback.SetFreq(true, cpuFreq); // res = TotalBench(EXTERNAL_CODECS_LOC_VARS complexInCommands, numThreads, dictIsDefined, dict, printCallback, &callback); // RINOK(res); bool forceUnpackSize = false; UInt32 unpackSize = dict; for (unsigned i = 0; ; i++) { // sync.Init(); if (sync.WasStopped()) return 0; if (sync.WasPaused()) { Sleep(200); continue; } { CSingleLock lock(&sync.CS, TRUE); if (sync.Stopped || sync.Paused) continue; //if (sync.Changed) sync.Init(); sync.NumThreads = numThreads; } CBenchCallback callback; callback.Sync = &sync; CBenchProps BenchProps; callback.SetFreq(true, cpuFreq); CBenchMethod bench = g_Bench[i]; if (bench.Name == NULL) break; BenchmarkDialog->AppendBenchInfo(GetUnicodeString(bench.Name)); BenchProps.DecComplexUnc = bench.DecComplexUnc; BenchProps.DecComplexCompr = bench.DecComplexCompr; BenchProps.EncComplex = bench.EncComplex; COneMethodInfo method; NCOM::CPropVariant propVariant; propVariant = bench.Name; RINOK(method.ParseMethodFromPROPVARIANT(L"", propVariant)); UInt32 unpackSize2 = unpackSize; if (!forceUnpackSize && bench.DictBits == 0) unpackSize2 = kFilterUnpackSize; HRESULT res = MethodBench( EXTERNAL_CODECS_LOC_VARS complexInCommands, false, numThreads, method, unpackSize2, bench.DictBits, NULL, &callback, &BenchProps); if (res == E_NOTIMPL) { // callback->Print(" ---"); // we need additional empty line as line for decompression results //if (!callback.Use2Columns) // callback.NewLine(); continue; } else { if (FAILED(res)) continue; RINOK(res); } BenchmarkDialog->UpdateLastBenchInfo(); } // res = TotalBench_Hash(EXTERNAL_CODECS_LOC_VARS complexInCommands, numThreads, // 1 << kNumHashDictBits, printCallback, &callback, &callback.EncodeRes, true, cpuFreq); // RINOK(res); // for (unsigned i = 0; ; i++) // { // // sync.Init(); // // if (sync.WasStopped()) // return 0; // if (sync.WasPaused()) // { // Sleep(200); // continue; // } // { // CSingleLock lock(&sync.CS, TRUE); // if (sync.Stopped || sync.Paused) // continue; // //if (sync.Changed) // sync.Init(); // sync.NumThreads = numThreads; // } // // CBenchCallback callback; // callback.Sync = &sync; // CTotalBenchRes EncodeRes; // // callback.SetFreq(true, cpuFreq); // // const CBenchHash &bench = g_Hash[i]; // if (bench.Name == NULL) // break; // // BenchmarkDialog->AppendBenchInfo(GetUnicodeString(bench.Name)); // // // callback->BenchProps.DecComplexUnc = bench.DecComplexUnc; // // callback->BenchProps.DecComplexCompr = bench.DecComplexCompr; // // callback->BenchProps.EncComplex = bench.EncComplex; // // COneMethodInfo method; // NCOM::CPropVariant propVariant; // propVariant = bench.Name; // RINOK(method.ParseMethodFromPROPVARIANT(L"", propVariant)); // // UInt32 bufSize = 1 << kNumHashDictBits; // // UInt64 speed; // HRESULT res = CrcBench( // EXTERNAL_CODECS_LOC_VARS // complexInCommands, // numThreads, bufSize, // speed, // bench.Complex, &bench.CheckSum, method, // NULL, &EncodeRes, showFreq, cpuFreq); // if (res == E_NOTIMPL) { // // callback->Print(" ---"); // } // else { // RINOK(res); // } // // BenchmarkDialog->UpdateLastBenchInfo(); // } { UInt32 resVal; UInt64 cpuFreqLastTemp = cpuFreq; RINOK(FreqBench(complexInCommands, numThreads, &printCallback, false, cpuFreqLastTemp, resVal)); } return S_OK; } catch (CSystemException &e) { BenchmarkDialog->MessageBoxError(HResultToMessage(e.ErrorCode)); return E_FAIL; } catch (...) { BenchmarkDialog->MessageBoxError(HResultToMessage(E_FAIL)); return E_FAIL; } } static void ParseNumberString(const UString &s, NWindows::NCOM::CPropVariant &prop) { const wchar_t *end; UInt64 result = ConvertStringToUInt64(s, &end); if (*end != 0 || s.IsEmpty()) prop = s; else if (result <= (UInt32)0xFFFFFFFF) prop = (UInt32)result; else prop = result; } HRESULT Benchmark( DECL_EXTERNAL_CODECS_LOC_VARS const CObjectVector<CProperty> /*props*/) { CThreadBenchmark benchmarker; #ifdef EXTERNAL_CODECS benchmarker.__externalCodecs = __externalCodecs; #endif CBenchmarkDialog bd; bd.Sync.DictionarySize = (UInt32)(Int32)-1; bd.Sync.NumThreads = (UInt32)(Int32)-1; COneMethodInfo method; UInt32 numCPUs = 1; #ifndef _7ZIP_ST numCPUs = NWindows::NSystem::GetNumberOfProcessors(); #endif UInt32 numThreads = numCPUs; // FOR_VECTOR (i, props) // { // const CProperty &prop = props[i]; // UString name = prop.Name; // name.MakeLower_Ascii(); // if (name.IsEqualToNoCase(L"m") && prop.Value == L"*") // { // continue; // } // // NWindows::NCOM::CPropVariant propVariant; // if (!prop.Value.IsEmpty()) // ParseNumberString(prop.Value, propVariant); // if (name.IsPrefixedBy(L"mt")) // { // #ifndef _7ZIP_ST // RINOK(ParseMtProp(name.Ptr(2), propVariant, numCPUs, numThreads)); // if (numThreads != numCPUs) // bd.Sync.NumThreads = numThreads; // #endif // continue; // } // if (name.IsEqualTo("testtime")) // { // // UInt32 testTime = 4; // // RINOK(ParsePropToUInt32(L"", propVariant, testTime)); // continue; // } // RINOK(method.ParseMethodFromPROPVARIANT(name, propVariant)); // } // bool totalBenchMode = (method.MethodName == L"*"); { UInt32 dict; if (method.Get_DicSize(dict)) bd.Sync.DictionarySize = dict; } benchmarker.BenchmarkDialog = &bd; unsigned threadID; HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, &CThreadBenchmark::MyThreadFunction, &benchmarker, 0, &threadID); if (hThread == NULL) return E_FAIL; bd.DoModal(); if (WaitForSingleObject(hThread, INFINITE) == WAIT_FAILED) return E_FAIL; return S_OK; } void CBenchmarkDialog::AppendBenchInfo(LPCWSTR methodName, BOOL finalize) { if (m_lstBench.m_hWnd == NULL) return; FString strMethodName = GetSystemString(methodName); int nIndex = m_lstBench.InsertItem(m_lstBench.GetItemCount(), strMethodName); if (finalize) { WCHAR s[16]; UInt64 speed; speed = Sync.CompressingInfo.GetSpeed(Sync.CompressingInfo.UnpackSize); speed = speed / 1024; ConvertUInt64ToString(speed, s); m_lstBench.SetItemText(nIndex, 1, GetSystemString(s)); m_lstBench.SetItemText(nIndex, 2, _T("KB/s")); speed = Sync.DecompressingInfo.GetSpeed(Sync.DecompressingInfo.UnpackSize); speed = speed / 1024; ConvertUInt64ToString(speed, s); m_lstBench.SetItemText(nIndex, 3, GetSystemString(s)); m_lstBench.SetItemText(nIndex, 4, _T("KB/s")); } else { m_lstBench.SetItemText(nIndex, 1, kProcessingString); m_lstBench.SetItemText(nIndex, 2, kProcessingString); m_lstBench.SetItemText(nIndex, 3, kProcessingString); m_lstBench.SetItemText(nIndex, 4, kProcessingString); } AdjustWidth(); m_lstBench.UpdateWindow(); if (!m_strModules.IsEmpty()) m_strModules += _T(", "); m_strModules += strMethodName; } void CBenchmarkDialog::UpdateLastBenchInfo() { if (m_lstBench.m_hWnd == NULL) return; int nIndex = m_lstBench.GetItemCount() - 1; WCHAR s[16]; UInt64 speed; speed = Sync.CompressingInfo.GetSpeed( Sync.CompressingInfo.UnpackSize * Sync.CompressingInfo.NumIterations); speed = speed / 1024; m_encodings.Add((int)speed); m_nEncMax = max(m_nEncMax, speed); ConvertUInt64ToString(speed, s); m_lstBench.SetItemText(nIndex, 1, GetSystemString(s)); m_lstBench.SetItemText(nIndex, 2, _T("KB/s")); speed = Sync.DecompressingInfo.GetSpeed( Sync.DecompressingInfo.UnpackSize * Sync.DecompressingInfo.NumIterations); speed = speed / 1024; m_decodings.Add((int)speed); m_nDecMax = max(m_nDecMax, speed); ConvertUInt64ToString(speed, s); m_lstBench.SetItemText(nIndex, 3, GetSystemString(s)); m_lstBench.SetItemText(nIndex, 4, _T("KB/s")); AdjustWidth(); UInt64 nEncSum = 0; FOR_VECTOR(i, m_encodings) { nEncSum += m_encodings[i]; } m_strTotalComp = FormatWithCommas(nEncSum / m_encodings.Size()).c_str(); m_strTotalComp += _T(" KB/s"); UInt64 nDecSum = 0; FOR_VECTOR(i, m_decodings) { nDecSum += m_decodings[i]; } m_strTotalDecomp = FormatWithCommas(nDecSum / m_decodings.Size()).c_str(); m_strTotalDecomp += _T(" KB/s"); } void CBenchmarkDialog::OnNMCustomdrawBench(NMHDR *pNMHDR, LRESULT *pResult) { LPNMLVCUSTOMDRAW pLVCD = reinterpret_cast<LPNMLVCUSTOMDRAW>(pNMHDR); int nRow = (int)pLVCD->nmcd.dwItemSpec; int nRowItemData = (int)pLVCD->nmcd.lItemlParam; *pResult = CDRF_DODEFAULT; switch (pLVCD->nmcd.dwDrawStage) { case CDDS_PREPAINT: *pResult |= CDRF_NOTIFYITEMDRAW; break; case CDDS_ITEMPREPAINT: *pResult = CDRF_NOTIFYSUBITEMDRAW; break; case CDDS_ITEMPREPAINT | CDDS_SUBITEM: if (pLVCD->iSubItem == 1 || pLVCD->iSubItem == 3) { int row = (int)pLVCD->nmcd.dwItemSpec; int col = pLVCD->iSubItem; CIntVector &speeds = ((col == 1) ? m_encodings : m_decodings); if (row < (int)speeds.Size()) { CRect rt; CDC *pDC = CDC::FromHandle(pLVCD->nmcd.hdc); int level = speeds[row]; m_lstBench.GetSubItemRect(row, col, LVIR_BOUNDS, rt); DrawLevel(pDC, &rt, level, pLVCD->iSubItem == 1); *pResult = CDRF_SKIPDEFAULT; } break; } default: break; } } void CBenchmarkDialog::DrawLevel(CDC *pDC, LPRECT lprt, UInt64 nLevel, BOOL enc) { UInt64 nMax = enc ? m_nEncMax : m_nDecMax; if (nMax <= 0) return; int nSaved = pDC->SaveDC(); BITMAP bm; CBitmap &bmp = enc ? m_bmpLevel1 : m_bmpLevel2; bmp.GetBitmap(&bm); CDC dcMem; dcMem.CreateCompatibleDC(pDC); dcMem.SelectObject(&bmp); CRect rt = *lprt; int nWidth = rt.Width(); rt.right = (int)(rt.left + nLevel * nWidth / nMax); pDC->FillSolidRect(lprt, RGB(255, 255, 255)); pDC->IntersectClipRect(&rt); pDC->SetStretchBltMode(HALFTONE); pDC->StretchBlt(lprt->left, lprt->top, lprt->right - lprt->left, lprt->bottom - lprt->top, &dcMem, 0, 0, bm.bmWidth, bm.bmHeight, SRCCOPY); // BLENDFUNCTION bf; // memset(&bf, 0, sizeof(bf)); // bf.BlendOp = AC_SRC_OVER; // bf.BlendFlags = 0; // bf.SourceConstantAlpha = 255; // bf.AlphaFormat = AC_SRC_ALPHA; // pDC->AlphaBlend(rt.left, rt.top, rt.Width(), rt.Height(), // &dcMem, 0, 0, // bm.bmWidth * rt.Width() / nWidth, bm.bmHeight, bf); pDC->SelectClipRgn(NULL); pDC->SetROP2(R2_XORPEN); CString str = FormatWithCommas(nLevel).c_str(); pDC->SetBkMode(TRANSPARENT); pDC->DrawText(str, lprt, DT_RIGHT | DT_VCENTER | DT_SINGLELINE); pDC->RestoreDC(nSaved); } void CBenchmarkDialog::OnSize(UINT nType, int cx, int cy) { CDialogEx::OnSize(nType, cx, cy); if (!IsWindow(m_lstBench)) return; AdjustWidth(); } void CBenchmarkDialog::AdjustWidth() { const int count = 5; CRect rt; m_lstBench.GetWindowRect(&rt); int width = 0; for (int i = 0; i < count; i++) { width += m_lstBench.GetColumnWidth(i); } // for (int i = 0; i < count; i++) // m_lstBench.SetColumnWidth(i, LVSCW_AUTOSIZE_USEHEADER); for (int i = 0; i < count; i++) { m_lstBench.SetColumnWidth(i, m_lstBench.GetColumnWidth(i) * rt.Width() / width); } m_lstBench.RedrawItems(0, count - 1); }
1136346879/loveSportsApp
src/cmccsi/mhealth/app/sports/bean/WeightInfo.java
<reponame>1136346879/loveSportsApp package cmccsi.mhealth.app.sports.bean; public class WeightInfo extends BaseNetItem { // 文件类型 public WeightInfoData datavalue; public String dataType = ""; public void setValue(WeightInfo date) { this.status = date.status; this.dataType = date.dataType; this.datavalue = date.datavalue; } @Override public void setValue(BaseNetItem bni) { if (null != bni) { setValue((WeightInfo) bni); } } @Override public boolean isValueData(BaseNetItem bni) { //** return !(datavalue==null || "".equals(datavalue.weight)); } }
kotp/facets
lemon/core/module/test_pathize.rb
<reponame>kotp/facets<gh_stars>1-10 Covers 'facets/module/pathize' require File.dirname(__FILE__) + '/test_helper.rb' Case Module do Unit :pathize do ExampleModule::ExampleClass.pathize.assert == 'example_module/example_class' end end
ignaciocarvajal/gameStrore-backEnd
src/main/java/com/everis/gameStore/domain/model/Images.java
<reponame>ignaciocarvajal/gameStrore-backEnd package com.everis.gameStore.domain.model; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import com.everis.gameStore.domain.util.Constants; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; /** * The Class Images. */ @Setter @Getter @AllArgsConstructor @NoArgsConstructor @Entity @Table(name = Constants.IMAGES) public class Images implements Serializable { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 1L; /** The id image. */ @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name = "id") private Long idImage; /** The file name. */ @Column(name = "file_name") private String fileName; /** The file download uri. */ @Column(name = "download_uri") private String fileDownloadUri; /** The file delete uri. */ @Column(name = "delete_uri") private String fileDeleteUri; /** The file type. */ @Column(name = "file_type") private String fileType; /** The size. */ @Column(name = "size") private Long size; }
PuQian/WebRTC
common/src/main/java/com/free4lab/account/model/WcsUserDAO.java
package com.free4lab.account.model; import java.util.List; import javax.persistence.Query; import com.free4lab.utils.sql.AbstractDAO; import com.free4lab.utils.sql.IEntityManagerHelper; import com.free4lab.utils.sql.entitymanager.NoCacheEntityManagerHelper; public class WcsUserDAO extends AbstractDAO<WcsUser> { public String getClassName() { return getEntityClass().getName(); } public Class<WcsUser> getEntityClass() { return WcsUser.class; } public static final String PU_NAME = "AccountPU"; public static final String USER_ID = "user_id"; public String getPUName() { return PU_NAME; } public IEntityManagerHelper getEntityManagerHelper() { return new NoCacheEntityManagerHelper(); } @SuppressWarnings("unchecked") public List<WcsUser> findByAccessTokenMiddle(String accessToken) { try { final String queryString = "select model from " + getClassName() + " model where model.access_token like '________" + accessToken + "________' order by model.begin_time desc "; Query query = getEntityManager().createQuery(queryString); return query.getResultList(); } catch (RuntimeException re) { throw re; } } public List<WcsUser> findByUser_Id(Object user_id ) { return findByProperty(USER_ID,user_id ); } }
noprobzcoder09/helixdev
public/angular/client-controllers/LoginController.js
(function () { 'use strict'; angular .module('app') .controller('LoginController', Controller); function Controller($location, $localStorage, AuthService, $scope) { var vm = this; vm.login = login; initController(); function initController() { /* reset login status */ AuthService.Logout(); $scope.bgLogin = true; }; function login() { AuthService.Login(vm.email, vm.password, function (result) { console.log(result); if (result === true) { $location.path('/dashboard'); $scope.currentPath = 'dashboard'; $scope.bgLogin = false; toastr['success']('Welcome '+$localStorage.currentUser.user.first_name+' '+$localStorage.currentUser.user.last_name); } else { toastr['error']('Invalid username or password.'); } }); }; } })();
RedBrumbler/virtuoso-codegen
include/UnityEngine/ExposedReference_1.hpp
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: System.ValueType #include "System/ValueType.hpp" // Including type: UnityEngine.PropertyName #include "UnityEngine/PropertyName.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: UnityEngine namespace UnityEngine { // Forward declaring type: Object class Object; // Forward declaring type: IExposedPropertyTable class IExposedPropertyTable; } // Completed forward declares // Type namespace: UnityEngine namespace UnityEngine { // Forward declaring type: ExposedReference`1<T> template<typename T> struct ExposedReference_1; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE_GENERIC_STRUCT(::UnityEngine::ExposedReference_1, "UnityEngine", "ExposedReference`1"); // Type namespace: UnityEngine namespace UnityEngine { // WARNING Size may be invalid! // WARNING Layout: Sequential may not be correctly taken into account! // Autogenerated type: UnityEngine.ExposedReference`1 // [TokenAttribute] Offset: FFFFFFFF // [UsedByNativeCodeAttribute] Offset: 56510C template<typename T> struct ExposedReference_1/*, public ::System::ValueType*/ { public: public: // [SerializeField] Offset: 0x56A248 // public UnityEngine.PropertyName exposedName // Size: 0x4 // Offset: 0x0 ::UnityEngine::PropertyName exposedName; // Field size check static_assert(sizeof(::UnityEngine::PropertyName) == 0x4); // [SerializeField] Offset: 0x56A258 // public UnityEngine.Object defaultValue // Size: 0x8 // Offset: 0x0 ::UnityEngine::Object* defaultValue; // Field size check static_assert(sizeof(::UnityEngine::Object*) == 0x8); public: // Creating value type constructor for type: ExposedReference_1 constexpr ExposedReference_1(::UnityEngine::PropertyName exposedName_ = {}, ::UnityEngine::Object* defaultValue_ = {}) noexcept : exposedName{exposedName_}, defaultValue{defaultValue_} {} // Creating interface conversion operator: operator ::System::ValueType operator ::System::ValueType() noexcept { return *reinterpret_cast<::System::ValueType*>(this); } // Autogenerated instance field getter // Get instance field: public UnityEngine.PropertyName exposedName ::UnityEngine::PropertyName& dyn_exposedName() { static auto ___internal__logger = ::Logger::get().WithContext("::UnityEngine::ExposedReference_1::dyn_exposedName"); auto ___internal__instance = *this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "exposedName"))->offset; return *reinterpret_cast<::UnityEngine::PropertyName*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: public UnityEngine.Object defaultValue ::UnityEngine::Object*& dyn_defaultValue() { static auto ___internal__logger = ::Logger::get().WithContext("::UnityEngine::ExposedReference_1::dyn_defaultValue"); auto ___internal__instance = *this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "defaultValue"))->offset; return *reinterpret_cast<::UnityEngine::Object**>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // public T Resolve(UnityEngine.IExposedPropertyTable resolver) // Offset: 0xFFFFFFFFFFFFFFFF T Resolve(::UnityEngine::IExposedPropertyTable* resolver) { static auto ___internal__logger = ::Logger::get().WithContext("::UnityEngine::ExposedReference_1::Resolve"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(*this, "Resolve", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(resolver)}))); return ::il2cpp_utils::RunMethodRethrow<T, false>(this, ___internal__method, resolver); } }; // UnityEngine.ExposedReference`1 // Could not write size check! Type: UnityEngine.ExposedReference`1 is generic, or has no fields that are valid for size checks! } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
joeyynchan/spyder
Spyder/app/src/main/java/g1436218/com/spyder/asyncTask/DownloadImageTask.java
<gh_stars>0 package g1436218.com.spyder.asyncTask; import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.media.Image; import android.os.AsyncTask; import android.util.Log; import android.widget.ImageView; import java.io.InputStream; import g1436218.com.spyder.R; import g1436218.com.spyder.object.Attendee; /** * Created by Cherie on 1/15/2015. */ public class DownloadImageTask extends AsyncTask<String, Void, Bitmap> { private ImageView bmImage; private Attendee attendee = null; private String TAG = "DownloadImageTask"; public DownloadImageTask(ImageView bmImage) { this.bmImage = bmImage; } public DownloadImageTask(ImageView bmImage, Attendee attendee){ this(bmImage); this.attendee = attendee; } protected Bitmap doInBackground(String... urls) { Log.d(TAG, "Downloading picture for " + attendee.toString()); String urldisplay = urls[0]; Bitmap mIcon11 = null; try { InputStream in = new java.net.URL(urldisplay).openStream(); mIcon11 = BitmapFactory.decodeStream(in); } catch (Exception e) { return null; } return mIcon11; } protected void onPostExecute(Bitmap result) { if (result == null) { bmImage.setImageResource(R.drawable.ic_launcher); } else { bmImage.setImageBitmap(result); Log.d(TAG, "setting photo"); attendee.setPhoto(result); } } }
vdrokov/components-1
components/components-salesforce/components-salesforce-definition/src/test/java/org/talend/components/salesforce/SalesforceModuleListPropertiesTest.java
<reponame>vdrokov/components-1 // ============================================================================ // // Copyright (C) 2006-2017 Talend Inc. - www.talend.com // // This source code is available under agreement available at // %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt // // You should have received a copy of the agreement // along with this program; if not, write to Talend SA // 9 rue Pages 92150 Suresnes, France // // ============================================================================ package org.talend.components.salesforce; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.junit.Before; import org.junit.Test; import org.talend.daikon.NamedThing; import org.talend.daikon.SimpleNamedThing; import org.talend.daikon.properties.presentation.Form; import org.talend.daikon.properties.service.PropertiesService; import org.talend.daikon.properties.service.PropertiesServiceImpl; /** * */ public class SalesforceModuleListPropertiesTest extends SalesforceTestBase { private final String connectionName = "___TEST"; private final String repoLocation = "___DRI"; private PropertiesService propertiesService; private SalesforceConnectionProperties connectionProperties; private SalesforceModuleListProperties properties; @Before public void setUp() { propertiesService = new PropertiesServiceImpl(); connectionProperties = new SalesforceConnectionProperties("connection"); connectionProperties.name.setValue(connectionName); properties = new SalesforceModuleListProperties("root"); properties.setConnection(connectionProperties); properties.setRepositoryLocation(repoLocation); } @Test public void testSetupProperties() { properties.setupProperties(); assertNotNull(properties.getConnectionProperties()); assertEquals(connectionProperties, properties.getConnectionProperties()); assertNotNull(properties.getRepositoryLocation()); assertEquals(repoLocation, properties.getRepositoryLocation()); } @Test public void testSetupLayout() { properties.init(); Form mainForm = properties.getForm(Form.MAIN); assertNotNull(mainForm.getWidget(properties.selectedModuleNames.getName())); } @Test public void testRefreshLayout() { properties.init(); properties.refreshLayout(properties.getForm(Form.MAIN)); Form mainForm = properties.getForm(Form.MAIN); assertNotNull(mainForm.getWidget(properties.selectedModuleNames.getName())); } @Test public void testBeforeFormPresentMain() throws Throwable { properties.init(); try (MockRuntimeSourceOrSinkTestFixture testFixture = new MockRuntimeSourceOrSinkTestFixture( equalTo(properties), createDefaultTestDataset())) { testFixture.setUp(); propertiesService.beforeFormPresent("Main", properties); assertThat((Iterable<NamedThing>) properties.selectedModuleNames.getPossibleValues(), containsInAnyOrder((NamedThing) new SimpleNamedThing("Account"), new SimpleNamedThing("Customer"))); Form mainForm = properties.getForm(Form.MAIN); assertTrue(mainForm.isAllowBack()); assertTrue(mainForm.isAllowFinish()); } } @Test public void testAfterFormFinishMain() throws Throwable { properties.init(); List<TestRepository.Entry> repoEntries = new ArrayList<>(); TestRepository repository = new TestRepository(repoEntries); propertiesService.setRepository(repository); try (MockRuntimeSourceOrSinkTestFixture testFixture = new MockRuntimeSourceOrSinkTestFixture( equalTo(properties), createDefaultTestDataset())) { testFixture.setUp(); properties.selectedModuleNames.setValue(Arrays.<NamedThing>asList( new SimpleNamedThing("Account"), new SimpleNamedThing("Customer"))); propertiesService.afterFormFinish("Main", properties); assertEquals(3, repoEntries.size()); // Connection entry TestRepository.Entry connRepoEntry = repoEntries.get(0); assertEquals(connectionName, connRepoEntry.getName()); assertThat(connRepoEntry.getProperties(), instanceOf(SalesforceConnectionProperties.class)); // Module entry 1 TestRepository.Entry repoEntry1 = repoEntries.get(1); assertEquals("Account", repoEntry1.getName()); assertEquals("main.schema", repoEntry1.getSchemaPropertyName()); assertEquals(testFixture.getTestDataset().getSchema("Account"), repoEntry1.getSchema()); assertThat(repoEntry1.getProperties(), instanceOf(SalesforceModuleProperties.class)); SalesforceModuleProperties modProps1 = (SalesforceModuleProperties) repoEntry1.getProperties(); assertEquals(connectionProperties, modProps1.getConnectionProperties()); assertEquals("Account", modProps1.moduleName.getValue()); assertEquals(testFixture.getTestDataset().getSchema("Account"), modProps1.main.schema.getValue()); assertNotNull(modProps1.getForm(Form.MAIN)); // Module entry 2 TestRepository.Entry repoEntry2 = repoEntries.get(2); assertEquals("Customer", repoEntry2.getName()); assertEquals("main.schema", repoEntry2.getSchemaPropertyName()); assertEquals(testFixture.getTestDataset().getSchema("Customer"), repoEntry2.getSchema()); assertThat(repoEntry2.getProperties(), instanceOf(SalesforceModuleProperties.class)); SalesforceModuleProperties modProps2 = (SalesforceModuleProperties) repoEntry2.getProperties(); assertEquals(connectionProperties, modProps2.getConnectionProperties()); assertEquals("Customer", modProps2.moduleName.getValue()); assertEquals(testFixture.getTestDataset().getSchema("Customer"), modProps2.main.schema.getValue()); assertNotNull(modProps2.getForm(Form.MAIN)); } } }
leelige/mindspore
research/cvtmodel/hrnet/src/hrnet_w18_small.py
<filename>research/cvtmodel/hrnet/src/hrnet_w18_small.py import mindspore.ops as P from mindspore import nn class Module3(nn.Cell): def __init__(self, conv2d_0_in_channels, conv2d_0_out_channels, conv2d_0_kernel_size, conv2d_0_stride, conv2d_0_padding, conv2d_0_pad_mode): super(Module3, self).__init__() self.conv2d_0 = nn.Conv2d(in_channels=conv2d_0_in_channels, out_channels=conv2d_0_out_channels, kernel_size=conv2d_0_kernel_size, stride=conv2d_0_stride, padding=conv2d_0_padding, pad_mode=conv2d_0_pad_mode, dilation=(1, 1), group=1, has_bias=True) self.relu_1 = nn.ReLU() def construct(self, x): opt_conv2d_0 = self.conv2d_0(x) opt_relu_1 = self.relu_1(opt_conv2d_0) return opt_relu_1 class Module10(nn.Cell): def __init__(self, conv2d_0_in_channels, conv2d_0_out_channels, conv2d_0_kernel_size, conv2d_0_stride, conv2d_0_padding, conv2d_0_pad_mode, module3_0_conv2d_0_in_channels, module3_0_conv2d_0_out_channels, module3_0_conv2d_0_kernel_size, module3_0_conv2d_0_stride, module3_0_conv2d_0_padding, module3_0_conv2d_0_pad_mode, module3_1_conv2d_0_in_channels, module3_1_conv2d_0_out_channels, module3_1_conv2d_0_kernel_size, module3_1_conv2d_0_stride, module3_1_conv2d_0_padding, module3_1_conv2d_0_pad_mode): super(Module10, self).__init__() self.module3_0 = Module3(conv2d_0_in_channels=module3_0_conv2d_0_in_channels, conv2d_0_out_channels=module3_0_conv2d_0_out_channels, conv2d_0_kernel_size=module3_0_conv2d_0_kernel_size, conv2d_0_stride=module3_0_conv2d_0_stride, conv2d_0_padding=module3_0_conv2d_0_padding, conv2d_0_pad_mode=module3_0_conv2d_0_pad_mode) self.module3_1 = Module3(conv2d_0_in_channels=module3_1_conv2d_0_in_channels, conv2d_0_out_channels=module3_1_conv2d_0_out_channels, conv2d_0_kernel_size=module3_1_conv2d_0_kernel_size, conv2d_0_stride=module3_1_conv2d_0_stride, conv2d_0_padding=module3_1_conv2d_0_padding, conv2d_0_pad_mode=module3_1_conv2d_0_pad_mode) self.conv2d_0 = nn.Conv2d(in_channels=conv2d_0_in_channels, out_channels=conv2d_0_out_channels, kernel_size=conv2d_0_kernel_size, stride=conv2d_0_stride, padding=conv2d_0_padding, pad_mode=conv2d_0_pad_mode, dilation=(1, 1), group=1, has_bias=True) def construct(self, x): module3_0_opt = self.module3_0(x) module3_1_opt = self.module3_1(module3_0_opt) opt_conv2d_0 = self.conv2d_0(module3_1_opt) return opt_conv2d_0 class Module1(nn.Cell): def __init__(self, conv2d_0_in_channels, conv2d_0_out_channels, conv2d_2_in_channels, conv2d_2_out_channels, conv2d_5_in_channels, conv2d_5_out_channels, conv2d_7_in_channels, conv2d_7_out_channels): super(Module1, self).__init__() self.conv2d_0 = nn.Conv2d(in_channels=conv2d_0_in_channels, out_channels=conv2d_0_out_channels, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1, 1, 1), pad_mode="pad", dilation=(1, 1), group=1, has_bias=True) self.relu_1 = nn.ReLU() self.conv2d_2 = nn.Conv2d(in_channels=conv2d_2_in_channels, out_channels=conv2d_2_out_channels, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1, 1, 1), pad_mode="pad", dilation=(1, 1), group=1, has_bias=True) self.relu_4 = nn.ReLU() self.conv2d_5 = nn.Conv2d(in_channels=conv2d_5_in_channels, out_channels=conv2d_5_out_channels, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1, 1, 1), pad_mode="pad", dilation=(1, 1), group=1, has_bias=True) self.relu_6 = nn.ReLU() self.conv2d_7 = nn.Conv2d(in_channels=conv2d_7_in_channels, out_channels=conv2d_7_out_channels, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1, 1, 1), pad_mode="pad", dilation=(1, 1), group=1, has_bias=True) self.relu_9 = nn.ReLU() def construct(self, x): opt_conv2d_0 = self.conv2d_0(x) opt_relu_1 = self.relu_1(opt_conv2d_0) opt_conv2d_2 = self.conv2d_2(opt_relu_1) opt_add_3 = P.Add()(opt_conv2d_2, x) opt_relu_4 = self.relu_4(opt_add_3) opt_conv2d_5 = self.conv2d_5(opt_relu_4) opt_relu_6 = self.relu_6(opt_conv2d_5) opt_conv2d_7 = self.conv2d_7(opt_relu_6) opt_add_8 = P.Add()(opt_conv2d_7, opt_relu_4) opt_relu_9 = self.relu_9(opt_add_8) return opt_relu_9 class Module8(nn.Cell): def __init__(self, conv2d_0_in_channels, conv2d_0_out_channels, resizenearestneighbor_1_size): super(Module8, self).__init__() self.conv2d_0 = nn.Conv2d(in_channels=conv2d_0_in_channels, out_channels=conv2d_0_out_channels, kernel_size=(1, 1), stride=(1, 1), padding=0, pad_mode="valid", dilation=(1, 1), group=1, has_bias=True) self.resizenearestneighbor_1 = P.ResizeNearestNeighbor(size=resizenearestneighbor_1_size, align_corners=False) def construct(self, x): opt_conv2d_0 = self.conv2d_0(x) opt_resizenearestneighbor_1 = self.resizenearestneighbor_1(opt_conv2d_0) return opt_resizenearestneighbor_1 class Module6(nn.Cell): def __init__(self, conv2d_0_in_channels, conv2d_0_out_channels, module3_0_conv2d_0_in_channels, module3_0_conv2d_0_out_channels, module3_0_conv2d_0_kernel_size, module3_0_conv2d_0_stride, module3_0_conv2d_0_padding, module3_0_conv2d_0_pad_mode): super(Module6, self).__init__() self.module3_0 = Module3(conv2d_0_in_channels=module3_0_conv2d_0_in_channels, conv2d_0_out_channels=module3_0_conv2d_0_out_channels, conv2d_0_kernel_size=module3_0_conv2d_0_kernel_size, conv2d_0_stride=module3_0_conv2d_0_stride, conv2d_0_padding=module3_0_conv2d_0_padding, conv2d_0_pad_mode=module3_0_conv2d_0_pad_mode) self.conv2d_0 = nn.Conv2d(in_channels=conv2d_0_in_channels, out_channels=conv2d_0_out_channels, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1, 1, 1), pad_mode="pad", dilation=(1, 1), group=1, has_bias=True) def construct(self, x): module3_0_opt = self.module3_0(x) opt_conv2d_0 = self.conv2d_0(module3_0_opt) return opt_conv2d_0 class MindSporeModel(nn.Cell): def __init__(self): super(MindSporeModel, self).__init__() self.conv2d_0 = nn.Conv2d(in_channels=3, out_channels=64, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1, 1, 1), pad_mode="pad", dilation=(1, 1), group=1, has_bias=True) self.relu_1 = nn.ReLU() self.module3_0 = Module3(conv2d_0_in_channels=64, conv2d_0_out_channels=64, conv2d_0_kernel_size=(3, 3), conv2d_0_stride=(2, 2), conv2d_0_padding=(1, 1, 1, 1), conv2d_0_pad_mode="pad") self.module10_0 = Module10(conv2d_0_in_channels=32, conv2d_0_out_channels=128, conv2d_0_kernel_size=(1, 1), conv2d_0_stride=(1, 1), conv2d_0_padding=0, conv2d_0_pad_mode="valid", module3_0_conv2d_0_in_channels=64, module3_0_conv2d_0_out_channels=32, module3_0_conv2d_0_kernel_size=(1, 1), module3_0_conv2d_0_stride=(1, 1), module3_0_conv2d_0_padding=0, module3_0_conv2d_0_pad_mode="valid", module3_1_conv2d_0_in_channels=32, module3_1_conv2d_0_out_channels=32, module3_1_conv2d_0_kernel_size=(3, 3), module3_1_conv2d_0_stride=(1, 1), module3_1_conv2d_0_padding=(1, 1, 1, 1), module3_1_conv2d_0_pad_mode="pad") self.conv2d_5 = nn.Conv2d(in_channels=64, out_channels=128, kernel_size=(1, 1), stride=(1, 1), padding=0, pad_mode="valid", dilation=(1, 1), group=1, has_bias=True) self.relu_11 = nn.ReLU() self.module3_1 = Module3(conv2d_0_in_channels=128, conv2d_0_out_channels=16, conv2d_0_kernel_size=(3, 3), conv2d_0_stride=(1, 1), conv2d_0_padding=(1, 1, 1, 1), conv2d_0_pad_mode="pad") self.module3_2 = Module3(conv2d_0_in_channels=128, conv2d_0_out_channels=32, conv2d_0_kernel_size=(3, 3), conv2d_0_stride=(2, 2), conv2d_0_padding=(1, 1, 1, 1), conv2d_0_pad_mode="pad") self.module1_0 = Module1(conv2d_0_in_channels=16, conv2d_0_out_channels=16, conv2d_2_in_channels=16, conv2d_2_out_channels=16, conv2d_5_in_channels=16, conv2d_5_out_channels=16, conv2d_7_in_channels=16, conv2d_7_out_channels=16) self.module1_1 = Module1(conv2d_0_in_channels=32, conv2d_0_out_channels=32, conv2d_2_in_channels=32, conv2d_2_out_channels=32, conv2d_5_in_channels=32, conv2d_5_out_channels=32, conv2d_7_in_channels=32, conv2d_7_out_channels=32) self.module8_0 = Module8(conv2d_0_in_channels=32, conv2d_0_out_channels=16, resizenearestneighbor_1_size=(56, 56)) self.relu_44 = nn.ReLU() self.conv2d_36 = nn.Conv2d(in_channels=16, out_channels=32, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1, 1, 1), pad_mode="pad", dilation=(1, 1), group=1, has_bias=True) self.relu_40 = nn.ReLU() self.module3_3 = Module3(conv2d_0_in_channels=32, conv2d_0_out_channels=64, conv2d_0_kernel_size=(3, 3), conv2d_0_stride=(2, 2), conv2d_0_padding=(1, 1, 1, 1), conv2d_0_pad_mode="pad") self.module1_2 = Module1(conv2d_0_in_channels=16, conv2d_0_out_channels=16, conv2d_2_in_channels=16, conv2d_2_out_channels=16, conv2d_5_in_channels=16, conv2d_5_out_channels=16, conv2d_7_in_channels=16, conv2d_7_out_channels=16) self.module1_3 = Module1(conv2d_0_in_channels=32, conv2d_0_out_channels=32, conv2d_2_in_channels=32, conv2d_2_out_channels=32, conv2d_5_in_channels=32, conv2d_5_out_channels=32, conv2d_7_in_channels=32, conv2d_7_out_channels=32) self.module1_4 = Module1(conv2d_0_in_channels=64, conv2d_0_out_channels=64, conv2d_2_in_channels=64, conv2d_2_out_channels=64, conv2d_5_in_channels=64, conv2d_5_out_channels=64, conv2d_7_in_channels=64, conv2d_7_out_channels=64) self.module8_1 = Module8(conv2d_0_in_channels=32, conv2d_0_out_channels=16, resizenearestneighbor_1_size=(56, 56)) self.module8_2 = Module8(conv2d_0_in_channels=64, conv2d_0_out_channels=16, resizenearestneighbor_1_size=(56, 56)) self.relu_91 = nn.ReLU() self.conv2d_78 = nn.Conv2d(in_channels=16, out_channels=32, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1, 1, 1), pad_mode="pad", dilation=(1, 1), group=1, has_bias=True) self.module8_3 = Module8(conv2d_0_in_channels=64, conv2d_0_out_channels=32, resizenearestneighbor_1_size=(28, 28)) self.relu_92 = nn.ReLU() self.module6_0 = Module6(conv2d_0_in_channels=16, conv2d_0_out_channels=64, module3_0_conv2d_0_in_channels=16, module3_0_conv2d_0_out_channels=16, module3_0_conv2d_0_kernel_size=(3, 3), module3_0_conv2d_0_stride=(2, 2), module3_0_conv2d_0_padding=(1, 1, 1, 1), module3_0_conv2d_0_pad_mode="pad") self.conv2d_74 = nn.Conv2d(in_channels=32, out_channels=64, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1, 1, 1), pad_mode="pad", dilation=(1, 1), group=1, has_bias=True) self.relu_96 = nn.ReLU() self.module3_4 = Module3(conv2d_0_in_channels=64, conv2d_0_out_channels=128, conv2d_0_kernel_size=(3, 3), conv2d_0_stride=(2, 2), conv2d_0_padding=(1, 1, 1, 1), conv2d_0_pad_mode="pad") self.module1_5 = Module1(conv2d_0_in_channels=16, conv2d_0_out_channels=16, conv2d_2_in_channels=16, conv2d_2_out_channels=16, conv2d_5_in_channels=16, conv2d_5_out_channels=16, conv2d_7_in_channels=16, conv2d_7_out_channels=16) self.module1_6 = Module1(conv2d_0_in_channels=32, conv2d_0_out_channels=32, conv2d_2_in_channels=32, conv2d_2_out_channels=32, conv2d_5_in_channels=32, conv2d_5_out_channels=32, conv2d_7_in_channels=32, conv2d_7_out_channels=32) self.module1_7 = Module1(conv2d_0_in_channels=64, conv2d_0_out_channels=64, conv2d_2_in_channels=64, conv2d_2_out_channels=64, conv2d_5_in_channels=64, conv2d_5_out_channels=64, conv2d_7_in_channels=64, conv2d_7_out_channels=64) self.module1_8 = Module1(conv2d_0_in_channels=128, conv2d_0_out_channels=128, conv2d_2_in_channels=128, conv2d_2_out_channels=128, conv2d_5_in_channels=128, conv2d_5_out_channels=128, conv2d_7_in_channels=128, conv2d_7_out_channels=128) self.module8_4 = Module8(conv2d_0_in_channels=32, conv2d_0_out_channels=16, resizenearestneighbor_1_size=(56, 56)) self.module8_5 = Module8(conv2d_0_in_channels=64, conv2d_0_out_channels=16, resizenearestneighbor_1_size=(56, 56)) self.module8_6 = Module8(conv2d_0_in_channels=128, conv2d_0_out_channels=16, resizenearestneighbor_1_size=(56, 56)) self.relu_174 = nn.ReLU() self.conv2d_133 = nn.Conv2d(in_channels=16, out_channels=32, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1, 1, 1), pad_mode="pad", dilation=(1, 1), group=1, has_bias=True) self.module8_7 = Module8(conv2d_0_in_channels=64, conv2d_0_out_channels=32, resizenearestneighbor_1_size=(28, 28)) self.module8_8 = Module8(conv2d_0_in_channels=128, conv2d_0_out_channels=32, resizenearestneighbor_1_size=(28, 28)) self.relu_175 = nn.ReLU() self.module6_1 = Module6(conv2d_0_in_channels=16, conv2d_0_out_channels=64, module3_0_conv2d_0_in_channels=16, module3_0_conv2d_0_out_channels=16, module3_0_conv2d_0_kernel_size=(3, 3), module3_0_conv2d_0_stride=(2, 2), module3_0_conv2d_0_padding=(1, 1, 1, 1), module3_0_conv2d_0_pad_mode="pad") self.conv2d_137 = nn.Conv2d(in_channels=32, out_channels=64, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1, 1, 1), pad_mode="pad", dilation=(1, 1), group=1, has_bias=True) self.module8_9 = Module8(conv2d_0_in_channels=128, conv2d_0_out_channels=64, resizenearestneighbor_1_size=(14, 14)) self.relu_176 = nn.ReLU() self.module10_1 = Module10(conv2d_0_in_channels=16, conv2d_0_out_channels=128, conv2d_0_kernel_size=(3, 3), conv2d_0_stride=(2, 2), conv2d_0_padding=(1, 1, 1, 1), conv2d_0_pad_mode="pad", module3_0_conv2d_0_in_channels=16, module3_0_conv2d_0_out_channels=16, module3_0_conv2d_0_kernel_size=(3, 3), module3_0_conv2d_0_stride=(2, 2), module3_0_conv2d_0_padding=(1, 1, 1, 1), module3_0_conv2d_0_pad_mode="pad", module3_1_conv2d_0_in_channels=16, module3_1_conv2d_0_out_channels=16, module3_1_conv2d_0_kernel_size=(3, 3), module3_1_conv2d_0_stride=(2, 2), module3_1_conv2d_0_padding=(1, 1, 1, 1), module3_1_conv2d_0_pad_mode="pad") self.module6_2 = Module6(conv2d_0_in_channels=32, conv2d_0_out_channels=128, module3_0_conv2d_0_in_channels=32, module3_0_conv2d_0_out_channels=32, module3_0_conv2d_0_kernel_size=(3, 3), module3_0_conv2d_0_stride=(2, 2), module3_0_conv2d_0_padding=(1, 1, 1, 1), module3_0_conv2d_0_pad_mode="pad") self.conv2d_149 = nn.Conv2d(in_channels=64, out_channels=128, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1, 1, 1), pad_mode="pad", dilation=(1, 1), group=1, has_bias=True) self.relu_184 = nn.ReLU() self.module10_2 = Module10(conv2d_0_in_channels=32, conv2d_0_out_channels=128, conv2d_0_kernel_size=(1, 1), conv2d_0_stride=(1, 1), conv2d_0_padding=0, conv2d_0_pad_mode="valid", module3_0_conv2d_0_in_channels=16, module3_0_conv2d_0_out_channels=32, module3_0_conv2d_0_kernel_size=(1, 1), module3_0_conv2d_0_stride=(1, 1), module3_0_conv2d_0_padding=0, module3_0_conv2d_0_pad_mode="valid", module3_1_conv2d_0_in_channels=32, module3_1_conv2d_0_out_channels=32, module3_1_conv2d_0_kernel_size=(3, 3), module3_1_conv2d_0_stride=(1, 1), module3_1_conv2d_0_padding=(1, 1, 1, 1), module3_1_conv2d_0_pad_mode="pad") self.conv2d_179 = nn.Conv2d(in_channels=16, out_channels=128, kernel_size=(1, 1), stride=(1, 1), padding=0, pad_mode="valid", dilation=(1, 1), group=1, has_bias=True) self.relu_206 = nn.ReLU() self.module10_3 = Module10(conv2d_0_in_channels=64, conv2d_0_out_channels=256, conv2d_0_kernel_size=(1, 1), conv2d_0_stride=(1, 1), conv2d_0_padding=0, conv2d_0_pad_mode="valid", module3_0_conv2d_0_in_channels=32, module3_0_conv2d_0_out_channels=64, module3_0_conv2d_0_kernel_size=(1, 1), module3_0_conv2d_0_stride=(1, 1), module3_0_conv2d_0_padding=0, module3_0_conv2d_0_pad_mode="valid", module3_1_conv2d_0_in_channels=64, module3_1_conv2d_0_out_channels=64, module3_1_conv2d_0_kernel_size=(3, 3), module3_1_conv2d_0_stride=(1, 1), module3_1_conv2d_0_padding=(1, 1, 1, 1), module3_1_conv2d_0_pad_mode="pad") self.conv2d_181 = nn.Conv2d(in_channels=32, out_channels=256, kernel_size=(1, 1), stride=(1, 1), padding=0, pad_mode="valid", dilation=(1, 1), group=1, has_bias=True) self.relu_207 = nn.ReLU() self.module3_5 = Module3(conv2d_0_in_channels=128, conv2d_0_out_channels=256, conv2d_0_kernel_size=(3, 3), conv2d_0_stride=(2, 2), conv2d_0_padding=(1, 1, 1, 1), conv2d_0_pad_mode="pad") self.module10_4 = Module10(conv2d_0_in_channels=128, conv2d_0_out_channels=512, conv2d_0_kernel_size=(1, 1), conv2d_0_stride=(1, 1), conv2d_0_padding=0, conv2d_0_pad_mode="valid", module3_0_conv2d_0_in_channels=64, module3_0_conv2d_0_out_channels=128, module3_0_conv2d_0_kernel_size=(1, 1), module3_0_conv2d_0_stride=(1, 1), module3_0_conv2d_0_padding=0, module3_0_conv2d_0_pad_mode="valid", module3_1_conv2d_0_in_channels=128, module3_1_conv2d_0_out_channels=128, module3_1_conv2d_0_kernel_size=(3, 3), module3_1_conv2d_0_stride=(1, 1), module3_1_conv2d_0_padding=(1, 1, 1, 1), module3_1_conv2d_0_pad_mode="pad") self.conv2d_183 = nn.Conv2d(in_channels=64, out_channels=512, kernel_size=(1, 1), stride=(1, 1), padding=0, pad_mode="valid", dilation=(1, 1), group=1, has_bias=True) self.relu_208 = nn.ReLU() self.module3_6 = Module3(conv2d_0_in_channels=256, conv2d_0_out_channels=512, conv2d_0_kernel_size=(3, 3), conv2d_0_stride=(2, 2), conv2d_0_padding=(1, 1, 1, 1), conv2d_0_pad_mode="pad") self.module10_5 = Module10(conv2d_0_in_channels=256, conv2d_0_out_channels=1024, conv2d_0_kernel_size=(1, 1), conv2d_0_stride=(1, 1), conv2d_0_padding=0, conv2d_0_pad_mode="valid", module3_0_conv2d_0_in_channels=128, module3_0_conv2d_0_out_channels=256, module3_0_conv2d_0_kernel_size=(1, 1), module3_0_conv2d_0_stride=(1, 1), module3_0_conv2d_0_padding=0, module3_0_conv2d_0_pad_mode="valid", module3_1_conv2d_0_in_channels=256, module3_1_conv2d_0_out_channels=256, module3_1_conv2d_0_kernel_size=(3, 3), module3_1_conv2d_0_stride=(1, 1), module3_1_conv2d_0_padding=(1, 1, 1, 1), module3_1_conv2d_0_pad_mode="pad") self.conv2d_189 = nn.Conv2d(in_channels=128, out_channels=1024, kernel_size=(1, 1), stride=(1, 1), padding=0, pad_mode="valid", dilation=(1, 1), group=1, has_bias=True) self.relu_211 = nn.ReLU() self.module3_7 = Module3(conv2d_0_in_channels=512, conv2d_0_out_channels=1024, conv2d_0_kernel_size=(3, 3), conv2d_0_stride=(2, 2), conv2d_0_padding=(1, 1, 1, 1), conv2d_0_pad_mode="pad") self.module3_8 = Module3(conv2d_0_in_channels=1024, conv2d_0_out_channels=2048, conv2d_0_kernel_size=(1, 1), conv2d_0_stride=(1, 1), conv2d_0_padding=0, conv2d_0_pad_mode="valid") self.avgpool2d_222 = nn.AvgPool2d(kernel_size=(7, 7)) self.flatten_223 = nn.Flatten() self.dense_224 = nn.Dense(in_channels=2048, out_channels=1000, has_bias=True) def construct(self, input_1): opt_conv2d_0 = self.conv2d_0(input_1) opt_relu_1 = self.relu_1(opt_conv2d_0) module3_0_opt = self.module3_0(opt_relu_1) module10_0_opt = self.module10_0(module3_0_opt) opt_conv2d_5 = self.conv2d_5(module3_0_opt) opt_add_10 = P.Add()(module10_0_opt, opt_conv2d_5) opt_relu_11 = self.relu_11(opt_add_10) module3_1_opt = self.module3_1(opt_relu_11) module3_2_opt = self.module3_2(opt_relu_11) module1_0_opt = self.module1_0(module3_1_opt) module1_1_opt = self.module1_1(module3_2_opt) module8_0_opt = self.module8_0(module1_1_opt) opt_add_41 = P.Add()(module1_0_opt, module8_0_opt) opt_relu_44 = self.relu_44(opt_add_41) opt_conv2d_36 = self.conv2d_36(module1_0_opt) opt_add_38 = P.Add()(opt_conv2d_36, module1_1_opt) opt_relu_40 = self.relu_40(opt_add_38) module3_3_opt = self.module3_3(opt_relu_40) module1_2_opt = self.module1_2(opt_relu_44) module1_3_opt = self.module1_3(opt_relu_40) module1_4_opt = self.module1_4(module3_3_opt) module8_1_opt = self.module8_1(module1_3_opt) opt_add_82 = P.Add()(module1_2_opt, module8_1_opt) module8_2_opt = self.module8_2(module1_4_opt) opt_add_88 = P.Add()(opt_add_82, module8_2_opt) opt_relu_91 = self.relu_91(opt_add_88) opt_conv2d_78 = self.conv2d_78(module1_2_opt) opt_add_83 = P.Add()(opt_conv2d_78, module1_3_opt) module8_3_opt = self.module8_3(module1_4_opt) opt_add_89 = P.Add()(opt_add_83, module8_3_opt) opt_relu_92 = self.relu_92(opt_add_89) module6_0_opt = self.module6_0(module1_2_opt) opt_conv2d_74 = self.conv2d_74(module1_3_opt) opt_add_90 = P.Add()(module6_0_opt, opt_conv2d_74) opt_add_93 = P.Add()(opt_add_90, module1_4_opt) opt_relu_96 = self.relu_96(opt_add_93) module3_4_opt = self.module3_4(opt_relu_96) module1_5_opt = self.module1_5(opt_relu_91) module1_6_opt = self.module1_6(opt_relu_92) module1_7_opt = self.module1_7(opt_relu_96) module1_8_opt = self.module1_8(module3_4_opt) module8_4_opt = self.module8_4(module1_6_opt) opt_add_152 = P.Add()(module1_5_opt, module8_4_opt) module8_5_opt = self.module8_5(module1_7_opt) opt_add_162 = P.Add()(opt_add_152, module8_5_opt) module8_6_opt = self.module8_6(module1_8_opt) opt_add_170 = P.Add()(opt_add_162, module8_6_opt) opt_relu_174 = self.relu_174(opt_add_170) opt_conv2d_133 = self.conv2d_133(module1_5_opt) opt_add_141 = P.Add()(opt_conv2d_133, module1_6_opt) module8_7_opt = self.module8_7(module1_7_opt) opt_add_163 = P.Add()(opt_add_141, module8_7_opt) module8_8_opt = self.module8_8(module1_8_opt) opt_add_171 = P.Add()(opt_add_163, module8_8_opt) opt_relu_175 = self.relu_175(opt_add_171) module6_1_opt = self.module6_1(module1_5_opt) opt_conv2d_137 = self.conv2d_137(module1_6_opt) opt_add_157 = P.Add()(module6_1_opt, opt_conv2d_137) opt_add_164 = P.Add()(opt_add_157, module1_7_opt) module8_9_opt = self.module8_9(module1_8_opt) opt_add_172 = P.Add()(opt_add_164, module8_9_opt) opt_relu_176 = self.relu_176(opt_add_172) module10_1_opt = self.module10_1(module1_5_opt) module6_2_opt = self.module6_2(module1_6_opt) opt_add_169 = P.Add()(module10_1_opt, module6_2_opt) opt_conv2d_149 = self.conv2d_149(module1_7_opt) opt_add_173 = P.Add()(opt_add_169, opt_conv2d_149) opt_add_177 = P.Add()(opt_add_173, module1_8_opt) opt_relu_184 = self.relu_184(opt_add_177) module10_2_opt = self.module10_2(opt_relu_174) opt_conv2d_179 = self.conv2d_179(opt_relu_174) opt_add_202 = P.Add()(module10_2_opt, opt_conv2d_179) opt_relu_206 = self.relu_206(opt_add_202) module10_3_opt = self.module10_3(opt_relu_175) opt_conv2d_181 = self.conv2d_181(opt_relu_175) opt_add_203 = P.Add()(module10_3_opt, opt_conv2d_181) opt_relu_207 = self.relu_207(opt_add_203) module3_5_opt = self.module3_5(opt_relu_206) opt_add_213 = P.Add()(opt_relu_207, module3_5_opt) module10_4_opt = self.module10_4(opt_relu_176) opt_conv2d_183 = self.conv2d_183(opt_relu_176) opt_add_204 = P.Add()(module10_4_opt, opt_conv2d_183) opt_relu_208 = self.relu_208(opt_add_204) module3_6_opt = self.module3_6(opt_add_213) opt_add_216 = P.Add()(opt_relu_208, module3_6_opt) module10_5_opt = self.module10_5(opt_relu_184) opt_conv2d_189 = self.conv2d_189(opt_relu_184) opt_add_209 = P.Add()(module10_5_opt, opt_conv2d_189) opt_relu_211 = self.relu_211(opt_add_209) module3_7_opt = self.module3_7(opt_add_216) opt_add_219 = P.Add()(opt_relu_211, module3_7_opt) module3_8_opt = self.module3_8(opt_add_219) opt_avgpool2d_222 = self.avgpool2d_222(module3_8_opt) opt_flatten_223 = self.flatten_223(opt_avgpool2d_222) opt_dense_224 = self.dense_224(opt_flatten_223) return opt_dense_224
secret32/sceonblog
src/main/java/top/sceon/blog/service/NoteService.java
package top.sceon.blog.service; import org.springframework.stereotype.Service; import top.sceon.blog.dao.NoteDao; import top.sceon.blog.entity.Note; import javax.annotation.Resource; /** * @author zhouwei * @since 2016/9/1 */ @Service public class NoteService extends BaseServiceImpl<Note, Integer> implements IBaseService<Note, Integer> { private NoteDao noteDao; public NoteDao getNoteDao() { return noteDao; } @Resource public void setNoteDao(NoteDao noteDao) { this.noteDao = noteDao; super.setBaseDao(noteDao); } }
martmists-gh/BDSP
include/il2cpp/UnityEngine/Scripting/APIUpdating/MovedFromAttribute.h
<gh_stars>1-10 #pragma once #include "il2cpp.h" void UnityEngine_Scripting_APIUpdating_MovedFromAttribute___ctor (UnityEngine_Scripting_APIUpdating_MovedFromAttribute_o* __this, bool autoUpdateAPI, System_String_o* sourceNamespace, System_String_o* sourceAssembly, System_String_o* sourceClassName, const MethodInfo* method_info); void UnityEngine_Scripting_APIUpdating_MovedFromAttribute___ctor (UnityEngine_Scripting_APIUpdating_MovedFromAttribute_o* __this, System_String_o* sourceNamespace, const MethodInfo* method_info);
segment-oj/segment-sandbox
src/utils/process.cc
#include "ssandbox/utils/process.h" #include <cerrno> #include <climits> #include <filesystem> #include <fmt/core.h> #include "ssandbox/utils/exceptions.h" bool ssandbox::process::check_process_alive(pid_t pid) { std::filesystem::path process_proc("/proc"); process_proc /= std::to_string(pid); if (!std::filesystem::exists(process_proc)) return false; // process does not exsit std::string statfilepath = fmt::format("/proc/{}/stat", pid); std::FILE* statfile = std::fopen(statfilepath.c_str(), "r"); if (statfile == nullptr) throw ssandbox::exceptions::syscall_error(errno, fmt::format("Cannot open process file of pid={}", pid), __FUNCTION__); char* stat = new char[64]; std::fscanf(statfile, "%*[0-9] (%*[^/()\n\r]) %63s", stat); bool ret = true; for (int i = 0; stat[i] != '\0'; ++i) { if (stat[i] == 'Z') ret = false; // Process has dead } std::fclose(statfile); delete[] stat; return ret; }
RemotecraftProject/RemotecraftApp
domain/src/main/java/com/remotecraft/app/domain/provider/ReceiverActionProvider.java
<filename>domain/src/main/java/com/remotecraft/app/domain/provider/ReceiverActionProvider.java package com.remotecraft.app.domain.provider; import io.reactivex.Maybe; public interface ReceiverActionProvider { Maybe<Integer> getWifiState(); }
fabiojna02/OpenCellular
firmware/coreboot/payloads/coreinfo/multiboot_module.c
<filename>firmware/coreboot/payloads/coreinfo/multiboot_module.c /* * This file is part of the coreinfo project. * * Copyright (C) 2008 <NAME> <<EMAIL>> * * 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; version 2 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #include <multiboot_tables.h> #include "coreinfo.h" #if IS_ENABLED(CONFIG_MODULE_MULTIBOOT) #define MAX_MEMORY_COUNT 10 static struct { int mem_count; struct { u64 start; u64 size; int type; } range[MAX_MEMORY_COUNT]; } cb_info; static int tables_good = 0; int multiboot_module_redraw(WINDOW *win) { int row = 2; int i; print_module_title(win, "Multiboot Tables"); if (tables_good == 0) { mvwprintw(win, row++, 1, "No multiboot tables were found"); return 0; } row++; mvwprintw(win, row++, 1, "-- Memory Map --"); for (i = 0; i < cb_info.mem_count; i++) { if (cb_info.range[i].type == 1) mvwprintw(win, row++, 3, " RAM: "); else mvwprintw(win, row++, 3, "Reserved: "); wprintw(win, "%16.16llx - %16.16llx", cb_info.range[i].start, cb_info.range[i].start + cb_info.range[i].size - 1); } return 0; } static void parse_memory(struct multiboot_header *table) { u8 *start = (u8 *) phys_to_virt(table->mmap_addr); u8 *ptr = start; int i = 0; cb_info.mem_count = 0; while(ptr < (start + table->mmap_length)) { struct multiboot_mmap *mmap = (struct multiboot_mmap *) ptr; cb_info.range[i].start = mmap->addr; cb_info.range[i].size = mmap->length; cb_info.range[i].type = mmap->type; if (++cb_info.mem_count == MAX_MEMORY_COUNT) return; ptr += (mmap->size + sizeof(mmap->size)); i++; } } static void parse_header(unsigned long addr) { struct multiboot_header *table = (struct multiboot_header *) addr; if (table->flags & MULTIBOOT_FLAGS_MMAP) parse_memory(table); } static int multiboot_module_init(void) { unsigned long mbaddr; tables_good = sysinfo_have_multiboot(&mbaddr); parse_header(mbaddr); return tables_good ? 0 : -1; } struct coreinfo_module multiboot_module = { .name = "Multiboot", .init = multiboot_module_init, .redraw = multiboot_module_redraw, }; #else struct coreinfo_module multiboot_module = { }; #endif /* CONFIG_MODULE_MULTIBOOT */
iboxdb/db4o-gpl
db4o.j/db4o-core/core/src/com/db4o/internal/query/processor/QCandidateBase.java
/* Copyright (C) 2004 - 2010 Versant Inc. http://www.db4o.com */ package com.db4o.internal.query.processor; import com.db4o.*; import com.db4o.foundation.*; import com.db4o.internal.*; public abstract class QCandidateBase extends TreeInt implements InternalCandidate { protected final QCandidates _candidates; protected List4 _dependants; boolean _include = true; Tree _pendingJoins; InternalCandidate _root; public QCandidateBase(QCandidates candidates, int id) { super(id); if (DTrace.enabled) { DTrace.CREATE_CANDIDATE.log(id); } _candidates = candidates; if(id == 0){ _key = candidates.generateCandidateId(); } if(Debug4.queries){ System.out.println("Candidate identified ID:" + _key ); } } protected void addDependant(InternalCandidate a_candidate) { _dependants = new List4(_dependants, a_candidate); } @Override public void doNotInclude() { include(false); if (_dependants != null) { Iterator4 i = new Iterator4Impl(_dependants); _dependants = null; while (i.moveNext()) { ((InternalCandidate) i.current()).doNotInclude(); } } } @Override public boolean evaluate(QPending pending) { if (Debug4.queries) { System.out.println("Pending arrived Join: " + pending._join.id() + " Constraint:" + pending._constraint.id() + " res:" + pending._result); } QPending oldPending = (QPending) Tree.find(_pendingJoins, pending); if (oldPending == null) { pending.changeConstraint(); _pendingJoins = Tree.add(_pendingJoins, pending.internalClonePayload()); return true; } _pendingJoins = _pendingJoins.removeNode(oldPending); oldPending._join.evaluatePending(this, oldPending, pending._result); return false; } public ObjectContainer objectContainer() { return container(); } public InternalCandidate getRoot() { return _root == null ? this : _root; } final LocalObjectContainer container() { return transaction().localContainer(); } @Override public final LocalTransaction transaction() { return _candidates.i_trans; } @Override public boolean include() { return _include; } /** * For external interface use only. Call doNotInclude() internally so * dependancies can be checked. */ public void include(boolean flag) { // TODO: // Internal and external flag may need to be handled seperately. _include = flag; if(Debug4.queries){ System.out.println("Candidate include " + flag + " ID: " + _key); } } @Override public Tree onAttemptToAddDuplicate(Tree oldNode) { _size = 0; _root = (InternalCandidate) oldNode; return oldNode; } @Override public boolean duplicates() { return _root != null; } public QCandidates candidates() { return _candidates; } @Override public void root(InternalCandidate root) { _root = root; } @Override public Tree pendingJoins() { return _pendingJoins; } @Override public int id() { return _key; } }
HowProgrammingWorks/JSTP
test/node/session.js
<filename>test/node/session.js 'use strict'; const test = require('tap'); const jstp = require('../..'); const app = require('../fixtures/application'); const application = new jstp.Application(app.name, app.interfaces); const serverConfig = { applications: [application] }; let server; let connection; let port; test.afterEach(done => { if (connection) { connection.close(); connection = null; } server.close(); done(); }); test.test('must reconnect to existing session', test => { server = jstp.net.createServer(serverConfig); server.listen(0, () => { port = server.address().port; jstp.net.connect(app.name, null, port, (error, conn, session) => { test.assertNot(error, 'handshake must not return an error'); test.equal(conn.username, null, 'username must be null'); test.assert( session instanceof jstp.Session, 'session must be an instance of jstp.Session' ); jstp.net.reconnect(conn, port, (error, conn, session) => { connection = conn; test.assertNot( error, 'must successfully reconnect to existing session' ); test.assertNot(session, 'must not return Session object'); test.end(); }); }); }); }); test.test('must not resend messages received by other side', test => { test.plan(7); server = jstp.net.createServer({ applications: [ new jstp.Application('testApp', { calculator: { doNothing(connection, callback) { test.pass('method must only be called once'); callback(null); }, }, }), ], }); server.listen(0, () => { port = server.address().port; jstp.net.connect(app.name, null, port, (error, conn, session) => { test.assertNot(error, 'handshake must not return an error'); test.equal(conn.username, null, 'username must be null'); test.assert( session instanceof jstp.Session, 'session must be an instance of jstp.Session' ); conn.callMethod('calculator', 'doNothing', [], error => { test.assertNot(error, 'call must not return an error'); jstp.net.reconnect(conn, port, (error, conn, session) => { connection = conn; test.assertNot( error, 'must successfully reconnect to existing session' ); test.assertNot(session, 'must not return Session object'); }); }); }); }); });
sebyx07/hyperstack
ruby/hyper-spec/lib/selenium/web_driver/firefox/profile.rb
module Selenium module WebDriver module Firefox class Profile class << self attr_accessor :firebug_version def firebug_version @firebug_version ||= '2.0.19-fx' end end def frame_position @frame_position ||= 'detached' end def frame_position=(position) @frame_position = %w[left right top detached].detect do |side| position && position[0].downcase == side[0] end || 'detached' end def enable_firebug(version = nil) version ||= Selenium::WebDriver::Firefox::Profile.firebug_version add_extension(File.expand_path("../../../../bin/firebug-#{version}.xpi", __FILE__)) # For some reason, Firebug seems to trigger the Firefox plugin check # (navigating to https://www.mozilla.org/en-US/plugincheck/ at startup). # This prevents it. See http://code.google.com/p/selenium/issues/detail?id=4619. self['extensions.blocklist.enabled'] = false # Prevent "Welcome!" tab self['extensions.firebug.showFirstRunPage'] = false # Enable for all sites. self['extensions.firebug.allPagesActivation'] = 'on' # Enable all features. %w[console net script].each do |feature| self["extensions.firebug.#{feature}.enableSites"] = true end # Closed by default, will open detached. self['extensions.firebug.framePosition'] = frame_position self['extensions.firebug.previousPlacement'] = 3 self['extensions.firebug.defaultPanelName'] = 'console' # Disable native "Inspect Element" menu item. self['devtools.inspector.enabled'] = false self['extensions.firebug.hideDefaultInspector'] = true end end end end end
ihmcrobotics/ihmc-open-robotics-software
ihmc-simple-whole-body-walking/src/main/java/us/ihmc/simpleWholeBodyWalking/SimpleControlManagerFactory.java
package us.ihmc.simpleWholeBodyWalking; import java.util.Collection; import java.util.HashMap; import java.util.Map; import gnu.trove.map.hash.TObjectDoubleHashMap; import us.ihmc.commonWalkingControlModules.capturePoint.BalanceManager; import us.ihmc.commonWalkingControlModules.capturePoint.CenterOfMassHeightManager; import us.ihmc.commonWalkingControlModules.configurations.ParameterTools; import us.ihmc.commonWalkingControlModules.configurations.WalkingControllerParameters; import us.ihmc.commonWalkingControlModules.controlModules.foot.FeetManager; import us.ihmc.commonWalkingControlModules.controlModules.pelvis.PelvisOrientationManager; import us.ihmc.commonWalkingControlModules.controlModules.rigidBody.RigidBodyControlManager; import us.ihmc.commonWalkingControlModules.controlModules.rigidBody.RigidBodyControlMode; import us.ihmc.commonWalkingControlModules.controllerCore.command.feedbackController.FeedbackControlCommandList; import us.ihmc.commonWalkingControlModules.momentumBasedController.HighLevelHumanoidControllerToolbox; import us.ihmc.commonWalkingControlModules.momentumBasedController.optimization.MomentumOptimizationSettings; import us.ihmc.euclid.geometry.Pose3D; import us.ihmc.euclid.referenceFrame.ReferenceFrame; import us.ihmc.euclid.tuple3D.interfaces.Vector3DReadOnly; import us.ihmc.graphicsDescription.yoGraphics.YoGraphicsListRegistry; import us.ihmc.log.LogTools; import us.ihmc.mecano.multiBodySystem.interfaces.RigidBodyBasics; import us.ihmc.robotics.contactable.ContactablePlaneBody; import us.ihmc.robotics.controllers.pidGains.PID3DGainsReadOnly; import us.ihmc.robotics.controllers.pidGains.PIDGainsReadOnly; import us.ihmc.robotics.controllers.pidGains.PIDSE3GainsReadOnly; import us.ihmc.robotics.controllers.pidGains.implementations.ParameterizedPIDGains; import us.ihmc.robotics.controllers.pidGains.implementations.ParameterizedPIDSE3Gains; import us.ihmc.robotics.dataStructures.parameters.ParameterVector3D; import us.ihmc.robotics.robotSide.RobotSide; import us.ihmc.yoVariables.parameters.DoubleParameter; import us.ihmc.yoVariables.providers.DoubleProvider; import us.ihmc.yoVariables.registry.YoRegistry; import us.ihmc.yoVariables.variable.YoDouble; public class SimpleControlManagerFactory { public static final String weightRegistryName = "MomentumOptimizationSettings"; public static final String jointspaceGainRegistryName = "JointspaceGains"; public static final String rigidBodyGainRegistryName = "RigidBodyGains"; public static final String footGainRegistryName = "FootGains"; public static final String comHeightGainRegistryName = "ComHeightGains"; private final YoRegistry registry = new YoRegistry(getClass().getSimpleName()); private final YoRegistry momentumRegistry = new YoRegistry(weightRegistryName); private final YoRegistry jointGainRegistry = new YoRegistry(jointspaceGainRegistryName); private final YoRegistry bodyGainRegistry = new YoRegistry(rigidBodyGainRegistryName); private final YoRegistry footGainRegistry = new YoRegistry(footGainRegistryName); private final YoRegistry comHeightGainRegistry = new YoRegistry(comHeightGainRegistryName); private SimpleBalanceManager balanceManager; private SimpleCenterOfMassHeightManager centerOfMassHeightManager; private SimpleFeetManager feetManager; private SimplePelvisOrientationManager pelvisOrientationManager; private final Map<String, RigidBodyControlManager> rigidBodyManagerMapByBodyName = new HashMap<>(); private HighLevelHumanoidControllerToolbox controllerToolbox; private WalkingControllerParameters walkingControllerParameters; private MomentumOptimizationSettings momentumOptimizationSettings; private final Map<String, PIDGainsReadOnly> jointGainMap = new HashMap<>(); private final Map<String, PID3DGainsReadOnly> taskspaceOrientationGainMap = new HashMap<>(); private final Map<String, PID3DGainsReadOnly> taskspacePositionGainMap = new HashMap<>(); private final Map<String, DoubleProvider> jointspaceWeightMap = new HashMap<>(); private final Map<String, DoubleProvider> userModeWeightMap = new HashMap<>(); private final Map<String, Vector3DReadOnly> taskspaceAngularWeightMap = new HashMap<>(); private final Map<String, Vector3DReadOnly> taskspaceLinearWeightMap = new HashMap<>(); private Vector3DReadOnly loadedFootAngularWeight; private Vector3DReadOnly loadedFootLinearWeight; private PIDSE3GainsReadOnly swingFootGains; private PIDSE3GainsReadOnly holdFootGains; private PIDGainsReadOnly walkingControllerComHeightGains; private DoubleProvider walkingControllerMaxComHeightVelocity; public SimpleControlManagerFactory(YoRegistry parentRegistry) { parentRegistry.addChild(registry); parentRegistry.addChild(momentumRegistry); parentRegistry.addChild(jointGainRegistry); parentRegistry.addChild(bodyGainRegistry); parentRegistry.addChild(footGainRegistry); parentRegistry.addChild(comHeightGainRegistry); } public void setHighLevelHumanoidControllerToolbox(HighLevelHumanoidControllerToolbox controllerToolbox) { this.controllerToolbox = controllerToolbox; } public void setWalkingControllerParameters(WalkingControllerParameters walkingControllerParameters) { this.walkingControllerParameters = walkingControllerParameters; momentumOptimizationSettings = walkingControllerParameters.getMomentumOptimizationSettings(); // Transform weights and gains to their parameterized versions. ParameterTools.extractJointGainMap(walkingControllerParameters.getJointSpaceControlGains(), jointGainMap, jointGainRegistry); ParameterTools.extract3DGainMap("Orientation", walkingControllerParameters.getTaskspaceOrientationControlGains(), taskspaceOrientationGainMap, bodyGainRegistry); ParameterTools.extract3DGainMap("Position", walkingControllerParameters.getTaskspacePositionControlGains(), taskspacePositionGainMap, bodyGainRegistry); ParameterTools.extractJointWeightMap("JointspaceWeight", momentumOptimizationSettings.getJointspaceWeights(), jointspaceWeightMap, momentumRegistry); ParameterTools.extractJointWeightMap("UserModeWeight", momentumOptimizationSettings.getUserModeWeights(), userModeWeightMap, momentumRegistry); ParameterTools.extract3DWeightMap("AngularWeight", momentumOptimizationSettings.getTaskspaceAngularWeights(), taskspaceAngularWeightMap, momentumRegistry); ParameterTools.extract3DWeightMap("LinearWeight", momentumOptimizationSettings.getTaskspaceLinearWeights(), taskspaceLinearWeightMap, momentumRegistry); loadedFootAngularWeight = new ParameterVector3D("LoadedFootAngularWeight", momentumOptimizationSettings.getLoadedFootAngularWeight(), momentumRegistry); loadedFootLinearWeight = new ParameterVector3D("LoadedFootLinearWeight", momentumOptimizationSettings.getLoadedFootLinearWeight(), momentumRegistry); swingFootGains = new ParameterizedPIDSE3Gains("SwingFoot", walkingControllerParameters.getSwingFootControlGains(), footGainRegistry); holdFootGains = new ParameterizedPIDSE3Gains("HoldFoot", walkingControllerParameters.getHoldPositionFootControlGains(), footGainRegistry); walkingControllerComHeightGains = new ParameterizedPIDGains("WalkingControllerComHeight", walkingControllerParameters.getCoMHeightControlGains(), comHeightGainRegistry); walkingControllerMaxComHeightVelocity = new DoubleParameter("MaximumVelocityWalkingControllerComHeight", comHeightGainRegistry, walkingControllerParameters.getMaximumVelocityCoMHeight()); } public SimpleBalanceManager getOrCreateBalanceManager() { if (balanceManager != null) return balanceManager; if (!hasHighLevelHumanoidControllerToolbox(BalanceManager.class)) return null; if (!hasWalkingControllerParameters(BalanceManager.class)) return null; if (!hasMomentumOptimizationSettings(BalanceManager.class)) return null; balanceManager = new SimpleBalanceManager(controllerToolbox, walkingControllerParameters, registry); return balanceManager; } public SimpleCenterOfMassHeightManager getOrCreateCenterOfMassHeightManager() { if (centerOfMassHeightManager != null) return centerOfMassHeightManager; if (!hasHighLevelHumanoidControllerToolbox(CenterOfMassHeightManager.class)) return null; if (!hasWalkingControllerParameters(CenterOfMassHeightManager.class)) return null; centerOfMassHeightManager = new SimpleCenterOfMassHeightManager(controllerToolbox, walkingControllerParameters, registry); centerOfMassHeightManager.setComHeightGains(walkingControllerComHeightGains, walkingControllerMaxComHeightVelocity); return centerOfMassHeightManager; } public RigidBodyControlManager getOrCreateRigidBodyManager(RigidBodyBasics bodyToControl, RigidBodyBasics baseBody, ReferenceFrame controlFrame, ReferenceFrame baseFrame) { if (bodyToControl == null) return null; String bodyName = bodyToControl.getName(); if (rigidBodyManagerMapByBodyName.containsKey(bodyName)) { RigidBodyControlManager manager = rigidBodyManagerMapByBodyName.get(bodyName); if (manager != null) return manager; } if (!hasWalkingControllerParameters(RigidBodyControlManager.class)) return null; if (!hasMomentumOptimizationSettings(RigidBodyControlManager.class)) return null; // Gains PID3DGainsReadOnly taskspaceOrientationGains = taskspaceOrientationGainMap.get(bodyName); PID3DGainsReadOnly taskspacePositionGains = taskspacePositionGainMap.get(bodyName); // Weights Vector3DReadOnly taskspaceAngularWeight = taskspaceAngularWeightMap.get(bodyName); Vector3DReadOnly taskspaceLinearWeight = taskspaceLinearWeightMap.get(bodyName); TObjectDoubleHashMap<String> homeConfiguration = walkingControllerParameters.getOrCreateJointHomeConfiguration(); Pose3D homePose = walkingControllerParameters.getOrCreateBodyHomeConfiguration().get(bodyName); RigidBodyBasics elevator = controllerToolbox.getFullRobotModel().getElevator(); YoDouble yoTime = controllerToolbox.getYoTime(); ContactablePlaneBody contactableBody = controllerToolbox.getContactableBody(bodyToControl); YoGraphicsListRegistry graphicsListRegistry = controllerToolbox.getYoGraphicsListRegistry(); RigidBodyControlMode defaultControlMode = walkingControllerParameters.getDefaultControlModesForRigidBodies().get(bodyName); RigidBodyControlManager manager = new RigidBodyControlManager(bodyToControl, baseBody, elevator, homeConfiguration, homePose, controlFrame, baseFrame, taskspaceAngularWeight, taskspaceLinearWeight, taskspaceOrientationGains, taskspacePositionGains, contactableBody, defaultControlMode, yoTime, graphicsListRegistry, registry); manager.setGains(jointGainMap); manager.setWeights(jointspaceWeightMap, userModeWeightMap); rigidBodyManagerMapByBodyName.put(bodyName, manager); return manager; } public SimpleFeetManager getOrCreateFeetManager() { if (feetManager != null) return feetManager; if (!hasHighLevelHumanoidControllerToolbox(FeetManager.class)) return null; if (!hasWalkingControllerParameters(FeetManager.class)) return null; if (!hasMomentumOptimizationSettings(FeetManager.class)) return null; feetManager = new SimpleFeetManager(controllerToolbox, walkingControllerParameters, swingFootGains, holdFootGains, registry); String footName = controllerToolbox.getFullRobotModel().getFoot(RobotSide.LEFT).getName(); Vector3DReadOnly angularWeight = taskspaceAngularWeightMap.get(footName); Vector3DReadOnly linearWeight = taskspaceLinearWeightMap.get(footName); if (angularWeight == null || linearWeight == null) { throw new RuntimeException("Not all weights defined for the foot control: " + footName + " needs weights."); } String otherFootName = controllerToolbox.getFullRobotModel().getFoot(RobotSide.RIGHT).getName(); if (taskspaceAngularWeightMap.get(otherFootName) != angularWeight || taskspaceLinearWeightMap.get(otherFootName) != linearWeight) { throw new RuntimeException("There can only be one weight defined for both feet. Make sure they are in the same GroupParameter"); } feetManager.setWeights(loadedFootAngularWeight, loadedFootLinearWeight, angularWeight, linearWeight); return feetManager; } public SimplePelvisOrientationManager getOrCreatePelvisOrientationManager() { if (pelvisOrientationManager != null) return pelvisOrientationManager; if (!hasHighLevelHumanoidControllerToolbox(PelvisOrientationManager.class)) return null; if (!hasWalkingControllerParameters(PelvisOrientationManager.class)) return null; if (!hasMomentumOptimizationSettings(PelvisOrientationManager.class)) return null; String pelvisName = controllerToolbox.getFullRobotModel().getPelvis().getName(); PID3DGainsReadOnly pelvisGains = taskspaceOrientationGainMap.get(pelvisName); Vector3DReadOnly pelvisAngularWeight = taskspaceAngularWeightMap.get(pelvisName); pelvisOrientationManager = new SimplePelvisOrientationManager(pelvisGains, controllerToolbox, registry); pelvisOrientationManager.setWeights(pelvisAngularWeight); pelvisOrientationManager.setPrepareForLocomotion(walkingControllerParameters.doPreparePelvisForLocomotion()); return pelvisOrientationManager; } private boolean hasHighLevelHumanoidControllerToolbox(Class<?> managerClass) { if (controllerToolbox != null) return true; missingObjectWarning(HighLevelHumanoidControllerToolbox.class, managerClass); return false; } private boolean hasWalkingControllerParameters(Class<?> managerClass) { if (walkingControllerParameters != null) return true; missingObjectWarning(WalkingControllerParameters.class, managerClass); return false; } private boolean hasMomentumOptimizationSettings(Class<?> managerClass) { if (momentumOptimizationSettings != null) return true; missingObjectWarning(MomentumOptimizationSettings.class, managerClass); return false; } private void missingObjectWarning(Class<?> missingObjectClass, Class<?> managerClass) { LogTools.warn(missingObjectClass.getSimpleName() + " has not been set, cannot create: " + managerClass.getSimpleName()); } public void initializeManagers() { if (balanceManager != null) balanceManager.initialize(); if (centerOfMassHeightManager != null) centerOfMassHeightManager.initialize(); if (pelvisOrientationManager != null) pelvisOrientationManager.initialize(); Collection<RigidBodyControlManager> bodyManagers = rigidBodyManagerMapByBodyName.values(); for (RigidBodyControlManager bodyManager : bodyManagers) { if (bodyManager != null) bodyManager.initialize(); } } public FeedbackControlCommandList createFeedbackControlTemplate() { FeedbackControlCommandList ret = new FeedbackControlCommandList(); if (feetManager != null) { FeedbackControlCommandList template = feetManager.createFeedbackControlTemplate(); for (int i = 0; i < template.getNumberOfCommands(); i++) ret.addCommand(template.getCommand(i)); } Collection<RigidBodyControlManager> bodyManagers = rigidBodyManagerMapByBodyName.values(); for (RigidBodyControlManager bodyManager : bodyManagers) { if (bodyManager != null) ret.addCommand(bodyManager.createFeedbackControlTemplate()); } if (centerOfMassHeightManager != null) ret.addCommand(centerOfMassHeightManager.createFeedbackControlTemplate()); if (pelvisOrientationManager != null) { ret.addCommand(pelvisOrientationManager.createFeedbackControlTemplate()); } return ret; } }
sodadata/soda-core
soda/core/soda/profiling/sample_tables_result.py
<reponame>sodadata/soda-core<gh_stars>1-10 from typing import List from soda.sampler.sample_ref import SampleRef from soda.sodacl.data_source_check_cfg import DataSourceCheckCfg class SampleTablesResultTable: def __init__(self, table_name: str, data_source: str, sample_ref: SampleRef): self.table_name: str = table_name self.data_source: str = data_source self.sample_ref: sample_ref = sample_ref def get_cloud_dict(self) -> dict: cloud_dict = { "table": self.table_name, "dataSource": self.data_source, "sampleFile": self.sample_ref.get_cloud_diagnostics_dict(), } return cloud_dict class SampleTablesResult: def __init__(self, data_source_check_cfg: DataSourceCheckCfg): self.data_source_check_cfg: DataSourceCheckCfg = data_source_check_cfg self.tables: List[SampleTablesResultTable] = [] def append_table(self, table_name: str, data_source_name: str, sample_ref: SampleRef) -> SampleTablesResultTable: table = SampleTablesResultTable(table_name, data_source_name, sample_ref) self.tables.append(table)
hernad/zimbra9
zm-mailbox/soap/src/java/com/zimbra/soap/mail/type/WatcherInfo.java
/* * ***** BEGIN LICENSE BLOCK ***** * Zimbra Collaboration Suite Server * Copyright (C) 2011, 2012, 2013, 2014, 2016 Synacor, Inc. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software Foundation, * version 2 of the License. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the 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 <https://www.gnu.org/licenses/>. * ***** END LICENSE BLOCK ***** */ package com.zimbra.soap.mail.type; import com.google.common.base.MoreObjects; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import java.util.Collections; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import com.zimbra.common.soap.MailConstants; @XmlAccessorType(XmlAccessType.NONE) public class WatcherInfo { /** * @zm-api-field-tag account-id * @zm-api-field-description Account ID */ @XmlAttribute(name=MailConstants.A_ID /* id */, required=true) private String id; /** * @zm-api-field-tag email-address * @zm-api-field-description Email address */ @XmlAttribute(name=MailConstants.A_EMAIL /* email */, required=true) private String email; /** * @zm-api-field-tag display-name * @zm-api-field-description Display name */ @XmlAttribute(name=MailConstants.A_NAME /* name */, required=true) private String name; /** * @zm-api-field-description List of items in the user's mailbox currently being watched by other users */ @XmlElement(name=MailConstants.E_ITEM /* item */, required=false) private List<IntegerIdAttr> items = Lists.newArrayList(); private WatcherInfo() { } private WatcherInfo(String id, String email, String name) { setId(id); setEmail(email); setName(name); } public static WatcherInfo createForIdEmailAndName(String id, String email, String name) { return new WatcherInfo(id, email, name); } public void setId(String id) { this.id = id; } public void setEmail(String email) { this.email = email; } public void setName(String name) { this.name = name; } public void setItems(Iterable <IntegerIdAttr> items) { this.items.clear(); if (items != null) { Iterables.addAll(this.items,items); } } public void addItem(IntegerIdAttr item) { this.items.add(item); } public String getId() { return id; } public String getEmail() { return email; } public String getName() { return name; } public List<IntegerIdAttr> getItems() { return Collections.unmodifiableList(items); } public MoreObjects.ToStringHelper addToStringInfo(MoreObjects.ToStringHelper helper) { return helper .add("id", id) .add("email", email) .add("name", name) .add("items", items); } @Override public String toString() { return addToStringInfo(MoreObjects.toStringHelper(this)).toString(); } }
RubbaBoy/jsyn
src/main/java/com/jsyn/unitgen/Grain.java
<gh_stars>100-1000 /* * Copyright 2011 <NAME>, Mobileer Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jsyn.unitgen; /** * A single Grain that is normally created and controlled by a GrainFarm. * * @author <NAME> (C) 2011 Mobileer Inc */ public class Grain implements GrainEnvelope { private double frameRate; private double amplitude = 1.0; private GrainSource source; private GrainEnvelope envelope; public Grain(GrainSource source, GrainEnvelope envelope) { this.source = source; this.envelope = envelope; } @Override public double next() { if (envelope.hasMoreValues()) { double env = envelope.next(); return source.next() * env * amplitude; } else { return 0.0; } } @Override public boolean hasMoreValues() { return envelope.hasMoreValues(); } @Override public void reset() { source.reset(); envelope.reset(); } public void setRate(double rate) { source.setRate(rate); } @Override public void setDuration(double duration) { envelope.setDuration(duration); } @Override public double getFrameRate() { return frameRate; } @Override public void setFrameRate(double frameRate) { this.frameRate = frameRate; source.setFrameRate(frameRate); envelope.setFrameRate(frameRate); } public double getAmplitude() { return amplitude; } public void setAmplitude(double amplitude) { this.amplitude = amplitude; } public GrainSource getSource() { return source; } }
IEnoobong/mmadu
mmadu-identity/src/main/java/com/mmadu/identity/providers/credentials/CredentialsHasher.java
package com.mmadu.identity.providers.credentials; import com.mmadu.identity.entities.ClientCredentials; import com.mmadu.identity.entities.ClientInstance; import com.mmadu.identity.entities.credentials.Credential; import com.mmadu.identity.entities.credentials.CredentialData; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.rest.core.annotation.HandleBeforeCreate; import org.springframework.data.rest.core.annotation.HandleBeforeSave; import org.springframework.data.rest.core.annotation.RepositoryEventHandler; import org.springframework.stereotype.Component; @Component @RepositoryEventHandler public class CredentialsHasher { private CredentialDataHashProvider hashProvider; private CredentialEncryptionProvider encryptionProvider; @Autowired public void setHashProvider(CredentialDataHashProvider hashProvider) { this.hashProvider = hashProvider; } @Autowired public void setEncryptionProvider(CredentialEncryptionProvider encryptionProvider) { this.encryptionProvider = encryptionProvider; } @HandleBeforeSave public void hashCredentialsBeforeSave(Credential credential) { hashCredentials(credential.getData()); } @HandleBeforeCreate public void hashCredentialsBeforeCreate(Credential credential) { hashCredentials(credential.getData()); } private void hashCredentials(CredentialData credentials) { credentials.hashData(hashProvider); credentials.encryptData(encryptionProvider); } }
devin-shi/angular-web-platform
node_modules/@delon/acl/esm2015/acl.js
import { Directive, ElementRef, Injectable, Input, NgModule, Renderer2 } from '@angular/core'; import { BehaviorSubject as BehaviorSubject$1 } from 'rxjs/BehaviorSubject'; import { Router } from '@angular/router'; import { Observable as Observable$1 } from 'rxjs/Observable'; import { of as of$1 } from 'rxjs/observable/of'; import { map, tap } from 'rxjs/operators'; import { CommonModule } from '@angular/common'; /** * @fileoverview added by tsickle * @suppress {checkTypes} checked by tsc */ /** * 访问控制服务 */ class ACLService { constructor() { this.roles = []; this.abilities = []; this.full = false; this.aclChange = new BehaviorSubject$1(null); } /** * ACL变更通知 * @return {?} */ get change() { return this.aclChange.asObservable(); } /** * 获取所有数据 * @return {?} */ get data() { return { full: this.full, roles: this.roles, abilities: this.abilities, }; } /** * @param {?} val * @return {?} */ parseACLType(val) { if (typeof val !== 'string' && !Array.isArray(val)) { return /** @type {?} */ (val); } if (Array.isArray(val)) { return /** @type {?} */ ({ role: /** @type {?} */ (val) }); } return /** @type {?} */ ({ role: [val], }); } /** * 设置当前用户角色或权限能力(会先清除所有) * @param {?} value * @return {?} */ set(value) { this.abilities = []; this.roles = []; this.add(value); this.aclChange.next(value); } /** * 标识当前用户为全量,即不受限 * @param {?} val * @return {?} */ setFull(val) { this.full = val; this.aclChange.next(val); } /** * 设置当前用户权限能力(会先清除所有) * @param {?} abilities * @return {?} */ setAbility(abilities) { this.set(/** @type {?} */ ({ ability: abilities })); } /** * 设置当前用户角色(会先清除所有) * @param {?} roles * @return {?} */ setRole(roles) { this.set(/** @type {?} */ ({ role: roles })); } /** * 为当前用户增加角色或权限能力 * @param {?} value * @return {?} */ add(value) { if (value.role && value.role.length > 0) { this.roles.push(...value.role); } if (value.ability && value.ability.length > 0) { this.abilities.push(...value.ability); } } /** * 为当前用户附加角色 * @param {?} roles * @return {?} */ attachRole(roles) { for (const /** @type {?} */ val of roles) { if (!this.roles.includes(val)) { this.roles.push(val); } } this.aclChange.next(this.data); } /** * 为当前用户附加权限 * @param {?} abilities * @return {?} */ attachAbility(abilities) { for (const /** @type {?} */ val of abilities) { if (!this.abilities.includes(val)) { this.abilities.push(val); } } this.aclChange.next(this.data); } /** * 为当前用户移除角色 * @param {?} roles * @return {?} */ removeRole(roles) { for (const /** @type {?} */ val of roles) { const /** @type {?} */ idx = this.roles.indexOf(val); if (idx !== -1) { this.roles.splice(idx, 1); } } this.aclChange.next(this.data); } /** * 为当前用户移除权限 * @param {?} abilities * @return {?} */ removeAbility(abilities) { for (const /** @type {?} */ val of abilities) { const /** @type {?} */ idx = this.abilities.indexOf(val); if (idx !== -1) { this.abilities.splice(idx, 1); } } this.aclChange.next(this.data); } /** * 当前用户是否有对应角色,其实 `number` 表示Ability * * - 当 `full: true` 或参数 `null` 时返回 `true` * - 若使用 `ACLType` 参数,可以指定 `mode` 校验模式 * @param {?} roleOrAbility * @return {?} */ can(roleOrAbility) { if (this.full === true || !roleOrAbility) { return true; } let /** @type {?} */ t = {}; if (typeof roleOrAbility === 'number') { t = { ability: [roleOrAbility] }; } else if (Array.isArray(roleOrAbility) && roleOrAbility.length > 0 && typeof roleOrAbility[0] === 'number') { t = { ability: roleOrAbility }; } else { t = this.parseACLType(roleOrAbility); } if (t.role) { if (t.mode === 'allOf') return t.role.every(v => this.roles.includes(v)); else return t.role.some(v => this.roles.includes(v)); } if (t.ability) { if (t.mode === 'allOf') return (/** @type {?} */ (t.ability)).every(v => this.abilities.includes(v)); else return (/** @type {?} */ (t.ability)).some(v => this.abilities.includes(v)); } return false; } /** * \@inner * @param {?} value * @return {?} */ parseAbility(value) { if (typeof value === 'number' || typeof value === 'string' || Array.isArray(value)) { value = /** @type {?} */ ({ ability: Array.isArray(value) ? value : [value] }); } delete value.role; return value; } /** * 当前用户是否有对应权限点 * @param {?} value * @return {?} */ canAbility(value) { return this.can(this.parseAbility(value)); } } ACLService.decorators = [ { type: Injectable }, ]; /** * @fileoverview added by tsickle * @suppress {checkTypes} checked by tsc */ class ACLDirective { /** * @param {?} el * @param {?} renderer * @param {?} srv */ constructor(el, renderer, srv) { this.el = el; this.renderer = renderer; this.srv = srv; this.change$ = /** @type {?} */ (this.srv.change.subscribe(() => this.set(this._value))); } /** * @param {?} value * @return {?} */ set acl(value) { this.set(value); } /** * @param {?} value * @return {?} */ set ability(value) { this.set(this.srv.parseAbility(value)); } /** * @param {?} value * @return {?} */ set(value) { const /** @type {?} */ CLS = 'acl__hide'; const /** @type {?} */ el = this.el.nativeElement; if (this.srv.can(value)) { this.renderer.removeClass(el, CLS); } else { this.renderer.addClass(el, CLS); } this._value = value; } /** * @return {?} */ ngOnDestroy() { this.change$.unsubscribe(); } } ACLDirective.decorators = [ { type: Directive, args: [{ selector: '[acl]', },] }, ]; /** @nocollapse */ ACLDirective.ctorParameters = () => [ { type: ElementRef, }, { type: Renderer2, }, { type: ACLService, }, ]; ACLDirective.propDecorators = { "acl": [{ type: Input, args: ['acl',] },], "ability": [{ type: Input, args: ['acl-ability',] },], }; /** * @fileoverview added by tsickle * @suppress {checkTypes} checked by tsc */ class DelonACLConfig { constructor() { /** * 路由守卫失败后跳转,默认:`/403` */ this.guard_url = '/403'; } } DelonACLConfig.decorators = [ { type: Injectable }, ]; /** * @fileoverview added by tsickle * @suppress {checkTypes} checked by tsc */ class ACLGuard { /** * @param {?} srv * @param {?} router * @param {?} options */ constructor(srv, router$$1, options) { this.srv = srv; this.router = router$$1; this.options = options; } /** * @param {?} guard * @return {?} */ process(guard) { return (guard && guard instanceof Observable$1 ? guard : of$1(typeof guard !== 'undefined' && guard !== null ? (/** @type {?} */ (guard)) : null)).pipe(map(v => this.srv.can(v)), tap(v => { if (v) return; this.router.navigateByUrl(this.options.guard_url); })); } /** * @param {?} route * @return {?} */ canLoad(route) { return this.process((route.data && route.data["guard"]) || null); } /** * @param {?} childRoute * @param {?} state * @return {?} */ canActivateChild(childRoute, state) { return this.canActivate(childRoute, state); } /** * @param {?} route * @param {?} state * @return {?} */ canActivate(route, state) { return this.process((route.data && route.data["guard"]) || null); } } ACLGuard.decorators = [ { type: Injectable }, ]; /** @nocollapse */ ACLGuard.ctorParameters = () => [ { type: ACLService, }, { type: Router, }, { type: DelonACLConfig, }, ]; /** * @fileoverview added by tsickle * @suppress {checkTypes} checked by tsc */ const SERVICES = [ACLService, ACLGuard]; const COMPONENTS = [ACLDirective]; class DelonACLModule { /** * @return {?} */ static forRoot() { return { ngModule: DelonACLModule, providers: [DelonACLConfig, ...SERVICES], }; } } DelonACLModule.decorators = [ { type: NgModule, args: [{ imports: [CommonModule], declarations: [...COMPONENTS], exports: [...COMPONENTS], },] }, ]; /** * @fileoverview added by tsickle * @suppress {checkTypes} checked by tsc */ /** * @fileoverview added by tsickle * @suppress {checkTypes} checked by tsc */ /** * Generated bundle index. Do not edit. */ export { ACLService, ACLDirective, DelonACLConfig, ACLGuard, DelonACLModule }; //# sourceMappingURL=acl.js.map
Oracle-Exam-Preparation/OCP
src/main/java/com/trl/theoreticalKnowledge/_enum/values/methods/a/a2/Example.java
<reponame>Oracle-Exam-Preparation/OCP package com.trl.theoreticalKnowledge._enum.methods.a.a2; public class Example { public static void main(String[] args) { } } enum Color { WHITE { public void doSomething() { System.out.println("WHITE"); } }, BLACK { public void doSomething() { System.out.println("BLACK"); } }, // Not compilation ERROR !!! This means that each and every enum value, not required to implement this method. RED, YELLOW; public void doSomething() { System.out.println("default action !!!"); } }
daxtens/travis-cookbooks
cookbooks/users/resources/github_keys.rb
<gh_stars>1-10 actions :create default_action :create attribute :id, kind_of: String, name_attribute: true attribute :github_username, kind_of: String
tianyudizhua/DanDanPlayForAndroid
app/src/main/java/com/xyoye/dandanplay/ui/weight/item/TorrentFileCheckItem.java
package com.xyoye.dandanplay.ui.weight.item; import android.graphics.drawable.Drawable; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.xyoye.dandanplay.R; import com.xyoye.dandanplay.bean.TorrentCheckBean; import com.xyoye.dandanplay.utils.CommonUtils; import com.xyoye.dandanplay.utils.interf.AdapterItem; import butterknife.BindView; /** * Created by xyoye on 2019/3/6. */ public class TorrentFileCheckItem implements AdapterItem<TorrentCheckBean> { @BindView(R.id.check_iv) ImageView checkIv; @BindView(R.id.file_name_tv) TextView fileNameTv; @BindView(R.id.file_size_tv) TextView fileSizeTv; private View mView; public TorrentFileCheckItem() { } @Override public int getLayoutResId() { return R.layout.item_torrent_file_check; } @Override public void initItemViews(View itemView) { mView = itemView; } @Override public void onSetViews() { } @Override public void onUpdateViews(TorrentCheckBean model, int position) { checkIv.setBackground(getCheckBoxBg(model.isChecked())); fileNameTv.setText(model.getName()); fileSizeTv.setText(CommonUtils.convertFileSize(model.getLength())); mView.setOnClickListener(v -> { model.setChecked(!model.isChecked()); checkIv.setBackground(getCheckBoxBg(model.isChecked())); }); } private Drawable getCheckBoxBg(boolean isCheck) { return isCheck ? CommonUtils.getResDrawable(R.drawable.ic_check_box_checked) : CommonUtils.getResDrawable(R.drawable.ic_check_box_uncheck); } }
VansPo/flickr-gallery
FlickrGallery/app/src/main/java/com/ipvans/flickrgallery/ui/main/MainAdapter.java
package com.ipvans.flickrgallery.ui.main; import android.support.v7.util.DiffUtil; import android.support.v7.widget.RecyclerView; import android.text.SpannableString; import android.text.Spanned; import android.text.TextUtils; import android.text.method.LinkMovementMethod; import android.text.style.ClickableSpan; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.ipvans.flickrgallery.R; import com.ipvans.flickrgallery.data.model.FeedItem; import com.ipvans.flickrgallery.utils.NoUnderlineClickableSpan; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class MainAdapter extends RecyclerView.Adapter<MainAdapter.ViewHolder> { private final TagClickListener tagClickListener; private LayoutInflater inflater; private List<FeedItem> items = new ArrayList<>(); public MainAdapter(TagClickListener tagClickListener) { this.tagClickListener = tagClickListener; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (inflater == null) inflater = LayoutInflater.from(parent.getContext()); return new ViewHolder(inflater.inflate(R.layout.item_main, parent, false)); } @Override public void onBindViewHolder(ViewHolder holder, int position) { holder.bind(items.get(position), position == items.size() - 1, tagClickListener); } @Override public int getItemCount() { return items.size(); } static class ViewHolder extends RecyclerView.ViewHolder { private ImageView image; private TextView title; private TextView author; private TextView tags; private View divider; ViewHolder(View itemView) { super(itemView); image = itemView.findViewById(R.id.image); title = itemView.findViewById(R.id.title); author = itemView.findViewById(R.id.author); tags = itemView.findViewById(R.id.tags); divider = itemView.findViewById(R.id.divider); } void bind(FeedItem item, boolean isLast, TagClickListener listener) { if (item.getMedia() != null && !TextUtils.isEmpty(item.getMedia().getUrl())) { Glide.with(itemView.getContext()) .load(item.getMedia().getUrl()) .centerCrop() .into(image); } title.setText(item.getTitle()); author.setText(itemView.getContext().getString(R.string.author, item.getAuthor())); divider.setVisibility(isLast ? View.GONE : View.VISIBLE); final SpannableString ss = new SpannableString(item.getTags()); final List<String> items = Arrays.asList(item.getTags().split(" ")); int start = 0, end; for (String tag : items) { end = start + tag.length(); if (start < end) { ss.setSpan(new NoUnderlineClickableSpan(v -> listener.onTagClicked(tag)), start, end, 0); } start += tag.length() + 1; } tags.setMovementMethod(LinkMovementMethod.getInstance()); tags.setText(ss, TextView.BufferType.SPANNABLE); } } void replace(List<FeedItem> data) { DiffUtil.DiffResult result = DiffUtil.calculateDiff(new FeedItemDiffUtil(items, data)); items.clear(); items.addAll(data); result.dispatchUpdatesTo(this); } void clear() { int size = items.size(); items.clear(); notifyItemRangeRemoved(0, size); } boolean isEmpty() { return items.isEmpty(); } public class FeedItemDiffUtil extends DiffUtil.Callback { private final List<FeedItem> oldList; private final List<FeedItem> newList; FeedItemDiffUtil(List<FeedItem> oldList, List<FeedItem> newList) { this.oldList = oldList; this.newList = newList; } @Override public int getOldListSize() { return oldList.size(); } @Override public int getNewListSize() { return newList.size(); } @Override public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) { return oldList.get(oldItemPosition).equals(newList.get(newItemPosition)); } @Override public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) { return oldList.get(oldItemPosition).equals(newList.get(newItemPosition)); } } interface TagClickListener { void onTagClicked(String tag); } }
iancardosozup/horusec
e2e/analysis/analysis_test.go
// Copyright 2021 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA // // 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 analysis_test import ( "encoding/json" "fmt" "os" "path/filepath" "runtime" "strings" "time" "github.com/ZupIT/horusec-devkit/pkg/enums/languages" "github.com/ZupIT/horusec-devkit/pkg/utils/logger" "github.com/google/uuid" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/ZupIT/horusec/config" "github.com/ZupIT/horusec/e2e/analysis" customimages "github.com/ZupIT/horusec/internal/entities/custom_images" "github.com/ZupIT/horusec/internal/utils/testutil" ) const ( isWindows = runtime.GOOS == "windows" isDarwin = runtime.GOOS == "darwin" horusecConfigName = "horusec-config.json" ) var _ = Describe("Run a complete horusec analysis when build tools locally", func() { tmpDir := CreateHorusecConfigAndReturnTMPDirectory() Describe("Running e2e tests when build tools locally", func() { allTestsCases := analysis.NewTestCase() for idx, testCase := range allTestsCases { if !isDarwin { horusecConfigFilePathBuildLocally := filepath.Join(tmpDir, horusecConfigName) RunTestCase(testCase, horusecConfigFilePathBuildLocally, "(build locally)", idx, len(allTestsCases)) time.Sleep(2 * time.Second) } horusecConfigFilePathDownloadFromDockerHub := filepath.Join(allTestsCases[idx].Command.Flags[testutil.StartFlagProjectPath], horusecConfigName) RunTestCase(testCase, horusecConfigFilePathDownloadFromDockerHub, "(download from dockerhub)", idx, len(allTestsCases)) time.Sleep(2 * time.Second) } }) AfterEach(func() { if err := os.RemoveAll(tmpDir); err != nil { Fail(fmt.Sprintf("Error on remove tmp folder: %v", err)) } }) }) func RunTestCase(testCase *analysis.TestCase, horusecConfigFilePath, runType string, idx, lenTestCase int) { testCase.Command.Flags[testutil.GlobalFlagConfigFilePath] = horusecConfigFilePath if isWindows && testCase.RequiredDocker { logger.LogInfo("Tool ignored because is required docker: ", runType, testCase.Tool, fmt.Sprintf("[%v/%v]", idx+1, lenTestCase)) return } logger.LogInfo("Preparing test for run e2e: ", runType, testCase.Tool, fmt.Sprintf("[%v/%v]", idx+1, lenTestCase)) session, err := testCase.RunAnalysisTestCase() if err != nil { Fail(fmt.Sprintf("Error on run analysis Test Case %s: %v", runType, err)) } session.Wait(testutil.AverageTimeoutAnalyzeForExamplesFolder) testCase.Command.Output = string(session.Out.Contents()) testCase.Command.ExitCode = session.ExitCode() It(fmt.Sprintf("Execute command without error for %s: %s", runType, testCase.Tool), func() { Expect(testCase.Command.ExitCode).Should(Equal(0)) }) It(fmt.Sprintf("Validate is outputs expected exists on tool %s: %s", runType, testCase.Tool), func() { for _, outputExpected := range testCase.Expected.OutputsContains { Expect(testCase.Command.Output).Should( ContainSubstring(outputExpected), fmt.Sprintf("The output [%s] not exist in output", outputExpected), testCase.Command.Output, ) } }) It(fmt.Sprintf("Validate is outputs not expected exists on tool %s: %s", runType, testCase.Tool), func() { for _, outputNotExpected := range testCase.Expected.OutputsNotContains { Expect(testCase.Command.Output).ShouldNot( ContainSubstring(outputNotExpected), fmt.Sprintf("The output [%s] exist in output", outputNotExpected), testCase.Command.Output, ) } }) } func CreateHorusecConfigAndReturnTMPDirectory() string { tmpDir := filepath.Join(os.TempDir(), "horusec-analysis-e2e-"+uuid.NewString()) horusecConfigPath := filepath.Join(tmpDir, horusecConfigName) if err := os.MkdirAll(tmpDir, os.ModePerm); err != nil { Fail(fmt.Sprintf("Error on create tmp folder: %v", err)) } horusecConfigFile, err := os.Create(horusecConfigPath) if err != nil { Fail(fmt.Sprintf("Error on create config file for scan on e2e test %v", err)) } horusecConfig := config.New() newCustomImages := customimages.Default() for k := range newCustomImages { if k == languages.CSharp { newCustomImages[k] = strings.ToLower("local-csharp:local") } else { newCustomImages[k] = strings.ToLower(fmt.Sprintf("local-%s:local", k)) } } horusecConfig.CustomImages = newCustomImages horusecConfigBytes, err := json.MarshalIndent(horusecConfig.ToMapLowerCase(), "", " ") if err != nil { Fail(fmt.Sprintf("Error on marshall horusec-config.json %v", err)) } _, err = horusecConfigFile.Write(horusecConfigBytes) if err != nil { Fail(fmt.Sprintf("Error on write config file for scan on e2e test %v", err)) } return tmpDir }
Leringit/Exercicios-de-Estudo-Paketa
exe07 - TrelloGenerico/class2/projects/crypto-currency/iluminados/api/src/routes/modules/logout.js
<gh_stars>1-10 import express from "express"; const app = express(); app.use(express.json()); app.get("./logout", function (req, res) { req.logout(); req.session.destroy(function (error) { res.redirect("./login"); }); }); export default app;
jiachen247/llvm-sauce
tests/sicp/chapter1/section3/subsection2/3.js
<reponame>jiachen247/llvm-sauce function sum(term, a, next, b) { return a > b ? 0 : term(a) + sum(term, next(a), next, b); } function pi_sum(a,b) { return sum(x => 1.0 / (x * (x + 2)), a, x => x + 4, b); } 8 * pi_sum(1, 1000); // expected: 3.139593
JaneliaSciComp/osgpyplusplus
src/modules/osg/generated_code/CoordinateSystemNode.pypp.hpp
// This file has been generated by Py++. #ifndef CoordinateSystemNode_hpp__pyplusplus_wrapper #define CoordinateSystemNode_hpp__pyplusplus_wrapper void register_CoordinateSystemNode_class(); #endif//CoordinateSystemNode_hpp__pyplusplus_wrapper
circinusX1/qgetic
getic/docsave.cpp
// z_ed2Doc.cpp : implementation of the Document class // #include "stdafx.h" #include "texref.h" #include "document.h" #include "view2d.h" #include "view3d.h" #include <algorithm> #include "lightbulb.h" #include "triggeritem.h" #include "sounditem.h" #include "gameitem.h" #include "geticapp.h" #include "cwaitcursor.h" #include "progressdlg.h" #define CHECK_COUNT(c_,max_,_expsion) if(c_>max_ ||c_<0)throw _expsion; int32_t Version = 0; //--------------------------------------------------------------------------------------- u_bool32 __FixBadName(char* pszname) { char invalids[] ="!@#$%^&^*()_+~|}{():\"\'.,<>?/-=\\]["; char* pinvalid = invalids; while(*pinvalid) { StripChar(pszname,*(pinvalid++)); } return 0; } //--------------------------------------------------------------------------------------- void CDocSaver::SerializeDoc(u_bool32 selection) { theApp->ReDir(); theApp->_errors.clear(); if(!this->FileWrap::Open(_filename.c_str(), _bsave ? "wb": "rb")) { return; } CWaitCursor cwc; _pTerBrush = 0; _selection = (_filename.find(".grs") != -1); _pref = (_filename.find(".gpm") != -1); SerializeHeader(); if(_selection) { SerializeTextures(); SerializeBrushes(); return; } if(!_pref) { SerializeScene(); SerializeSettings(); SerializeCompSettings(); } test(); SerializeTextures(); SerializeBrushes(); SerializeTerrain(); if(!_pref) { SerializeItems(); SerializeMotions(); SerializeScripts(); SerializeCatFiles(); SerializeDescriptions(); if(!_bsave) { Pd->_use2splitidx = tmax(_maxspliterIdx+1, Pd->_use2splitidx); } } Pd->RecreateAmbLmap(); if(!theApp->_errors.empty()) { char cd[255]; string all; int32_t lines = 0; getcwd(cd,254); all = "\r\n"; all += cd; all += "\r\nCannot Find: \r\n"; FOREACH(vvector<string>, theApp->_errors, pps) { all += *pps; all += "\r\n"; if(++lines>32) { all += "..."; break; } } theApp->_errors.clear(); TAfxMessageBox(all.c_str(), MB_OK|MB_ICONWARNING); } } //---------------------------------------------------------------------------------------- void CDocSaver::SerializeHeader() { char szSig[5]; if(_pref) ::strcpy(szSig, GeticPrimitiveFile); else ::strcpy(szSig, GeticGeometryRawFile); this->Serialize(szSig,4); if(!_bsave) { if(!strcmp(szSig,GeticPrimitiveFile)) { _pref=1; } else if(strcmp(szSig,GeticGeometryRawFile)) { throw "Invalid File Signature"; } } this->test(); this->Serialize(_version); Version = _version; if(_version < DOC_VERSION4) { throw "Invalid File Version. "; } } //---------------------------------------------------------------------------------------- void CDocSaver::SerializeScene() { size_t sz = sizeof(SCENE()._si); assert(this->Serialize(SCENE()._si)); if(!_bsave) { if(_version < DOC_VERSION5) { SCENE()._si.fogNear = 0; SCENE()._si.fogFar = 0; SCENE()._si.fogDens = 0; SCENE()._si.fogColor = ZWHITE; } } } //---------------------------------------------------------------------------------------- void CDocSaver::SerializeSettings() { View2D* pTX = VIEW2D('z'); View2D* pTY = VIEW2D('y'); View2D* pTZ = VIEW2D('x'); this->test(); this->Serialize(GCarving); this->Serialize(pTX->_zoom); this->Serialize(pTX->_shifty); this->Serialize(pTX->_shiftx); this->Serialize(pTY->_zoom); this->Serialize(pTY->_shifty); this->Serialize(pTY->_shiftx); this->Serialize(pTZ->_zoom); this->Serialize(pTZ->_shifty); this->Serialize(pTZ->_shiftx); this->Serialize(Pd->_cam._pos); this->Serialize(Pd->_cam._euler); } //---------------------------------------------------------------------------------------- void CDocSaver::SerializeCompSettings() { this->Serialize(COMP()->_bSaveFinalBSP); this->Serialize(COMP()->_szipit); this->Serialize(COMP()->_bSaveImages); this->Serialize(COMP()->_maxFacesLeaf); this->Serialize(COMP()->_bSaveCats); this->Serialize(COMP()->_bSavePortals); this->Serialize(COMP()->_bPolySortCrit); this->Serialize(COMP()->_bMergeNarrowLeafs); this->Serialize(COMP()->_bSaveSkyDom); this->Serialize(COMP()->_bLightMaps); this->Serialize(COMP()->_b3SampleLM); this->Serialize(COMP()->_bAvoidNonOrt); this->Serialize(COMP()->_bUseUserPriority); this->Serialize(COMP()->_bPvsMethod); this->Serialize(COMP()->_bZones); this->Serialize(COMP()->_bPvsMethod); // dup this->Serialize(COMP()->_removeOnePolyLeaf); this->Serialize(COMP()->_portalCutFlag); this->Serialize(COMP()->_balance); this->Serialize(COMP()->_lmapMaxSize); this->Serialize(COMP()->_lMapLumelSz); this->Serialize(COMP()->_bLmPatch); this->Serialize(COMP()->_bExportFile); if(_version >= DOC_VERSION5) { this->Serialize(COMP()->_bSaveBigTerrain); this->Serialize(COMP()->_bSaveBigTerrainBSP); } if(_version >= DOC_VERSION7) { this->Serialize(COMP()->_bConvexEarly); // additional data added this->Serialize(COMP()->_bCompressPvs); this->Serialize(COMP()->_bAABBTreeCsgTer); this->Serialize(COMP()->_lmpowof2); this->Serialize(COMP()->_lmConst); this->Serialize(COMP()->_bGeticBSP ); this->Serialize(COMP()->_bPolySortCrit); // dup this->Serialize(COMP()->_bConvexEarly); //here next used var this->Serialize(COMP()->_bConvexEarly); } if(_version >= DOC_VERSION8) { int32_t dummy; this->Serialize(COMP()->_lmapIntens); this->Serialize(dummy); // dummy this->Serialize(dummy); this->Serialize(dummy); } } //---------------------------------------------------------------------------------------- void CDocSaver::SerializeTextures() { this->test(); int32_t nCount = 0; if(_bsave) { // // count textures (excluding lightmaps). we dont save lmaps at all // TexSys::iterator bt = theApp->_TexSys.begin(); TexSys::iterator et = theApp->_TexSys.end(); for(;bt != et; bt++) { Texture& tex = (*bt).second; if(!strncmp(tex.filename, "@L",2)) continue; ++nCount; } this->Write(nCount); int32_t cntTex = 0; _texassoc[_dumptex.hTex] = -1; bt = theApp->_TexSys.begin(); for(;bt != et; bt++) { Texture& tex = (*bt).second; //80 is sieze of T if(!strncmp(tex.filename, "@L",2)) { continue; } _texassoc[tex.hTex.hTex] = cntTex++; // map index with texid this->Write(tex); } return; } size_t sz = 0; if(_version < DOC_VERSION10) sz = sizeof(Fl_TextureOld); else sz = sizeof(Fl_Texture); Fl_Texture tex_new ; Fl_TextureOld tex ; //TODO DANGER SIZE FT_ this->Read(nCount); for(int32_t i=0; i < nCount; i++) { CHECK_COUNT(nCount,65535,"To many textures: Limit is 65535"); if(_version < DOC_VERSION10) { this->Read(tex); if(tex.cx==0 || tex.cy==0) continue; if(tex.cx>=2048 || tex.cy>=2048) continue; if(_version < DOC_VERSION5) { tex.hTex.glTarget= 0; tex.hTex.envMode = 0; tex.hTex.genST = 0; } Fl_Texture tex2(tex); Texture ttx(tex2); _texNames.push_back(ttx); } else { this->Read(tex_new); if(tex_new.cx==0 || tex_new.cy==0) continue; if(tex_new.cx>=2048 || tex_new.cy>=2048) continue; if(_version < DOC_VERSION5) { tex_new.hTex.glTarget= 0; tex_new.hTex.envMode = 0; tex_new.hTex.genST = 0; } Texture ttx(tex_new); _texNames.push_back(ttx); } } } //---------------------------------------------------------------------------------------- void CDocSaver::SerializeBrushes() { if(_bsave) { PBrushes* brshses = 0 ; if(_selection) brshses = &Pd->_pSelBrushes; else brshses = SCENE().GetPrimitives(); int32_t nBrushes = brshses->size(); this->Write(nBrushes); FOREACH(PBrushes, (*brshses), ppb) { Brush* pB = (*ppb); pB->Recalc(); SerializeBrush(pB); } } else { int32_t nBrushes; if(_pref) nBrushes=1; else { this->Read(nBrushes); } CHECK_COUNT(nBrushes,32768 ,"To many brushes: Limit is 32768"); for(int32_t ib=0; ib<nBrushes;ib++) { Brush* pB = new Brush; SerializeBrush(pB); Pd->AddBrush(pB); if(!pB->IsSolid() || pB->IsProjector()) { Pd->SelectBrush(pB); } } ++Brush::GID; } } //---------------------------------------------------------------------------------------- void CDocSaver::SerializeBrush(Brush* pB) { this->test(); this->Serialize(pB->_unicID ); this->Serialize(pB->_t ); this->Serialize(pB->_r ); this->Serialize(pB->_s ); this->Serialize(pB->_brushflags ); this->Serialize(pB->_brushprops ); this->Serialize(pB->_physicsA); this->Serialize(pB->_rotSteps); this->Serialize(pB->_rotSteps); this->Serialize(pB->_physicsD); size_t sss = sizeof(pB->_cf); this->Serialize(pB->_cf); // creation flags this->Serialize(pB->_polySec); this->Serialize(pB->_thikness); memset(pB->_name, 0, sizeof(pB->_name)); this->Serialize(pB->_name, 16); this->Serialize(pB->_group ); if(_bsave) { int32_t motionIdx = SCENE().GetIndex(pB->_pMotion); this->Write(motionIdx); int32_t nCountPolys = pB->_polys.size(); this->Write(nCountPolys); FOREACH(Polys, pB->_polys, pp) { SerializePolygon(pB, &(*pp)); } } else { pB->_group += Pd->_maxUsedGrp; int32_t motionIdx ; this->Read(motionIdx); if(motionIdx>=0) // for redoing the pointer in the motion object { _dynaBrushes[pB->_unicID] = pB; // store this brush here, process later } pB->_pMotion = 0; int32_t nCountPolys ; this->Read(nCountPolys ); CHECK_COUNT(nCountPolys,1024, MKSTR("To many polygons per brush %s: Limit is 1024",pB->_name)); for(int32_t vx=0; vx < nCountPolys ; vx++) { do{ Poly pl; SerializePolygon(pB, &pl); pB->_polys << pl; pl.Clear(); }while(0); } if(pB->_brushflags & BRSH_BIGTERRAIN) { _pTerBrush = pB; } pB->Dirty(1); pB->Recalc(1); Brush::GID = tmax(Brush::GID, pB->_unicID); } KEEP_WAIT(MKSTR("Processing Brush %d ",pB->_unicID)); } //---------------------------------------------------------------------------------------- void CDocSaver::SerializePolygon(Brush* pB, Poly* pp) { for(int32_t k=0;k<4;k++) { if(_bsave) { map<int32_t, int32_t>::iterator fi = _texassoc.find((int32_t)pp->GetHtex(k)); if(fi != _texassoc.end()) { int32_t fisec = fi->second; this->Write(fisec); } else { int32_t it = -1; this->Write(it); } this->Write(pp->Apply(k)); } else { int32_t texID, applyTex; this->test(); this->Read(texID); this->Read(applyTex); if(texID >=0 && (u_int32_t)texID < _texNames.size()) { pp->SetApply(applyTex,k); pp->SetTex(_texNames[texID].filename, k, _texNames[texID].hTex.glTarget); if(_dumptex == pp->GetHtex(k)) { string serr = _texNames[texID].filename; theApp->_errors.push_unique(serr); } } } } u_int32_t utempval = pp->Combine(); this->Serialize(utempval); this->Serialize(pp->_polyflags); this->Serialize(pp->_polyflags2); this->Serialize(pp->_polyprops); this->Serialize(pp->_use2splitidx); this->Serialize(pp->_texcoord ); this->Serialize(pp->_lmInfo); this->Serialize(pp->_colorD); this->Serialize(pp->_colorE); this->Serialize(pp->_colorS); this->Serialize(pp->_shiness); this->Serialize(pp->_tanimA); this->Serialize(pp->_tanimB); this->Serialize(pp->_texV1); this->Serialize(pp->_texV2); this->Serialize(pp->_bump); this->Serialize(pp->_friction); if(_bsave) { //TODO DANGER SIZE FT_ int32_t nCount = (*pp)._vtci.size(); this->Write(nCount); FOREACH(vvector<Vtx2>, pp->_vtci, pv) { this->Write((*pv));//sizeof is 96 } } else { _maxspliterIdx = tmax(_maxspliterIdx, pp->_use2splitidx); pp->_pBrush = pB; int32_t nVxes = 0; this->Read(nVxes); CHECK_COUNT(nVxes,128, MKSTR("Too many vertexes per polygon: %s",pB->_name)); Fl_Vtx2_Old vtx_old; Fl_Vtx2 vtx; size_t sznew = sizeof(vtx); for(int32_t v=0; v < nVxes; v++) { if(_version < DOC_VERSION10) { this->Read(&vtx_old, sizeof(vtx_old)); //84 Fl_Vtx2 new_vx(vtx_old); Vtx2 fvtx(new_vx); pp->_vtci << fvtx; } else { this->Read(&vtx, sizeof(vtx)); Vtx2 fvtx(vtx); pp->_vtci << fvtx; } } pp->Recalc(); } } //--------------------------------------------------------------------------------------- void CDocSaver::SerializeItems() { int32_t nItemsCount; if(_bsave) { nItemsCount = Pd->GetItems()->size(); this->Serialize(nItemsCount); FOREACH(vvector<SceItem*>, (*Pd->GetItems()), ppi) { SceItem* pi = *ppi; SerializeItem(pi); } } else { this->Serialize(nItemsCount); CHECK_COUNT(nItemsCount,2048,"Too many items per scene: Limit is 2048"); for(int32_t vx=0; vx < nItemsCount ; vx++) { SceItem* pi = SerializeItem(0); SceItem::_GItemID = tmax(SceItem::_GItemID, (int32_t)pi->_id); pi->_flags &= ~BRSH_NEW; pi->Commit(); SCENE().AddItem(pi); BARDLG()->AddItem(pi); } ++SceItem::_GItemID; } } //---------------------------------------------------------------------------------------- SceItem* CDocSaver::SerializeItem(SceItem* pi) { if(!pi) //load { int32_t itemItem; this->Read(itemItem); pi = SceItem::CreateSci(itemItem); } else { this->Write(pi->_item); } pi->Serialize(this, _texNames, _texassoc); return pi; } //---------------------------------------------------------------------------------------- void CDocSaver::SerializeMotions() { if(_bsave) { int32_t nCount = SCENE().GetMotions()->size(); this->Write(nCount); FOREACH(vvector<CMotion*>, (*SCENE().GetMotions()), ppMotion) { CMotion* pM = *ppMotion; this->Write(pM->_bLoop); this->Write(pM->_center); this->Write(pM->_pBrush->_unicID); int32_t nCount = pM->GetNodesCount(); this->Write(nCount); for(int32_t i=0; i<nCount; i++) { MState* pS = pM->GetState(i); this->Write(pS->_pos); this->Write(pS->_euler); this->Write(pS->_trTimes[0]); this->Write(pS->_trTimes[1]); this->Write(pS->_trRots[0]); this->Write(pS->_trRots[1]); } } } else { int32_t nCount = 0,nIndex=0; this->Read(nCount); CHECK_COUNT(nCount,128,"Too many motions: Limit is 128"); for (int32_t i=0;i<nCount;i++) { CMotion* pM = new CMotion(0, 0, 0); this->Read(pM->_bLoop); this->Read(pM->_center); // // link them back // this->Read(nIndex); // uuid of brush pM->_pBrush = _dynaBrushes[nIndex]; // take it from array if(pM->_pBrush) { pM->_pBrush->_pMotion = pM; // link back } this->Read(pM->_iNodes); for(int32_t i=0; i < pM->_iNodes; i++) { MState state; this->Read(state._pos); this->Read(state._euler); this->Read(state._trTimes[0]); this->Read(state._trTimes[1]); this->Read(state._trRots[0]); this->Read(state._trRots[1]); pM->_states << state; } if(pM->_pBrush) SCENE().AddMotion(pM); else delete pM; } } } //---------------------------------------------------------------------------------------- void CDocSaver::SerializeScripts() { if(_bsave) { int32_t tmpVal = 0; int32_t nCount = SCENE().GetScripts()->size(); this->Write(nCount); FOREACH(vvector<ScriptItem*>, (*SCENE().GetScripts()), ppScript) { ScriptItem* pSi = *ppScript; tmpVal = pSi->_name.length(); this->Write(tmpVal); this->Write((void*)pSi->_name.c_str(),pSi->_name.length()); tmpVal = pSi->_script.length(); this->Write(tmpVal); this->Write((void*)pSi->_script.c_str(), pSi->_script.length()); } } else { int32_t nCount = 0; int32_t nLength = 0; char szBuff[_MAX_PATH]; char* pszScr; this->Read(nCount); CHECK_COUNT(nCount,256, "Too many scipt items: Limit is 256"); for(int32_t i=0; i<nCount; i++) { ScriptItem* pSci = new ScriptItem(); // script file name this->Read(nLength); memset(szBuff,0,sizeof(szBuff)); this->Read(szBuff, nLength); pSci->_name = szBuff; // script content this->Read(nLength); pszScr = new char[nLength]; if(pszScr) { memset(pszScr,0,sizeof(nLength)); this->Read(pszScr, nLength); pSci->_script = pszScr; SCENE().AddScript(pSci); delete[] pszScr; } else { delete pSci; } } } } //---------------------------------------------------------------------------------------- void CDocSaver::SerializeCatFiles() { char sFileName[_MAX_PATH] = {0}; if(_bsave) { if(theApp->XsdCatItmFile()[0]) strcpy(sFileName, theApp->XsdCatItmFile()); this->Write((void*)sFileName,_MAX_PATH); } else { this->Read((void*)sFileName,_MAX_PATH); if(sFileName[0]) { if(SCENE().SearchCats((char*)sFileName)) { theApp->XsdCatItmFile((char*)sFileName); } } } } //---------------------------------------------------------------------------------------- void CDocSaver::SerializeTerrain() { CBigTerrain& terr = SCENE().Terrain(); if(_bsave) { terr.Serialize(this, _texNames, _texassoc); } else if(_version >= DOC_VERSION5) // load these sections { terr.Serialize(this, _texNames, _texassoc); terr.p_dummyBrush = _pTerBrush; if(_pTerBrush) _pTerBrush->_pUsrData = &terr; } } //---------------------------------------------------------------------------------------- void CDocSaver::SerializeDescriptions() { BTF_Details detcell; int32_t ncount = 0; map<string ,string>& descs = SCENE().Descriptions(); if(_bsave) { ncount = descs.size(); this->Write(ncount); for(map<string ,string>::iterator b = descs.begin(); b != descs.end(); b++) { SCopy(detcell.name, (char*)(*b).first.c_str(), sizeof(detcell.name)); detcell.length = (*b).second.length(); this->Write(detcell); this->WriteTextAsIs((*b).second.c_str()); } } else if(_version >= DOC_VERSION5)// load these sections { char tmp[16384]; this->Read(ncount); CHECK_COUNT(ncount,1024, "Too many detail descriptors. Limit is 1024"); for(int32_t i=0; i < ncount; i++) { this->Read(detcell); this->Read(tmp, detcell.length); tmp[detcell.length] = 0; descs[detcell.name] = tmp; } } } //---------------------------------------------------------------------------------------- void Document::SavePrefFile() { /* theApp->ReDir(); DlgCpxPrimnames d; if(d.DoModal() == IDOK) { theApp->ReDir(); CDirChange cdd(d._curPath.c_str()); cdd.UseObj(); PBrushes* pBrushes = _scene.GetBrushes(); FOREACH(PBrushes, (*pBrushes), ppCpxBrush) { do{ Brush brush = *(*ppCpxBrush); brush.Recalc(); v3d_t center = brush._box.GetCenter(); brush.Move(-center); char locName[64]; _tcscpy(locName, brush._name); if(__FixBadName(locName)) continue; CDocSaver ds(MKSTR("%s.gpm",locName), true, true); if(ds.Open()) { ds.SerializeHeader(); ds.SerializeTextures(); ds.SerializeBrush(&brush); ds.Close(); } }while(0); } } (VIEW3D(0,0))->SetFocus(); */ } //---------------------------------------------------------------------------------------- u_bool32 Document::LoadPrefFile(const char* szFileName, Brush** pBRet) { Brush* pB = 0; CDirChange cdd(""); cdd.UseObj(); CDocSaver ds(szFileName, false); // load, pref try { if(ds.Open()) { ds.SerializeHeader(); if(ds.IsPerf()) { ds.SerializeTextures(); if(pB = new Brush()) { do{ CDirChange cdc(""); theApp->ReDir(); ds.SerializeBrush(pB); pB->_unicID = Brush::GID++; }while(0); pB->_pMotion=0; if(!(pB->_brushflags & BRSH_SOLID) && !pB->IsProjector()) { SelectBrush(pB); Recut(); } } } ds.Close(); } } catch(const string ex) { TAfxMessageBox(ex.c_str(),MB_OK|MB_ICONHAND); delete pB; pB = 0; } catch(...) { TAfxMessageBox("File Is Malformated or file version is too old.",MB_OK|MB_ICONHAND); delete pB; pB = 0; } if(pBRet) { *pBRet = pB; } return pB!=0; } //---------------------------------------------------------------------------------------- class NO_VT VRMLWritter { public: VRMLWritter(FileWrap* pfw):_pfw(pfw),_tabs(0){} void Write(const char* p,...) { va_list args; va_start(args, p); ::snprintf(_s, sizeof(_s) / sizeof(char), p, args); va_end(args); for(int32_t i=0; i<_tabs; i++) _pfw->WriteTextAsIs(" "); _pfw->WriteTextAsIs(_s); _pfw->WriteTextAsIs("\r\n"); } void Tab(){ for(int32_t i=0; i<_tabs; i++) _pfw->WriteTextAsIs(" "); } void WriteValNoCR(const char* p,...) { va_list args; va_start(args, p); ::snprintf(_s, sizeof(_s) / sizeof(char), p, args); va_end(args); _pfw->WriteTextAsIs(_s); } void WriteValue(const char* sect, char* p) { for(int32_t i=0; i<_tabs; i++) _pfw->WriteTextAsIs(" "); _pfw->WriteTextAsIs(MKSTR("%s\t",sect)); _pfw->WriteTextAsIs(p); _pfw->WriteTextAsIs("\r\n"); } void WriteValue(const char* sect) { for(int32_t i=0; i<_tabs; i++) _pfw->WriteTextAsIs(" "); _pfw->WriteTextAsIs(MKSTR("%s\r\n",sect)); } void WriteValue(const char* sect, v2d_t& f) { for(int32_t i=0; i<_tabs; i++) _pfw->WriteTextAsIs(" "); _pfw->WriteTextAsIs(MKSTR("%s\t",sect)); _pfw->WriteTextAsIs(MKSTR("%f %f", f.u,f.v)); _pfw->WriteTextAsIs("\r\n"); } void WriteValue(const char* sect, u_rgba_t& f) { for(int32_t i=0; i<_tabs; i++) _pfw->WriteTextAsIs(" "); _pfw->WriteTextAsIs(MKSTR("%s\t",sect)); _pfw->WriteTextAsIs(MKSTR("%d ", f.r)); _pfw->WriteTextAsIs(MKSTR("%d ", f.g)); _pfw->WriteTextAsIs(MKSTR("%d ", f.b)); _pfw->WriteTextAsIs(MKSTR("%d", f.a)); _pfw->WriteTextAsIs("\r\n"); } void WriteValue(const char* sect, v3d_t& f) { for(int32_t i=0; i<_tabs; i++) _pfw->WriteTextAsIs(" "); _pfw->WriteTextAsIs(MKSTR("%s\t",sect)); _pfw->WriteTextAsIs(MKSTR("%f ", f.x)); _pfw->WriteTextAsIs(MKSTR("%f ", f.y)); _pfw->WriteTextAsIs(MKSTR("%f", f.z)); _pfw->WriteTextAsIs("\r\n"); } void WriteValue(const char* sect, u_int32_t f) { WriteValue(sect, (int32_t) f); } void WriteValue(const char* sect, u_int64_t f) { WriteValue(sect, (u_int64_t) f); } void WriteValue(const char* sect, int32_t f) { for(int32_t i=0; i<_tabs; i++) _pfw->WriteTextAsIs(" "); _pfw->WriteTextAsIs(MKSTR("%s\t",sect)); _pfw->WriteTextAsIs(MKSTR("%d", f)); _pfw->WriteTextAsIs("\r\n"); } void WriteValue(const char* sect, float f) { for(int32_t i=0; i<_tabs; i++) _pfw->WriteTextAsIs(" "); _pfw->WriteTextAsIs(MKSTR("%s\t",sect)); _pfw->WriteTextAsIs(MKSTR("%f", (float)f)); _pfw->WriteTextAsIs("\r\n"); } void Open(char* p) { int32_t i; for( i=0; i<_tabs; i++) _pfw->WriteTextAsIs(" "); _pfw->WriteTextAsIs(p); _pfw->WriteTextAsIs("\r\n"); for(i=0; i<_tabs; i++) _pfw->WriteTextAsIs(" "); _pfw->WriteTextAsIs("{\r\n"); ++_tabs; } void Close() { --_tabs; _pfw->WriteTextAsIs("\r\n"); for(int32_t i=0; i<_tabs; i++) _pfw->WriteTextAsIs(" "); _pfw->WriteTextAsIs("}\r\n"); } private: char _s[512]; FileWrap* _pfw; int32_t _tabs; }; struct XmlFace{ XmlFace():vxi(4),tc1i(4),tc2i(4),tc3i(4){} vvector<int32_t> vxi; vvector<int32_t> tc1i; vvector<int32_t> tc2i; vvector<int32_t> tc3i; int32_t clri[3]; //asde Poly* pPoly; }; typedef struct _GUID { u_int32_t Data1; u_int16_t Data2; u_int16_t Data3; u_int8_t Data4[8]; } GUID; //--------------------------------------------------------------------------------------- void Document::SaveInXML(const char* pSzName, u_bool32 bBrshes) { map<int32_t,int32_t> texids; int32_t idx = 0; FileWrap fw; int32_t fileVer = DOC_VERSION5; int32_t cntTex=0; GUID g = {0}; CWaitCursor cwc; theApp->ReDir(); BARDLG()->OnApply() ; fw.Open(pSzName,"wb"); VRMLWritter w(&fw); w.Open((char*)MKSTR("getic #%d",DOC_VERSION10)); w.Open("level"); if(_scene._si.sceneSpash>=0) w.WriteValue(MKSTR("splash '%s'",_scene._si.sceneSpash)); w.WriteValue("author", _scene._si.author); w.WriteValue("comments",_scene._si.comments); w.WriteValue("leveltype",_scene._si.levelType); w.WriteValue("actors",_scene._si.maxActors); w.WriteValue("fargs",_scene._si.maxFrags); w.WriteValue("time",_scene._si.maxTime); w.Close(); w.Open("scene"); w.WriteValue("coordsystem","left"); if(GMeters == 1) w.WriteValue("measureunit", "centimeter radians"); else if(GMeters == 100) w.WriteValue("measureunit", "meter radians"); else w.WriteValue("measureunit", "feet radians"); w.WriteValue("globallight",_scene._si.defLumin); w.WriteValue("gravitation",-(int32_t)_scene._si.gravAcc); if(_scene._si.fogNear ||_scene._si.fogFar) { w.Open("fog"); w.WriteValue("near",_scene._si.fogNear); w.WriteValue("far",_scene._si.fogFar); w.WriteValue("color",_scene._si.fogColor); w.WriteValue("density",_scene._si.fogDens); w.WriteValue("falloff",_scene._si.fogFallOff); w.Close(); } w.Open("camera"); w.WriteValue("position", _cam._pos); w.WriteValue("orientation", _cam._euler); w.WriteValue("focalDistance", 8.0f); w.WriteValue("heightAngle", _scene._si.camFov); w.Close(); w.Open("textures"); texids[0] = 0; // map index with texid TexSys::iterator bt = theApp->_TexSys.begin(); TexSys::iterator et = theApp->_TexSys.end(); for(;bt != et; bt++) { Texture& tex = (*bt).second; texids[tex.hTex.hTex] = cntTex++; if(! strncmp(tex.filename, "@L", 2)) { continue; } w.Write("filename '%s' %d %d %d %x", tex.filename, tex.cx, tex.cy, tex.bpp, tex.hTex.glTarget); } w.Close(); vvector<XmlFace> faces(4096); vvector<u_rgba_t> colors(4096); vvector<v3d_t> vxes(16384); vvector<v2d_t> tcs(8912); u_int32_t k; PBrushes* brshses = _scene.GetPrimitives(); FOREACH(PBrushes, (*brshses), ppb) { Brush* pB = (*ppb)->_pResult; FOREACH(Polys, pB->_polys, pp) { XmlFace xf; xf.pPoly = (Poly*)&(*pp); k = colors.push_unique(pp->_colorD); xf.clri[0] = k; k = colors.push_unique(pp->_colorS); xf.clri[1] = k; k = colors.push_unique(pp->_colorE); xf.clri[2] = k; FOREACH(vvector<Vtx2>, pp->_vtci, pv) { vxes.push_unique((pv)->_xyz,&k); xf.vxi << k; tcs.push_unique((pv)->_uv[0],&k); xf.tc1i << k; tcs.push_unique((pv)->_uv[1],&k); xf.tc2i << k; tcs.push_unique((pv)->_uv[2],&k); xf.tc3i << k; } faces << xf; } } w.Open("points3Df"); FOREACH(vvector<v3d_t>, vxes, pv3) { w.WriteValue("", *pv3); // index } w.Close(); w.Open("points2Df"); FOREACH(vvector<v2d_t>, tcs, puv) { w.WriteValue("", *puv); // index } w.Close(); w.Open("colrs4ub"); FOREACH(vvector<u_rgba_t>, colors, pcrl) { w.WriteValue("", *pcrl); // index } w.Close(); w.Open("faces"); int32_t index=0; FOREACH(vvector<XmlFace>, faces, pxmlf) { w.Open((char*)MKSTR("%d", index++)); if(pxmlf->pPoly->_polyflags || pxmlf->pPoly->_polyflags2) w.Write("flags %x %x %x ", pxmlf->pPoly->_polyprops, pxmlf->pPoly->_polyflags, pxmlf->pPoly->_polyflags2); w.Write("textureindex %d", texids[pxmlf->pPoly->GetHtex(0)]); if(pxmlf->pPoly->Apply(0)) w.Write("texapplymodes %x", pxmlf->pPoly->Apply(0)); w.Write("colorindex %d %d %d",pxmlf->clri[0], pxmlf->clri[1], pxmlf->clri[2]); if(pxmlf->pPoly->_shiness) w.Write("shiness %d",pxmlf->pPoly->_shiness); if(pxmlf->pPoly->_bump!=1) w.Write("physics %f %f",pxmlf->pPoly->_bump, pxmlf->pPoly->_friction); if(pxmlf->pPoly->_use2splitidx!=-1) w.WriteValue("splitter",pxmlf->pPoly->_use2splitidx); w.Open("vertexes"); vvector<int32_t>::iterator ivx = pxmlf->vxi.begin(); vvector<int32_t>::iterator itc1i = pxmlf->tc1i.begin(); // vvector<int32_t>::iterator itc2i = pxmlf->tc2i.begin(); // vvector<int32_t>::iterator itc3i = pxmlf->tc3i.begin(); w.Tab(); for(;ivx != pxmlf->vxi.end();ivx++, itc1i++)//, itc3i++, itc2i++) { w.WriteValNoCR("[%d %d] ",*ivx, *itc1i);//, *itc2i, *itc3i); } w.Close(); w.Close(); } w.Close(); w.Open("brushes"); vvector<XmlFace>::iterator xmlfi = faces.begin(); int32_t fIdx=0; FOREACH(PBrushes, (*brshses), ppb) { Brush* pB = (*ppb)->_pResult; pB->_name[15] = 0; w.Open(pB->_name); w.Write("flags %x %x",pB->_brushflags, pB->_brushprops); if(pB->_group) w.Write("group %d",pB->_group); int32_t idxMotion = _scene.GetIndex(pB->_pMotion); if(idxMotion!=-1) w.WriteValue("motionsindex",idxMotion); w.Open("faceindexes"); idx = 0; w.Tab(); FOREACH(Polys, pB->_polys, pp) { w.WriteValNoCR("%d ",fIdx++); } w.Close(); w.Close(); } w.Close(); w.Open("items"); { FOREACH(vvector<SceItem*>, (*GetItems()), pItemPtr) { SceItem* pItem = *pItemPtr; pItem->_name[24] = 0; w.Open(pItem->_name); { w.WriteValue("type",pItem->_item); w.WriteValue("group",pItem->_group); w.WriteValue("category",(char*)pItem->_catname); w.Write("flags %x %x",pItem->_props, pItem->_flags); w.WriteValue("color4ub",pItem->_colorD); w.WriteValue("position",pItem->_t); w.WriteValue("scalation",pItem->_s); w.WriteValue("orientation",pItem->_euler); w.WriteValue("texture", (char*)MKSTR("%d %d",texids[pItem->GetHtex(0)],pItem->Apply(0))); switch(pItem->_item) { default: break; case ITM_LIGTBULB: w.WriteValue("specularangle",((CLightBulb*)pItem)->_specAngle); w.WriteValue("intensity",((CLightBulb*)pItem)->_lmIntensity); w.WriteValue("maximradius",((CLightBulb*)pItem)->_radius); w.WriteValue("minimhallo",((CLightBulb*)pItem)->_halloRadMin); w.WriteValue("maximhallo",((CLightBulb*)pItem)->_halloRadMax); break; case ITM_TRIGER: { u_int32_t ptr = -1; v3d_t ex = ((TriggerItem*)pItem)->_drawBrush._box.GetExtends(); w.WriteValue("effectpoint",((TriggerItem*)pItem)->_efectPoint); w.WriteValue("extends",ex); } break; } w.Close(); } } w.Close(); } w.Open("motions"); { FOREACH(vvector<CMotion*>, (*_scene.GetMotions()), ppMotion) { CMotion* pM = *ppMotion; w.WriteValue("closed", pM->_bLoop); w.WriteValue("center",pM->_center); w.WriteValue("brushindex", pM->_pBrush->_unicID); w.Open("path"); { for(int32_t i=0;i<pM->GetNodesCount();i++) { MState* pS = pM->GetState(i); w.WriteValue("position", pS->_pos); w.WriteValue("orientation", pS->_euler); } w.Close(); } } w.Close(); } w.Open("scripts"); FOREACH(vvector<ScriptItem*>, (*_scene.GetScripts()), ppScript) { ScriptItem* pSi = *ppScript; w.Open("script"); { fw.Write((void*)pSi->_script.c_str(),pSi->_script.length()); w.Close(); } } w.Close(); } //--------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------- void Document::ReadFromFile(const char* szFilename) { Invalidate(); //theApp->PumpMessage(WM_PAINT,10); char sigFile[5] = {0}; FileWrap fw; if(!fw.Open(szFilename,"rb")) { TAfxMessageBox(MKSTR("Cannot Open The File: '%s'. Error: %d ", szFilename, GetLastError()),MB_OK|MB_ICONHAND); return; } fw.Read(sigFile,4); if(strcmp(sigFile,"GGRF") && strcmp(sigFile,"GPGF")) { fw.Close(); TAfxMessageBox("Current File Is Not a Getic Geometry File",MB_OK|MB_ICONHAND); return; } fw.Read(i_geomfilever); fw.Close(); if(i_geomfilever == DOC_VERSION3 || i_geomfilever == DOC_VERSION2) { TAfxMessageBox("Very old files are not longer suported...",MB_OK|MB_ICONHAND); return ; } else if(i_geomfilever >= DOC_VERSION4) { START_WAIT("Please Wait..."); CDocSaver cfv(szFilename, false); try{ GCur g(VIEW3D(0,0)); cfv.SerializeDoc(0); Recut(); DeselectAll(); //(VIEW3D(0,0))->SetFocus(); END_WAIT(""); //AfxGetMainWnd()->SendMessage(WM_COMMAND, PB_REFR); Pd->Invalidate(); return; }catch(const char* ex) { END_WAIT(""); TAfxMessageBox(ex,MB_OK|MB_ICONHAND); } catch(...) { END_WAIT(""); TAfxMessageBox("Unknkown Exception. File is malformated",MB_OK|MB_ICONHAND); } } else { TAfxMessageBox("Error Reading File. Version Not Longer Supported",MB_OK|MB_ICONHAND); } InitDocVars(); //(VIEW3D(0,0))->SetFocus(); //AfxGetMainWnd()->SendMessage(WM_COMMAND, PB_REFR); Pd->Invalidate(); } void Document::ReadFromBSP(const char* szFilename) { }
apocalyptech/minecraftxray
src/com/apocalyptech/minecraft/xray/BlockTypeFilename.java
<gh_stars>10-100 /** * Copyright (c) 2010-2012, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Minecraft X-Ray team nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL VINCENT VOLLERS OR CJ KUCERA 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. */ package com.apocalyptech.minecraft.xray; import java.util.Map; import java.util.HashMap; import java.util.ArrayList; import java.awt.Color; import java.io.InputStream; import java.io.IOException; import static com.apocalyptech.minecraft.xray.MinecraftConstants.*; /** */ public class BlockTypeFilename extends BlockType { // YAML Attributes private String tex; private HashMap<Integer, String> tex_data; private HashMap<String, String> tex_direction; private HashMap<DIRECTION_REL, String> tex_direction_int; private HashMap<String, String> tex_extra; // Attributes brought over from BlockTypeCollection public String texpath; public BlockTypeFilename() { super(); } public void setTex(String tex) { this.tex = tex; } public String getTex() { return this.tex; } public void setTex_data(HashMap<Integer, String> tex_data) { this.tex_data = tex_data; } public HashMap<Integer, String> getTex_data() { return this.tex_data; } public void setTex_direction(HashMap<String, String> tex_direction) { this.tex_direction = tex_direction; } public HashMap<String, String> getTex_direction() { return this.tex_direction; } public void setTex_extra(HashMap<String, String> tex_extra) { this.tex_extra = tex_extra; } public HashMap<String, String> getTex_extra() { return this.tex_extra; } /** * Pulls data from the master collection */ public void pullDataFromCollection(BlockTypeCollection collection) { super.pullDataFromCollection(collection); this.texpath = collection.getTexpath(); } /** * Returns the full filename for the given texture file */ private String getFullTextureFilename(String filename) { return this.texpath + "/" + filename; } /** * Gets a list of all texture filenames we're using */ public ArrayList<String> getTextureFilenames() { HashMap<String, Integer> tempMap = new HashMap<String, Integer>(); ArrayList<String> list = new ArrayList<String>(); list.add(this.tex); if (this.tex_data != null) { for (String tex : this.tex_data.values()) { if (!tempMap.containsKey(tex)) { tempMap.put(tex, null); list.add(tex); } } } if (this.tex_direction_int != null) { for (String tex : this.tex_direction_int.values()) { if (!tempMap.containsKey(tex)) { tempMap.put(tex, null); list.add(tex); } } } if (this.tex_extra != null) { for (String tex : this.tex_extra.values()) { if (!tempMap.containsKey(tex)) { tempMap.put(tex, null); list.add(tex); } } } return list; } /** * Sets our "real" texture values * * TODO: Exception error reporting */ public void setTextureFilenameMapping(HashMap<String, Integer> texmap) throws BlockTypeLoadException { // First the "main" texture if (texmap.containsKey(this.tex)) { this.tex_idx = texmap.get(this.tex); } else { throw new BlockTypeLoadException("No texture mapping found for " + this.tex); } // Now data the data mapping if (this.tex_data != null && this.tex_data.size() > 0) { this.texture_data_map = new HashMap<Byte, Integer>(); for (Map.Entry<Integer, String> entry : this.tex_data.entrySet()) { if (texmap.containsKey(entry.getValue())) { this.texture_data_map.put(entry.getKey().byteValue(), texmap.get(entry.getValue())); } else { throw new BlockTypeLoadException("No texture mapping found for " + entry.getValue()); } } } // Now direction data mapping if (this.tex_direction_int != null && this.tex_direction_int.size() > 0) { this.texture_dir_map = new HashMap<DIRECTION_REL, Integer>(); for (Map.Entry<DIRECTION_REL, String> entry : this.tex_direction_int.entrySet()) { if (texmap.containsKey(entry.getValue())) { this.texture_dir_map.put(entry.getKey(), texmap.get(entry.getValue())); } else { throw new BlockTypeLoadException("No texture mapping found for " + entry.getValue()); } } } // Now the "extra" textures if (this.tex_extra != null && this.tex_extra.size() > 0) { this.texture_extra_map = new HashMap<String, Integer>(); for (Map.Entry<String, String> entry : this.tex_extra.entrySet()) { if (texmap.containsKey(entry.getValue())) { this.texture_extra_map.put(entry.getKey(), texmap.get(entry.getValue())); } else { throw new BlockTypeLoadException("No texture mapping found for " + entry.getValue()); } } } } /** * Attempts to open the file, to make sure that it's readable before we go * any further. This should be the full path, post-normalization. */ private static void checkTextureAvailability(String filename) throws BlockTypeLoadException { try { InputStream stream = MinecraftEnvironment.getMinecraftTexturepackData(filename); if (stream == null) { throw new BlockTypeLoadException("File " + filename + " is not found"); } stream.close(); } catch (IOException e) { throw new BlockTypeLoadException("Error while opening " + filename + ": " + e.toString(), e); } } /** * Normalizes our data from what we get from YAML, to a format that's * easier to deal with in X-Ray. * * TODO: Exception error reporting */ public void normalizeData() throws BlockTypeLoadException { // First check our super super.normalizeData(); // Now check for some required attributes if (this.tex == null || this.tex.length() == 0) { throw new BlockTypeLoadException("tex is a required attribute"); } // Now do the actual normalizing... Modify our textures to use the full path this.tex = this.getFullTextureFilename(this.tex); checkTextureAvailability(this.tex); if (this.tex_data != null && this.tex_data.size() > 0) { for (Map.Entry<Integer, String> entry : this.tex_data.entrySet()) { entry.setValue(this.getFullTextureFilename(entry.getValue())); checkTextureAvailability(entry.getValue()); } } if (this.tex_direction != null && this.tex_direction.size() > 0) { this.tex_direction_int = new HashMap<DIRECTION_REL, String>(); for (Map.Entry<String, String> entry: this.tex_direction.entrySet()) { DIRECTION_REL dir; try { dir = DIRECTION_REL.valueOf(entry.getKey()); } catch (IllegalArgumentException e) { throw new BlockTypeLoadException("Invalid relative direction: " + entry.getKey()); } this.tex_direction_int.put(dir, this.getFullTextureFilename(entry.getValue())); checkTextureAvailability(this.tex_direction_int.get(dir)); } } if (this.tex_extra != null && this.tex_extra.size() > 0) { for (Map.Entry<String, String> entry : this.tex_extra.entrySet()) { entry.setValue(this.getFullTextureFilename(entry.getValue())); checkTextureAvailability(entry.getValue()); } } } }
apdoerL/condition-order-server
condition-core/src/main/java/org/apdoer/condition/core/utils/RedisKeyBuildUtils.java
<filename>condition-core/src/main/java/org/apdoer/condition/core/utils/RedisKeyBuildUtils.java package org.apdoer.condition.core.utils; public class RedisKeyBuildUtils { private static final String PUSH_USER_GROUP_REDIS_KEY = "PUG_";// 用户组 public static String buildPushUserGroupRedisKey(Integer userId) { return PUSH_USER_GROUP_REDIS_KEY + userId; } }
MultiCoreNetwork/AIO
plugin/src/main/java/it/multicoredev/aio/storage/config/sections/AfkSection.java
<filename>plugin/src/main/java/it/multicoredev/aio/storage/config/sections/AfkSection.java package it.multicoredev.aio.storage.config.sections; import com.google.gson.annotations.SerializedName; import it.multicoredev.mclib.json.JsonConfig; import java.util.ArrayList; import java.util.List; /** * Copyright © 2021 - 2022 by <NAME> * This file is part of AIO. * AIO is under "The 3-Clause BSD License", you can find a copy <a href="https://opensource.org/licenses/BSD-3-Clause">here</a>. * <p> * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * <p> * 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. */ public class AfkSection extends JsonConfig { @SerializedName("afk_cooldown") private Integer afkCooldown; @SerializedName("afk_remove_on_movement") public Boolean afkRemoveOnMovement; @SerializedName("afk_remove_on_click") public Boolean afkRemoveOnInteract; @SerializedName("afk_remove_on_message") public Boolean afkRemoveOnMessage; @SerializedName("afk_remove_on_command") public Boolean afkRemoveOnCommand; @SerializedName("afk_remove_on_damage") public Boolean afkRemoveOnDamage; @SerializedName("afk_invulnerability") public Boolean afkInvulnerability; @SerializedName("show_in_display_name") public Boolean modifyDisplayName; @SerializedName("afk_remove_command_blacklist") private List<String> afkRemoveCommandBlacklist; @Override public void init() { if (afkCooldown == null) afkCooldown = 60; if (afkRemoveOnMovement == null) afkRemoveOnMovement = true; if (afkRemoveOnInteract == null) afkRemoveOnInteract = true; if (afkRemoveOnMessage == null) afkRemoveOnMessage = true; if (afkRemoveOnCommand == null) afkRemoveOnCommand = true; if (afkRemoveOnDamage == null) afkRemoveOnDamage = false; if (afkInvulnerability == null) afkInvulnerability = false; if (modifyDisplayName == null) modifyDisplayName = false; if (afkRemoveCommandBlacklist == null) afkRemoveCommandBlacklist = new ArrayList<>(); } public boolean hasAfkCooldown() { return afkCooldown > 0; } public Integer getAfkCooldown() { return afkCooldown; } public boolean isCommandBlacklisted(String cmd) { return afkRemoveCommandBlacklist.stream().anyMatch(cmd::equalsIgnoreCase); } }
KxmischesDomi/Utility
jda-manager/src/main/java/net/anweisen/utilities/jda/manager/EventCreator.java
<filename>jda-manager/src/main/java/net/anweisen/utilities/jda/manager/EventCreator.java package net.anweisen.utilities.jda.manager; import net.anweisen.utilities.jda.manager.hooks.event.CommandEvent; import net.anweisen.utilities.jda.manager.hooks.registered.RegisteredCommand; import net.anweisen.utilities.jda.manager.process.CommandPreProcessInfo; import javax.annotation.Nonnull; /** * @author anweisen | https://github.com/anweisen * @since 1.0 */ public interface EventCreator { @Nonnull CommandEvent createEvent(@Nonnull CommandManager manager, @Nonnull CommandPreProcessInfo info, @Nonnull RegisteredCommand command, boolean useEmbeds); }
BD2K-DDI/ddi-service-db
src/main/java/uk/ac/ebi/ddi/service/db/service/similarity/ITermInDBService.java
package uk.ac.ebi.ddi.service.db.service.similarity; import org.bson.types.ObjectId; import org.springframework.data.domain.Page; import org.springframework.stereotype.Repository; import uk.ac.ebi.ddi.service.db.model.similarity.TermInDB; import java.util.List; /** * Created by mingze on 30/07/15. */ @Repository public interface ITermInDBService { /** * Create a new term in the MongoDB * * @param termInDB the term to be inserted in the database * @return the inserted term */ TermInDB insert(TermInDB termInDB); List<TermInDB> insert(List<TermInDB> terms); /** * read a term from database * * @param id of the term entry in database * @return a term */ TermInDB read(ObjectId id); /** * Read all the terms from the database * * @return A list of terms */ Page<TermInDB> readAll(int pageStart, int size); /** * Update a term entry in the database using the new information * * @param termInDB the new datasetAccess information * @return the updated datasetAccess. */ TermInDB update(TermInDB termInDB); /** * Remove a DatasetAccess in the Database using the id. * * @param id Identifier of the term to be removed from the database * @return the removed term */ TermInDB delete(ObjectId id); TermInDB readByName(String termName); boolean isTermExist(String termName); long getNumberOfTermsInDB(); void deleteAll(); List<TermInDB> readAllInOneType(String dataType); List<TermInDB> readAllUncalculatedTermsInOneType(String dataType); }
jesse-gallagher/XPagesExtensionLibrary
extlib/lwp/product/runtime/eclipse/plugins/com.ibm.xsp.extlib.domino/resources/web/dwa/lv/nls/iw/listview_c.js
({ D_DIR_DEFAULT: "rtl", D_GIGABYTES: "%1G", D_KILOBYTES: "%1K", D_MEGABYTES: "%1M", D_NUMFMT_DECIMALSYMBOL: ".", D_NUMFMT_THOUSANDSSEPARATOR: ",", D_PADDING_REVERSE: "padding-left", D_TERABYTES: "%1T" })
mccormickmichael/laurel
scaffold/iam/group_sync.py
import logging from . import load_policy_map logger = logging.getLogger('laurel.iam.GroupSync') class GroupSync(object): def __init__(self, boto3_session, iam_stack_name=None): self._session = boto3_session self._iam = self._session.resource('iam') self._policy_map = load_policy_map(boto3_session, iam_stack_name) def sync(self, group_dict, dry_run): current_groups = self._iam.groups.all() defined_group_names = group_dict.keys() current_group_names = [g.name for g in current_groups] logger.info('current groups: {}'.format(sorted(current_group_names))) logger.info('defined groups: {}'.format(sorted(defined_group_names))) groups_to_create = [g for g in defined_group_names if g not in current_group_names] groups_to_update = [g for g in current_groups if g.name in defined_group_names] self.create_groups(groups_to_create, group_dict, dry_run) self.update_groups(groups_to_update, group_dict, dry_run) def create_groups(self, names, group_dict, dry_run): # TODO: honor dry_run parameter for name in names: policy_names = group_dict[name] logger.info('creating group {}'.format(name)) group = self._iam.create_group(GroupName=name) for policy_name in policy_names: logger.info('attaching policy {} to group {}'.format(policy_name, name)) group.attach_policy(PolicyArn=self.get_policy_arn(policy_name)) def update_groups(self, groups, group_dict, dry_run): # TODO: honor dry_run parameter for group in groups: current_policies = group.attached_policies.all() defined_policy_names = group_dict[group.name] current_policy_names = [p.policy_name for p in current_policies] # !!BUG!! policy names for policies created by CloudFormation are the CF resource names # These will not match the names given in the group_dict. # group_dict uses the CF logical name. # moving all policy management out of CF will fix this issue. policy_arns_to_detach = [p.arn for p in current_policies if p.policy_name not in defined_policy_names] policy_names_to_attach = [p for p in defined_policy_names if p not in current_policy_names] for arn in policy_arns_to_detach: logger.info('detaching {} from group {}'.format(arn, group.name)) group.detach_policy(PolicyArn=arn) for name in policy_names_to_attach: arn = self.get_policy_arn(name) logger.info('attaching {} to group {}'.format(arn, group.name)) group.attach_policy(PolicyArn=arn) def get_policy_arn(self, policy_name): return self._policy_map[policy_name]
ocamler/expense-www
src/js/date/components/details.js
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { AmountItem } from './amount_item'; @connect( state => ({ details: state.details }) ) export default class extends Component { render() { const { method_payment, amounts } = this.props.details; const total = amounts.reduce((prevVal, i) => { return prevVal + parseFloat(i.amount); }, 0.00); return ( <div> <h4 className="text-center close-bottom"> <small>{'Payment Method:'}</small> {' '} {method_payment} </h4> <h4 className="text-center close-bottom"> <small>{'Items:'}</small> </h4> <ul className="expenseItemReview"> {amounts.map(i => ( <AmountItem key={i.id} id={i.id} amount={i.amount} cat_desc={i.cat_desc} isTaxd={i.isTaxd} /> ))} </ul> {amounts.length > 1 ? ( <p className="text-center"> <i>{'Total: $'}<b>{total}</b></i> </p> ) : ''} </div> ) } } // TODO: put all this info in a <table>
enerc/zsearch
src/queries/model/and.cpp
#include "and.hpp" #include "../../queries/builders/ast.hpp" using namespace std; namespace queries::model { void AndModel::execute(queries::builders::AST *ast) { if (exprList.size() != 2) { Log::error(ast->getQueryStatus(),"SQL query AND should have 2 childrens. "+ast->getSaveqQuery()); return; } auto a = exprList.at(0)->getWorkingSet(); auto b = exprList.at(1)->getWorkingSet(); if (a == nullptr || b == nullptr || exprList.at(0)->getWorkingSetSize() != exprList.at(1)->getWorkingSetSize()) { Log::error(ast->getQueryStatus(),"SQL query AND failed "+ast->getSaveqQuery()); return; } allocWorkingSet(exprList.at(0)->getWorkingSetSize()); fastAnd(workingSet,a,b,workingSetSize); exprList.at(0)->freeWorkingSet(); exprList.at(1)->freeWorkingSet(); nbResults = fastCount(workingSet,workingSetSize); } }
nicho92/mtgDesktopCompanion
src/main/java/org/magic/api/beans/audit/TaskInfo.java
<filename>src/main/java/org/magic/api/beans/audit/TaskInfo.java package org.magic.api.beans.audit; import java.time.Instant; public class TaskInfo extends AbstractAuditableItem { public enum STATE {NEW,STARTED,CANCELED,FINISHED} public enum TYPE {WORKER,RUNNABLE} private static final long serialVersionUID = 1L; private Instant created; private String name; private STATE status = STATE.NEW; private TYPE type=TYPE.RUNNABLE; private transient Runnable runnable; public Instant getCreated() { return created; } public void setCreated(Instant createdDate) { this.created = createdDate; } public TaskInfo(Runnable r) { this.runnable=r; created = Instant.now(); } public void setStatus(STATE status) { this.status = status; } public STATE getStatus() { return status; } public String getName() { return name; } public void setName(String name) { this.name = name; } public TYPE getType() { return type; } public void setType(TYPE type) { this.type = type; } public void setRunnable(Runnable runnable) { this.runnable=runnable; } public Runnable getRunnable() { return runnable; } }
tes/marketplace-demo
src/mixins/authDialog.js
<filename>src/mixins/authDialog.js import * as mutationTypes from 'src/store/mutation-types' export default { methods: { openAuthDialog ({ persistent = false, formType, redirectAfterSignup = false, action } = {}) { if (formType) { this.$store.commit({ type: mutationTypes.SET_AUTH_DIALOG_FORM_TYPE, formType }) } if (action) { this.$store.commit({ type: mutationTypes.SET_AUTH_DIALOG_ACTION, action }) } this.$store.commit(mutationTypes.TOGGLE_AUTH_DIALOG, { visible: true, persistent }) this.$store.commit(mutationTypes.SET_AUTH_DIALOG_REDIRECTION_AFTER_SIGNUP, { redirectAfterSignup }) }, closeAuthDialog () { this.$store.commit(mutationTypes.TOGGLE_AUTH_DIALOG, { visible: false, persistent: false }) } } }
FavyTeam/Elderscape_server
source/game/object/areas/WildernessObjects.java
<filename>source/game/object/areas/WildernessObjects.java package game.object.areas; import game.content.miscellaneous.PlayerMiscContent; import game.content.miscellaneous.Teleport; import game.content.miscellaneous.Web; import game.object.ObjectEvent; import game.object.custom.DoorEvent; import game.player.Area; import game.player.Player; import game.player.event.CycleEvent; import game.player.event.CycleEventContainer; import game.player.event.CycleEventHandler; /** * Handles objects of Wilderness * * @author MGT Madness 27-10-2013 */ public class WildernessObjects { /** * Perform actions of the objects in Wilderness. */ public static boolean doWildernessObject(final Player player, int objectType) { if (!Area.inDangerousPvpArea(player)) { return false; } int playerX = player.getX(); int playerY = player.getY(); switch (objectType) { // Crevice at Mage bank stairs dungeon where Hill giants, Fire giants and Chaos dwarfs are at case 19043: if (System.currentTimeMillis() - player.agility4 < 1700) { return true; } player.agility4 = System.currentTimeMillis(); if (player.getObjectX() == 3046 && player.getObjectY() == 10327) { player.startAnimation(844); player.doingActionEvent(2); player.wildCrevice = true; player.timeUsedLadder = System.currentTimeMillis(); CycleEventHandler.getSingleton().addEvent(player, new CycleEvent() { @Override public void execute(CycleEventContainer container) { container.stop(); } @Override public void stop() { player.getPA().movePlayer(3048, 10336, 0); player.wildCrevice = false; } }, 2); } else if (player.getObjectX() == 3048 && player.getObjectY() == 10335) { player.timeUsedLadder = System.currentTimeMillis(); player.startAnimation(844); player.doingActionEvent(2); player.wildCrevice = true; CycleEventHandler.getSingleton().addEvent(player, new CycleEvent() { @Override public void execute(CycleEventContainer container) { container.stop(); } @Override public void stop() { player.getPA().movePlayer(3046, 10326, 0); player.wildCrevice = false; } }, 2); } return true; // Crevice that leads to inside wilderness gwd dungeon, east of revenants and south of Hobgoblins at 30 wilderness. case 26766: if (System.currentTimeMillis() - player.agility4 < 1700) { return true; } player.agility4 = System.currentTimeMillis(); if (player.getObjectX() == 3016 && player.getObjectY() == 3738) { player.startAnimation(844); player.doingActionEvent(2); player.wildCrevice = true; player.timeUsedLadder = System.currentTimeMillis(); CycleEventHandler.getSingleton().addEvent(player, new CycleEvent() { @Override public void execute(CycleEventContainer container) { container.stop(); } @Override public void stop() { player.getPA().movePlayer(3065, 10159, 3); player.wildCrevice = false; } }, 2); } return true; // Crevice that leads to 28 wilderness south of hobgoblins case 26767: if (System.currentTimeMillis() - player.agility4 < 1700) { return true; } player.agility4 = System.currentTimeMillis(); if (player.getObjectX() == 3065 && player.getObjectY() == 10160) { player.startAnimation(844); player.doingActionEvent(2); player.wildCrevice = true; player.timeUsedLadder = System.currentTimeMillis(); CycleEventHandler.getSingleton().addEvent(player, new CycleEvent() { @Override public void execute(CycleEventContainer container) { container.stop(); } @Override public void stop() { player.getPA().movePlayer(3017, 3740, 0); player.wildCrevice = false; } }, 2); } return true; // Ship's ladder, first floor. case 245: if (player.getObjectX() == 3019 && player.getObjectY() == 3959) { return false; } if (System.currentTimeMillis() - player.agility4 < 1100) { return true; } player.agility4 = System.currentTimeMillis(); player.timeUsedLadder = System.currentTimeMillis(); player.getPA().movePlayer(playerX, playerY + 2, 2); return true; // Ship's ladder, second floor. case 246: if (System.currentTimeMillis() - player.agility4 < 1100) { return true; } player.agility4 = System.currentTimeMillis(); player.timeUsedLadder = System.currentTimeMillis(); player.getPA().movePlayer(playerX, playerY - 2, 1); return true; // Ladder. case 272: ObjectEvent.climbUpLadder(player, player.getX(), player.getY(), 1); return true; // Ladder. case 273: ObjectEvent.climbDownLadder(player, player.getX(), player.getY(), 0); return true; // Mage bank lever that leads to inside Mage bank case 5959: if (player.getX() != 3090) { return true; } player.turnPlayerTo(player.getObjectX() - 1, player.getObjectY()); Teleport.startTeleport(player, 2539, 4712, 0, "LEVER"); return true; // Lever at Mage arena that leads to inside Mage arena case 9706: if (player.getX() == 3105 && player.getY() == 3956) { Teleport.startTeleport(player, 3105, 3951, 0, "LEVER"); } return true; // Lever at Mage arena that leads to outside Mage arena. case 9707: if (player.getX() == 3105 && player.getY() == 3951) { Teleport.startTeleport(player, 3105, 3956, 0, "LEVER"); } return true; //Ladder at Lesser demon area outside Kbd case 18987: if (player.getX() == 3016 && player.getY() == 3849 || player.getX() == 3017 && player.getY() == 3848 || player.getX() == 3017 && player.getY() == 3850) { ObjectEvent.climbDownLadder(player, 3069, 10255, 0); } return true; //Ladder, leads to lesser demon area outside Kbd area. case 18988: ObjectEvent.climbUpLadder(player, 3016, 3849, 0); return true; // Lever located at 42 wilderness, beside the spiders, This is the lever to enter KBD area. case 1816: player.turnPlayerTo(3067, 10252); Teleport.startTeleport(player, 2271, 4680, 0, "LEVER"); return true; // Lever located at 50 wild that leads to Ardougne case 1814: if (player.getX() != 3153 && player.getX() != 3923) { return true; } Teleport.startTeleport(player, 2561, 3311, 0, "LEVER"); return true; // Staircase, west of outside of Magebank. case 16664: if (System.currentTimeMillis() - player.agility1 < 1100) { return true; } if (player.getX() != 3045 && player.getX() != 3044) { return true; } player.agility1 = System.currentTimeMillis(); if (player.getObjectX() == 3044 && player.getObjectY() == 3924) { player.timeUsedLadder = System.currentTimeMillis(); player.getPA().movePlayer(3044, 10322, 0); } return true; // Staircase case 16665: if (System.currentTimeMillis() - player.agility1 < 1100) { return true; } if (player.getX() != 3045 && player.getX() != 3044) { return true; } player.agility1 = System.currentTimeMillis(); player.timeUsedLadder = System.currentTimeMillis(); player.getPA().movePlayer(3044, 3927, 0); return true; // Web case 733: Web.slash(player, 946); return true; case 11834: case 11727: case 11726: DoorEvent.openAutomaticDoor(player); return true; case 411: PlayerMiscContent.prayAtAltar(player); return true; } return false; } }
rawhiteside/jr
actions/thorns-for-bugs.rb
<reponame>rawhiteside/jr<gh_stars>0 require 'action' require 'walker' class ThornRun < Action def initialize super('Thorn run 2', 'Gather') end def find_one_window(x, y) w = PinnableWindow.from_point(Point.new(x, y)) unless w msg = 'Missed a pinned thorn dialog' UserIO.error(msg) raise Exception.new(msg) end w end def find_windows left_count = 10 mid_count = 3 @windows = [] x = 60 y = 70 left_count.times do |i| w = find_one_window(x, y) @windows << w y = w.rect.y + w.rect.height + 30 end x = 280 y = 70 mid_count.times do |i| w = find_one_window(x, y) @windows << w y = w.rect.y + w.rect.height + 30 end return @windows end # Need to wait until the thorn actuall gets harvested. Refresh it # until we fine the word "More" def wait_for_more(w) 6.times do sleep 0.5 w.refresh return true if w.read_text =~ /More/ end return false end def harvest(w) loop do w.refresh if w.click_on('Gather') return if wait_for_more(w) end end end def get_drop_window(parent) comps = [ {:type => :point, :name => 'drop', :label => 'Pinned drop menu'}, ] vals = UserIO.prompt(parent, persistence_name, action_name, comps) return nil unless vals w = PinnableWindow.from_point(point_from_hash(vals, 'drop')) return w end def thorn_paths [ # First thorn is at [4431, -5853] nil, nil, nil, nil, nil, [4439, -5845], nil, nil, [4447, -5841], nil, nil, nil, # back to beginning. [4431, -5853], ] end def setup(parent) @drop = get_drop_window(parent) end def act walker = Walker.new windows = find_windows loop do paths = thorn_paths windows.each do |w| harvest(w) path = paths.shift if path # Convenience, so we canput just coords into the thorn_paths list path = [path] unless path[0].kind_of?(Array) walker.walk_path(path) end end @drop.refresh @drop.click_on('Thorns') HowMuch.max end end end Action.add_action(ThornRun.new)
HandsomeOrange/jxc-admin
java/cloud/web/web-modules/system/src/main/java/cn/toesbieya/jxc/system/controller/SupplierController.java
package cn.toesbieya.jxc.system.controller; import cn.toesbieya.jxc.common.model.entity.SysSupplier; import cn.toesbieya.jxc.common.model.vo.R; import cn.toesbieya.jxc.system.model.vo.SupplierSearch; import cn.toesbieya.jxc.system.service.SupplierService; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; @RestController @RequestMapping("supplier") public class SupplierController { @Resource private SupplierService service; @GetMapping("getLimitRegion") public R getLimitRegion() { return R.success(service.getLimitRegion()); } @PostMapping("search") public R search(@RequestBody SupplierSearch vo) { return R.success(service.search(vo)); } @PostMapping("add") public R add(@RequestBody SysSupplier supplier) { String errMsg = validateCreateParam(supplier); if (errMsg != null) return R.fail("创建失败," + errMsg); supplier.setId(null); supplier.setCtime(System.currentTimeMillis()); return service.add(supplier); } @PostMapping("update") public R update(@RequestBody SysSupplier supplier) { String errMsg = validateUpdateParam(supplier); return errMsg == null ? service.update(supplier) : R.fail("修改失败," + errMsg); } @PostMapping("del") public R del(@RequestBody SysSupplier supplier) { if (supplier.getId() == null) return R.fail("删除失败,参数错误"); return service.del(supplier); } private String validateCreateParam(SysSupplier supplier) { if (StringUtils.isEmpty(supplier.getName())) return "供应商名称不能为空"; if (StringUtils.isEmpty(supplier.getRegion())) return "供应商行政区域不能为空"; if (StringUtils.isEmpty(supplier.getAddress())) return "供应商地址不能为空"; if (StringUtils.isEmpty(supplier.getLinkman())) return "供应商联系人不能为空"; if (StringUtils.isEmpty(supplier.getLinkphone())) return "供应商联系电话不能为空"; return null; } private String validateUpdateParam(SysSupplier supplier) { if (supplier.getId() == null) return "参数错误"; return validateCreateParam(supplier); } }
sho25/activemq
activemq-http/src/test/java/org/apache/activemq/transport/http/HttpJMSMessagesWithCompressionTest.java
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/** * 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. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|activemq operator|. name|transport operator|. name|http package|; end_package begin_import import|import name|java operator|. name|net operator|. name|URISyntaxException import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Arrays import|; end_import begin_import import|import name|java operator|. name|util operator|. name|concurrent operator|. name|atomic operator|. name|AtomicInteger import|; end_import begin_import import|import name|javax operator|. name|jms operator|. name|BytesMessage import|; end_import begin_import import|import name|javax operator|. name|jms operator|. name|Connection import|; end_import begin_import import|import name|javax operator|. name|jms operator|. name|ConnectionFactory import|; end_import begin_import import|import name|javax operator|. name|jms operator|. name|Destination import|; end_import begin_import import|import name|javax operator|. name|jms operator|. name|JMSException import|; end_import begin_import import|import name|javax operator|. name|jms operator|. name|MapMessage import|; end_import begin_import import|import name|javax operator|. name|jms operator|. name|Message import|; end_import begin_import import|import name|javax operator|. name|jms operator|. name|MessageConsumer import|; end_import begin_import import|import name|javax operator|. name|jms operator|. name|MessageProducer import|; end_import begin_import import|import name|javax operator|. name|jms operator|. name|ObjectMessage import|; end_import begin_import import|import name|javax operator|. name|jms operator|. name|Session import|; end_import begin_import import|import name|javax operator|. name|jms operator|. name|StreamMessage import|; end_import begin_import import|import name|javax operator|. name|jms operator|. name|TextMessage import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|activemq operator|. name|ActiveMQConnectionFactory import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|activemq operator|. name|broker operator|. name|BrokerService import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|After import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|Assert import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|Before import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|Test import|; end_import begin_class specifier|public class|class name|HttpJMSMessagesWithCompressionTest block|{ specifier|private specifier|static specifier|final name|AtomicInteger name|counter init|= operator|new name|AtomicInteger argument_list|( literal|1 argument_list|) decl_stmt|; enum|enum name|DESTINATION_TYPE block|{ name|TOPIC block|, name|QUEUE block|} empty_stmt|; specifier|protected name|BrokerService name|broker decl_stmt|; specifier|protected name|Connection name|connection decl_stmt|; specifier|protected name|DESTINATION_TYPE name|destinationType init|= name|DESTINATION_TYPE operator|. name|QUEUE decl_stmt|; annotation|@ name|Before specifier|public name|void name|setUp parameter_list|() throws|throws name|Exception block|{ name|broker operator|= name|createBroker argument_list|() expr_stmt|; name|broker operator|. name|start argument_list|() expr_stmt|; name|WaitForJettyListener operator|. name|waitForJettySocketToAccept argument_list|( name|getBrokerURL argument_list|() argument_list|) expr_stmt|; name|ConnectionFactory name|factory init|= name|createConnectionFactory argument_list|() decl_stmt|; name|connection operator|= name|factory operator|. name|createConnection argument_list|() expr_stmt|; block|} annotation|@ name|After specifier|public name|void name|tearDown parameter_list|() throws|throws name|Exception block|{ if|if condition|( name|connection operator|!= literal|null condition|) block|{ name|connection operator|. name|close argument_list|() expr_stmt|; block|} if|if condition|( name|broker operator|!= literal|null condition|) block|{ name|broker operator|. name|stop argument_list|() expr_stmt|; block|} block|} specifier|protected name|ConnectionFactory name|createConnectionFactory parameter_list|() throws|throws name|URISyntaxException block|{ name|ActiveMQConnectionFactory name|factory init|= operator|new name|ActiveMQConnectionFactory argument_list|( name|getBrokerURL argument_list|() argument_list|) decl_stmt|; name|factory operator|. name|setTrustedPackages argument_list|( name|Arrays operator|. name|asList argument_list|( literal|"java.lang" operator|. name|split argument_list|( literal|"," argument_list|) argument_list|) argument_list|) expr_stmt|; return|return name|factory return|; block|} specifier|protected name|String name|getBrokerURL parameter_list|() block|{ return|return literal|"http://localhost:8161?useCompression=true" return|; block|} specifier|protected name|BrokerService name|createBroker parameter_list|() throws|throws name|Exception block|{ name|BrokerService name|answer init|= operator|new name|BrokerService argument_list|() decl_stmt|; name|answer operator|. name|setPersistent argument_list|( literal|false argument_list|) expr_stmt|; name|answer operator|. name|setUseJmx argument_list|( literal|false argument_list|) expr_stmt|; name|answer operator|. name|setManagementContext argument_list|( literal|null argument_list|) expr_stmt|; name|answer operator|. name|addConnector argument_list|( name|getBrokerURL argument_list|() argument_list|) expr_stmt|; return|return name|answer return|; block|} specifier|protected name|Destination name|createDestination parameter_list|( name|Session name|session parameter_list|, name|DESTINATION_TYPE name|destinationType parameter_list|) throws|throws name|JMSException block|{ switch|switch condition|( name|destinationType condition|) block|{ case|case name|TOPIC case|: return|return name|session operator|. name|createTopic argument_list|( literal|"TOPIC." operator|+ name|counter operator|. name|getAndIncrement argument_list|() argument_list|) return|; case|case name|QUEUE case|: return|return name|session operator|. name|createQueue argument_list|( literal|"QUEUE." operator|+ name|counter operator|. name|getAndIncrement argument_list|() argument_list|) return|; block|} name|Assert operator|. name|fail argument_list|( literal|"Invalid destination type: " operator|+ name|destinationType argument_list|) expr_stmt|; return|return literal|null return|; block|} specifier|abstract class|class name|MessageCommand parameter_list|< name|M extends|extends name|Message parameter_list|> block|{ specifier|public specifier|final name|void name|assertMessage parameter_list|( name|M name|message parameter_list|) throws|throws name|JMSException block|{ name|Assert operator|. name|assertNotNull argument_list|( name|message argument_list|) expr_stmt|; name|completeCheck argument_list|( name|message argument_list|) expr_stmt|; block|} specifier|public specifier|abstract name|void name|completeCheck parameter_list|( name|M name|message parameter_list|) throws|throws name|JMSException function_decl|; specifier|public specifier|abstract name|M name|createMessage parameter_list|( name|Session name|session parameter_list|) throws|throws name|JMSException function_decl|; block|} annotation|@ name|SuppressWarnings argument_list|( literal|"unchecked" argument_list|) specifier|private parameter_list|< name|E extends|extends name|Message parameter_list|> name|void name|executeTest parameter_list|( name|MessageCommand argument_list|< name|E argument_list|> name|messageCommand parameter_list|) throws|throws name|JMSException block|{ comment|// Receive a message with the JMS API name|connection operator|. name|start argument_list|() expr_stmt|; name|Session name|session init|= name|connection operator|. name|createSession argument_list|( literal|false argument_list|, name|Session operator|. name|AUTO_ACKNOWLEDGE argument_list|) decl_stmt|; name|Destination name|destination init|= name|createDestination argument_list|( name|session argument_list|, name|destinationType argument_list|) decl_stmt|; name|MessageConsumer name|consumer init|= name|session operator|. name|createConsumer argument_list|( name|destination argument_list|) decl_stmt|; name|MessageProducer name|producer init|= name|session operator|. name|createProducer argument_list|( name|destination argument_list|) decl_stmt|; block|{ name|E name|message init|= name|messageCommand operator|. name|createMessage argument_list|( name|session argument_list|) decl_stmt|; name|producer operator|. name|send argument_list|( name|message argument_list|) expr_stmt|; block|} block|{ name|E name|message init|= operator|( name|E operator|) name|consumer operator|. name|receive argument_list|( literal|1000 argument_list|) decl_stmt|; name|messageCommand operator|. name|assertMessage argument_list|( name|message argument_list|) expr_stmt|; block|} name|Assert operator|. name|assertNull argument_list|( name|consumer operator|. name|receiveNoWait argument_list|() argument_list|) expr_stmt|; block|} annotation|@ name|Test specifier|public name|void name|testTextMessage parameter_list|() throws|throws name|Exception block|{ name|executeTest argument_list|( operator|new name|MessageCommand argument_list|< name|TextMessage argument_list|> argument_list|() block|{ specifier|private name|String name|textString init|= literal|"This is a simple text string" decl_stmt|; specifier|public name|TextMessage name|createMessage parameter_list|( name|Session name|session parameter_list|) throws|throws name|JMSException block|{ return|return name|session operator|. name|createTextMessage argument_list|( name|textString argument_list|) return|; block|} specifier|public name|void name|completeCheck parameter_list|( name|TextMessage name|message parameter_list|) throws|throws name|JMSException block|{ name|Assert operator|. name|assertEquals argument_list|( literal|"The returned text string was different" argument_list|, name|textString argument_list|, name|message operator|. name|getText argument_list|() argument_list|) expr_stmt|; block|} block|} argument_list|) expr_stmt|; block|} annotation|@ name|Test specifier|public name|void name|testBytesMessage parameter_list|() throws|throws name|Exception block|{ name|executeTest argument_list|( operator|new name|MessageCommand argument_list|< name|BytesMessage argument_list|> argument_list|() block|{ specifier|private name|byte index|[] name|bytes init|= literal|"This is a simple text string" operator|. name|getBytes argument_list|() decl_stmt|; specifier|public name|BytesMessage name|createMessage parameter_list|( name|Session name|session parameter_list|) throws|throws name|JMSException block|{ name|BytesMessage name|message init|= name|session operator|. name|createBytesMessage argument_list|() decl_stmt|; name|message operator|. name|writeBytes argument_list|( name|bytes argument_list|) expr_stmt|; return|return name|message return|; block|} specifier|public name|void name|completeCheck parameter_list|( name|BytesMessage name|message parameter_list|) throws|throws name|JMSException block|{ name|byte index|[] name|result init|= operator|new name|byte index|[ name|bytes operator|. name|length index|] decl_stmt|; name|message operator|. name|readBytes argument_list|( name|result argument_list|) expr_stmt|; name|Assert operator|. name|assertArrayEquals argument_list|( literal|"The returned byte array was different" argument_list|, name|bytes argument_list|, name|result argument_list|) expr_stmt|; block|} block|} argument_list|) expr_stmt|; block|} annotation|@ name|Test specifier|public name|void name|testMapMessage parameter_list|() throws|throws name|Exception block|{ name|executeTest argument_list|( operator|new name|MessageCommand argument_list|< name|MapMessage argument_list|> argument_list|() block|{ specifier|public name|MapMessage name|createMessage parameter_list|( name|Session name|session parameter_list|) throws|throws name|JMSException block|{ name|MapMessage name|message init|= name|session operator|. name|createMapMessage argument_list|() decl_stmt|; name|message operator|. name|setInt argument_list|( literal|"value" argument_list|, literal|13 argument_list|) expr_stmt|; return|return name|message return|; block|} specifier|public name|void name|completeCheck parameter_list|( name|MapMessage name|message parameter_list|) throws|throws name|JMSException block|{ name|Assert operator|. name|assertEquals argument_list|( literal|"The returned mapped value was different" argument_list|, literal|13 argument_list|, name|message operator|. name|getInt argument_list|( literal|"value" argument_list|) argument_list|) expr_stmt|; block|} block|} argument_list|) expr_stmt|; block|} annotation|@ name|Test specifier|public name|void name|testObjectMessage parameter_list|() throws|throws name|Exception block|{ name|executeTest argument_list|( operator|new name|MessageCommand argument_list|< name|ObjectMessage argument_list|> argument_list|() block|{ specifier|private name|Long name|value init|= operator|new name|Long argument_list|( literal|101 argument_list|) decl_stmt|; specifier|public name|ObjectMessage name|createMessage parameter_list|( name|Session name|session parameter_list|) throws|throws name|JMSException block|{ return|return name|session operator|. name|createObjectMessage argument_list|( name|value argument_list|) return|; block|} specifier|public name|void name|completeCheck parameter_list|( name|ObjectMessage name|message parameter_list|) throws|throws name|JMSException block|{ name|Assert operator|. name|assertEquals argument_list|( literal|"The returned object was different" argument_list|, name|value argument_list|, name|message operator|. name|getObject argument_list|() argument_list|) expr_stmt|; block|} block|} argument_list|) expr_stmt|; block|} annotation|@ name|Test specifier|public name|void name|testStreamMessage parameter_list|() throws|throws name|Exception block|{ name|executeTest argument_list|( operator|new name|MessageCommand argument_list|< name|StreamMessage argument_list|> argument_list|() block|{ specifier|private name|Long name|value init|= operator|new name|Long argument_list|( literal|1013 argument_list|) decl_stmt|; specifier|public name|StreamMessage name|createMessage parameter_list|( name|Session name|session parameter_list|) throws|throws name|JMSException block|{ name|StreamMessage name|message init|= name|session operator|. name|createStreamMessage argument_list|() decl_stmt|; name|message operator|. name|writeObject argument_list|( name|value argument_list|) expr_stmt|; return|return name|message return|; block|} specifier|public name|void name|completeCheck parameter_list|( name|StreamMessage name|message parameter_list|) throws|throws name|JMSException block|{ name|Assert operator|. name|assertEquals argument_list|( literal|"The returned stream object was different" argument_list|, name|value argument_list|, name|message operator|. name|readObject argument_list|() argument_list|) expr_stmt|; block|} block|} argument_list|) expr_stmt|; block|} block|} end_class end_unit
lechium/tvOS130Headers
System/Library/PrivateFrameworks/AppStoreDaemon.framework/Support/appstored/URLResponseDecoder.h
<reponame>lechium/tvOS130Headers<filename>System/Library/PrivateFrameworks/AppStoreDaemon.framework/Support/appstored/URLResponseDecoder.h<gh_stars>10-100 /* * This header is generated by classdump-dyld 1.0 * on Tuesday, November 5, 2019 at 2:38:48 AM Mountain Standard Time * Operating System: Version 13.0 (Build 17J586) * Image Source: /System/Library/PrivateFrameworks/AppStoreDaemon.framework/Support/appstored * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. */ #import <AppleMediaServices/AMSURLResponseDecoder.h> #import <appstored/AMSResponseDecoding.h> @protocol OS_dispatch_queue; @class NSObject, NSMutableDictionary; @interface URLResponseDecoder : AMSURLResponseDecoder <AMSResponseDecoding> { NSObject*<OS_dispatch_queue> _dispatchQueue; NSMutableDictionary* _requestProperties; } -(id)init; -(id)resultFromResult:(id)arg1 error:(id*)arg2 ; -(void)_discardRequestPropertiesForTask:(id)arg1 ; -(id)_dequeueRequestPropertiesForTask:(id)arg1 ; -(void)_processResponseDictionary:(id)arg1 withRequestProperties:(id)arg2 ; -(void)_importKeyBagFromDictionary:(id)arg1 ; -(void)discardRequestPropertiesForTask:(id)arg1 ; -(void)registerRequestProperties:(id)arg1 forTask:(id)arg2 ; @end
thetw/twin.macro
src/variants.js
<filename>src/variants.js<gh_stars>0 /* eslint-disable @typescript-eslint/restrict-plus-operands */ import cleanSet from 'clean-set' import { logGeneralError } from './logging' import { get, throwIf } from './utils' import { SPACE_ID } from './constants' const getPeerValueFromVariant = variant => get(/\.peer:(.+) ~ &/.exec(variant), '1') /** * Combine peers when they are used in succession */ const combinePeers = ({ variants }) => variants .map((_, i) => { let isPeer = false let index = i let returnVariant const peerList = [] do { const peer = getPeerValueFromVariant(variants[index]) isPeer = Boolean(peer) if (isPeer) { peerList.push(peer) variants[index] = null index = index + 1 } else { returnVariant = peerList.length === 0 ? variants[index] : `.peer:${peerList.join(':')} ~ &` } } while (isPeer) return returnVariant }) .filter(Boolean) const addSassyPseudo = ({ variants, state }) => { if (!state.configTwin.sassyPseudo) return variants return variants.map(v => v.replace(/(?<= ):|^:/g, '&:')) } const formatTasks = [combinePeers, addSassyPseudo] const addVariants = ({ results, style, pieces, state }) => { let { variants, hasVariants } = pieces if (!hasVariants) return style for (const task of formatTasks) { variants = task({ variants, state }) } let styleWithVariants // eslint-disable-next-line prefer-const styleWithVariants = cleanSet(results, variants, { ...get(styleWithVariants, variants, {}), ...style, }) return styleWithVariants } function findRightBracket( classes, start = 0, end = classes.length, brackets = ['(', ')'] ) { let stack = 0 for (let index = start; index < end; index++) { if (classes[index] === brackets[0]) { stack += 1 } else if (classes[index] === brackets[1]) { if (stack === 0) return if (stack === 1) return index stack -= 1 } } } const sliceToSpace = str => { const spaceIndex = str.indexOf(' ') if (spaceIndex === -1) return str return str.slice(0, spaceIndex) } // eslint-disable-next-line max-params function spreadVariantGroups( classes, context = '', importantContext = false, start = 0, end ) { if (classes === '') return [] const results = [] classes = classes.slice(start, end).trim() // variant / class / group const reg = /(\[.*?]:|[\w-<>]+:)|([\w-./[\]]+!?)|\(|(\S+)/g let match const baseContext = context while ((match = reg.exec(classes))) { const [, variant, className, weird] = match if (variant) { // Replace arbitrary variant spaces with a placeholder to avoid incorrect splitting const spaceReplacedVariant = variant.replace(/\s+/g, SPACE_ID) context += spaceReplacedVariant // Skip empty classes if (/\s/.test(classes[reg.lastIndex])) { context = baseContext continue } if (classes[reg.lastIndex] === '(') { const closeBracket = findRightBracket(classes, reg.lastIndex) throwIf(typeof closeBracket !== 'number', () => logGeneralError( `An ending bracket ')' wasn’t found for these classes:\n\n${classes}` ) ) const importantGroup = classes[closeBracket + 1] === '!' results.push( ...spreadVariantGroups( classes, context, importantContext || importantGroup, reg.lastIndex + 1, closeBracket ) ) reg.lastIndex = closeBracket + (importantGroup ? 2 : 1) context = baseContext } } else if (className && className.includes('[')) { const closeBracket = findRightBracket( classes, match.index, classes.length, ['[', ']'] ) throwIf(typeof closeBracket !== 'number', () => logGeneralError( `An ending bracket ']' wasn’t found for these classes:\n\n${classes}` ) ) const importantGroup = classes[closeBracket + 1] === '!' const cssClass = classes.slice(match.index, closeBracket + 1) const hasSlashOpacity = classes.slice(closeBracket + 1, closeBracket + 2) === '/' const opacityValue = hasSlashOpacity ? sliceToSpace(classes.slice(closeBracket + 1)) : '' // Convert spaces in classes to a temporary string so the css won't be // split into multiple classes const spaceReplacedClass = cssClass // Normalise the spacing - single spaces only // Replace spaces with the space id stand-in // Remove newlines within the brackets to allow multiline values .replace(/\s+/g, SPACE_ID) results.push( context + spaceReplacedClass + opacityValue + (importantGroup || importantContext ? '!' : '') ) reg.lastIndex = closeBracket + (importantGroup ? 2 : 1) + opacityValue.length context = baseContext } else if (className) { const tail = !className.endsWith('!') && importantContext ? '!' : '' results.push(context + className + tail) context = baseContext } else if (weird) { results.push(context + weird) } else { const closeBracket = findRightBracket(classes, match.index) throwIf(typeof closeBracket !== 'number', () => logGeneralError( `An ending bracket ')' wasn’t found for these classes:\n\n${classes}` ) ) const importantGroup = classes[closeBracket + 1] === '!' results.push( ...spreadVariantGroups( classes, context, importantContext || importantGroup, match.index + 1, closeBracket ) ) reg.lastIndex = closeBracket + (importantGroup ? 2 : 1) } } return results } const handleVariantGroups = classes => spreadVariantGroups(classes).join(' ') export { addVariants, handleVariantGroups }
mdziadkowiec95/mern-todo-app
client/src/components/molecules/Popover/Popover.js
import React, { useState } from 'react' import styles from './Popover.module.scss' import PropTypes from 'prop-types' import classNames from 'classnames/bind' const cn = classNames.bind(styles) const generateTooltipPositionCSS = (top, right, bottom, left, centerType) => { const styles = { top: top, bottom: bottom, left: left, right: right, } if (centerType) { const isVertical = centerType === 'vertical' styles.transform = isVertical ? `translateY(${bottom ? 50 : -50}%)` : `translateX(${right ? 50 : -50}%)` } return styles } const getTooltipPositionCSS = (position, gap) => { const fullDimPlusSpace = `calc(100% + ${gap}px)` switch (position) { case 'top': return generateTooltipPositionCSS(null, null, fullDimPlusSpace, '50%', 'horizontal') case 'right': return generateTooltipPositionCSS('50%', null, null, fullDimPlusSpace, 'vertical') case 'bottom': return generateTooltipPositionCSS(fullDimPlusSpace, null, null, '50%', 'horizontal') case 'left': return generateTooltipPositionCSS('50%', fullDimPlusSpace, null, null, 'vertical') default: return generateTooltipPositionCSS(null, null, fullDimPlusSpace, '50%', 'horizontal') } } const Popover = ({ text, children, position, gap, delay }) => { const [isHovered, setIsHovered] = useState(false) const handleMouseOver = () => { setIsHovered(true) } const handleMouseLeave = () => { setIsHovered(false) } const TooltipClassName = cn('popover__tooltip', { 'popover__tooltip--delayed': delay, }) if (!text) return null return ( <div onMouseOver={handleMouseOver} onFocus={handleMouseOver} onMouseLeave={handleMouseLeave} className={cn('popover')} > {isHovered && ( <span className={TooltipClassName} style={{ ...getTooltipPositionCSS(position, gap), animationDelay: `${delay}ms` }} > {text} </span> )} {children} </div> ) } Popover.propTypes = { position: PropTypes.oneOf(['top', 'right', 'bottom', 'left']), text: PropTypes.string.isRequired, gap: PropTypes.number, delay: PropTypes.number, children: PropTypes.node, } Popover.defaultProps = { position: 'top', gap: 10, delay: 0, } export default Popover
Deyk/learning-spring
library/src/main/java/ru/otus/spring/library/rest/AuthorController.java
<filename>library/src/main/java/ru/otus/spring/library/rest/AuthorController.java package ru.otus.spring.library.rest; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import ru.otus.spring.library.domain.Author; import ru.otus.spring.library.rest.model.AuthorDto; import ru.otus.spring.library.service.AuthorService; import ru.otus.spring.library.service.LibraryServiceException; import java.util.List; import java.util.stream.Collectors; @RestController public class AuthorController { private final AuthorService authorService; public AuthorController(AuthorService authorService) { this.authorService = authorService; } @GetMapping("/authors") public List<AuthorDto> getAllAuthors() { List<Author> allAuthors = authorService.getAllAuthors(); return allAuthors.stream().map(AuthorDto::toDto).collect(Collectors.toList()); } @PostMapping("/authors/add") public AuthorDto addAuthor(@RequestParam("authorName") String authorName) { Author author = authorService.addAuthor(authorName); return new AuthorDto(author); } @PostMapping("/authors/edit") public AuthorDto editAuthors(@RequestBody AuthorDto authorDto) throws LibraryServiceException { Author author = authorService.updateAuthor(authorDto.getId(), authorDto.getName()); return new AuthorDto(author); } @DeleteMapping("/authors/delete") public ResponseEntity deleteAuthor(@RequestParam("id") String id) { try { authorService.deleteAuthorById(id); } catch (LibraryServiceException e) { return ResponseEntity.status(HttpStatus.CONFLICT).body(e.getMessage()); } return ResponseEntity.ok().body(true); } @ExceptionHandler(LibraryServiceException.class) public ResponseEntity<String> handleNotEnoughFunds(LibraryServiceException ex) { return ResponseEntity.badRequest().body("Not found author"); } }
sptz45/coeus
src/test/scala/com/tzavellas/coeus/mvc/WebResponseTest.scala
/* - Coeus web framework ------------------------- * * Licensed under the Apache License, Version 2.0. * * Author: <NAME> */ package com.tzavellas.coeus package mvc import org.junit.Test import org.junit.Assert._ import org.springframework.mock.web.MockHttpServletResponse import test.Assertions.assertThrows import http.HttpStatus class WebResponseTest { val mock = new MockHttpServletResponse val response = new WebResponse(mock) @Test def setting_the_content_type() { response.contentType = "application/xml" assertEquals("application/xml", mock.getContentType) assertEquals(mock.getContentType, response.contentType) } @Test def setting_status_code() { response.status = HttpStatus.SEE_OTHER assertEquals(HttpStatus.SEE_OTHER, mock.getStatus) } @Test def setting_error_status() { response.sendError(HttpStatus.NOT_FOUND, "404 - Page Not Found") assertEquals(HttpStatus.NOT_FOUND, mock.getStatus) } @Test def error_accepts_only_error_codes() { assertThrows[IllegalArgumentException] { response.sendError(HttpStatus.OK, "message") } assertThrows[IllegalArgumentException] { response.sendError(HttpStatus.CONTINUE, "message") } assertThrows[IllegalArgumentException] { response.sendError(HttpStatus.SEE_OTHER, "message") } } @Test def prevent_caching_sets_cache_control_headers() { response.preventCaching() assertEquals("no-cache, no-store", mock.getHeader("Cache-Control")) } @Test def expires_cache_control() { response.expires(maxAge=1000) assertEquals("max-age=1000", mock.getHeader("Cache-Control")) response.expires(maxAge=1000, "public", "must-revalidate") assertEquals("max-age=1000, public, must-revalidate", mock.getHeader("Cache-Control")) } }
Sproutigy/LucenePlus
core/src/main/java/com/sproutigy/libs/luceneplus/core/search/LuceneSearchResults.java
package com.sproutigy.libs.luceneplus.core.search; import com.sproutigy.libs.luceneplus.core.CloseableIterator; import java.io.IOException; import java.util.List; public interface LuceneSearchResults extends CloseableIterator<LuceneSearchHit> { boolean hasTotal(); long total(); boolean hasCount(); int count(); /** * Loads entire results with whole documents into memory. * Not recommended for larger result sets, in such cases use iterator instead. * @return list of hits * @throws IOException */ List<LuceneSearchHit> toList() throws IOException; }
orth0dox/liliths-throne-public
src/com/lilithsthrone/game/sex/managers/dominion/SMGloryHoleSex.java
<filename>src/com/lilithsthrone/game/sex/managers/dominion/SMGloryHoleSex.java package com.lilithsthrone.game.sex.managers.dominion; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import com.lilithsthrone.game.character.GameCharacter; import com.lilithsthrone.game.inventory.InventorySlot; import com.lilithsthrone.game.sex.Sex; import com.lilithsthrone.game.sex.SexPositionSlot; import com.lilithsthrone.game.sex.SexPositionType; import com.lilithsthrone.game.sex.managers.SexManagerDefault; /** * @since 0.2.9 * @version 0.2.9 * @author Innoxia */ public class SMGloryHoleSex extends SexManagerDefault { public SMGloryHoleSex(Map<GameCharacter, SexPositionSlot> dominants, Map<GameCharacter, SexPositionSlot> submissives) { super(SexPositionType.GLORY_HOLE_SEX, dominants, submissives); } @Override public boolean isPlayerAbleToSwapPositions() { return false; } @Override public boolean isPositionChangingAllowed(GameCharacter character) { return Sex.isDom(character); } @Override public boolean isAbleToRemoveOthersClothing(GameCharacter character){ return false; } @Override public boolean isPlayerAbleToStopSex() { return true; } @Override public List<InventorySlot> getSlotsConcealed(GameCharacter character) { List<InventorySlot> concealedSlots = new ArrayList<>(); if(Sex.getSexPositionSlot(character)==SexPositionSlot.GLORY_HOLE_FUCKED) { Collections.addAll(concealedSlots, InventorySlot.values()); concealedSlots.remove(InventorySlot.MOUTH); concealedSlots.remove(InventorySlot.PENIS); concealedSlots.remove(InventorySlot.VAGINA); concealedSlots.remove(InventorySlot.GROIN); concealedSlots.remove(InventorySlot.LEG); } else if(Sex.getSexPositionSlot(character)==SexPositionSlot.BREEDING_STALL_FUCKING) { Collections.addAll(concealedSlots, InventorySlot.values()); concealedSlots.remove(InventorySlot.PENIS); concealedSlots.remove(InventorySlot.VAGINA); concealedSlots.remove(InventorySlot.GROIN); concealedSlots.remove(InventorySlot.LEG); } else if(Sex.getSexPositionSlot(character)==SexPositionSlot.GLORY_HOLE_RECEIVING_ORAL_ONE) { Collections.addAll(concealedSlots, InventorySlot.values()); concealedSlots.remove(InventorySlot.PENIS); concealedSlots.remove(InventorySlot.VAGINA); concealedSlots.remove(InventorySlot.GROIN); concealedSlots.remove(InventorySlot.LEG); } return concealedSlots; } }
anyex-net/aeron
aeron-client/src/main/c/aeron_counters.h
<filename>aeron-client/src/main/c/aeron_counters.h /* * Copyright 2014-2022 Real Logic Limited. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef AERON_C_COUNTERS_H #define AERON_C_COUNTERS_H // Driver counters #define AERON_COUNTER_SYSTEM_COUNTER_TYPE_ID (0) #define AERON_COUNTER_PUBLISHER_LIMIT_NAME "pub-lmt" #define AERON_COUNTER_PUBLISHER_LIMIT_TYPE_ID (1) #define AERON_COUNTER_SENDER_POSITION_NAME "snd-pos" #define AERON_COUNTER_SENDER_POSITION_TYPE_ID (2) #define AERON_COUNTER_RECEIVER_HWM_NAME "rcv-hwm" #define AERON_COUNTER_RECEIVER_HWM_TYPE_ID (3) #define AERON_COUNTER_SUBSCRIPTION_POSITION_NAME "sub-pos" #define AERON_COUNTER_SUBSCRIPTION_POSITION_TYPE_ID (4) #define AERON_COUNTER_RECEIVER_POSITION_NAME "rcv-pos" #define AERON_COUNTER_RECEIVER_POSITION_TYPE_ID (5) #define AERON_COUNTER_SEND_CHANNEL_STATUS_NAME "snd-channel" #define AERON_COUNTER_SEND_CHANNEL_STATUS_TYPE_ID (6) #define AERON_COUNTER_RECEIVE_CHANNEL_STATUS_NAME "rcv-channel" #define AERON_COUNTER_RECEIVE_CHANNEL_STATUS_TYPE_ID (7) #define AERON_COUNTER_SENDER_LIMIT_NAME "snd-lmt" #define AERON_COUNTER_SENDER_LIMIT_TYPE_ID (9) #define AERON_COUNTER_PER_IMAGE_TYPE_ID (10) #define AERON_COUNTER_CLIENT_HEARTBEAT_TIMESTAMP_NAME "client-heartbeat" #define AERON_COUNTER_CLIENT_HEARTBEAT_TIMESTAMP_TYPE_ID (11) #define AERON_COUNTER_PUBLISHER_POSITION_NAME "pub-pos (sampled)" #define AERON_COUNTER_PUBLISHER_POSITION_TYPE_ID (12) #define AERON_COUNTER_SENDER_BPE_NAME "snd-bpe" #define AERON_COUNTER_SENDER_BPE_TYPE_ID (13) #define AERON_COUNTER_RCV_LOCAL_SOCKADDR_NAME "rcv-local-sockaddr" #define AERON_COUNTER_SND_LOCAL_SOCKADDR_NAME "snd-local-sockaddr" #define AERON_COUNTER_LOCAL_SOCKADDR_TYPE_ID (14) // AERON_EF_VI reserved range 50-74 // AERON_DPDK reserved range 75-99 // Archive counters #define AERON_COUNTER_ARCHIVE_RECORDING_POSITION_TYPE_ID (100); #define AERON_COUNTER_ARCHIVE_ERROR_COUNT_TYPE_ID (101); #define AERON_COUNTER_ARCHIVE_CONTROL_SESSIONS_TYPE_ID (102); // Cluster counters #define AERON_COUNTER_CLUSTER_CONSENSUS_MODULE_STATE_TYPE_ID (200) #define AERON_COUNTER_CLUSTER_NODE_ROLE_TYPE_ID (201) #define AERON_COUNTER_CLUSTER_CONTROL_TOGGLE_TYPE_ID (202) #define AERON_COUNTER_CLUSTER_COMMIT_POSITION_TYPE_ID (203) #define AERON_COUNTER_CLUSTER_RECOVERY_STATE_TYPE_ID (204) #define AERON_COUNTER_CLUSTER_SNAPSHOT_COUNTER_TYPE_ID (205) #define AERON_COUNTER_CLUSTER_ELECTION_STATE_TYPE_ID (207) #define AERON_COUNTER_CLUSTER_BACKUP_STATE_TYPE_ID (208) #define AERON_COUNTER_CLUSTER_BACKUP_LIVE_LOG_POSITION_TYPE_ID (209) #define AERON_COUNTER_CLUSTER_BACKUP_QUERY_DEADLINE_TYPE_ID (210) #define AERON_COUNTER_CLUSTER_BACKUP_ERROR_COUNT_TYPE_ID (211) #define AERON_COUNTER_CLUSTER_CONSENSUS_MODULE_ERROR_COUNT_TYPE_ID (212) #define AERON_COUNTER_CLUSTER_CLIENT_TIMEOUT_COUNT_TYPE_ID (213) #define AERON_COUNTER_CLUSTER_INVALID_REQUEST_COUNT_TYPE_ID (214) #define AERON_COUNTER_CLUSTER_CLUSTERED_SERVICE_ERROR_COUNT_TYPE_ID (215) #endif //AERON_C_COUNTERS_H
vadim8kiselev/public-enemy
src/main/java/com/kiselev/enemy/network/instagram/api/internal2/requests/accounts/AccountsTwoFactorLoginRequest.java
package com.kiselev.enemy.network.instagram.api.internal2.requests.accounts; import com.kiselev.enemy.network.instagram.api.internal2.IGClient; import com.kiselev.enemy.network.instagram.api.internal2.models.IGPayload; import com.kiselev.enemy.network.instagram.api.internal2.requests.IGPostRequest; import com.kiselev.enemy.network.instagram.api.internal2.requests.accounts.AccountsLoginRequest.LoginPayload; import com.kiselev.enemy.network.instagram.api.internal2.responses.accounts.LoginResponse; import lombok.Getter; import lombok.NonNull; import lombok.RequiredArgsConstructor; @RequiredArgsConstructor public class AccountsTwoFactorLoginRequest extends IGPostRequest<LoginResponse> { @NonNull private String username, password, code, identifier; @Override public IGPayload getPayload(IGClient client) { return new LoginPayload(username, password) { @Getter private final String verification_code = code; @Getter private final String two_factor_identifier = identifier; }; } @Override public String path() { return "accounts/two_factor_login/"; } @Override public Class<LoginResponse> getResponseType() { return LoginResponse.class; } }
nkrios/grr
grr/server/grr_response_server/gui/static/angular-components/core/confirmation-dialog-directive.js
goog.module('grrUi.core.confirmationDialogDirective'); goog.module.declareLegacyNamespace(); /** * Controller for ConfirmationDialogDirective. * * @constructor * @param {!angular.Scope} $scope * @param {!angular.$timeout} $timeout * @ngInject */ const ConfirmationDialogController = function($scope, $timeout) { /** @private {!angular.Scope} */ this.scope_ = $scope; /** @private {!angular.$timeout} */ this.timeout_ = $timeout; /** @export {?string} */ this.error; /** @export {?string} */ this.success; }; /** * Calls the proceed function provided in the scope. * * @export */ ConfirmationDialogController.prototype.proceed = function() { var result = this.scope_.proceed(); if(result){ result.then(function success(successMessage) { this.success = successMessage; if (this.scope_['autoCloseOnSuccess']) { this.timeout_(function() { this.close(); }.bind(this), 1000); } }.bind(this), function failure(errorMessage) { this.error = errorMessage; }.bind(this)); } }; /** * AngularJS UI attaches a $dismiss method to the modal scope. Since the modal scope * is a potentially indirect parent of the current scope, we need to search for * the method in the scope hierarchy. * * @export */ ConfirmationDialogController.prototype.dismiss = function() { var curScope = this.scope_; while (curScope && !curScope['$dismiss']) { curScope = curScope.$parent; } if (curScope) { curScope['$dismiss'](); } }; /** * AngularJS UI attaches a $close method to the modal scope. Since the modal scope * is a potentially indirect parent of the current scope, we need to search for * the method in the scope hierarchy. * * @export */ ConfirmationDialogController.prototype.close = function() { var curScope = this.scope_; while (curScope && !curScope['$close']) { curScope = curScope.$parent; } if (curScope) { curScope['$close'](); } }; /** * Directive that displays a confirmation dialog. * * @return {!angular.Directive} Directive definition object. */ exports.ConfirmationDialogDirective = function() { return { scope: { title: '=', closeName: '=', cancelName: '=', proceedName: '=', proceedClass: '=', proceed: '&', canProceed: '&?', autoCloseOnSuccess: '=' }, restrict: 'E', transclude: true, templateUrl: '/static/angular-components/core/confirmation-dialog.html', controller: ConfirmationDialogController, controllerAs: 'controller' }; }; /** * Name of the directive in Angular. * * @const * @export */ exports.ConfirmationDialogDirective.directive_name = 'grrConfirmationDialog';
IBMStreams/OSStreams
src/cpp/SPL/Runtime/ProcessingElement/JNISPLRuntimeBridge.cpp
/* * Copyright 2021 IBM Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <Runtime/ProcessingElement/JNISPLRuntimeBridge.h> #include <SPL/Runtime/Common/RuntimeDebug.h> #include <SPL/Runtime/Operator/Port/TupleVisualizer.h> #include <SPL/Runtime/ProcessingElement/PEImpl.h> #include <SPL/Runtime/ProcessingElement/ViewProperties.h> #include <SPL/Runtime/Serialization/NativeByteBuffer.h> #include <SPL/Runtime/Utility/Visibility.h> #include <algorithm> #include <cassert> #include <dlfcn.h> #include <map> using namespace std; using namespace SPL; using namespace SPL::JNI; static const char* jniBridgeClassName = "com/ibm/streams/operator/internal/jni/JNISPLRuntimeBridge"; // Map from internal log and trace values to external static jint mapTraceLogLevelToExternal(int level); static string dotName(const char* s) { string name(s); replace(name.begin(), name.end(), '/', '.'); return name; } JNISPLRuntimeBridge::JNISPLRuntimeBridge(JavaVM* vm) : jvm_(vm) { JVMEnv env(vm); assert(env.isAttached()); JClass jnibridge(env.get(), jniBridgeClassName); setAppLogLevel_ = jnibridge.getStaticMethodID("setAppLogLevel", "(I)V"); setAppTrcLevel_ = jnibridge.getStaticMethodID("setAppTrcLevel", "(I)V"); setVisualizing_ = jnibridge.getStaticMethodID("setVisualizing", "(Z)V"); startSPLJavaRuntime_ = jnibridge.getStaticMethodID("startSPLJavaRuntime", "(Ljava/lang/String;[Ljava/lang/String;)V"); shutdownSPLJavaRuntime_ = jnibridge.getStaticMethodID("shutdownSPLJavaRuntime", "(Z)V"); connectOperators_ = jnibridge.getStaticMethodID("connectOperators", "()V"); addView_ = jnibridge.getStaticMethodID("addView", "(IIJ)V"); deleteView_ = jnibridge.getStaticMethodID("deleteView", "(IIJ)V"); bridgeClass_ = reinterpret_cast<jclass>(env->NewGlobalRef(jnibridge.get())); APPTRC(L_INFO, "Successfully loaded class " << dotName(jniBridgeClassName), SPL_PE_DBG); } JNISPLRuntimeBridge::~JNISPLRuntimeBridge() {} void JNISPLRuntimeBridge::startSPLJavaRuntime(string const& model, vector<string> const* params) { JVMEnv env(jvm_); assert(env.isAttached()); APPTRC(L_DEBUG, "Starting the SPL Java runtime", SPL_PE_DBG); SPL::JNI::JString jstrModel(env.get(), model); SPL::JNI::JObjectArray jParams(env.get(), params); env->CallStaticVoidMethod(bridgeClass_, startSPLJavaRuntime_, jstrModel.get(), jParams.get()); processException(env.get()); APPTRC(L_INFO, "Started the SPL Java runtime", SPL_PE_DBG); } void JNISPLRuntimeBridge::shutdownSPLJavaRuntime(bool finalNotice) { JVMEnv env(jvm_); assert(env.isAttached()); env->CallStaticVoidMethod(bridgeClass_, shutdownSPLJavaRuntime_, finalNotice); // just log exceptions, if any, don't rethrow processException(env.get(), false); releaseJavaBridge(env.get()); } void JNISPLRuntimeBridge::logLevelUpdate(int level) { JVMEnv env(jvm_); assert(env.isAttached()); env->CallStaticVoidMethod(bridgeClass_, setAppLogLevel_, mapTraceLogLevelToExternal(level)); processException(env.get()); } void JNISPLRuntimeBridge::traceLevelUpdate(int level) { JVMEnv env(jvm_); assert(env.isAttached()); env->CallStaticVoidMethod(bridgeClass_, setAppTrcLevel_, mapTraceLogLevelToExternal(level)); processException(env.get()); } void JNISPLRuntimeBridge::visualizerUpdate(bool isVisualizing) { JVMEnv env(jvm_); assert(env.isAttached()); env->CallStaticVoidMethod(bridgeClass_, setVisualizing_, isVisualizing); processException(env.get()); } void JNISPLRuntimeBridge::connectOperators() { JVMEnv env(jvm_); assert(env.isAttached()); env->CallStaticVoidMethod(bridgeClass_, connectOperators_); processException(env.get()); } void JNISPLRuntimeBridge::addView(int operatorIndex, int outputPortIndex, ViewProperties* properties) { JVMEnv env(jvm_); assert(env.isAttached()); env->CallStaticVoidMethod(bridgeClass_, addView_, operatorIndex, outputPortIndex, properties); processException(env.get()); } void JNISPLRuntimeBridge::deleteView(int operatorIndex, int outputPortIndex, ViewProperties* properties) { JVMEnv env(jvm_); assert(env.isAttached()); env->CallStaticVoidMethod(bridgeClass_, deleteView_, operatorIndex, outputPortIndex, properties); processException(env.get()); } static jint mapTraceLogLevelToExternal(int level) { switch (level) { case iL_OFF: return L_OFF; case iL_ERROR: return L_ERROR; case iL_WARN: return L_WARN; case iL_INFO: return L_INFO; case iL_DEBUG: return L_DEBUG; case iL_TRACE: return L_TRACE; } return L_ERROR; } void JNISPLRuntimeBridge::processException(JNIEnv* env, bool rethrow /* = true */) { jthrowable thr = env->ExceptionOccurred(); if (thr == NULL) { return; } env->ExceptionClear(); JClass throwableClass(env, "java/lang/Throwable", env->GetObjectClass(thr)); // TODO use Throwable.getLocalizedMessage() instead? // jmethodID throwable_getLocalizedMessage = // throwableClass.getMethodID("getLocalizedMessage", "()Ljava/lang/String;"); JStringUTFChars // msg(env, (jstring) env->CallObjectMethod(thr, throwable_getLocalizedMessage)); jmethodID throwable_toString = throwableClass.getMethodID("toString", "()Ljava/lang/String;"); JStringUTFChars msg(env, (jstring)env->CallObjectMethod(thr, throwable_toString)); // Map some java exceptions to equivalent SPLRuntime exceptions JClass ioExceptionClass(env, "java/io/IOException"); if (rethrow) { if (throwableClass.isAssignableFrom(ioExceptionClass)) { THROW(SPLRuntimeIO, msg.c_str()); } THROW(SPLRuntime, msg.c_str()); } else { APPTRC(L_WARN, "Java exception caught: " << msg.c_str(), SPL_PE_DBG); } } ///////////////////////////////////////////////////////////////////////////// // Functions invoked by com.ibm.streams.operator.internal.jni.JNISPLRuntimeBridge #ifdef __cplusplus extern "C" { #endif //... /* * Class: com_ibm_streams_operator_internal_jni_JNISPLRuntimeBridge * Method: visualizeTuple * Signature: (IIL/java/nio/ByteBuffer;I)V */ JNIEXPORT DLL_PUBLIC void JNICALL Java_com_ibm_streams_operator_internal_jni_JNISPLRuntimeBridge_visualizeTuple(JNIEnv* env, jclass clz, jint operatorIndex, jint outputPortIndex, jobject rawTuple, jint tupleSize) { PEImpl* pi = dynamic_cast<PEImpl*>(&SPL::ProcessingElement::pe()); void* rawTupleData = env->GetDirectBufferAddress(rawTuple); NativeByteBuffer buf((unsigned char*)rawTupleData, tupleSize); OperatorImpl& operatorImpl = pi->getOperatorImpl(operatorIndex); operatorImpl.visualizeTuple(outputPortIndex, buf); } /* * Class: com_ibm_streams_operator_internal_jni_JNISPLRuntimeBridge * Method: setTagData * Signature: (Ljava/lang/String;Ljava/util/Map;)V */ JNIEXPORT DLL_PUBLIC void JNICALL Java_com_ibm_streams_operator_internal_jni_JNISPLRuntimeBridge_setTagData(JNIEnv* env, jclass clz, jstring tagName, jobject tagValues) { PEImpl* pi = dynamic_cast<PEImpl*>(&SPL::ProcessingElement::pe()); try { JStringUTFChars tagNameC(env, tagName); std::map<std::string, std::string> tagValuesMap; JClass setClass(env, "java/util/Set"); jmethodID setIteratorMethod = setClass.getMethodID("iterator", "()Ljava/util/Iterator;"); JClass mapClass(env, "java/util/Map"); jmethodID mapKeySetMethod = mapClass.getMethodID("keySet", "()Ljava/util/Set;"); jmethodID mapGetMethod = mapClass.getMethodID("get", "(Ljava/lang/Object;)Ljava/lang/Object;"); JClass iteratorClass(env, "java/util/Iterator"); jmethodID iteratorNextMethod = iteratorClass.getMethodID("next", "()Ljava/lang/Object;"); jmethodID iteratorHasNextMethod = iteratorClass.getMethodID("hasNext", "()Z"); // Set<String> keys = tagValues.keySet(); // Iterator<String> keysIterator = keys.iterator(); // while (keysIterator.hasNext()) { // String key = keysIterator.next(); // String value = tagValues.get(key); // JStringUTFChars keyC(env, key); // JStringUTFChars valueC(env, value); // tagValuesMap[key] = value; // } jobject keys = env->CallObjectMethod(tagValues, mapKeySetMethod); jobject keysIterator = env->CallObjectMethod(keys, setIteratorMethod); while (env->CallBooleanMethod(keysIterator, iteratorHasNextMethod)) { jstring key = static_cast<jstring>(env->CallObjectMethod(keysIterator, iteratorNextMethod)); jstring value = static_cast<jstring>(env->CallObjectMethod(tagValues, mapGetMethod, key)); // The Java map allows nulls on key and value, but the C++ class // does not. Discard and warn. if (key != NULL && value != NULL) { JStringUTFChars keyC(env, key); JStringUTFChars valueC(env, value); tagValuesMap[keyC.c_str()] = valueC.c_str(); } else { if (key == NULL) { APPTRC(L_WARN, "Tag data for tag name " << tagNameC.c_str() << ": value with null key discarded.", SPL_PE_DBG); } if (value == NULL) { APPTRC(L_WARN, "Tag data for tag name " << tagNameC.c_str() << ": key with null value discarded.", SPL_PE_DBG); } } } pi->setTagData(tagNameC.c_str(), tagValuesMap); } catch (Distillery::DistilleryException const& e) { jclass expClass = env->FindClass("java/lang/Exception"); env->ThrowNew(expClass, e.getExplanation().c_str()); } } /* * Class: com_ibm_streams_operator_internal_jni_JNISPLRuntimeBridge * Method: getApplicationConfigAsByteArray * Signature: (Ljava/lang/String;)[B */ JNIEXPORT DLL_PUBLIC jbyteArray JNICALL Java_com_ibm_streams_operator_internal_jni_JNISPLRuntimeBridge_getApplicationConfigAsByteArray( JNIEnv* env, jclass clz, jstring cfgName) { JStringUTFChars cfgNameC(env, cfgName); try { PEImpl* pi = dynamic_cast<PEImpl*>(&SPL::ProcessingElement::pe()); PlatformAdapter& platform = pi->getPlatform(); std::map<std::string, std::string> properties; platform.getAppConfig(platform.getUserSessionId(), cfgNameC.c_str(), properties); // Serialized using Java byte order NetworkByteBuffer buf; buf.addInt32(0); // version 0 buf.addInt32(properties.size()); // map entry count for (std::map<std::string, std::string>::iterator it = properties.begin(); it != properties.end(); ++it) { rstring rkey(it->first); buf.addSTLString(rkey); rstring rvalue(it->second); buf.addSTLString(rvalue); } // Copy into a Java byte array, we can't use a ByteBuffer as the C++ // buffer will become invalid once this function returns. return JByteArray::newArray(env, buf.getPtr(), buf.getContentSize()); } catch (Distillery::DistilleryException const& e) { env->ThrowNew(env->FindClass("java/lang/RuntimeException"), (std::string("Cannot retrieve application configuration for ") + cfgNameC.c_str() + ". " + e.getExplanation()) .c_str()); } catch (std::exception const& e) { env->ThrowNew(env->FindClass("java/lang/RuntimeException"), (std::string("Cannot retrieve application configuration for ") + cfgNameC.c_str() + ". " + e.what()) .c_str()); } catch (...) { env->ThrowNew(env->FindClass("java/lang/RuntimeException"), (std::string("Cannot retrieve application configuration for ") + cfgNameC.c_str() + ". Unknown exception.") .c_str()); } return NULL; // squelch compiler warnings } #ifdef __cplusplus } #endif
bimslab/mobileapp_eegmuselib
ios/Pods/Headers/Public/libmuse/Muse/api/IXNMuseArtifactPacket.h
// AUTOGENERATED FILE - DO NOT MODIFY! // This file generated by Djinni from packets.djinni #import <Foundation/Foundation.h> /** Provides access to calculated artifacts. */ @interface IXNMuseArtifactPacket : NSObject - (nonnull instancetype)initWithHeadbandOn:(BOOL)headbandOn blink:(BOOL)blink jawClench:(BOOL)jawClench timestamp:(int64_t)timestamp; + (nonnull instancetype)museArtifactPacketWithHeadbandOn:(BOOL)headbandOn blink:(BOOL)blink jawClench:(BOOL)jawClench timestamp:(int64_t)timestamp; /** * Flag which represents if the %Muse Headband is on a person's head. * Headband On detection is one of the first things muse elements * algorithm does. If this flag is false you will not see other artifact * or band power data. * \return \c true if the headband is on. \c false otherwise. */ @property (nonatomic, readonly) BOOL headbandOn; /** * Eye blinking flag. * \return \c true if an eye blink was detected. \c false otherwise. */ @property (nonatomic, readonly) BOOL blink; /** * Jaw clench flag. * \return \c true if a jaw clench was detected. \c false otherwise. */ @property (nonatomic, readonly) BOOL jawClench; /** * Microseconds since epoch (usually Jan 1, 1970). * \return the timestamp of the packet expressed in microseconds since epoch. */ @property (nonatomic, readonly) int64_t timestamp; @end
arturodrigues/carbon
src/components/popover-container/popover-container.stories.js
import React from 'react'; import { withKnobs, text } from '@storybook/addon-knobs'; import PopoverContainer from './popover-container.component'; export default { title: 'Test/Popover Container', component: PopoverContainer, decorators: [withKnobs], parameters: { info: { disable: true }, docs: { page: null } } }; export const Basic = () => { const title = text('title', 'Title'); return ( <PopoverContainer title={ title } /> ); };