repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
jancajthaml/sqlg
sqlg-core/src/main/java/org/umlg/sqlg/sql/dialect/SqlSchemaChangeDialect.java
package org.umlg.sqlg.sql.dialect; import com.fasterxml.jackson.databind.JsonNode; import org.umlg.sqlg.structure.SqlgExceptions; import org.umlg.sqlg.structure.SqlgGraph; import java.time.LocalDateTime; /** * Date: 2016/09/03 * Time: 4:09 PM */ public interface SqlSchemaChangeDialect extends SqlDialect { default void lock(SqlgGraph sqlgGraph) { throw SqlgExceptions.multipleJvmNotSupported(dialectName()); } default void registerListener(SqlgGraph sqlgGraph) { throw SqlgExceptions.multipleJvmNotSupported(dialectName()); } default void unregisterListener() { throw SqlgExceptions.multipleJvmNotSupported(dialectName()); } default int notifyChange(SqlgGraph sqlgGraph, LocalDateTime timestamp, JsonNode jsonNode) { throw SqlgExceptions.multipleJvmNotSupported(dialectName()); } }
deniscostadsc/playground
solutions/beecrowd/1002/1002.cpp
<gh_stars>10-100 #include <cstdio> int main() { double n; scanf("%lf", &n); printf("A=%.4f\n", n * n * 3.14159); return 0; }
skubit/skubit-iab-embedded
app/src/main/java/com/skubit/bitid/activities/ImportActivity.java
<reponame>skubit/skubit-iab-embedded /** * Copyright 2015 Skubit * * 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.skubit.bitid.activities; import com.skubit.bitid.ImportKeysResponse; import com.skubit.bitid.fragments.ImportFragment; import com.skubit.bitid.loaders.ImportKeysTaskLoader; import com.skubit.dialog.ProgressActivity; import com.skubit.iab.loaders.LoaderId; import android.app.LoaderManager; import android.content.Loader; import android.os.Bundle; import android.os.Environment; import java.io.File; public class ImportActivity extends ProgressActivity<Bundle> implements LoaderManager.LoaderCallbacks<ImportKeysResponse> { // LoaderManagerCallback<Bundle> //{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); replaceFragment(new ImportFragment(), "import"); } @Override public Loader<ImportKeysResponse> onCreateLoader(int id, Bundle args) { return new ImportKeysTaskLoader(this, new File(Environment.getExternalStorageDirectory(), "bitid/" + args.getString("fileName")), args.getString("password")); } @Override public void onLoadFinished(Loader<ImportKeysResponse> loader, ImportKeysResponse data) { showMessage(data.getMessage()); } @Override public void onLoaderReset(Loader<ImportKeysResponse> loader) { } @Override public void load(Bundle data, int type) { getLoaderManager().restartLoader(LoaderId.IMPORT_LOADER, data, this); } }
assaf-08/TopToy
src/main/java/utils/statistics/Statistics.java
package utils.statistics; import blockchain.data.BCS; import utils.config.Config; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import static java.lang.Math.max; public class Statistics { private final static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(Statistics.class); static ExecutorService worker = Executors.newSingleThreadExecutor(); static private long start; static private long stop; static private int h1 = 0; static private int h2 = 0; static private int id = -1; static private AtomicInteger all = new AtomicInteger(0); static private AtomicInteger pos = new AtomicInteger(0); static private AtomicInteger opt = new AtomicInteger(0); static private AtomicInteger neg = new AtomicInteger(0); static private AtomicInteger tmo = new AtomicInteger(0); static private AtomicInteger actTmo = new AtomicInteger(0); static private AtomicInteger maxTmo = new AtomicInteger(0); static private AtomicInteger syncs = new AtomicInteger(0); static private AtomicLong negTime = new AtomicLong(0); static private AtomicBoolean active = new AtomicBoolean(false); private static int txCount = 0; private static int nob = 0; private static int neb = 0; private static int txInBlock = 0; private static int stBlockNum = 0; private static double acBP2T = 0; private static double acBP2D = 0; private static double acBP2DL = 0; private static double acHP2T = 0; private static double acHP2D = 0; private static double acHT2D = 0; private static double acHP2DL = 0; private static double acHD2DL = 0; static public void updateAll() { if (!active.get()) return; all.incrementAndGet(); } static public void updateOpt() { if (!active.get()) return; opt.incrementAndGet(); } static public void updatePos() { if (!active.get()) return; pos.incrementAndGet(); } static public void updateNeg() { if (!active.get()) return; neg.incrementAndGet(); } static public void updateSyncs() { if (!active.get()) return; syncs.incrementAndGet(); } static public void updateNegTime(long time) { if (!active.get()) return; negTime.addAndGet(time); } static public void activate(int id) { if (active.get()) return; logger.info("Start statistics"); Statistics.id = id; active.set(true); h1 = BCS.height(); start = System.currentTimeMillis(); worker.submit(() -> { try { collectReasults(); } catch (InterruptedException e) { logger.error(e); } }); } static public void deactivate() { if (!active.get()) return; logger.info("stop statistics"); active.set(false); h2 = BCS.height(); stop = System.currentTimeMillis(); worker.shutdownNow(); } static public void updateTmo(int newTmo) { if (!active.get()) return; tmo.addAndGet(newTmo); } static public void updateActTmo(int newActTmo) { if (!active.get()) return; tmo.addAndGet(newActTmo); } static public void updateMaxTmo(int newMaxTmo) { if (!active.get()) return; maxTmo.set(max(maxTmo.get(), newMaxTmo)); } public static int getNeg() { return neg.get(); } public static int getH1() { return h1; } public static int getAll() { return all.get(); } public static int getH2() { return h2; } public static int getOpt() { return opt.get(); } public static int getPos() { return pos.get(); } public static long getActTmo() { return actTmo.get(); } public static long getStart() { return start; } public static long getStop() { return stop; } public static long getTmo() { return tmo.get(); } public static long getMaxTmo() { return maxTmo.get(); } public static int getSyncs() { return syncs.get(); } public static long getNegTime() { return negTime.get(); } public static int getTxCount() { return txCount; } public static double getAcBP2D() { return acBP2D; } public static double getAcBP2T() { return acBP2T; } public static double getAcHP2D() { return acHP2D; } public static double getAcHP2T() { return acHP2T; } public static double getAcHT2D() { return acHT2D; } public static int getNeb() { return neb; } public static int getNob() { return nob; } public static int getTxInBlock() { return txInBlock; } public static int getStBlockNum() { return stBlockNum; } public static double getAcBP2DL() { return acBP2DL; } public static double getAcHD2DL() { return acHD2DL; } public static double getAcHP2DL() { return acHP2DL; } public static boolean isActive() { return active.get(); } private static void collectForBlock(BCStat b) { long curr = System.currentTimeMillis(); nob++; if (b.txCount == 0) { neb++; } txCount += b.txCount; if (b.pid == id) { stBlockNum++; acBP2T += b.hst.getTentativeTime() - b.bst .getProposeTime(); acBP2D += b.hst.getDefiniteTime() - b.bst .getProposeTime(); acBP2DL += curr - b.bst.getProposeTime(); acHP2T += b.hst.getTentativeTime() - b.hst .getProposeTime(); acHP2D += b.hst.getDefiniteTime() - b.hst .getProposeTime(); acHT2D += b.hst.getDefiniteTime() - b.hst .getTentativeTime(); acHP2DL += curr - b.hst.getProposeTime(); acHD2DL += curr - b.hst.getDefiniteTime(); } } private static void collectReasults() throws InterruptedException { int workers = Config.getC(); int h = getH1(); while (active.get()) { for (int i = 0 ; i < workers ; i++) { BCStat b = BCS.bGetBCStat(i, h); if (b == null) continue; collectForBlock(b); } h++; } } }
U131025/FRDStravaClient
FRDStravaClientDemo/FRDStravaClientDemo/UploadViewController.h
// // UploadViewController.h // FRDStravaClientDemo // // Created by <NAME> on 6/9/14. // Copyright (c) 2014 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> @interface UploadViewController : UIViewController @end
hjc851/Dataset2-HowToDetectAdvancedSourceCodePlagiarism
Variant Programs/3-3/21/GSim.java
<gh_stars>0 public class GSim { public GSim(int northwestward, int transcaucasian) { northeasternAtoll = new Isla("N", northwestward); southeastArchipelago = new Isla("S", transcaucasian); } private Isla northeasternAtoll; public synchronized void initiating() { northeasternAtoll.conduct(); southeastArchipelago.conduct(); } private Isla southeastArchipelago; }
fishstormX/logsight
logsight-admin/src/main/java/cn/fishmaple/logsight/analyser/logFilter/LogFilterConsts.java
<gh_stars>10-100 package cn.fishmaple.logsight.analyser.logFilter; public class LogFilterConsts { public final static String TRACE_LOGLEVEL = "TRACE"; public final static String DEBUG_LOGLEVEL = "DEBUG"; public final static String INFO_LOGLEVEL = "INFO"; public final static String WARN_LOGLEVEL = "WARN"; public final static String ERROR_LOGLEVEL = "ERROR"; public final static LogFilter EXCEPTION_FILTER = new ExceptionLogFilter(); public final static LogLevelLogFilter TRACE_LOGLEVEL_FILTER = new LogLevelLogFilter(TRACE_LOGLEVEL,DEBUG_LOGLEVEL,INFO_LOGLEVEL,WARN_LOGLEVEL,ERROR_LOGLEVEL); public final static LogLevelLogFilter DEBUG_LOGLEVEL_FILTER = new LogLevelLogFilter(DEBUG_LOGLEVEL,INFO_LOGLEVEL,WARN_LOGLEVEL,ERROR_LOGLEVEL); public final static LogLevelLogFilter INFO_LOGLEVEL_FILTER = new LogLevelLogFilter(INFO_LOGLEVEL,WARN_LOGLEVEL,ERROR_LOGLEVEL); public final static LogLevelLogFilter WARN_LOGLEVEL_FILTER = new LogLevelLogFilter(WARN_LOGLEVEL,ERROR_LOGLEVEL); public final static LogLevelLogFilter ERROR_LOGLEVEL_FILTER = new LogLevelLogFilter(ERROR_LOGLEVEL); }
fengsam6/cloundDemo
user-auth/src/main/java/com/feng/auth/service/DBUserDetailsService.java
<reponame>fengsam6/cloundDemo<filename>user-auth/src/main/java/com/feng/auth/service/DBUserDetailsService.java package com.feng.auth.service; import com.feng.auth.entity.JwtUser; import com.feng.common.entity.ResponseResult; import com.feng.user.entity.SkUser; import com.feng.auth.feign.UserClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import java.util.ArrayList; public class DBUserDetailsService implements UserDetailsService { @Autowired private UserClient userClient; @Override public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException { ResponseResult<SkUser> userResponse = userClient.getUserByUserName(userName); SkUser user = userResponse.getData(); if (user == null) { return null; } return new JwtUser(user.getId(),userName, user.getPassword()); } }
fossabot/thonk-bot
events/message.js
const db = require('quick.db'); const config = require('../cfg/config.js'); exports.run = async (client, message, respondFile, talkedRecently) => { let prefix; if (message.channel.type === 'text') { const prefixFetched = await db.fetch(`prefix_${message.guild.id}`); prefixFetched ? prefix = prefixFetched : prefix = config.prefix; } else prefix = config.prefix; const prefixMention = new RegExp(`^<@!?${client.user.id}>`); if (message.content.match(prefixMention) && message.channel.type === 'text') message.channel.send(`**My prefix here is** \`${prefix}\` `); const args = message.content.slice(prefix.length).trim().split(/ +/g); const commandName = args.shift().toLowerCase(); if(message.author.bot || !message.content.startsWith(prefix)) return; if (talkedRecently.has(message.author.id)) return message.reply('please wait 3 seconds').then(m => m.delete(3000)); if (!config.ownerID.includes(message.author.id)) talkedRecently.add(message.author.id); setTimeout(() => { talkedRecently.delete(message.author.id); }, 3000); const command = client.commands.get(commandName) || client.commands.find(command => command.aliases && command.aliases.includes(commandName)); //eslint-disable-line no-shadow if (!command) return; if (command.hidden && config.ownerID.includes(message.author.id)) return; if (command.guildOnly && message.channel.type !== 'text') return message.reply(`${message.author}, I can\'t execute that command inside DMs!`); if (command.args && !args.length) { let reply = `\<:redtick:412529964945113100> You didn\'t provide any arguments, ${message.author}!`; if (command.usage) reply += `\nThe proper usage would be: \`${prefix}${command.name} ${command.usage}\``; return message.channel.send(reply); } if (command.ownerOnly && !config.ownerID.includes(message.author.id)) return message.channel.send(`${message.author}, you don\'t have permission to use this command!`); try { command.execute(message, args); console.log(`${message.author.username} used the command '${command.name}' `); } catch (err) { console.log(err); } };
shyrwinsia/saxo_openapi
tests/test_chart_charts.py
<gh_stars>10-100 # -*- coding: utf-8 -*- """Tests for `saxo_openapi` package.""" import requests_mock from .unittestsetup import test_generic, ReqMockTest import saxo_openapi.endpoints.chart as ch from parameterized import parameterized class TestSaxo_Chart_Charts(ReqMockTest): """Tests for `chart-charts` endpoints.""" def setUp(self): super(TestSaxo_Chart_Charts, self).setUp() @parameterized.expand([ (ch.charts, "GetChartData", {}), (ch.charts, "CreateChartDataSubscription", {"data": { "Arguments": { "AssetType": "FxSpot", "Count": 2, "Horizon": 1, "Uic": 21 }, "ContextId": "20190830035501020", "Format": "application/json", "ReferenceId": "UIC_21", "RefreshRate": 1000 }}), (ch.charts, "ChartDataRemoveSubscriptions", {'ContextId': 'ctxt_20190311'}), (ch.charts, "ChartDataRemoveSubscription", {'ContextId': 'ctxt_20190311', 'ReferenceId': 'UIC_21'}) ]) @requests_mock.Mocker(kw='mock') def test_all(self, _mod, clsNm, route, **kwargs): test_generic(self, _mod, clsNm, route, **kwargs)
victor-lh/spotify-web-api-client
spotify-web-api-client/src/main/java/com/victorlh/spotify/apiclient/models/deserializer/PlayableItemDeserializer.java
<filename>spotify-web-api-client/src/main/java/com/victorlh/spotify/apiclient/models/deserializer/PlayableItemDeserializer.java<gh_stars>0 package com.victorlh.spotify.apiclient.models.deserializer; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.ObjectCodec; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import com.victorlh.spotify.apiclient.models.IPlayableItem; import com.victorlh.spotify.apiclient.models.enums.PlayableType; import com.victorlh.spotify.apiclient.models.objects.EpisodeObject; import com.victorlh.spotify.apiclient.models.objects.TrackObject; import org.apache.commons.lang3.StringUtils; import java.io.IOException; public class PlayableItemDeserializer extends StdDeserializer<IPlayableItem> { public PlayableItemDeserializer() { this(null); } public PlayableItemDeserializer(Class<?> vc) { super(vc); } protected IPlayableItem getPlayable(JsonParser jp, JsonNode node) throws JsonProcessingException { ObjectCodec codec = jp.getCodec(); JsonNode typeNode = node.get("type"); String type = typeNode == null ? null : typeNode.asText(); if (type != null) { if (StringUtils.equals(PlayableType.track.name(), type)) { return codec.treeToValue(node, TrackObject.class); } if (StringUtils.equals(PlayableType.episode.name(), type)) { return codec.treeToValue(node, EpisodeObject.class); } } else { return getPlayableByError(jp, node); } return null; } protected IPlayableItem getPlayableByError(JsonParser jp, JsonNode node) throws JsonProcessingException { ObjectCodec codec = jp.getCodec(); JsonProcessingException error; try { return codec.treeToValue(node, TrackObject.class); } catch (JsonProcessingException e) { error = e; } try { return codec.treeToValue(node, EpisodeObject.class); } catch (JsonProcessingException ignored) { } throw error; } @Override public IPlayableItem deserialize(JsonParser jp, DeserializationContext ctx) throws IOException { ObjectCodec codec = jp.getCodec(); JsonNode node = codec.readTree(jp); return getPlayable(jp, node); } }
project-William/RenderX
RenderX/src/RenderX/Base/Event/MouseEvent.h
#pragma once #include "Event.h" namespace renderx::base { class MouseMovedEvent :public Event { private: float m_Xpos, m_Ypos; public: MouseMovedEvent(float x, float y) :m_Xpos(x), m_Ypos(y) { } ~MouseMovedEvent() {} float GetMouseXPos()const { return m_Xpos; } float GetMouseYPos()const { return m_Ypos; } glm::vec2 GetMousePos()const { return glm::vec2(m_Xpos, m_Ypos); } EVENT_CLASS_TYPE(RX_MOUSE_MOVE) EVENT_NAME_TYPE(RX_MOUSE_MOVE) EVENT_CATEGORY_TYPE(RX_EVENT_CATEGORY_MOUSE | RX_EVENT_CATEGORY_INPUT) }; class MouseScrollEvent :public Event { private: float m_XOffset, m_YOffset; public: MouseScrollEvent(float xoffset, float yoffset) :m_XOffset(xoffset), m_YOffset(yoffset) { } ~MouseScrollEvent() {} float GetXOffset()const { return m_XOffset; } float GetYOffset()const { return m_YOffset; } EVENT_CLASS_TYPE(RX_MOUSE_SCROLL) EVENT_NAME_TYPE(RX_MOUSE_SCROLL) EVENT_CATEGORY_TYPE(RX_EVENT_CATEGORY_MOUSE | RX_EVENT_CATEGORY_INPUT) }; class MouseButtonEvent :public Event { protected: int m_MouseButton; MouseButtonEvent(int button) :m_MouseButton(button) { } public: int GetMouseButton()const { return m_MouseButton; } EVENT_CLASS_TYPE(RX_MOUSE_BUTTON) EVENT_NAME_TYPE(RX_MOUSE_BUTTON) EVENT_CATEGORY_TYPE(RX_EVENT_CATEGORY_MOUSE | RX_EVENT_CATEGORY_MOUSE_BUTTON | RX_EVENT_CATEGORY_INPUT) }; class MousePressedEvent :public MouseButtonEvent { public: MousePressedEvent(int button) :MouseButtonEvent(button) { } EVENT_CLASS_TYPE(RX_MOUSE_PRESS) EVENT_NAME_TYPE(RX_MOUSE_PRESS) }; class MouseRelasedEvent :public MouseButtonEvent { public: MouseRelasedEvent(int button) :MouseButtonEvent(button) { } EVENT_CLASS_TYPE(RX_MOUSE_RELEASE) EVENT_NAME_TYPE(RX_MOUSE_RELEASE) }; }
refactorzone/spring-boot-validators
src/main/java/zone/refactor/spring/validation/validator/UuidValidator.java
package zone.refactor.spring.validation.validator; import java.util.regex.Pattern; public class UuidValidator extends PatternValidator { private final static Pattern pattern = Pattern.compile( "\\A[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\\Z" ); public UuidValidator() { super(pattern); } @Override public String getErrorKey() { return BuiltInError.UUID.toString(); } @Override public boolean equals(Object other) { return other instanceof UuidValidator; } }
dkov01/TSS.MSR
TSS.Java/src/tss/tpm/TPM2_VerifySignature_REQUEST.java
package tss.tpm; import tss.*; // -----------This is an auto-generated file: do not edit //>>> /** * This command uses loaded keys to validate a signature on a message with the * message digest passed to the TPM. */ public class TPM2_VerifySignature_REQUEST extends TpmStructure { /** * handle of public key that will be used in the validation * Auth Index: None */ public TPM_HANDLE keyHandle; /** digest of the signed message */ public byte[] digest; /** signature to be tested */ public TPMU_SIGNATURE signature; public TPM2_VerifySignature_REQUEST() {} /** * @param _keyHandle handle of public key that will be used in the validation * Auth Index: None * @param _digest digest of the signed message * @param _signature signature to be tested * (One of [TPMS_SIGNATURE_RSASSA, TPMS_SIGNATURE_RSAPSS, TPMS_SIGNATURE_ECDSA, * TPMS_SIGNATURE_ECDAA, TPMS_SIGNATURE_SM2, TPMS_SIGNATURE_ECSCHNORR, TPMT_HA, * TPMS_SCHEME_HASH, TPMS_NULL_SIGNATURE]) */ public TPM2_VerifySignature_REQUEST(TPM_HANDLE _keyHandle, byte[] _digest, TPMU_SIGNATURE _signature) { keyHandle = _keyHandle; digest = _digest; signature = _signature; } public int GetUnionSelector_signature() { if (signature instanceof TPMS_SIGNATURE_RSASSA) { return 0x0014; } if (signature instanceof TPMS_SIGNATURE_RSAPSS) { return 0x0016; } if (signature instanceof TPMS_SIGNATURE_ECDSA) { return 0x0018; } if (signature instanceof TPMS_SIGNATURE_ECDAA) { return 0x001A; } if (signature instanceof TPMS_SIGNATURE_SM2) { return 0x001B; } if (signature instanceof TPMS_SIGNATURE_ECSCHNORR) { return 0x001C; } if (signature instanceof TPMT_HA) { return 0x0005; } if (signature instanceof TPMS_SCHEME_HASH) { return 0x7FFF; } if (signature instanceof TPMS_NULL_SIGNATURE) { return 0x0010; } throw new RuntimeException("Unrecognized type"); } @Override public void toTpm(OutByteBuf buf) { keyHandle.toTpm(buf); buf.writeInt(digest != null ? digest.length : 0, 2); if (digest != null) buf.write(digest); buf.writeInt(GetUnionSelector_signature(), 2); ((TpmMarshaller)signature).toTpm(buf); } @Override public void initFromTpm(InByteBuf buf) { keyHandle = TPM_HANDLE.fromTpm(buf); int _digestSize = buf.readInt(2); digest = new byte[_digestSize]; buf.readArrayOfInts(digest, 1, _digestSize); int _signatureSigAlg = buf.readInt(2); signature=null; if(_signatureSigAlg==TPM_ALG_ID.RSASSA.toInt()) {signature = new TPMS_SIGNATURE_RSASSA();} else if(_signatureSigAlg==TPM_ALG_ID.RSAPSS.toInt()) {signature = new TPMS_SIGNATURE_RSAPSS();} else if(_signatureSigAlg==TPM_ALG_ID.ECDSA.toInt()) {signature = new TPMS_SIGNATURE_ECDSA();} else if(_signatureSigAlg==TPM_ALG_ID.ECDAA.toInt()) {signature = new TPMS_SIGNATURE_ECDAA();} // code generator workaround BUGBUG >> (probChild)else if(_signatureSigAlg==TPM_ALG_ID.SM2.toInt()) {signature = new TPMS_SIGNATURE_SM2();} // code generator workaround BUGBUG >> (probChild)else if(_signatureSigAlg==TPM_ALG_ID.ECSCHNORR.toInt()) {signature = new TPMS_SIGNATURE_ECSCHNORR();} else if(_signatureSigAlg==TPM_ALG_ID.HMAC.toInt()) {signature = new TPMT_HA();} else if(_signatureSigAlg==TPM_ALG_ID.ANY.toInt()) {signature = new TPMS_SCHEME_HASH();} else if(_signatureSigAlg==TPM_ALG_ID.NULL.toInt()) {signature = new TPMS_NULL_SIGNATURE();} if (signature == null) throw new RuntimeException("Unexpected type selector " + TPM_ALG_ID.fromInt(_signatureSigAlg).name()); signature.initFromTpm(buf); } @Override public byte[] toTpm() { OutByteBuf buf = new OutByteBuf(); toTpm(buf); return buf.getBuf(); } public static TPM2_VerifySignature_REQUEST fromTpm (byte[] x) { TPM2_VerifySignature_REQUEST ret = new TPM2_VerifySignature_REQUEST(); InByteBuf buf = new InByteBuf(x); ret.initFromTpm(buf); if (buf.bytesRemaining()!=0) throw new AssertionError("bytes remaining in buffer after object was de-serialized"); return ret; } public static TPM2_VerifySignature_REQUEST fromTpm (InByteBuf buf) { TPM2_VerifySignature_REQUEST ret = new TPM2_VerifySignature_REQUEST(); ret.initFromTpm(buf); return ret; } @Override public String toString() { TpmStructurePrinter _p = new TpmStructurePrinter("TPM2_VerifySignature_REQUEST"); toStringInternal(_p, 1); _p.endStruct(); return _p.toString(); } @Override public void toStringInternal(TpmStructurePrinter _p, int d) { _p.add(d, "TPM_HANDLE", "keyHandle", keyHandle); _p.add(d, "byte", "digest", digest); _p.add(d, "TPMU_SIGNATURE", "signature", signature); } } //<<<
LLiuHuan/arco-design-pro-gin
api/v1/enter.go
<filename>api/v1/enter.go package v1 import ( "github.com/lliuhuan/arco-design-pro-gin/api/v1/example" "github.com/lliuhuan/arco-design-pro-gin/api/v1/system" ) type ApiV1Group struct { System system.ApiGroup Example example.ApiGroup } var ApiV1GroupApp = new(ApiV1Group)
salbertson/gitsh
lib/gitsh/tab_completion/dsl/concatenation_factory.rb
module Gitsh module TabCompletion module DSL class ConcatenationFactory attr_reader :parts def initialize(parts) @parts = parts end def build(start_state, options = {}) with_optional_end_state(options) do parts.inject(start_state) do |state, part| part.build(state, options) end end end private def with_optional_end_state(options) end_state = options.delete(:end_state) if end_state last_state = yield last_state.add_free_transition(end_state) end_state else yield end end end end end end
ultimatezen/felix
Felix/action_delete_matches.h
<gh_stars>0 #pragma once #include "undoable_action.h" #include "TranslationMemory.h" #include "record.h" #include "FelixModelInterface.h" namespace action { /** Deletes specified group of matches from TM */ class ActionDeleteMatches : public UndoableAction { public: typedef std::vector<mem_engine::search_match_ptr> match_vec ; model_iface_ptr m_controller ; match_vec m_matches ; ActionDeleteMatches(model_iface_ptr controller, match_vec &matches); void undo(); void redo(); wstring name(); } ; }
pigatron-industries/xen_sequence
src/sequencer_src/interface/views/parameters/TickEventsParameterView.h
#ifndef TickEventParameterView_h #define TickEventParameterView_h #include <inttypes.h> #include "AbstractParameterView.h" #include "EventParameterView.h" #include "sequencer/midi/MidiEventHandler.h" #include "model/SequenceTickEvents.h" #define MAX_EVENTS 5 class TickEventsParameterView : public AbstractParameterView { public: TickEventsParameterView(); //virtual InterfaceEvent handleEvent(InterfaceEvent event); void setTickEvents(SequenceTickEvents* tickEvents, uint16_t barIndex, uint8_t channelIndex, uint8_t tickIndex); SequenceTickEvents* getTickEvents() { return tickEvents; } bool handleMidiEvent(const MidiMessage& message); int getSelectedEventIndex(); protected: virtual void updateDataFromField(ParameterField* field); private: EventParameterView eventParametersViews[MAX_EVENTS]; SequenceTickEvents* tickEvents; uint16_t barIndex; uint8_t channelIndex; uint8_t tickIndex; EventParameterView* getSelectedEventParameters(); bool handleMidiMessage(const MidiMessage& message, EventType eventType); int getMatchingEventIndex(const MidiMessage& message, int startIndex = 0); int createEvent(EventType eventType); }; #endif
sukhmankhangura/micropurchase-develop
app/view_models/confirm_bid_view_model.rb
<gh_stars>0 class ConfirmBidViewModel attr_reader :auction, :bid def initialize(auction:, bid:) @auction = auction @bid = bid end def auction_id auction.id end def bid_amount bid.amount end def title auction.title end def time_left "Ends in #{distance_of_time_to_now}" end def html_description MarkdownRender.new(auction.description).to_s end private def distance_of_time_to_now HumanTime.new(time: auction.ended_at).distance_of_time_to_now end end
AnnaPedko/ICTasks
task24/task24/main.c
// // main.c // task24 // // Created by <NAME>. on 12.04.17. // Copyright © 2017 <NAME>. All rights reserved. // //2. Створити функцію, яка б як параметр приймала bool, а повертала строку true або false в залужності від значення параметру. /* Також, є група математичних операцій, яка виконується над числами, результатом яких є bool: > - більше - вертає правду, якщо лівий операнд більший за правий; >= - більше або дорівнює - вертає правду, якщо лівий операнд більше або дорівнює правому; < - менше - вертає правду, якщо лівий операнд менший за правий; <= - менше або дорівнює - вертає правду, якщо лівий операнд менше або дорівнює правому; != - не дорвінює - вертає правду, якщо лівий операнд не дорівнює правому; == - дорвінює - вертає правду, якщо лівий операнд дорівнює правому. */ #include <stdio.h> #include "ICReturnBool.h" int main(int argc, const char * argv[]) { int firstOperand = 10; int secondOperand = 15; printf("%i > %i -> %s\n", secondOperand, firstOperand, ICReturnBool(secondOperand > firstOperand)); printf("%i >= %i -> %s\n", secondOperand, firstOperand, ICReturnBool(secondOperand >= firstOperand)); printf("%i < %i -> %s\n", secondOperand, firstOperand, ICReturnBool(secondOperand < firstOperand)); printf("%i < %i -> %s\n", firstOperand, secondOperand, ICReturnBool(firstOperand < secondOperand)); printf("%i >= %i -> %s\n", firstOperand, secondOperand, ICReturnBool(firstOperand >= secondOperand)); printf("%i <= %i -> %s\n", firstOperand, secondOperand, ICReturnBool(firstOperand <= secondOperand)); printf("%i != %i -> %s\n", firstOperand, secondOperand, ICReturnBool(firstOperand != secondOperand)); printf("%i == %i -> %s\n", firstOperand, secondOperand, ICReturnBool(firstOperand == secondOperand)); printf("%i == %i -> %s\n", firstOperand, firstOperand, ICReturnBool(firstOperand == firstOperand)); return 0; }
josehu07/SplitFS
kernel/linux-5.4/sound/soc/codecs/88pm860x-codec.h
/* SPDX-License-Identifier: GPL-2.0-only */ /* * 88pm860x-codec.h -- 88PM860x ALSA SoC Audio Driver * * Copyright 2010 Marvell International Ltd. * <NAME> <<EMAIL>> */ #ifndef __88PM860X_H #define __88PM860X_H #define PM860X_PCM_IFACE_1 0xb0 #define PM860X_PCM_IFACE_2 0xb1 #define PM860X_PCM_IFACE_3 0xb2 #define PM860X_PCM_RATE 0xb3 #define PM860X_EC_PATH 0xb4 #define PM860X_SIDETONE_L_GAIN 0xb5 #define PM860X_SIDETONE_R_GAIN 0xb6 #define PM860X_SIDETONE_SHIFT 0xb7 #define PM860X_ADC_OFFSET_1 0xb8 #define PM860X_ADC_OFFSET_2 0xb9 #define PM860X_DMIC_DELAY 0xba #define PM860X_I2S_IFACE_1 0xbb #define PM860X_I2S_IFACE_2 0xbc #define PM860X_I2S_IFACE_3 0xbd #define PM860X_I2S_IFACE_4 0xbe #define PM860X_EQUALIZER_N0_1 0xbf #define PM860X_EQUALIZER_N0_2 0xc0 #define PM860X_EQUALIZER_N1_1 0xc1 #define PM860X_EQUALIZER_N1_2 0xc2 #define PM860X_EQUALIZER_D1_1 0xc3 #define PM860X_EQUALIZER_D1_2 0xc4 #define PM860X_LOFI_GAIN_LEFT 0xc5 #define PM860X_LOFI_GAIN_RIGHT 0xc6 #define PM860X_HIFIL_GAIN_LEFT 0xc7 #define PM860X_HIFIL_GAIN_RIGHT 0xc8 #define PM860X_HIFIR_GAIN_LEFT 0xc9 #define PM860X_HIFIR_GAIN_RIGHT 0xca #define PM860X_DAC_OFFSET 0xcb #define PM860X_OFFSET_LEFT_1 0xcc #define PM860X_OFFSET_LEFT_2 0xcd #define PM860X_OFFSET_RIGHT_1 0xce #define PM860X_OFFSET_RIGHT_2 0xcf #define PM860X_ADC_ANA_1 0xd0 #define PM860X_ADC_ANA_2 0xd1 #define PM860X_ADC_ANA_3 0xd2 #define PM860X_ADC_ANA_4 0xd3 #define PM860X_ANA_TO_ANA 0xd4 #define PM860X_HS1_CTRL 0xd5 #define PM860X_HS2_CTRL 0xd6 #define PM860X_LO1_CTRL 0xd7 #define PM860X_LO2_CTRL 0xd8 #define PM860X_EAR_CTRL_1 0xd9 #define PM860X_EAR_CTRL_2 0xda #define PM860X_AUDIO_SUPPLIES_1 0xdb #define PM860X_AUDIO_SUPPLIES_2 0xdc #define PM860X_ADC_EN_1 0xdd #define PM860X_ADC_EN_2 0xde #define PM860X_DAC_EN_1 0xdf #define PM860X_DAC_EN_2 0xe1 #define PM860X_AUDIO_CAL_1 0xe2 #define PM860X_AUDIO_CAL_2 0xe3 #define PM860X_AUDIO_CAL_3 0xe4 #define PM860X_AUDIO_CAL_4 0xe5 #define PM860X_AUDIO_CAL_5 0xe6 #define PM860X_ANA_INPUT_SEL_1 0xe7 #define PM860X_ANA_INPUT_SEL_2 0xe8 #define PM860X_PCM_IFACE_4 0xe9 #define PM860X_I2S_IFACE_5 0xea #define PM860X_SHORTS 0x3b #define PM860X_PLL_ADJ_1 0x3c #define PM860X_PLL_ADJ_2 0x3d /* bits definition */ #define PM860X_CLK_DIR_IN 0 #define PM860X_CLK_DIR_OUT 1 #define PM860X_DET_HEADSET (1 << 0) #define PM860X_DET_MIC (1 << 1) #define PM860X_DET_HOOK (1 << 2) #define PM860X_SHORT_HEADSET (1 << 3) #define PM860X_SHORT_LINEOUT (1 << 4) #define PM860X_DET_MASK 0x1F extern int pm860x_hs_jack_detect(struct snd_soc_component *, struct snd_soc_jack *, int, int, int, int); extern int pm860x_mic_jack_detect(struct snd_soc_component *, struct snd_soc_jack *, int); #endif /* __88PM860X_H */
transitive-bullshit/puppeteer-email
packages/puppeteer-email-provider-yahoo/lib/signup.js
'use strict' // TODO: remove manual inputs for edge cases and bail instead -- breaks batch jobs const delay = require('delay') // const faker = require('faker') // TODO module.exports = async (user, opts) => { const { smsNumberVerifier, browser } = opts const page = await browser.newPage() await page.goto('https://login.yahoo.com/account/create') // basic user info // --------------- await page.type('input[name=firstName]', user.firstName, { delay: 40 }) await delay(250) await page.type('input[name=lastName]', user.lastName, { delay: 8 }) await delay(330) await page.type('input[name=yid]', user.username, { delay: 32 }) await delay(134) // sms validation // -------------- if (!smsNumberVerifier) { throw new Error('sms validation required') } let attempts = 0 let service = 'yahoo' let number do { number = await smsNumberVerifier.getNumber({ service }) if (!number) throw new Error() // TODO const info = smsNumberVerifier.getNumberInfo(number) if (!info || !info.isValid()) throw new Error() // TODO // select country code prefix await page.select('select[name=shortCountryCode]', info.getRegionCode().toUpperCase()) // ignore country code prefix const shortNumber = info.getNumber('significant') await page.type('input[name=phone]', shortNumber, { delay: 13 }) // birth date // ---------- await delay(33) await page.type('input[name=password]', user.password, { delay: 3 }) await delay(47) await page.select('select[name=mm]', user.birthday.month) await delay(62) await page.type('input[name=dd]', user.birthday.day) await delay(23) await page.type('input[name=yyyy]', user.birthday.year) await delay(76) await Promise.all([ page.click('button[type=submit]', { delay: 9 }), page.waitForNavigation({ timeout: 0 }) ]) await delay(1000) let error = null if (await page.$('#reg-error-phone')) { await page.waitFor('#reg-error-phone', { visible: true }) .then(() => page.$eval('#reg-error-phone', (e) => e.innerText)) .then((e) => { error = e.trim() }) } if (error) { ++attempts console.warn(`phone number error "${number}" (${attempts} attempts):`, error) if (smsNumberVerifier.provider.addNumberToBlacklist) { const result = await smsNumberVerifier.provider.addNumberToBlacklist({ service, number }) console.warn('sms adding to blacklist', { service, number }, result) } if (++attempts > 3) { throw new Error(`phone number error: ${error}`) } await delay(5000) } else { break } } while (true) // TODO: waitForNavigation also happens for errors and wipes out most fields // birth date, password, and phone number stuffs // if there's an error, // sms validation // -------------- let waitForNavigation = true const waitForManualInput = async (msg) => { console.warn(msg) console.warn('waiting for manual input...') await page.waitForNavigation({ timeout: 200000 }) waitForNavigation = false } if (await page.$('button[type=submit][name=sendCode]')) { await page.click('button[type=submit][name=sendCode]', { delay: 9 }) await page.waitFor('input[name=code]') const authCodes = await smsNumberVerifier.getAuthCodes({ number, service }) console.log('sms request', service, number, authCodes) if (authCodes.length) { for (let i = 0; i < authCodes.length; ++i) { const code = authCodes[i] await page.type('input[name=code]', code) let error = false await Promise.all([ page.click('button[name=verifyCode]', { delay: 4 }), Promise.race([ page.waitForNavigation({ timeout: 0 }) .then(() => { waitForNavigation = false }), page.waitFor('.error-msg', { visible: true }) .then(() => page.$eval('.error-msg', (e) => e.innerText)) .then((e) => { error = e.trim() }) ]) ]) if (error) { console.warn('sms code error', { number, code }, error) await delay(1000) await page.focus('input[type=code]') for (let i = 0; i < code.length + 8; ++i) { await page.keyboard.press('Backspace') } await delay(1000) } else { break } } } if (waitForNavigation) { await waitForManualInput('sms number verification failed') } } await page.waitFor('.mail-button-wait button[type=submit]', { visible: true }) await Promise.all([ page.click('.mail-button-wait button[type=submit]', { delay: 9 }), page.waitForNavigation() ]) // main account page // ----------------- await page.goto('http://mail.yahoo.com/') // email inbox first-run // --------------------- await delay(800) // close any first-run dialogs while (true) { if (!await page.$('button[title=Close]')) break await page.click('button[title=Close]', { delay: 9 }) await delay(350) try { await page.click('button[title="Not now"]', { delay: 9 }) } catch (err) { } } // should now be at https://mail.yahoo.com/mail/inbox await page.close() }
ochibooh/square-java-sdk
src/main/java/com/squareup/square/models/RetrieveInventoryChangesResponse.java
package com.squareup.square.models; import java.util.Objects; import java.util.*; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonGetter; import com.squareup.square.http.client.HttpContext; public class RetrieveInventoryChangesResponse { @JsonCreator public RetrieveInventoryChangesResponse( @JsonProperty("errors") List<Error> errors, @JsonProperty("changes") List<InventoryChange> changes, @JsonProperty("cursor") String cursor) { this.errors = errors; this.changes = changes; this.cursor = cursor; } private HttpContext httpContext; private final List<Error> errors; private final List<InventoryChange> changes; private final String cursor; @Override public int hashCode() { return Objects.hash(errors, changes, cursor); } @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof RetrieveInventoryChangesResponse)) { return false; } RetrieveInventoryChangesResponse retrieveInventoryChangesResponse = (RetrieveInventoryChangesResponse) o; return Objects.equals(errors, retrieveInventoryChangesResponse.errors) && Objects.equals(changes, retrieveInventoryChangesResponse.changes) && Objects.equals(cursor, retrieveInventoryChangesResponse.cursor); } public HttpContext getContext() { return httpContext; } /** * Getter for Errors. * Any errors that occurred during the request. */ @JsonGetter("errors") public List<Error> getErrors() { return this.errors; } /** * Getter for Changes. * The set of inventory changes for the requested object and locations. */ @JsonGetter("changes") public List<InventoryChange> getChanges() { return this.changes; } /** * Getter for Cursor. * The pagination cursor to be used in a subsequent request. If unset, * this is the final response. * See the [Pagination](https://developer.squareup.com/docs/docs/working-with-apis/pagination) guide for more information. */ @JsonGetter("cursor") public String getCursor() { return this.cursor; } public Builder toBuilder() { Builder builder = new Builder() .errors(getErrors()) .changes(getChanges()) .cursor(getCursor()); return builder; } public static class Builder { private HttpContext httpContext; private List<Error> errors; private List<InventoryChange> changes; private String cursor; public Builder() { } public Builder httpContext(HttpContext httpContext) { this.httpContext = httpContext; return this; } public Builder errors(List<Error> value) { errors = value; return this; } public Builder changes(List<InventoryChange> value) { changes = value; return this; } public Builder cursor(String value) { cursor = value; return this; } public RetrieveInventoryChangesResponse build() { RetrieveInventoryChangesResponse model = new RetrieveInventoryChangesResponse(errors, changes, cursor); model.httpContext = httpContext; return model; } } }
TimothyGillespie/lombok-intellij-plugin
test-manual/src/main/java/de/plushnikov/findusages/FindUsageWither.java
package de.plushnikov.findusages; import lombok.Value; import lombok.With; import lombok.experimental.Wither; @With @Value public class FindUsageWither { private int foo; private String bar; public static void main(String[] args) { FindUsageWither findUsageWither = new FindUsageWither(1, "bar"); findUsageWither .withBar("myBar") .withFoo(1981); System.out.println("Bar is: " + findUsageWither.getBar()); System.out.println("Foo is: " + findUsageWither.getFoo()); } }
skyflashde/nf-interpreter
targets/FreeRTOS_ESP32/ESP32_WROOM_32/Include/CLR_Startup_Thread.h
// // Copyright (c) 2017 The nanoFramework project contributors // See LICENSE file in the project root for full license information. // #ifndef _CLRSTARTUPTHREAD_ #define _CLRSTARTUPTHREAD_ // declaration of RTOS thread void CLRStartupThread(void const * argument); #endif //_CLRSTARTUPTHREAD_
zhoujiagen/giant-data-analysis
temporal-data-and-realtime-algorithm/temporal-apache-spark-streaming/src/main/java/com/spike/giantdataanalysis/spark/streaming/support/package-info.java
/** * */ /** * @author jiedong * */ package com.spike.giantdataanalysis.spark.streaming.support;
UM-ARM-Lab/mab_ms
deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgWrappers/osgFX/Effect.cpp
// *************************************************************************** // // Generated automatically by genwrapper. // Please DO NOT EDIT this file! // // *************************************************************************** #include <osgIntrospection/ReflectionMacros> #include <osgIntrospection/TypedMethodInfo> #include <osgIntrospection/StaticMethodInfo> #include <osgIntrospection/Attributes> #include <osg/CopyOp> #include <osg/NodeVisitor> #include <osg/Object> #include <osgFX/Effect> #include <osgFX/Technique> // Must undefine IN and OUT macros defined in Windows headers #ifdef IN #undef IN #endif #ifdef OUT #undef OUT #endif BEGIN_ENUM_REFLECTOR(osgFX::Effect::TechniqueSelection) I_DeclaringFile("osgFX/Effect"); I_EnumLabel(osgFX::Effect::AUTO_DETECT); END_REFLECTOR BEGIN_ABSTRACT_OBJECT_REFLECTOR(osgFX::Effect) I_DeclaringFile("osgFX/Effect"); I_BaseType(osg::Group); I_Constructor0(____Effect, "", ""); I_ConstructorWithDefaults2(IN, const osgFX::Effect &, copy, , IN, const osg::CopyOp &, copyop, osg::CopyOp::SHALLOW_COPY, ____Effect__C5_Effect_R1__C5_osg_CopyOp_R1, "", ""); I_Method1(bool, isSameKindAs, IN, const osg::Object *, obj, Properties::VIRTUAL, __bool__isSameKindAs__C5_osg_Object_P1, "return true if this and obj are of the same kind of object. ", ""); I_Method0(const char *, libraryName, Properties::VIRTUAL, __C5_char_P1__libraryName, "return the name of the node's library. ", ""); I_Method0(const char *, className, Properties::VIRTUAL, __C5_char_P1__className, "return the name of the node's class type. ", ""); I_Method0(const char *, effectName, Properties::PURE_VIRTUAL, __C5_char_P1__effectName, "get the name of this Effect ", ""); I_Method0(const char *, effectDescription, Properties::PURE_VIRTUAL, __C5_char_P1__effectDescription, "get a brief description of this Effect ", ""); I_Method0(const char *, effectAuthor, Properties::PURE_VIRTUAL, __C5_char_P1__effectAuthor, "get the effect author's name ", ""); I_Method0(bool, getEnabled, Properties::NON_VIRTUAL, __bool__getEnabled, "get whether the effect is enabled or not ", ""); I_Method1(void, setEnabled, IN, bool, v, Properties::NON_VIRTUAL, __void__setEnabled__bool, "set whether the effect is enabled or not ", ""); I_Method0(void, setUpDemo, Properties::VIRTUAL, __void__setUpDemo, "optional: set effect parameters to produce a visually significant result to be used in demo applications like osgfxbrowser. ", "Default is to do nothing. "); I_Method0(int, getNumTechniques, Properties::NON_VIRTUAL, __int__getNumTechniques, "get the number of techniques defined for this Effect ", ""); I_Method1(osgFX::Technique *, getTechnique, IN, int, i, Properties::NON_VIRTUAL, __Technique_P1__getTechnique__int, "get the i-th Technique ", ""); I_Method1(const osgFX::Technique *, getTechnique, IN, int, i, Properties::NON_VIRTUAL, __C5_Technique_P1__getTechnique__int, "get the i-th const Technique ", ""); I_Method0(int, getSelectedTechnique, Properties::NON_VIRTUAL, __int__getSelectedTechnique, "get the index of the currently selected Technique ", ""); I_MethodWithDefaults1(void, selectTechnique, IN, int, i, osgFX::Effect::AUTO_DETECT, Properties::NON_VIRTUAL, __void__selectTechnique__int, "select a technique or enable automatic detection ", ""); I_Method1(void, traverse, IN, osg::NodeVisitor &, nv, Properties::VIRTUAL, __void__traverse__osg_NodeVisitor_R1, "custom traversal ", ""); I_Method1(void, inherited_traverse, IN, osg::NodeVisitor &, nv, Properties::NON_VIRTUAL, __void__inherited_traverse__osg_NodeVisitor_R1, "default traversal ", ""); I_ProtectedMethod0(void, dirtyTechniques, Properties::NON_VIRTUAL, Properties::NON_CONST, __void__dirtyTechniques, "force rebuilding of techniques on next traversal ", ""); I_ProtectedMethod1(void, addTechnique, IN, osgFX::Technique *, tech, Properties::NON_VIRTUAL, Properties::NON_CONST, __void__addTechnique__Technique_P1, "add a technique to the Effect ", ""); I_ProtectedMethod0(bool, define_techniques, Properties::PURE_VIRTUAL, Properties::NON_CONST, __bool__define_techniques, "abstract method to be implemented in derived classes; its purpose if to create the techniques that can be used for obtaining the desired effect. ", "You will usually call addTechnique() inside this method. "); I_SimpleProperty(bool, Enabled, __bool__getEnabled, __void__setEnabled__bool); I_SimpleProperty(int, SelectedTechnique, __int__getSelectedTechnique, 0); I_ArrayProperty(osgFX::Technique *, Technique, __Technique_P1__getTechnique__int, 0, __int__getNumTechniques, 0, 0, 0); END_REFLECTOR
kellyselden/ember-cli-dependency-graph
test/fixtures/code-corps-ember/code-corps-ember/transforms/array.js
<filename>test/fixtures/code-corps-ember/code-corps-ember/transforms/array.js define('code-corps-ember/transforms/array', ['exports', 'ember-data'], function (exports, _emberData) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var typeOf = Ember.typeOf; var Transform = _emberData.default.Transform; exports.default = Transform.extend({ deserialize: function deserialize(serialized) { var type = typeOf(serialized); return type === 'array' ? serialized : []; }, serialize: function serialize(deserialized) { var type = typeOf(deserialized); if (type === 'array') { return deserialized; } else if (type === 'string') { return deserialized.split(',').map(function (item) { return item.trim(); }); } else { return []; } } }); });
wedataintelligence/vivaldi-source
chromium/content/browser/time_zone_monitor_android.cc
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/time_zone_monitor_android.h" #include "base/android/context_utils.h" #include "base/android/jni_android.h" #include "jni/TimeZoneMonitor_jni.h" namespace content { TimeZoneMonitorAndroid::TimeZoneMonitorAndroid() : TimeZoneMonitor() { impl_.Reset(Java_TimeZoneMonitor_getInstance( base::android::AttachCurrentThread(), base::android::GetApplicationContext(), reinterpret_cast<intptr_t>(this))); } TimeZoneMonitorAndroid::~TimeZoneMonitorAndroid() { Java_TimeZoneMonitor_stop(base::android::AttachCurrentThread(), impl_.obj()); } // static bool TimeZoneMonitorAndroid::Register(JNIEnv* env) { return RegisterNativesImpl(env); } void TimeZoneMonitorAndroid::TimeZoneChangedFromJava( JNIEnv* env, const JavaParamRef<jobject>& caller) { NotifyRenderers(); } // static scoped_ptr<TimeZoneMonitor> TimeZoneMonitor::Create() { return scoped_ptr<TimeZoneMonitor>(new TimeZoneMonitorAndroid()); } } // namespace content
asumit499/Python-BootCamp
total_avg.py
<reponame>asumit499/Python-BootCamp<gh_stars>1-10 a=int(input("Enter the first number")) b=int(input("Enter the second number")) c=int(input("Enter the third number")) d=int(input("Enter the fourth number")) total=a+b+c+d average=total/4 print("Total of the four numbers=",total,"\naverage of the four numbers=",average)
jmckaskill/subversion
glib/gtimer.c
/* GLIB - Library of useful routines for C programming * Copyright (C) 1995-1997 <NAME>, <NAME> and <NAME> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ /* * Modified by the GLib Team and others 1997-1999. See the AUTHORS * file for a list of people on the GLib Team. See the ChangeLog * files for a list of changes. These files are distributed with * GLib at ftp://ftp.gtk.org/pub/gtk/. */ /* * MT safe */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "glib.h" #ifdef HAVE_UNISTD_H #include <unistd.h> #endif /* HAVE_UNISTD_H */ #ifndef NATIVE_WIN32 #include <sys/time.h> #endif /* NATIVE_WIN32 */ #ifdef NATIVE_WIN32 #include <windows.h> #endif /* NATIVE_WIN32 */ typedef struct _GRealTimer GRealTimer; struct _GRealTimer { #ifdef NATIVE_WIN32 DWORD start; DWORD end; #else /* !NATIVE_WIN32 */ struct timeval start; struct timeval end; #endif /* !NATIVE_WIN32 */ guint active : 1; }; GTimer* g_timer_new (void) { GRealTimer *timer; timer = g_new (GRealTimer, 1); timer->active = TRUE; #ifdef NATIVE_WIN32 timer->start = GetTickCount (); #else /* !NATIVE_WIN32 */ gettimeofday (&timer->start, NULL); #endif /* !NATIVE_WIN32 */ return ((GTimer*) timer); } void g_timer_destroy (GTimer *timer) { g_return_if_fail (timer != NULL); g_free (timer); } void g_timer_start (GTimer *timer) { GRealTimer *rtimer; g_return_if_fail (timer != NULL); rtimer = (GRealTimer*) timer; rtimer->active = TRUE; #ifdef NATIVE_WIN32 rtimer->start = GetTickCount (); #else /* !NATIVE_WIN32 */ gettimeofday (&rtimer->start, NULL); #endif /* !NATIVE_WIN32 */ } void g_timer_stop (GTimer *timer) { GRealTimer *rtimer; g_return_if_fail (timer != NULL); rtimer = (GRealTimer*) timer; rtimer->active = FALSE; #ifdef NATIVE_WIN32 rtimer->end = GetTickCount (); #else /* !NATIVE_WIN32 */ gettimeofday (&rtimer->end, NULL); #endif /* !NATIVE_WIN32 */ } void g_timer_reset (GTimer *timer) { GRealTimer *rtimer; g_return_if_fail (timer != NULL); rtimer = (GRealTimer*) timer; #ifdef NATIVE_WIN32 rtimer->start = GetTickCount (); #else /* !NATIVE_WIN32 */ gettimeofday (&rtimer->start, NULL); #endif /* !NATIVE_WIN32 */ } gdouble g_timer_elapsed (GTimer *timer, gulong *microseconds) { GRealTimer *rtimer; gdouble total; #ifndef NATIVE_WIN32 struct timeval elapsed; #endif /* NATIVE_WIN32 */ g_return_val_if_fail (timer != NULL, 0); rtimer = (GRealTimer*) timer; #ifdef NATIVE_WIN32 if (rtimer->active) rtimer->end = GetTickCount (); /* Check for wraparound, which happens every 49.7 days. * No, Win95 machines probably are never running for that long, * but NT machines are. */ if (rtimer->end < rtimer->start) total = (UINT_MAX - (rtimer->start - rtimer->end)) / 1000.0; else total = (rtimer->end - rtimer->start) / 1000.0; if (microseconds) { if (rtimer->end < rtimer->start) *microseconds = ((UINT_MAX - (rtimer->start - rtimer->end)) % 1000) * 1000; else *microseconds = ((rtimer->end - rtimer->start) % 1000) * 1000; } #else /* !NATIVE_WIN32 */ if (rtimer->active) gettimeofday (&rtimer->end, NULL); if (rtimer->start.tv_usec > rtimer->end.tv_usec) { rtimer->end.tv_usec += 1000000; rtimer->end.tv_sec--; } elapsed.tv_usec = rtimer->end.tv_usec - rtimer->start.tv_usec; elapsed.tv_sec = rtimer->end.tv_sec - rtimer->start.tv_sec; total = elapsed.tv_sec + ((gdouble) elapsed.tv_usec / 1e6); if (total < 0) { total = 0; if (microseconds) *microseconds = 0; } else if (microseconds) *microseconds = elapsed.tv_usec; #endif /* !NATIVE_WIN32 */ return total; }
wsavran/opensha
src/main/java/org/opensha/sha/earthquake/calc/recurInterval/gui/PlottingPanel.java
package org.opensha.sha.earthquake.calc.recurInterval.gui; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.swing.JPanel; import org.opensha.commons.data.function.DiscretizedFunc; import org.opensha.commons.gui.plot.GraphWidget; import org.opensha.commons.gui.plot.GraphWindow; import org.opensha.commons.gui.plot.PlotElement; import com.google.common.collect.Lists; /** * It represents a tab in each tabbed pane of the Probability Dist GUI * * @author vipingupta * */ public class PlottingPanel extends JPanel { private GraphWidget graphWidget; private List<PlotElement> funcList; public PlottingPanel() { this.setLayout(new GridBagLayout()); funcList = new ArrayList<PlotElement>(); graphWidget = new GraphWidget(); this.add(graphWidget, new GridBagConstraints( 0, 0, 1, 1, 1.0, 1.0 , GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets( 0, 0, 0, 0 ), 0, 0 )); } /** * Add Graph Panel * */ public void addGraphPanel() { graphWidget.getPlotSpec().setPlotElems(funcList); this.graphWidget.drawGraph(); graphWidget.validate(); graphWidget.repaint(); } public void plotGraphUsingPlotPreferences() { this.clearPlot(); this.addGraphPanel(); } public void save() { try { this.graphWidget.save(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void print() { this.graphWidget.print(); } public void peelOff() { GraphWindow graphWindow = new GraphWindow(graphWidget); this.remove(graphWidget); graphWidget = new GraphWidget(); funcList = Lists.newArrayList(); this.add(graphWidget, new GridBagConstraints( 0, 0, 1, 1, 1.0, 1.0 , GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets( 0, 0, 0, 0 ), 0, 0 )); graphWindow.setVisible(true); } public void clearPlot() { this.graphWidget.removeChartAndMetadata(); this.funcList.clear(); graphWidget.setAutoRange(); graphWidget.validate(); graphWidget.repaint(); } /** * Add a function to the list of functions to be plotted * * @param func */ public void addFunc(DiscretizedFunc func) { funcList.add(func); this.addGraphPanel(); } }
simoncozens/pysilfont
examples/gdl/font.py
<gh_stars>10-100 #!/usr/bin/env python 'The main font object for GDL creation. Depends on fonttools' __url__ = 'http://github.com/silnrsi/pysilfont' __copyright__ = 'Copyright (c) 2012 SIL International (http://www.sil.org)' __license__ = 'Released under the MIT License (http://opensource.org/licenses/MIT)' import os, re, traceback from silfont.gdl.glyph import Glyph from silfont.gdl.psnames import Name from xml.etree.cElementTree import ElementTree, parse, Element from fontTools.ttLib import TTFont # A collection of glyphs that have a given attachment point defined class PointClass(object) : def __init__(self, name) : self.name = name self.glyphs = [] self.dias = [] def addBaseGlyph(self, g) : self.glyphs.append(g) def addDiaGlyph(self, g) : self.dias.append(g) g.isDia = True def hasDias(self) : if len(self.dias) and len(self.glyphs) : return True else : return False def classGlyphs(self, isDia = False) : if isDia : return self.dias else : return self.glyphs def isNotInClass(self, g, isDia = False) : if not g : return False if not g.isDia : return False if isDia : return g not in self.dias else : return g not in self.dias and g not in self.glyphs class FontClass(object) : def __init__(self, elements = None, fname = None, lineno = None, generated = False, editable = False) : self.elements = elements or [] self.fname = fname self.lineno = lineno self.generated = generated self.editable = editable def append(self, element) : self.elements.append(element) class Font(object) : def __init__(self, fontfile) : self.glyphs = [] self.psnames = {} self.canons = {} self.gdls = {} self.anchors = {} self.ligs = {} self.subclasses = {} self.points = {} self.classes = {} self.aliases = {} self.rules = {} self.posRules = {} if fontfile : self.font = TTFont(fontfile) for i, n in enumerate(self.font.getGlyphOrder()) : self.addGlyph(i, n) else : self.font = None def __len__(self) : return len(self.glyphs) # [] syntax returns the indicated element of the glyphs array. def __getitem__(self, y) : try : return self.glyphs[y] except IndexError : return None def glyph(self, name) : return self.psnames.get(name, None) def alias(self, s) : return self.aliases.get(s, s) def emunits(self) : return 0 def initGlyphs(self, nGlyphs) : #print "Font::initGlyphs",nGlyphs self.glyphs = [None] * nGlyphs self.numRealGlyphs = nGlyphs # does not include pseudo-glyphs self.psnames = {} self.canons = {} self.gdls = {} self.classes = {} def addGlyph(self, index = None, psName = None, gdlName = None, factory = Glyph) : #print "Font::addGlyph",index,psName,gdlName if psName in self.psnames : return self.psnames[psName] if index is not None and index < len(self.glyphs) and self.glyphs[index] : g = self.glyphs[index] return g g = factory(psName, index) # create a new glyph of the given class self.renameGlyph(g, psName, gdlName) if index is None : # give it the next available index index = len(self.glyphs) self.glyphs.append(g) elif index >= len(self.glyphs) : self.glyphs.extend([None] * (len(self.glyphs) - index + 1)) self.glyphs[index] = g return g def renameGlyph(self, g, name, gdlName = None) : if g.psname != name : for n in g.parseNames() : del self.psnames[n.psname] del self.canons[n.canonical()] if gdlName : self.setGDL(g, gdlName) else : self.setGDL(g, g.GDLName()) for n in g.parseNames() : if n is None : break self.psnames[n.psname] = g self.canons[n.canonical()] = (n, g) def setGDL(self, glyph, name) : if not glyph : return n = glyph.GDLName() if n != name and n in self.gdls : del self.gdls[n] if name and name in self.gdls and self.gdls[name] is not glyph : count = 1 index = -2 name = name + "_1" while name in self.gdls : if self.gdls[name] is glyph : break count = count + 1 name = name[0:index] + "_" + str(count) if count == 10 : index = -3 if count == 100 : index = -4 self.gdls[name] = glyph glyph.setGDL(name) def addClass(self, name, elements, fname = None, lineno = 0, generated = False, editable = False) : if name : self.classes[name] = FontClass(elements, fname, lineno, generated, editable) def addGlyphClass(self, name, gid, editable = False) : if name not in self.classes : self.classes[name] = FontClass() if gid not in self.classes[name].elements : self.classes[name].append(gid) def addRules(self, rules, index) : self.rules[index] = rules def addPosRules(self, rules, index) : self.posRules[index] = rules def classUpdated(self, name, value) : c = [] if name in self.classes : for gid in self.classes[name].elements : g = self[gid] if g : g.removeClass(name) if value is None and name in classes : del self.classes[name] return for n in value.split() : g = self.gdls.get(n, None) if g : c.append(g.gid) g.addClass(name) if name in self.classes : self.classes[name].elements = c else : self.classes[name] = FontClass(c) # Return the list of classes that should be updated in the AP XML file. # This does not include classes that are auto-generated or defined in the hand-crafted GDL code. def filterAutoClasses(self, names, autoGdlFile) : res = [] for n in names : c = self.classes[n] if not c.generated and (not c.fname or c.fname == autoGdlFile) : res.append(n) return res def loadAlias(self, fname) : with open(fname) as f : for l in f.readlines() : l = l.strip() l = re.sub(ur'#.*$', '', l).strip() if not len(l) : continue try : k, v = re.split(ur'\s*[,;\s]\s*', l, 1) except ValueError : k = l v = '' self.aliases[k] = v # TODO: move this method to GraideFont, or refactor def loadAP(self, apFileName) : if not os.path.exists(apFileName) : return False etree = parse(apFileName) self.initGlyphs(len(etree.getroot())) # guess each child is a glyph i = 0 for e in etree.getroot().iterfind("glyph") : g = self.addGlyph(i, e.get('PSName')) g.readAP(e, self) i += 1 return True def saveAP(self, apFileName, autoGdlFile) : root = Element('font') root.set('upem', str(self.emunits())) root.set('producer', 'graide 1.0') root.text = "\n\n" for g in self.glyphs : if g : g.createAP(root, self, autoGdlFile) ElementTree(root).write(apFileName, encoding="utf-8", xml_declaration=True) def createClasses(self) : self.subclasses = {} for k, v in self.canons.items() : if v[0].ext : h = v[0].head() o = self.canons.get(h.canonical(), None) if o : if v[0].ext not in self.subclasses : self.subclasses[v[0].ext] = {} self.subclasses[v[0].ext][o[1].GDLName()] = v[1].GDLName() # for g in self.glyphs : # if not g : continue # for c in g.classes : # if c not in self.classes : # self.classes[c] = [] # self.classes[c].append(g.gid) def calculatePointClasses(self) : self.points = {} for g in self.glyphs : if not g : continue for apName in g.anchors.keys() : genericName = apName[:-1] # without the M or S if genericName not in self.points : self.points[genericName] = PointClass(genericName) if apName.endswith('S') : self.points[genericName].addBaseGlyph(g) else : self.points[genericName].addDiaGlyph(g) def calculateOTLookups(self) : if self.font : for t in ('GSUB', 'GPOS') : if t in self.font : self.font[t].table.LookupList.process(self) def getPointClasses(self) : if len(self.points) == 0 : self.calculatePointClasses() return self.points def ligClasses(self) : self.ligs = {} for g in self.glyphs : if not g or not g.name : continue (h, t) = g.name.split_last() if t : o = self.canons.get(h.canonical(), None) if o and o[0].ext == t.ext : t.ext = None t.cname = None tn = t.canonical(noprefix = True) if tn in self.ligs : self.ligs[tn].append((g.GDLName(), o[0].GDL())) else : self.ligs[tn] = [(g.GDLName(), o[0].GDL())] def outGDL(self, fh, args) : munits = self.emunits() fh.write('table(glyph) {MUnits = ' + str(munits) + '};\n') nglyphs = 0 for g in self.glyphs : if not g or not g.psname : continue if g.psname == '.notdef' : fh.write(g.GDLName() + ' = glyphid(0)') else : fh.write(g.GDLName() + ' = postscript("' + g.psname + '")') outs = [] if len(g.anchors) : for a in g.anchors.keys() : v = g.anchors[a] outs.append(a + "=point(" + str(int(v[0])) + "m, " + str(int(v[1])) + "m)") for (p, v) in g.gdl_properties.items() : outs.append("%s=%s" % (p, v)) if len(outs) : fh.write(" {" + "; ".join(outs) + "}") fh.write(";\n") nglyphs += 1 fh.write("\n") fh.write("\n/* Point Classes */\n") for p in sorted(self.points.values(), key=lambda x: x.name) : if not p.hasDias() : continue n = p.name + "Dia" self.outclass(fh, "c" + n, p.classGlyphs(True)) self.outclass(fh, "cTakes" + n, p.classGlyphs(False)) self.outclass(fh, 'cn' + n, filter(lambda x : p.isNotInClass(x, True), self.glyphs)) self.outclass(fh, 'cnTakes' + n, filter(lambda x : p.isNotInClass(x, False), self.glyphs)) fh.write("\n/* Classes */\n") for c in sorted(self.classes.keys()) : # c = class name, l = class object if c not in self.subclasses and not self.classes[c].generated : # don't output the class to the AP file if it was autogenerated self.outclass(fh, c, self.classes[c].elements) for p in self.subclasses.keys() : ins = [] outs = [] for k, v in self.subclasses[p].items() : ins.append(k) outs.append(v) n = p.replace('.', '_') self.outclass(fh, 'cno_' + n, ins) self.outclass(fh, 'c' + n, outs) fh.write("/* Ligature Classes */\n") for k in sorted(self.ligs.keys()) : self.outclass(fh, "clig" + k, map(lambda x: self.gdls[x[0]], self.ligs[k])) self.outclass(fh, "cligno_" + k, map(lambda x: self.gdls[x[1]], self.ligs[k])) fh.write("\nendtable;\n") fh.write("/* Substitution Rules */\n") for k, v in sorted(self.rules.items(), key=lambda x:map(int,x[0].split('_'))) : fh.write('\n// lookup ' + k + '\n') fh.write('// ' + "\n// ".join(v) + "\n") fh.write("\n/* Positioning Rules */\n") for k, v in sorted(self.posRules.items(), key=lambda x:map(int,x[0].split('_'))) : fh.write('\n// lookup ' + k + '\n') fh.write('// ' + "\n// ".join(v) + "\n") fh.write("\n\n#define MAXGLYPH %d\n\n" % (nglyphs - 1)) if args.include : fh.write("#include \"%s\"\n" % args.include) def outPosRules(self, fh, num) : fh.write(""" #ifndef opt2 #define opt(x) [x]? #define opt2(x) [opt(x) x]? #define opt3(x) [opt2(x) x]? #define opt4(x) [opt3(x) x]? #endif #define posrule(x) c##x##Dia {attach{to=@1; at=x##S; with=x##M}} / cTakes##x##Dia opt4(cnTakes##x##Dia) _; table(positioning); pass(%d); """ % num) for p in self.points.values() : if p.hasDias() : fh.write("posrule(%s);\n" % p.name) fh.write("endpass;\nendtable;\n") def outclass(self, fh, name, glyphs) : fh.write(name + " = (") count = 1 sep = "" for g in glyphs : if not g : continue if isinstance(g, basestring) : fh.write(sep + g) else : if g.GDLName() is None : print "Can't output " + str(g.gid) + " to class " + name else : fh.write(sep + g.GDLName()) if count % 8 == 0 : sep = ',\n ' else : sep = ', ' count += 1 fh.write(');\n\n')
FlyAlCode/FlightSim
third_lib/include/mrsid/MrSIDPasswordDelegate.h
/* $Id$ */ /* ////////////////////////////////////////////////////////////////////////// // // // This code is Copyright (c) 2004 LizardTech, Inc, 1008 Western Avenue, // // Suite 200, Seattle, WA 98104. Unauthorized use or distribution // // prohibited. Access to and use of this code is permitted only under // // license from LizardTech, Inc. Portions of the code are protected by // // US and foreign patents and other filings. All Rights Reserved. // // // ////////////////////////////////////////////////////////////////////////// */ /* PUBLIC */ #ifndef MRSIDPASSWORDDELEGATE_H #define MRSIDPASSWORDDELEGATE_H #include "lti_types.h" LT_BEGIN_NAMESPACE(LizardTech) /** * delegate for locked MrSID images * * This abstract class is used with MrSIDImageReaderBase::setPasswordDelegate() * to supply a user-callback mechanism for supplying text passwords to * the internal MrSID decoder logic. * * Users should derive their own class from this, supplying their own * reportIncorrectPassword() and getPassword() methods. */ class MrSIDPasswordDelegate { LT_DISALLOW_COPY_CONSTRUCTOR(MrSIDPasswordDelegate); public: /** * constructor */ MrSIDPasswordDelegate(); /** * destructor */ virtual ~MrSIDPasswordDelegate(); /** * user function for user notification * * This function is called by the decoder if the password * entered was incorrect. Derived classes must implement * this function, e.g. to pop up a message box, abort the * operation, etc. * * @return success or failure in reporting to user */ virtual LT_STATUS reportIncorrectPassword() = 0; /** * user function for getting the password * * This function is called by the decoder to request a password * from the user. Derived classes must implement * this function, e.g. to pop up a text-entry dialog box. * * The implementation of this function must copy the password * into the buffer pointed by getPasswordBuffer(). * * @return success or failure in getting password from user */ virtual LT_STATUS getPassword() = 0; protected: /** * get password buffer * * This function returns a pointer to the allocated area for the * password obtained from the user. * * @return pointer to the password buffer */ char* getPasswordBuffer(); /** * get password buffer length * * This function returns the length of the buffer returned from * getPasswordBuffer(). * * @return length of the password buffer */ lt_uint32 getPasswordBufferLength(); private: class EncryptImp; struct Data; Data *m_data; friend class MrSIDImageReaderInterface; friend class MG2ImageWriter; friend class MG3ImageWriter; friend class MG4ImageWriter; void registerProvider(); }; /** * simple concrete delegate for locked MrSID images * * This class is a concrete password delegate class which just * takes a fixed string in its ctor. */ class MrSIDSimplePasswordDelegate : public MrSIDPasswordDelegate { LT_DISALLOW_COPY_CONSTRUCTOR(MrSIDSimplePasswordDelegate); public: /** * constructor * * Create a password delegate, using the given string. * * @param password the password to use to unlock the image */ MrSIDSimplePasswordDelegate(const char* password); /** * failure user notification * * This function just returns LT_STS_Failure. * * @return always LT_STS_Failure */ LT_STATUS reportIncorrectPassword(); /** * get the password * * This function does nothing, as the password is fixed (determined * by parameter to constructor). * * @return always LT_STS_Success */ LT_STATUS getPassword(); }; LT_END_NAMESPACE(LizardTech) #endif // MRSIDPASSWORDDELEGATE_H
onedata/onedata-gui-common
addon/utils/computed-aspect-options-array.js
/** * Created computed property which gets/sets an array and deserializes/serializes it * into `navigationState.aspectOptions` in form of string. * * @module utils/computed-aspect-options-array * @author <NAME> * @copyright (C) 2021 ACK CYFRONET AGH * @license This software is released under the MIT license cited in 'LICENSE.txt'. */ import { computed } from '@ember/object'; import { isEmpty } from '@ember/utils'; import { isArray } from '@ember/array'; export default function computedAspectOptionsArray(propertyName) { const navigationStatePropertyPath = `navigationState.aspectOptions.${propertyName}`; return computed(navigationStatePropertyPath, { get() { const rawSelected = this.get(navigationStatePropertyPath); return rawSelected && rawSelected.split(',') || []; }, set(key, value) { this.get('navigationState').changeRouteAspectOptions({ [propertyName]: !isEmpty(value) && isArray(value) && value.join(',') || null, }); return value; }, }); }
glass-candle/herald
app/presentation/jobs/source_blogposts.rb
# frozen_string_literal: true module Presentation module Jobs class SourceBlogposts < BaseJob include Import['application.operations.blogs.source'] include Dry::Monads::Result::Mixin sidekiq_options retry: 5 def perform(blog_id) result = source.call(blog_id) case result in Failure App[:sentry_adapter].add_tags(blog_id: blog_id) App[:sentry_adapter].add_breadcrumb(blog_id, :blog_id, 'Blog ID') App[:sentry_adapter].add_breadcrumb(result.failure, :failure, 'Failure') App[:sentry_adapter].capture_message('Blog sourcing has failed') result.value! in Success result.value! end end end end end
RussellChamp/cover-api
application/models/file_test.go
package models import ( "time" ) func (ms *ModelSuite) TestFile_ConvertToAPI() { user := CreateUserFixtures(ms.DB, 1).Users[0] file := CreateFileFixtures(ms.DB, 1, user.ID).Files[0] got := file.ConvertToAPI(ms.DB) ms.Equal(file.ID, got.ID) ms.Equal(file.URL, got.URL) ms.Equal(file.URLExpiration, got.URLExpiration) ms.WithinDuration(file.URLExpiration, got.URLExpiration, time.Minute) ms.Equal(file.Name, got.Name) ms.Equal(file.Size, got.Size) ms.Equal(file.ContentType, got.ContentType) ms.Equal(file.CreatedByID, got.CreatedByID) }
Jeremyyang920/datadog-agent
pkg/collector/corechecks/snmp/utils.go
<reponame>Jeremyyang920/datadog-agent package snmp import ( "fmt" "hash/fnv" "strconv" "strings" "github.com/DataDog/datadog-agent/pkg/util" ) func createStringBatches(elements []string, size int) ([][]string, error) { var batches [][]string if size <= 0 { return nil, fmt.Errorf("batch size must be positive. invalid size: %d", size) } for i := 0; i < len(elements); i += size { j := i + size if j > len(elements) { j = len(elements) } batch := elements[i:j] batches = append(batches, batch) } return batches, nil } func copyStrings(tags []string) []string { newTags := make([]string, len(tags)) copy(newTags, tags) return newTags } func buildDeviceID(origTags []string) (string, []string) { h := fnv.New64() var tags []string for _, tag := range origTags { if strings.HasPrefix(tag, subnetTagPrefix+":") { continue } tags = append(tags, tag) } tags = util.SortUniqInPlace(tags) for _, tag := range tags { // the implementation of h.Write never returns a non-nil error _, _ = h.Write([]byte(tag)) } return strconv.FormatUint(h.Sum64(), 16), tags }
sarrvesh/Obit
ObitSystem/ObitSD/share/scripts/scriptGCXSelImage.py
# Program to image selected data import OTF, Image, OSystem, OErr # Init Obit err=OErr.OErr() ObitSys=OSystem.OSystem ("Python", 1, 103, 1, ["None"], 1, ["../PythonData/"], 1, 0, err) OErr.printErrMsg(err, "Error with Obit startup") # Files disk = 1 inFile = "GCXbandSelOTF.fits" # input OTF data dirtFile = "!XDirty.fits" # output dirty image file # Set data inData = OTF.newPOTF("Input data", inFile, disk, 1, err) OErr.printErrMsg(err, "Error creating input data object") # Imaging parameters OTF.ImageInput["InData"] = inData OTF.ImageInput["disk"] = disk OTF.ImageInput["OutName"] = dirtFile OTF.ImageInput["ra"] = 266.2540 # Center RA OTF.ImageInput["dec"] = -29.38028 # Center Dec OTF.ImageInput["xCells"] = 20.0 / 3600.0 # "X" cell spacing, deg OTF.ImageInput["yCells"] = 20.0 / 3600.0 # "Y" cell spacing, deg OTF.ImageInput["nx"] = 500 # number of cells in X OTF.ImageInput["ny"] = 500 # number of cells in X OTF.ImageInput["gainuse"] = 0 # Which cal table to apply, -1 = none OTF.ImageInput["flagver"] = -1 # Which flag table to apply, -1 = none OTF.input(OTF.ImageInput) Dirty = OTF.makeImage(err) # Shutdown OErr.printErr(err) print 'Imaged',inFile,'to',dirtFile
renedlog/vespa
searchlib/src/vespa/searchlib/diskindex/disktermblueprint.cpp
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "disktermblueprint.h" #include <vespa/searchlib/common/bitvectoriterator.h> #include <vespa/searchlib/queryeval/booleanmatchiteratorwrapper.h> #include <vespa/searchlib/queryeval/intermediate_blueprints.h> #include <vespa/searchlib/queryeval/equiv_blueprint.h> #include <vespa/vespalib/util/stringfmt.h> #include <vespa/log/log.h> LOG_SETUP(".diskindex.disktermblueprint"); using search::BitVectorIterator; using search::fef::TermFieldMatchDataArray; using search::index::Schema; using search::queryeval::BooleanMatchIteratorWrapper; using search::queryeval::FieldSpecBase; using search::queryeval::FieldSpecBaseList; using search::queryeval::SearchIterator; using search::queryeval::LeafBlueprint; using search::queryeval::EquivBlueprint; using search::queryeval::Blueprint; namespace search::diskindex { namespace { vespalib::string getName(uint32_t indexId) { return vespalib::make_string("fieldId(%u)", indexId); } } DiskTermBlueprint::DiskTermBlueprint(const FieldSpecBase & field, const DiskIndex & diskIndex, DiskIndex::LookupResult::UP lookupRes, bool useBitVector) : SimpleLeafBlueprint(field), _field(field), _diskIndex(diskIndex), _lookupRes(std::move(lookupRes)), _useBitVector(useBitVector), _fetchPostingsDone(false), _hasEquivParent(false), _postingHandle(), _bitVector() { setEstimate(HitEstimate(_lookupRes->counts._numDocs, _lookupRes->counts._numDocs == 0)); } namespace { bool areAnyParentsEquiv(const Blueprint * node) { return (node == nullptr) ? false : (dynamic_cast<const EquivBlueprint *>(node) != nullptr) ? true : areAnyParentsEquiv(node->getParent()); } } void DiskTermBlueprint::fetchPostings(const queryeval::ExecuteInfo &execInfo) { (void) execInfo; _hasEquivParent = areAnyParentsEquiv(getParent()); _bitVector = _diskIndex.readBitVector(*_lookupRes); if (!_useBitVector || !_bitVector) { _postingHandle = _diskIndex.readPostingList(*_lookupRes); } _fetchPostingsDone = true; } SearchIterator::UP DiskTermBlueprint::createLeafSearch(const TermFieldMatchDataArray & tfmda, bool strict) const { if (_bitVector && (_useBitVector || (tfmda[0]->isNotNeeded() && !_hasEquivParent))) { LOG(debug, "Return BitVectorIterator: %s, wordNum(%" PRIu64 "), docCount(%" PRIu64 ")", getName(_lookupRes->indexId).c_str(), _lookupRes->wordNum, _lookupRes->counts._numDocs); return BitVectorIterator::create(_bitVector.get(), *tfmda[0], strict); } SearchIterator::UP search(_postingHandle->createIterator(_lookupRes->counts, tfmda, _useBitVector)); if (_useBitVector) { LOG(debug, "Return BooleanMatchIteratorWrapper: %s, wordNum(%" PRIu64 "), docCount(%" PRIu64 ")", getName(_lookupRes->indexId).c_str(), _lookupRes->wordNum, _lookupRes->counts._numDocs); return std::make_unique<BooleanMatchIteratorWrapper>(std::move(search), tfmda); } LOG(debug, "Return posting list iterator: %s, wordNum(%" PRIu64 "), docCount(%" PRIu64 ")", getName(_lookupRes->indexId).c_str(), _lookupRes->wordNum, _lookupRes->counts._numDocs); return search; } }
opengauss-mirror/DataStudio
code/datastudio/src/org.opengauss.mppdbide.view/src/org/opengauss/mppdbide/view/terminal/queryexecution/SqlQueryExecutionWorkingContext.java
/* * Copyright (c) 2022 Huawei Technologies Co.,Ltd. * * openGauss is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ package org.opengauss.mppdbide.view.terminal.queryexecution; import java.util.ArrayList; import org.opengauss.mppdbide.utils.MPPDBIDEConstants; /** * * Title: class * * Description: The Class SqlQueryExecutionWorkingContext. * * @since 3.0.0 */ public class SqlQueryExecutionWorkingContext { /* Array will never be accessed out of bound, this is ensured by design */ private ArrayList<String> queryArray = new ArrayList<String>(MPPDBIDEConstants.OBJECT_ARRAY_SIZE); private int nextQueryId = 0; /** * Gets the query array. * * @return the query array */ public ArrayList<String> getQueryArray() { return queryArray; } /** * Checks for next. * * @return true, if successful */ public boolean hasNext() { return nextQueryId < queryArray.size() ? true : false; } /** * Next. * * @return the string */ public String next() { return queryArray.get(nextQueryId++); } /** * Gets the current query. * * @return the current query */ public String getCurrentQuery() { return queryArray.get(nextQueryId - 1); } /** * Update current query. * * @param query the query */ public void updateCurrentQuery(String query) { queryArray.add(nextQueryId - 1, query); queryArray.remove(nextQueryId); } /** * Previous. * * @return the string */ public String previous() { return queryArray.get(--nextQueryId); } }
CyberAgent/valor
valor-trino/src/main/java/jp/co/cyberagent/valor/trino/ValorModule.java
<filename>valor-trino/src/main/java/jp/co/cyberagent/valor/trino/ValorModule.java package jp.co.cyberagent.valor.trino; import static com.google.common.base.Preconditions.checkArgument; import static java.util.Objects.requireNonNull; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.deser.std.FromStringDeserializer; import com.google.inject.Binder; import com.google.inject.Inject; import com.google.inject.Module; import com.google.inject.Scopes; import com.google.inject.TypeLiteral; import io.trino.spi.connector.ConnectorPageSinkProvider; import io.trino.spi.connector.ConnectorPageSourceProvider; import io.trino.spi.type.Type; import io.trino.spi.type.TypeManager; import io.trino.sql.analyzer.TypeSignatureTranslator; import java.util.Collections; import java.util.Map; import jp.co.cyberagent.valor.spi.ValorConf; import jp.co.cyberagent.valor.spi.ValorContext; public class ValorModule implements Module { private final ValorConnectorId connectorId; private final TypeManager typeManager; private final ValorContext context; private final Map<String, ValorConf> nameSpaceConfigs; public ValorModule(String connectorId, TypeManager typeManager, ValorContext context) { this(connectorId, typeManager, context, Collections.EMPTY_MAP); } public ValorModule(String connectorId, TypeManager typeManager, ValorContext context, Map<String, ValorConf> nsConf) { this.connectorId = new ValorConnectorId(connectorId); this.typeManager = typeManager; this.context = context; this.nameSpaceConfigs = nsConf; } @Override public void configure(Binder binder) { binder.bind(ValorConnectorId.class).toInstance(connectorId); binder.bind(TypeManager.class).toInstance(typeManager); binder.bind(ValorContext.class).toInstance(context); binder.bind(ValorConnector.class).in(Scopes.SINGLETON); binder.bind(ValorSplitManager.class).in(Scopes.SINGLETON); binder.bind(ValorMetadata.class).in(Scopes.SINGLETON); binder.bind(ValorRecordSetProvider.class).in(Scopes.SINGLETON); binder.bind(ConnectorPageSinkProvider.class).to(ValorPageSinkProvider.class) .in(Scopes.SINGLETON); binder.bind(ConnectorPageSourceProvider.class).to(ValorPageSourceProvider.class) .in(Scopes.SINGLETON); binder.bind(new TypeLiteral<Map<String, ValorConf>>(){}).toInstance(nameSpaceConfigs); } public static final class TypeDeserializer extends FromStringDeserializer<Type> { private final TypeManager typeManager; @Inject public TypeDeserializer(TypeManager typeManager) { super(Type.class); this.typeManager = requireNonNull(typeManager, "typeManager is null"); } @Override protected Type _deserialize(String value, DeserializationContext context) { Type type = typeManager.getType( TypeSignatureTranslator.parseTypeSignature(value, Collections.emptySet())); checkArgument(type != null, "Unknown type %s", value); return type; } } }
microservices-training/food2go
ftgo-kitchen-service/src/main/java/net/training/ftgo/kitchenservice/web/KitchenServiceWebConfiguration.java
<reponame>microservices-training/food2go<filename>ftgo-kitchen-service/src/main/java/net/training/ftgo/kitchenservice/web/KitchenServiceWebConfiguration.java package net.training.ftgo.kitchenservice.web; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import net.training.ftgo.kitchenservice.domain.KitchenDomainConfiguration; @Configuration @Import(KitchenDomainConfiguration.class) @ComponentScan public class KitchenServiceWebConfiguration { }
lunarhook/lunarhook-lunarhook
lunarhook/src/LunarCourse/QDateBase/UniversBookPageModule.js
import React, {Component} from 'react'; import {AppRegistry,View,Text} from 'react-native'; import {six_random_NaJia} from '../../kit/UniversechangesLib/SixrandomLib/SixrandomModule' var UniversBookPageModule = new Array() var UniversBookPageModule = new Array() UniversBookPageModule[0] = {"icon":"☯️","key":"0","name": "六十四卦序","p":"总序","content":[ "乾、坤、震、艮、离、坎、兑、巽", "☰、☷、☳、☶、☲、☵、☱、☴", "乾三连,坤六断;震仰盂,艮覆碗。", "离中虚,坎中满;兑上缺,巽下断。", ]} var randomindex = 0 for(var key in six_random_NaJia){ randomindex = six_random_NaJia[key].key UniversBookPageModule[randomindex]=six_random_NaJia[key] UniversBookPageModule[randomindex].content = [ six_random_NaJia[key].name, six_random_NaJia[key].icon, undefined!=six_random_NaJia[key].extname?six_random_NaJia[key].extname:"", undefined!=six_random_NaJia[key].extnameexp?six_random_NaJia[key].extnameexp:"", undefined!=six_random_NaJia[key].base?six_random_NaJia[key].base:"", undefined!=six_random_NaJia[key].def?six_random_NaJia[key].def:"", undefined!=six_random_NaJia[key].story?six_random_NaJia[key].story:"", undefined!=six_random_NaJia[key].extexp?six_random_NaJia[key].extexp:"", undefined!=six_random_NaJia[key].extexp1?six_random_NaJia[key].extexp1:"", undefined!=six_random_NaJia[key].ext?six_random_NaJia[key].ext:"", undefined!=six_random_NaJia[key].exp1?six_random_NaJia[key].exp1:"", undefined!=six_random_NaJia[key].exp2?six_random_NaJia[key].exp2:"", undefined!=six_random_NaJia[key].exp3?six_random_NaJia[key].exp3:"", undefined!=six_random_NaJia[key].exp4?six_random_NaJia[key].exp4:"", undefined!=six_random_NaJia[key].exp5?six_random_NaJia[key].exp5:"", undefined!=six_random_NaJia[key].exp6?six_random_NaJia[key].exp6:"", undefined!=six_random_NaJia[key].exp7?six_random_NaJia[key].exp7:"", undefined!=six_random_NaJia[key].exp8?six_random_NaJia[key].exp8:"", undefined!=six_random_NaJia[key].exp9?six_random_NaJia[key].exp9:"", undefined!=six_random_NaJia[key].exp10?six_random_NaJia[key].exp10:"", undefined!=six_random_NaJia[key].exp11?six_random_NaJia[key].exp11:"", undefined!=six_random_NaJia[key].exp12?six_random_NaJia[key].exp12:"", undefined!=six_random_NaJia[key].exp13?six_random_NaJia[key].exp13:"", undefined!=six_random_NaJia[key].exp14?six_random_NaJia[key].exp14:"", ] UniversBookPageModule[randomindex].index = "易经" } UniversBookPageModule[65]={"icon":"☯️","key":"65","name": "系辞上传","p":"十翼","index":"易经","content":[ "系辞传上·第一章 \n\n\t天尊地卑,乾坤定矣。卑高以陈,贵贱位矣。动静有常,刚柔断矣。方以类聚,物以群分,吉凶生矣。 在天成象,在地成形,变化见矣。\n\t是故刚柔相摩,八卦相荡,鼓之以雷霆,润之以风雨;日月运行,一寒一暑。\n\t乾道成男,坤道成女。乾知大始,坤作成物。\n\t乾以易知,坤以简能;易则易知,简则易从;易知则有亲,易从则有功;有亲则可久,有功则可大;可久则贤人之德,可大则贤人之业。易简而天下之理得矣。天下之理得,而成位乎其中矣。", "系辞传上·第二章 \n\n\t圣人设卦观象,系辞焉!而明吉凶,刚柔相推而生变化。是故吉凶者,失得之象也;悔吝者,忧虞之象也;变化者,进退之象也;刚柔者,昼夜之象也。六爻之动,三极之道也。\n\t是故君子所居而安者,《易》之序也;所乐而玩者,爻之辞也。是故君子居则观其象而玩其辞,动则观其变而玩其占,是以自天佑之,吉无不利。", "系辞传上·第三章\n\n\t彖者,言乎象者也;爻者,言乎变者也。吉凶者,言乎其失得也;悔吝者,言乎其小疵也。无咎者,善补过者也。\n\t是故列贵贱者存乎位,齐小大者存乎卦,辩吉凶者存乎辞,忧悔吝者存乎介,震无咎者存乎悔。\n\t是故卦有小大,辞有险易;辞也者,各指其所之。", "系辞传上·第四章\n\n\t《易》与天地准,故能弥纶天地之道。\n\t仰以观于天文,俯以察于地理,是故知幽明之故;\n\t原始反终,故知死生之说;精气为物,游魂为变,是故知鬼神之情状。\n\t与天地相似,故不违;知周乎万物,而道济天下,故不过;旁行而不流,乐天知命,故不忧;安土敦乎仁,故能爱。范围天地之化而不过,曲成万物而不遗,通乎昼夜之道而知,故神无方而《易》无体。", "系辞传上·第五章\n\n\t一阴一阳之谓道。\n\t继之者善也,成之者性也。仁者见之谓之仁,知者见之谓之知,百姓日用而不知,故君子之道鲜矣。\n\t显诸仁,藏诸用,鼓万物而不与圣人同忧,盛德大业至矣哉!\n\t富有之谓大业,日新之谓盛德。生生之谓易,成象之谓乾,效法之谓坤,极数知来之谓占,通变之谓事,阴阳不测之谓神。", "系辞传上·第六章\n\n\t夫《易》广矣大矣,以言乎远则不御,以言乎迩则静而正,以言乎天地之间则备矣。\n\t夫乾,其静也专,其动也直,是以大生焉。\n\t夫坤,其静也翕,其动也辟,是以广生焉。\n\t广大配天地,变通配四时,阴阳之义配日月,易简之善配至德。", "系辞传上·第七章\n\n\t子曰:《易》,其至矣乎! \n\t夫《易》,圣人所以崇德而广业也。知崇礼卑,崇效天,卑法地。天地设位,而《易》行乎其中矣。成性存存,道义之门。", "系辞传上·第八章\n\n\t圣人有以见天下之赜,而拟诸其形容,像其物宜,是故谓之象。\n\t圣人有以见天下之动,而观其会通,以行其典礼,系辞焉以断其吉凶,是故谓之爻。\n\t言天下之至赜而不可恶也。言天下之至动而不可乱也。拟之而后言,议之而后动,拟议以成其变化。\n\t「鸣鹤在阴,其子和之。我有好爵,吾与尔靡之。」子曰:「君子居其室,出其言善,则千里之外应之,况其迩者乎?居其室,出其言不善,则千里之外违之,况其迩者乎?言出乎身,加乎民;行发乎迩,见乎远。言行,君子之枢机。枢机之发,荣辱之主也。言行,君子之所以动天地也,可不慎乎!」\n\t《同人》:先号啕而后笑。子曰:「君子之道,或出或处,或默或语。二人同心,其利断金。同心之言,其臭如兰。」\n\t初六,藉用白茅,无咎。子曰:「苟错诸地而可矣,藉之用茅,何咎之有?慎之至也。夫茅之为物薄,而用可重也。慎斯术也以往,其无所失矣。」\n\t劳谦,君子有终,吉。子曰:「劳而不伐,有功而不德,厚之至也。语以其功下人者也。德言盛,礼言恭;谦也者,致恭以存其位者也。」\n\t亢龙有悔。子曰:「贵而无位,高而无民,贤人在下位而无辅,是以动而有悔也。」\n\t不出户庭,无咎。子曰:「乱之所生也,则言语以为阶。君不密则失臣,臣不密则失身,几事不密则害成。是以君子慎密而不出也。」\n\t子曰:「作《易》者,其知盗乎?《易》曰『负且乘,致寇至。』负也者,小人之事也。乘也者,君子之器也。小人而乘君子之器,盗思夺之矣。上慢下暴,盗思伐之矣。慢藏诲盗,冶容诲淫。《易》曰:『负且乘,致寇至。』盗之招也。」", "系辞传上·第九章\n\n\t天一,地二;天三,地四;天五,地六;天七,地八;天九,地十。天数五,地数五,五位相得而各有合;天数二十有五,地数三十,凡天地之数五十有五,此所以成变化而行鬼神也。\n\t大衍之数五十,其用四十有九。分而为二以像两,挂一以像三,揲之以四以象四时,归奇于扐以象闰;五岁再闰,故再扐而后挂。\n\t《乾》之策二百一十有六,《坤》之策百四十有四,凡三百六十,当期之日。二篇之策,万有一千五百二十,当万物之数也。是故四营而成《易》,十有八变而成卦,八卦而小成。引而伸之,触类而长之,天下之能事毕矣。\n\t显道神德行,是故可与酬酢,可与佑神矣。子曰:「知变化之道者,其知神之所为乎。」", "系辞传上·第十章\n\n\t《易》有圣人之道四焉:以言者尚其辞,以动者尚其变,以制器者尚其象,以卜筮者尚其占。\n\t是以君子将有为也,将有行也,问焉而以言,其受命也如响。无有远近幽深,遂知来物。非天下之至精,其孰能与于此。参伍以变,错综其数。通其变,遂成天下之文;极其数,遂定天下之象。非天下之至变,其孰能与于此。《易》无思也,无为也,寂然不动,感而遂通天下之故。非天下之至神,其孰能与于此。\n\t夫《易》,圣人之所以极深而研几也。唯深也,故能通天下之志;唯几也,故能成天下之务;唯神也,故不疾而速,不行而至。子曰:「《易》有圣人之道四焉」者,此之谓也。", "系辞传上·第十一章\n\n\t子曰:「夫《易》何为者也?夫《易》开物成务,冒天下之道,如斯而已者也。」\n\t是故圣人以通天下之志,以定天下之业,以断天下之疑。\n\t是故蓍之德圆而神,卦之德方以知,六爻之义易以贡。圣人以此洗心,退藏于密,吉凶与民同患。神以知来,知以藏往,其孰能与于此哉!古之聪明睿知,神武而不杀者夫。\n\t是以明于天之道,而察于民之故,是兴神物以前民用。圣人以此斋戒,以神明其德夫。\n\t是故阖户谓之坤,辟户谓之乾,一阖一辟谓之变,往来不穷谓之通,见乃谓之象,形乃谓之器,制而用之谓之法,利用出入,民咸用之谓之神。\n\t是故《易》有太极,是生两仪。两仪生四象。四象生八卦。八卦定吉凶,吉凶生大业。\n\t是故法象莫大乎天地;变通莫大乎四时;县象着明莫大乎日月;崇高莫大乎富贵;备物致用,立成器以为天下利,莫大乎圣人探赜索隐,钩深致远,以定天下之吉凶,成天下之亹亹者,莫大乎蓍龟。\n\t是故天生神物,圣人则之;天地变化,圣人效之;天垂象,见吉凶,圣人像之;河出图,洛出书,圣人则之。\n\t《易》有四象,所以示也。系辞焉,所以告也;定之以吉凶,所以断也。", "系辞传上·第十二章\n\n\t《易》曰:「自天佑之,吉无不利。」子曰:「佑者,助也。天之所助者,顺也;人之所助者,信也。履信思乎顺,又以尚贤也。是以『自天佑之,吉无不利』也。」\n\t子曰:「书不尽言,言不尽意。」然则圣人之意,其不可见乎?子曰:「圣人立象以尽意,设卦以尽情伪,系辞焉以尽其言。变而通之以尽利,鼓之舞之以尽神。」\n\t乾坤,其《易》之蕴邪?乾坤成列,而《易》立乎其中矣。乾坤毁,则无以见《易》。《易》不可见,则乾坤或几乎息矣。\n\t是故形而上者谓之道,形而下者谓之器。化而裁之谓之变,推而行之谓之通,举而错之天下之民谓之事业。\n\t是故夫象,圣人有以见天下之赜,而拟诸其形容,像其物宜,是故谓之象。圣人有以见天下之动,而观其会通,以行其典礼,系辞焉以断其吉凶,是故谓之爻。\n\t极天下之赜者存乎卦,鼓天下之动者存乎辞;化而裁之存乎变;推而行之存乎通;神而明之存乎其人;默而成之,不言而信,存乎德行。", "","","","", ] } UniversBookPageModule[66]={"icon":"☯️","key":"66","name": "系辞下传","p":"十翼","index":"易经","content":[ "系辞传下·第一章\n\n\t八卦成列,像在其中矣;因而重之,爻在其中矣;刚柔相推,变在其中焉;系辞焉而命之,动在其中矣。吉凶悔吝者,生乎动者也;刚柔者,立本者也;变通者,趋时者也。吉凶者,贞胜者也;天地之道,贞观者也;日月之道,贞明者也;天下之动,贞夫一者也。\n\t夫乾,确然示人易矣;夫坤,隤然示人简矣。\n\t爻也者,效此者也。象也者,像此者也;爻象动乎内,吉凶见乎外,功业见乎变,圣人之情见乎辞。\n\t天地之大德曰生,圣人之大宝曰位。何以守位?曰仁。何以聚人?曰财。理财正辞、禁民为非曰义。", "系辞传下·第二章\n\n\t  古者包牺氏之王天下也,仰则观象于天,俯则观法于地,观鸟兽之文与地之宜,近取诸身,远取诸物,于是始作八卦,以通神明之德,以类万物之情。\n\t作结绳而为网罟,以佃以渔,盖取诸离。\n\t包牺氏没,神农氏作,斫木为耜,揉木为耒,耒耨之利,以教天下,盖取诸《益》。日中为市,致天下之民,聚天下之货,交易而退,各得其所,盖取诸《噬嗑》。神农氏没,黄帝、尧、舜氏作,通其变,使民不倦,神而化之,使民宜之。《易》穷则变,变则通,通则久。是以「自天佑之,吉无不利」。黄帝、尧、舜垂衣裳而天下治,盖取诸乾、坤。\n\tt刳木为舟,剡木为楫,舟楫之利,以济不通,致远以利天下,盖取诸涣。\n\tt服牛乘马,引重致远,以利天下,盖取诸随。\n\t重门击柝,以待暴客,盖取诸豫。断木为杵,掘地为臼,杵臼之利,万民以济,盖取诸小过。\n\t弦木为弧,剡木为矢,弧矢之利,以威天下,盖取诸睽。\n\t上古穴居而野处,后世圣人易之以宫室,上栋下宇,以待风雨,盖取诸大壮。\n\t古之葬者,厚衣之以薪,葬之中野,不封不树,丧期无数。后世圣人易之以棺椁,盖取诸大过。\n\t上古结绳而治,后世圣人易之以书契,百官以治,万民以察,盖取诸夬。", "系辞传下·第三章\n\n\t是故《易》者,象也;象也者,象也。\n\t彖者,材也;爻也者,效天下之动者也。\n\t是故吉凶生而悔吝著也。", "系辞传下·第四章\n\n\t  阳卦多阴,阴卦多阳,其故何也?阳卦奇,阴卦偶。\n\t其德行何也?阳一君而二民,君子之道也。阴二君而一民,小人之道也。", "系辞传下·第五章\n\n\t  《易》曰「憧憧往来,朋从尔思。」子曰:「天下何思何虑?天下同归而殊途,一致而百虑。天下何思何虑?日往则月来,月往则日来,日月相推而明生焉。寒往则暑来,暑往则寒来,寒暑相推而岁成焉。往者屈也,来者信也,屈信相感而利生焉。尺蠖之屈,以求信也;龙蛇之蛰,以存身也。精义入神,以致用也;利用安身,以崇德也。过此以往,未之或知也;穷神知化,德之盛也。」\n\t《易》曰:「困于石,据于蒺藜,入于其宫,不见其妻,凶。」子曰:「非所困而困焉,名必辱。非所据而据焉,身必危。既辱且危,死期将至,妻其可得见耶!」\n\t《易》曰:「公用射隼于高墉之上,获之,无不利。」子曰:「隼者,禽也;弓矢者,器也;射之者,人也。君子藏器于身,待时而动,何不利之有?动而不括,是以出而有获,语成器而动者也。」\n\t子曰:「小人不耻不仁,不畏不义,不见利不劝,不威不惩。小惩而不诫,此小人之福也。《易》曰:『履校灭趾,无咎。』此之谓也。」\n\t「善不积不足以成名,恶不积不足以灭身。小人以小善为无益而弗为也,以小恶为无伤而弗去也,故恶积而不可掩,罪大而不可解。《易》曰:『何校灭耳,凶。』」\n\t子曰:「危者,安其位者也;亡者,保其存者也;乱者,有其治者也。是故君子安而不忘危,存而不忘亡,治而不忘乱,是以身安而国家可保也。《易》曰:『其亡其亡,系于苞桑。』」\n\t子曰:「德薄而位尊,知小而谋大,力少而任重,鲜不及矣。《易》曰:『鼎折足,覆公餗,其形渥,凶。』言不胜其任也。」\n\t子曰:「知几其神乎!君子上交不谄,下交不渎,其知几乎?几者,动之微,吉之先见者也。君子见几而作,不俟终日。\n\t《易》曰:『介于石,不终日,贞吉。』介如石焉,宁用终日?断可识矣。君子知微知彰,知柔知刚,万夫之望。」 子曰:「颜氏之子,其殆庶几乎?有不善未尝不知,知之未尝复行也。《易》曰:『不远复,无祗悔,元吉。』」\n\t天地氤氲,万物化醇。男女构精,万物化生。《易》曰:『三人行则损一人,一人行则得其友。』言致一也。\n\t子曰:「君子安其身而后动,易其心而后语,定其交而后求。君子修此三者,故全也。危以动,则民不与也;惧以语,则民不应也;无交而求,则民不与也;莫之与,则伤之者至矣。《易》曰:『莫益之,或击之,立心勿恒,凶。』」", "系辞传下·第六章\n\n\t子曰:「乾坤,其《易》之门耶?」\n\t乾,阳物也;坤,阴物也。阴阳合德,而刚柔有体。以体天地之撰,以通神明之德。其称名也,杂而不越。于稽其类,其衰世之意邪?\n\t夫《易》,彰往而察来,而微显阐幽,开而当名,辨物正言断辞,则备矣。\n\t其称名也小,其取类也大。其旨远,其辞文,其言曲而中,其事肆而隐。因贰以济民行,以明失得之报。", "系辞传下·第七章\n\n\t  《易》之兴也,其于中古乎?作《易》者,其有忧患乎?\n\t是故履,德之基也;谦,德之柄也;复,德之本也;恒,德之固也;损,德之修也;益,德之裕也;困,德之辨也;井,德之地也;巽,德之制也。\n\t履,和而至。谦,尊而光;复,小而辨于物;恒,杂而不厌;损,先难而后易;益,长裕而不设;困,穷而通;井,居其所而迁;巽,称而隐。\n\t履以和行,谦以制礼,复以自知,恒以一德,损以远害,益以兴利,困以寡怨,井以辨义,巽以行权。", "系辞传下·第八章\n\n\t  《易》之为书也!不可远,为道也屡迁,变动不居,周流六虚,上下无常,刚柔相易,不可为典要,唯变所适。\n\t 其出入以度外内,使知惧。又明于忧患与故。无有师保,如临父母。初率其辞而揆其方,既有典常。苟非其人,道不虚行。", "系辞传下·第九章\n\n\t《易》之为书也,原始要终,以为质也。六爻相杂,唯其时物也。其初难知,其上易知,本末也。初辞拟之,卒成之终。\n\t若夫杂物撰德,辩是与非,则非其中爻不备。噫!亦要存亡吉凶,则居可知矣。知者观其彖辞,则思过半矣。\n\t二与四同功而异位,其善不同;二多誉,四多惧,近也。\n\t柔之为道,不利远者;其要无咎。其用柔中也。\n\t三与五同功而异位,三多凶,五多功,贵贱之等也。其柔危,其刚胜耶?", "系辞传下·第十章\n\n\t  《易》之为书也,广大悉备。有天道焉,有人道焉,有地道焉。兼三才而两之,故六。六者非它也,三材之道也。\n\t道有变动,故曰爻;爻有等,故曰物;物相杂,故曰文;文不当,故吉凶生焉。", "系辞传下·第十一章\n\n\t《易》之兴也,其当殷之末世,周之盛德耶?当文王与纣之事耶?\n\t是故其辞危。危者使平,易者使倾。其道甚大,百物不废。惧以终始,其要无咎,此之谓《易》之道也。", "系辞传下·第十二章\n\n\t  夫乾,天下之至健也,德行恒易以知险。夫坤,天下之至顺也,德行恒简以知阻。能说诸心,能研诸侯之虑,定天下之吉凶,成天下之亹亹者。\n\t是故变化云为,吉事有祥。象事知器,占事知来。天地设位,圣人成能。人谋鬼谋,百姓与能。\n\t八卦以象告,爻彖以情言,刚柔杂居,而吉凶可见矣。\n\t变动以利言,吉凶以情迁。是故爱恶相攻而吉凶生,远近相取而悔吝生,情伪相感而利害生。\n\t凡《易》之情,近而不相得则凶,或害之,悔且吝。\n\t将叛者其辞惭,中心疑者其辞枝,吉人之辞寡,躁人之辞多,诬善之人其辞游,失其守者其辞屈。", ]} UniversBookPageModule[67]={"icon":"☯️","key":"67","name": "说卦传","p":"十翼","index":"易经","content":[ "说卦传", "说卦传·第一章\n\t昔者,圣人之作易也,幽赞于神明而生蓍。参(sān)天两地而倚数;观变于阴阳,而立卦;发挥于刚柔,而生爻;和顺于道德,而理于义;穷理尽性,以至于命。", "说卦传·第二章\n\t昔者圣人之作易也,将以顺性命之理。是以立天之道,曰阴与阳;立地之道,曰柔与刚;立人之道,曰仁与义。兼三才而两之,故易六画而成卦。 分阴分阳,迭用柔刚,故易六位而成章。", "说卦传·第三章\n\t天地定位,山泽通气,雷风相薄,水火不相射,八卦相错,数往者顺,知来者逆;是故,易逆数也。", "说卦传·第四章\n\t雷以动之,风以散之,雨以润之, 日以烜之,艮以止之,兑以说之,乾以君之,坤以藏之。", "说卦传·第五章\n\t帝出乎震,齐乎巽,相见乎离,致役乎坤,说言乎兑,战乎乾,劳乎坎,成言乎艮。万物出乎震,震东方也。齐乎巽,巽东南也,齐也者,言万物之洁齐也。离也者,明也,万物皆相见,南方之卦也,圣人南面而听天下,向明而治,盖取诸此也。坤也者地也,万物皆致养焉,故曰致役乎坤。兑正秋也,万物之所说也,故曰说;言乎兑。战乎乾,乾西北之卦也,言阴阳相薄也。坎者水也,正北方之卦也,劳卦也,万物之所归也,故曰劳乎坎。艮东北之卦也,万物之所终而所成始也,故曰成言乎艮。", "说卦传·第六章\n\t神也者,妙万物而为言者也。动万物者,莫疾乎雷;桡万物者,莫疾乎风;燥万物者,莫熯乎火;说万物者,莫说乎泽;润万物者,莫润乎水;终万物始万物者,莫盛乎艮。故水火相逮,雷风不相悖,山泽通气,然后能变化,既成万物也。", "说卦传·第七章\n\t乾,健也;坤,顺也; 震,动也; 巽,入也;坎,陷也;离,丽也;艮,止也;兑,说也。", "说卦传·第八章\n\t乾为马,坤为牛,震为龙,巽为鸡,坎为豕,离为雉,艮为狗,兑为羊。", "说卦传·第九章\n\t乾为首,坤为腹,震为足,巽为股,坎为耳,离为目,艮为手,兑为口。", "说卦传·第十章\n\t乾天也,故称乎父,坤地也,故称乎母;震一索而得男,故谓之长男;巽一索而得女,故谓之长女;坎再索而得男,故谓之中男;离再索而得女,故谓之中女;艮三索而得男,故谓之少男;兑三索而得女,故谓之少女。", "说卦传·第十一章\n\t乾为天、为圜(yuán,圆环)、为君、为父、为玉、为金、为寒、为冰、为大赤、为良马、为瘠马、为驳马、为木果。", "\n\t坤为地、为母、为布、为釜、为吝啬、为均、为子母牛、为大舆、为文、为众、为柄、其于地也为黑。", "\n\t震为雷、为龙、为玄黄、为敷、为大涂、为长子、为决躁、为苍筤(láng)竹、为萑(huán,芦)苇。其于马也,为善鸣、为馵(zhù,左足白)足,为的颡(sǎng,额头)。其于稼也,为反生。其究为健,为蕃鲜。", "\n\t巽为木、为风、为长女、为绳直、为工、为白、为长、为高、为进退、为不果、为臭。其于人也,为寡发、为广颡、为多白眼、为近利市三倍。 其究为躁卦。", "\n\t坎为水、为沟渎、为隐伏、为矫輮(róu,使弯曲)、为弓轮。其于人也,为加忧、为心病、为耳痛、为血卦、为赤。其于马也,为美脊、为亟心、为下首、为薄蹄、为曳。其于舆也,为多眚(shěng,“过失”之意)。 为通、为月、为盗。其于木也,为坚多心。", "\n\t离为火、为日、为电、为中女、为甲胄、为戈兵。其于人也,为大腹,为乾卦。为鳖、为蟹、为蠃(luó,螺)、为蚌、为龟。其于木也,为科上槁。", "\n\t艮为山、为径路、为小石、为门阙、为果苽、为阍寺、为指、为狗、为鼠、为黔喙之属。其于木也,为坚多节。", "\n\t兑为泽、为少女、为巫、为口舌、为毁折、为附决。其于地也,刚卤。 为妾、为羊。", "","","","", ]} UniversBookPageModule[68]={"icon":"☯️","key":"68","name": "序卦传","p":"十翼","index":"易经","content":[ "序卦传", "有天地,然后万物生焉。 \n盈天地之间者,唯万物,故受之以屯;\n屯者 盈也,屯者物之始生也。 \n物生必蒙,故受之以蒙;\n蒙者蒙也,物之稚也。 物稚不可不养也,故受之以需;需者饮食之道也。饮食必有讼,故受之以 讼。讼必有众起,故受之以师;师者众也。 众必有所比,故受之以比;比 者比也。 比必有所畜也,故受之以小畜。物畜然后有礼,故受之以履。履 而泰,然后安,故受之以泰;泰者通也。 物不可以终通,故受之以否。物 不可以终否,故受之以同人。 与人同者,物必归焉,故受之以大有。有大 者不可以盈,故受之以谦。 有大而能谦,必豫,故受之以豫。 豫必有随, 故受之以随。 以喜随人者,必有事,故受之以蛊;蛊者事也。有事而后可 大,故受之以临;临者大也。 物大然后可观,故受之以观。可观而后有所 合,故受之以噬嗑;嗑者合也。 物不可以苟合而已,故受之以贲;贲者饰 也。 致饰然后亨,则尽矣,故受之以剥;剥者剥也。物不可以终尽,剥穷 上反下,故受之以复。 复则不妄矣,故受之以无妄。有无妄然后可畜,故 受之以大畜。 物畜然后可养,故受之以颐;颐者养也。不养则不可动,故 受之以大过。物不可以终过,故受之以坎;坎者陷也。 陷必有所丽,故受 之以离;离者丽也。", "有天地,然后有万物; \n有万物,然后有男女; 有男女,然后有夫妇; 有夫妇,然后有父子;有父子然后有君臣;有君臣,然后有上下;有上下, 然后礼仪有所错。 夫妇之道,不可以不久也,故受之以恒;恒者久也。物 不可以久居其所,故受之以遁; 遁者退也。 物不可终遁,故受之以大壮。 物不可以终壮,故受之以晋;晋者进也。进必有所伤,故受之以明夷; 夷者伤也。 伤于外者,必反其家,故受之以家人。家道穷必乖,故受之以 睽;睽者乖也。 乖必有难,故受之以蹇;蹇者难也。物不可终难,故受之 以解;解者缓也。 缓必有所失,故受之以损;损而不已,必益,故受之以 益。益而不已,必决,故受之以夬; 夬者决也。决必有所遇,故受之以 姤;姤者遇也。物相遇而后聚,故受之以萃;萃者聚也。 聚而上者,谓 之升,故受之以升。升而不已,必困,故受之以困。 困乎上者,必反下, 故受之以井。 井道不可不革,故受之以革。 革物者莫若鼎,故受之以鼎。 主器者莫若长子,故受之以震;震者动也。 物不可以终动,止之,故受之 以艮;艮者止也。 物不可以终止,故受之以渐;渐者进也。 进必有所归, 故受之以归妹。 得其所归者必大,故受之以丰;丰者大也。穷大者必失其 居,故受之以旅。 旅而无所容,故受之以巽;巽者入也。入而后说之,故 受之以兑;兑者说也。 说而后散之,故受之以涣;涣者离也。物不可以终 离,故受之以节。节而信之,故受之以中孚。 有其信者,必行之,故受之 以小过。有过物者,必济,故受之既济。物不可穷也,故受之以未济终焉。", "","","","", ]} UniversBookPageModule[69]={"icon":"☯️","key":"68","name": "杂卦传","p":"十翼","index":"易经","content":[ "杂卦传", "乾刚,坤柔,比乐,师忧。", "临、观之义,或与或求。", "屯见而不失其居。蒙杂而著。", "震起也,艮止也;损益盛衰之始也。", "大畜时也。无妄灾也。", "萃聚,而升不来也。", "谦轻,而豫怠也。", "噬嗑食也,贲无色也。", "兑见,而巽伏也。", "随无故也,蛊则饬也。", "剥烂也,复反也。", "晋昼也,明夷诛也。", "井通,而困相遇也。", "咸速也,恒久也。", "涣离也,节止也;", "解缓也,蹇难也;", "睽外也,家人内也;", "否泰反其类也。", "大壮则止,遁则退也。", "大有众也,同人亲也;革去故也,鼎取新也;小过过也,中孚信也;丰多故也,亲寡旅也。", "离上,而坎下也。", "小畜寡也,履不处也。", "需不进也,讼不亲也。", "大过颠也。姤遇也,柔遇刚也。", "渐女归,待男行也。颐养正也,既济定也。", "归妹女之终也。未济男之穷也。", "夬决也,刚决柔也,君子道长,小人道忧也。", "","","","", ]} UniversBookPageModule[70]={"icon":"☯️","key":"68","name": "文言传","p":"十翼","index":"易经","content":[ "乾文言", "“元”者,善之长也;“亨”者,嘉之会也;“利”者,义之和也;“贞”者,事之干也。君子体仁足以长人,嘉会足以合礼,利物足以和义,贞固足以干事。君子行此四德者,故曰:“乾、元、亨、利、贞。”初九曰:“潜龙勿用。”何谓也?子曰:“龙德而隐者也,不易乎世,不成乎名,遯世无闷,不见是而无闷,乐则行之,忧则违之,确乎其不可拔,潜龙也。”九二曰:“见龙在田,利见大人。”何谓也?子曰:“龙德而正中者也。庸言之信,庸行之谨,闲邪存其诚,善世而不伐,德博而化。", "《易》曰‘见龙在田,利见大人’。君德也。”九三曰:“君子终日乾乾,夕惕若厉,无咎。”何谓也?子曰:“君子进德修业。忠信所以进德也。修辞立其诚,所以居业也。知至至之,可与几也。知终终之,可与存义也。是故居上位而不骄,在下位而不忧,故乾乾因其时而惕,虽危无咎矣。”九四曰:“或跃在渊,无咎。”何谓也?子曰:“上下无常,非为邪也。进退无恒,非离群也。君子进德修业,欲及时也,故无咎。”九五曰:“飞龙在天,利见大人。”何谓也?子曰:“同声相应,同气相求。水流湿,火就燥。云从龙,风从虎。圣人作而万物覩。本乎天者亲上,本乎地者亲下。则各从其类也。”上九曰:“亢龙有悔。”何谓也?子曰:“贵而无位,高而无民,贤人在下位而无辅,是以动而有悔也。”", "“潜龙勿用”,下也;“见龙在田”,时舍也;“终日乾乾”,行事也;“或跃在渊”,自试也;“飞龙在天”,上治也;“亢龙有悔”,穷之灾也;乾元“用九”,天下治也。“潜龙勿用”,阳气潜藏;“见龙在田”,天下文明;“终日乾乾”,与时偕行;“或跃在渊”,乾道乃革;“飞龙在天”,乃位乎天德;“亢龙有悔”,与时偕极;乾元“用九”,乃见天则。乾“元”者,始而亨者也;“利贞”者,性情也。乾始能以美利利天下,不言所利,大矣哉,大哉乾乎,刚健中正,纯粹精也。六爻发挥,旁通情也,时乘六龙,以御天也。云行雨施,天下平也。", "君子以成德为行,日可见之行也。“潜”之为言也,隐而未见,行而未成,是以君子弗用也。君子学以聚之,问以辩之,宽以居之,仁以行之。《易》曰:“见龙在田,利见大人。”君德也。九三重刚而不中,上不在天,下不在田,故乾乾因其时而惕,虽危“无咎”矣。九四重刚而不中,上不在天,下不在田,中不在人,故“或”之,或之者,疑之也。故“无咎”。夫“大人”者,与天地合其德,与日月合其明,与四时合其序,与鬼神合其吉凶。先天而天弗违,后天而奉天时,天且弗违,而况于人乎!况于鬼神乎!“亢”之为言也,知进而不知退,知存而不知亡,知得而不知丧,其唯圣人乎!知进退存亡而不失其正者,其唯圣人乎!", "", "", "坤文言", "坤至柔而动也刚,至静而德方,后得主而有常,含万物而化光。坤道其顺乎,承天而时行。积善之家必有余庆,积不善之家必有余殃。臣弑其君,子弑其父,非一朝一夕之故,其所由来者渐矣。由辩之不早辩也。", "《易》曰:“履霜,坚冰至。”盖言顺也。“直”其正也,“方”其义也。君子敬以直内,义以方外,敬义立而德不孤。“直方大,不习无不利。”则不疑其所行也。阴虽有美,“含”之以从王事,弗敢成也。地道也,妻道也,臣道也。地道“无成”而代“有终”也。天地变化,草木蕃,天地闭,贤人隐。", "《易》曰:“括囊,无咎无誉。”盖言谨也。君子“黄”中通理,正位居体,美在其中,而畅于四支,发于事业,美之至也!阴疑于阳必战,为其嫌于无阳也。故称“龙”焉犹未离其类也,故称“血”焉。夫“玄黄”者,天地之杂也,天玄而地黄。", "","","","", ]} module.exports={UniversBookPageModule:UniversBookPageModule};
jamessspanggg/ChairVisE
src/test/java/sg/edu/nus/comp/cs3219/viz/VizApplicationTests.java
<filename>src/test/java/sg/edu/nus/comp/cs3219/viz/VizApplicationTests.java //package sg.edu.nus.comp.cs3219.viz; // //import org.junit.Test; //import org.junit.runner.RunWith; //import org.springframework.boot.test.context.SpringBootTest; //import org.springframework.test.context.junit4.SpringRunner; // //@RunWith(SpringRunner.class) //@SpringBootTest //public class VizApplicationTests { // // @Test // public void contextLoads() { // // make sure it run // } // //}
sag-tgo/xpybuild
tests/build_utilities/native_config.xpybuild.py
<reponame>sag-tgo/xpybuild import os from propertysupport import * from buildcommon import * from pathsets import * from utils.compilers import GCC, VisualStudio # some basic defaults for recent default compilers for running our testcases with if isWindows(): VSROOT=r'c:\Program Files (x86)\Microsoft Visual Studio 14.0' assert os.path.exists(VSROOT), 'Cannot find Visual Studio installed in: %s'%VSROOT setGlobalOption('native.include', [r"%s\VC\ATLMFC\INCLUDE" % VSROOT, r"%s\VC\INCLUDE" % VSROOT, r"C:\Program Files (x86)\Windows Kits\10\Include\10.0.10240.0\ucrt"]) setGlobalOption('native.libpaths', [r"%s\VC\ATLMFC\LIB\amd64" % VSROOT, r"%s\VC\LIB\amd64" % VSROOT, r"C:\Program Files (x86)\Windows Kits\10\Lib\10.0.10240.0\ucrt\x64", r"C:\Program Files (x86)\Windows Kits\8.1\Lib\winv6.3\um\x64"]) setGlobalOption('native.compilers', VisualStudio(VSROOT+r'\VC\bin\amd64')) setGlobalOption('native.cxx.flags', ['/EHa', '/GR', '/O2', '/Ox', '/Ot', '/MD', '/nologo']) setGlobalOption('native.cxx.path', ["%s\Common7\IDE" % VSROOT,r"%s\VC\BIN\amd64" % VSROOT, "%s\Common7\Tools" % VSROOT, r"c:\Windows\Microsoft.NET\Framework\v3.5"]) else: setGlobalOption('native.compilers', GCC()) setGlobalOption('native.cxx.flags', ['-fPIC', '-O3', '--std=c++0x'])
jameshforster/AdvancedRocketry
src/main/java/zmaster587/advancedRocketry/client/render/RocketRenderHelper.java
package zmaster587.advancedRocketry.client.render; import org.lwjgl.opengl.GL11; public class RocketRenderHelper { public static void renderOrbit(double x, double y, double z, double xRadius, double yRadius, double phase) { renderOrbit(x, y, z, xRadius, yRadius, 0, 0); } public static void renderOrbit(double x, double y, double z, double xRadius, double yRadius, double xOffset, double yOffset) { GL11.glLineWidth(20/(float)(Math.pow(x - 0.5 - xOffset, 2) + Math.pow(y - 0.5 - yOffset, 2) + Math.pow(z - 0.5, 2))); GL11.glBegin(GL11.GL_LINE_STRIP); for(int i = 0; i < 13; i++) GL11.glVertex3d(xOffset + 0.5 + xRadius*Math.cos((Math.PI*i)/6)/2.2, yOffset - 0.5 + yRadius*Math.sin((Math.PI*i)/6)/2.2, 0); GL11.glEnd(); } public static void renderPositionAlongOrbit(double x, double y, double z, double xRadius, double yRadius, double phase, double xOffset, double yOffset) { GL11.glPointSize(200/(float)(Math.pow(x - 0.5 - xOffset, 2) + Math.pow(y - yOffset - 0.5, 2) + Math.pow(z - 0.5, 2))); GL11.glBegin(GL11.GL_POINTS); GL11.glVertex3d(xOffset + 0.5 + xRadius*Math.cos((Math.PI*phase)/180)/2.2, yOffset - 0.5 + yRadius*Math.sin((Math.PI*phase)/180)/2.2, 0); GL11.glEnd(); } }
AlHeamer/eve-indy-watch
app/controllers/personal_access_tokens_controller.rb
# frozen_string_literal: true class PersonalAccessTokensController < ApplicationController before_action :authenticate_user! before_action :find_pat, only: %i[destroy] layout 'settings' def index @pats = policy_scope(current_user.personal_access_tokens.order(created_at: :desc)) end def new @pat = OauthAccessToken.new end def create create_params[:scopes] = create_params[:scopes].reject { |s| Doorkeeper.config.scopes.exclude?(s) } @pat_application = current_user.personal_access_token_applications.build(create_params.slice(:scopes)) @pat = @pat_application.access_tokens.build(create_params.merge(resource_owner_id: current_user.id)) if @pat_application.save flash[:success] = "Personal access token created successfully. Copy the token value because it will only be shown once: #{@pat.token}" redirect_to settings_personal_access_tokens_path else flash[:error] = 'Error creating personal access token.' render :new end end def show; end def destroy @pat.destroy flash[:success] = 'Personal access token successfully deleted.' redirect_to settings_personal_access_tokens_path end private def find_pat @pat = authorize(current_user.personal_access_tokens.find(params[:id])) end def create_params @create_params ||= params.require(:oauth_access_token).permit(:description, scopes: []) end end
fahadnasrullah109/KalturaClient-Android
KalturaClient/src/main/java/com/kaltura/client/types/Filter.java
<reponame>fahadnasrullah109/KalturaClient-Android // =================================================================================================== // _ __ _ _ // | |/ /__ _| | |_ _ _ _ _ __ _ // | ' </ _` | | _| || | '_/ _` | // |_|\_\__,_|_|\__|\_,_|_| \__,_| // // This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // // Copyright (C) 2006-2018 Kaltura Inc. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // // @ignore // =================================================================================================== package com.kaltura.client.types; import android.os.Parcel; import com.google.gson.JsonObject; import com.kaltura.client.Params; import com.kaltura.client.types.ObjectBase; import com.kaltura.client.types.SearchItem; import com.kaltura.client.utils.GsonParser; import com.kaltura.client.utils.request.MultiRequestBuilder; /** * This class was generated using exec.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") @MultiRequestBuilder.Tokenizer(Filter.Tokenizer.class) public abstract class Filter extends ObjectBase { public interface Tokenizer extends ObjectBase.Tokenizer { String orderBy(); SearchItem.Tokenizer advancedSearch(); } private String orderBy; private SearchItem advancedSearch; // orderBy: public String getOrderBy(){ return this.orderBy; } public void setOrderBy(String orderBy){ this.orderBy = orderBy; } public void orderBy(String multirequestToken){ setToken("orderBy", multirequestToken); } // advancedSearch: public SearchItem getAdvancedSearch(){ return this.advancedSearch; } public void setAdvancedSearch(SearchItem advancedSearch){ this.advancedSearch = advancedSearch; } public Filter() { super(); } public Filter(JsonObject jsonObject) throws APIException { super(jsonObject); if(jsonObject == null) return; // set members values: orderBy = GsonParser.parseString(jsonObject.get("orderBy")); advancedSearch = GsonParser.parseObject(jsonObject.getAsJsonObject("advancedSearch"), SearchItem.class); } public Params toParams() { Params kparams = super.toParams(); kparams.add("objectType", "KalturaFilter"); kparams.add("orderBy", this.orderBy); kparams.add("advancedSearch", this.advancedSearch); return kparams; } @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); dest.writeString(this.orderBy); dest.writeParcelable(this.advancedSearch, flags); } public Filter(Parcel in) { super(in); this.orderBy = in.readString(); this.advancedSearch = in.readParcelable(SearchItem.class.getClassLoader()); } }
gxw1/review_the_national_post-graduate_entrance_examination
books_and_notes/professional_courses/C++_Programming/sources/cpp_code/lab/Chapter5/ex5-14/ex5-14.cpp
#include <iostream> using namespace std; class Boat; class Car { private: int weight; public: Car(int j) { weight = j; } friend int getTotalWeight(Car &aCar, Boat &aBoat); }; class Boat { private: int weight; public: Boat(int j) { weight = j; } friend int getTotalWeight(Car &aCar, Boat &aBoat); }; int getTotalWeight(Car &aCar, Boat &aBoat) { return aCar.weight + aBoat.weight; } int main() { Car c1(4); Boat b1(5); cout << getTotalWeight(c1, b1) << endl; return 0; }
PopupMC/VariableHealth
src/main/java/com/popupmc/variablehealth/system/scaling/ScaleBasics.java
<reponame>PopupMC/VariableHealth<gh_stars>0 package com.popupmc.variablehealth.system.scaling; import com.popupmc.variablehealth.VariableHealth; import com.popupmc.variablehealth.system.BaseSystem; import com.popupmc.variablehealth.system.System; import com.popupmc.variablehealth.utility.MathTools; import com.popupmc.variablehealth.utility.RandomTools; import org.jetbrains.annotations.NotNull; public class ScaleBasics extends BaseSystem { public ScaleBasics(int maxScalePercent, int scaleGranularityCount, @NotNull System system, @NotNull VariableHealth plugin) { super(system, plugin); this.scaleMax = MathTools.createEasyDivider(maxScalePercent, system.level.data.maxLevel); this.scaleGranularityCount = scaleGranularityCount; this.scaleGranularityAmount = system.level.data.maxLevel / scaleGranularityCount; } public double genericScale(double val, int level, boolean increaseOnly) { // Used to countdown levels left // Ideally we want a random number for each level // But that's computationally expensive // So instead we do short bursts, this keeps track of that int levelLeft = level; // final product int percentChange = 0; // Begin looping our predefined granularity for(int i = 0; i < scaleGranularityCount; i++) { // Get a number between 1 and our max genericScale int tmp = RandomTools.getRandomRange1(scaleMax); // If the short burst is greater than levels left, don't do a short burst, do the remainder levels // and stop here if(scaleGranularityAmount > levelLeft) { percentChange += (tmp * levelLeft); break; } // Otherwise do the full short burst and subtract burst done from levels left else { percentChange += (tmp * scaleGranularityAmount); levelLeft -= scaleGranularityAmount; } } if(increaseOnly) percentChange += 100; // Convert to an actual percent double percentChangeFloat = percentChange * 0.01; return val * percentChangeFloat; } public final int scaleMax; public final int scaleGranularityCount; public final int scaleGranularityAmount; }
dram/metasfresh
backend/de.metas.procurement.base/src/main/java/de/metas/procurement/base/order/impl/OrderHeaderAggregation.java
<reponame>dram/metasfresh package de.metas.procurement.base.order.impl; import de.metas.adempiere.model.I_C_Order; import de.metas.bpartner.service.IBPartnerDAO; import de.metas.common.util.time.SystemTime; import de.metas.document.engine.DocStatus; import de.metas.document.engine.IDocument; import de.metas.document.engine.IDocumentBL; import de.metas.order.IOrderBL; import de.metas.util.Services; import org.adempiere.model.InterfaceWrapperHelper; import org.compiere.model.I_C_BPartner; import org.compiere.util.Env; import org.compiere.util.TimeUtil; import java.sql.Timestamp; import java.util.Properties; /* * #%L * de.metas.procurement.base * %% * Copyright (C) 2016 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ public class OrderHeaderAggregation { // services private final transient IOrderBL orderBL = Services.get(IOrderBL.class); private final transient IDocumentBL docActionBL = Services.get(IDocumentBL.class); private final transient IBPartnerDAO bpartnersRepo = Services.get(IBPartnerDAO.class); private I_C_Order order; private OrderLinesAggregator orderLinesAggregator = null; public I_C_Order build() { if (order == null) { // nothing to build return null; } // // Build and save all order lines orderLinesAggregator.closeAllGroups(); // // Process the order docActionBL.processEx(order, IDocument.ACTION_Complete, IDocument.STATUS_Completed); return order; } public void add(final PurchaseCandidate candidate) { if (candidate.isZeroQty()) { return; } if (order == null) { order = createOrder(candidate); orderLinesAggregator = new OrderLinesAggregator(order); } orderLinesAggregator.add(candidate); } private I_C_Order createOrder(final PurchaseCandidate candidate) { final int adOrgId = candidate.getAD_Org_ID(); final int warehouseId = candidate.getM_Warehouse_ID(); final I_C_BPartner bpartner = bpartnersRepo.getById(candidate.getC_BPartner_ID()); final int pricingSystemId = candidate.getM_PricingSystem_ID(); // the price is taken from the candidates and C_OrderLine.IsManualPrice is set to 'Y' // gh #1088 I have no clue wtf the comment above "the price is taken from..." is supposed to mean. // So instead of using M_PriceList_ID_None here, we use the candidate's PL. // Because otherwise, de.metas.order.model.interceptor.C_Order#onPriceListChangeInterceptor(...) will update the order pricing system to M_PricingSystem_ID_None // and then the system won't be able to get the new order lines' C_TaxCategories and MOrderLine.beforeSave() will fail // final int priceListId = MPriceList.M_PriceList_ID_None; final int priceListId = candidate.getM_PriceList_ID(); final int currencyId = candidate.getC_Currency_ID(); final Timestamp datePromised = candidate.getDatePromised(); final Timestamp dateOrdered = TimeUtil.min(SystemTime.asDayTimestamp(), datePromised); final I_C_Order order = InterfaceWrapperHelper.newInstance(I_C_Order.class); // // Doc type order.setAD_Org_ID(adOrgId); order.setIsSOTrx(false); orderBL.setDefaultDocTypeTargetId(order); // // Warehouse order.setM_Warehouse_ID(warehouseId); // // BPartner orderBL.setBPartner(order, bpartner); orderBL.setBill_User_ID(order); // // Dates order.setDateOrdered(dateOrdered); order.setDateAcct(dateOrdered); order.setDatePromised(datePromised); // // Price list if (pricingSystemId > 0) { order.setM_PricingSystem_ID(pricingSystemId); } if (priceListId > 0) { order.setM_PriceList_ID(priceListId); } order.setC_Currency_ID(currencyId); // // SalesRep: // * let it to be set from BPartner (this was done above, by orderBL.setBPartner method) // * if not set use it from context final Properties ctx = InterfaceWrapperHelper.getCtx(order); if (order.getSalesRep_ID() <= 0) { order.setSalesRep_ID(Env.getContextAsInt(ctx, Env.CTXNAME_SalesRep_ID)); } if (order.getSalesRep_ID() <= 0) { order.setSalesRep_ID(Env.getAD_User_ID(ctx)); } order.setDocStatus(DocStatus.Drafted.getCode()); order.setDocAction(IDocument.ACTION_Complete); // // Save & return InterfaceWrapperHelper.save(order); return order; } }
tsadm/webapp
src/tsadmhost/tests/test.py
<reponame>tsadm/webapp from tsadm.tests import TSAdmTestBase from ..models import HostDB class TSAdmHostTest(TSAdmTestBase): def setUp(self): super(TSAdmHostTest, self).setUp() def test_HostView(self): resp = self.client.get(self.getURL('host:home', kwargs={'ID': 1})) self.assertContains(resp, 'TEST:host.fqdn:fake0.tsadm.test', status_code=200) def test_HostViewNotFound(self): resp = self.client.get(self.getURL('host:home', kwargs={'ID': 0})) self.assertEqual(resp.status_code, 400)
sentient-lang/sentient-lang
spec/sentient/integration/level3/collectSpec.js
"use strict"; var compiler = "../../../../lib/sentient/compiler"; var Level1Compiler = require(compiler + "/level1Compiler"); var Level2Compiler = require(compiler + "/level2Compiler"); var Level3Compiler = require(compiler + "/level3Compiler"); var runtime = "../../../../lib/sentient/runtime"; var Level1Runtime = require(runtime + "/level1Runtime"); var Level2Runtime = require(runtime + "/level2Runtime"); var Level3Runtime = require(runtime + "/level3Runtime"); var Machine = require("../../../../lib/sentient/machine"); describe("Integration: 'collect'", function () { it("collects N elements into an array", function () { var program = Level3Compiler.compile({ instructions: [ { type: "constant", value: 1 }, { type: "constant", value: -2 }, { type: "constant", value: 3 }, { type: "collect", width: 3 }, { type: "pop", symbol: "foo" }, { type: "variable", symbol: "foo" }, { type: "constant", value: true }, { type: "constant", value: false }, { type: "collect", width: 2 }, { type: "pop", symbol: "bar" }, { type: "variable", symbol: "bar" }, { type: "integer", symbol: "a", width: 6 }, { type: "integer", symbol: "b", width: 6 }, { type: "push", symbol: "a" }, { type: "push", symbol: "b" }, { type: "duplicate" }, { type: "constant", value: 5 }, { type: "equal" }, { type: "invariant" }, { type: "collect", width: 2 }, { type: "pop", symbol: "baz" }, { type: "variable", symbol: "baz" }, { type: "push", symbol: "foo" }, { type: "push", symbol: "baz" }, { type: "collect", width: 2 }, { type: "pop", symbol: "qux" }, { type: "variable", symbol: "qux" }, { type: "push", symbol: "bar" }, { type: "collect", width: 1 }, { type: "collect", width: 1 }, { type: "collect", width: 1 }, { type: "collect", width: 1 }, { type: "collect", width: 1 }, { type: "pop", symbol: "abc" }, { type: "variable", symbol: "abc" } ] }); program = Level2Compiler.compile(program); program = Level1Compiler.compile(program); var assignments = Level3Runtime.encode(program, {}); assignments = Level2Runtime.encode(program, assignments); assignments = Level1Runtime.encode(program, assignments); var result = Machine.run(program, assignments)[0]; result = Level1Runtime.decode(program, result); result = Level2Runtime.decode(program, result); result = Level3Runtime.decode(program, result); expect(result.foo).toEqual([1, -2, 3]); expect(result.bar).toEqual([true, false]); expect(result.baz).toEqual([0, 5]); expect(result.qux).toEqual([ [1, -2, 3], [0, 5] ]); expect(result.abc).toEqual([[[[[[true, false]]]]]]); }); it("allows empty arrays", function () { var program = Level3Compiler.compile({ instructions: [ { type: "collect", width: 0 }, { type: "pop", symbol: "a" }, { type: "constant", value: 10 }, { type: "collect", width: 1 }, { type: "collect", width: 0 }, { type: "collect", width: 2 }, { type: "pop", symbol: "b" }, { type: "constant", value: 10 }, { type: "collect", width: 1 }, { type: "collect", width: 1 }, { type: "collect", width: 0 }, { type: "collect", width: 1 }, { type: "collect", width: 0 }, { type: "collect", width: 3 }, { type: "pop", symbol: "c" }, { type: "variable", symbol: "a" }, { type: "variable", symbol: "b" }, { type: "variable", symbol: "c" } ] }); program = Level2Compiler.compile(program); program = Level1Compiler.compile(program); var assignments = Level3Runtime.encode(program, {}); assignments = Level2Runtime.encode(program, assignments); assignments = Level1Runtime.encode(program, assignments); var result = Machine.run(program, assignments)[0]; result = Level1Runtime.decode(program, result); result = Level2Runtime.decode(program, result); result = Level3Runtime.decode(program, result); expect(result).toEqual({ a: [], b: [[10], []], c: [[[10]], [[]], []] }); }); it("allows nested empty arrays", function () { var program = Level3Compiler.compile({ instructions: [ { type: "constant", value: 10 }, { type: "collect", width: 1 }, { type: "collect", width: 1 }, { type: "collect", width: 1 }, { type: "collect", width: 0 }, { type: "collect", width: 1 }, { type: "collect", width: 1 }, { type: "collect", width: 2 }, { type: "pop", symbol: "out" }, { type: "variable", symbol: "out" } ] }); program = Level2Compiler.compile(program); program = Level1Compiler.compile(program); var assignments = Level3Runtime.encode(program, {}); assignments = Level2Runtime.encode(program, assignments); assignments = Level1Runtime.encode(program, assignments); var result = Machine.run(program, assignments)[0]; result = Level1Runtime.decode(program, result); result = Level2Runtime.decode(program, result); result = Level3Runtime.decode(program, result); expect(result).toEqual({ out: [[[[10]]], [[[]]]] }); }); it("throws an error for mixed type arrays", function () { expect(function () { Level3Compiler.compile({ instructions: [ { type: "constant", value: 1 }, { type: "constant", value: true }, { type: "collect", width: 2 } ] }); }).toThrow(); }); it("throws an error for nested mixed type arrays", function () { expect(function () { Level3Compiler.compile({ instructions: [ { type: "constant", value: 1 }, { type: "collect", width: 1 }, { type: "constant", value: true }, { type: "collect", width: 1 }, { type: "collect", width: 2 } ] }); }).toThrow(); }); });
TheShaders/Tecto
include/resize.h
#ifndef __RESIZE_H__ #define __RESIZE_H__ #include <types.h> #define RESIZE_TIMER_START 60 typedef enum { Size_Grown, Size_Shrunk } SizeState; typedef enum { Resize_Starting, Resize_Ending } ResizeTrigger; enum { ResizeType_Shrink_While_Held, ResizeType_Grow_While_Held, ResizeType_Interactable }; typedef u8 ResizeType; typedef void (*ResizeCallback)(ResizeParams *newState, ResizeTrigger trigger); typedef struct ResizeParams_t { SizeState curSize : 1; int growTemporary : 1; int growAllowed : 1; int shrinkAllowed : 1; int horizontalIndicator : 1; int reserved : 3; u8 grownTime; u8 resizeTimer; ResizeType type; u8 restoreTimer; float smallScale; float largeScale; ResizeCallback callback; } ResizeParams; void tickResizables(void); #endif
unseenme/mindspore
predict/src/operator/cpu/include/op_func_comm.h
/** * Copyright 2019 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef PREDICT_SRC_OPERATOR_CPU_INCLUDE_OP_FUNC_COMM_H_ #define PREDICT_SRC_OPERATOR_CPU_INCLUDE_OP_FUNC_COMM_H_ #include <cstdint> #include <cstdio> #include <cmath> #include <cstring> #include <algorithm> #include "src/op_common.h" #include "include/tensor.h" #ifdef MS_USE_NEON #include <arm_neon.h> #endif // MS_USE_NEON namespace mindspore { namespace predict { #ifdef __cplusplus extern "C" { #endif #define CAL_STEP 4 void MSAddBias(float *dst, const float *bias, size_t planeNumber, size_t biasNumber); void MSAddBiasRelu(float *dst, const float *bias, size_t planeNumber, size_t biasNumber); void MSAddBiasRelu6(float *dst, const float *bias, size_t planeNumber, size_t biasNumber); void MSPackC4Uint8(uint8_t *dst, const uint8_t *src, size_t area, size_t depth); void MSUnpackC4(float *dst, const float *src, size_t area, size_t depth); void MSUnpackC4Uint8(uint8_t *dst, const uint8_t *src, size_t area, size_t depth); void MSTensorConvertNHWCToNC4HW4(float *dst, const float *src, size_t area, size_t depth); void MSTensorConvertNC4HW4ToNHWC(float *dst, const float *src, size_t area, size_t depth); void MSUnpackC4(float *dst, const float *src, size_t area, size_t depth); void MSCopyC4WithStride(const float *source, float *dest, size_t srcStride, size_t dstStride, size_t count); void MSUInt8ToInt16WithOffsetC4Common(int16_t *dst, const uint8_t *src, size_t zeroPoint, size_t sizeQuad, size_t dstStride, size_t srcStride); void MSUInt8ToInt16WithOffsetC4Fast(int16_t *dst, const uint8_t *src, size_t zeroPoint, size_t sizeQuad, size_t depthQuad, size_t dstZStep, size_t srcZStep); int MSPackC4(float *dst, const float *src, size_t area, size_t depth); int NchwToNc4hw4(const Tensor *input, Tensor *output); int Nc4hw4ToNchw(const Tensor *input, Tensor *output); #ifdef __cplusplus } #endif } // namespace predict } // namespace mindspore #endif // PREDICT_SRC_OPERATOR_CPU_INCLUDE_OP_FUNC_COMM_H_
NCIP/psc
core/src/main/java/edu/northwestern/bioinformatics/studycalendar/dao/StudySegmentDao.java
/*L * Copyright Northwestern University. * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.io/psc/LICENSE.txt for details. */ package edu.northwestern.bioinformatics.studycalendar.dao; import edu.northwestern.bioinformatics.studycalendar.domain.StudySegment; import java.util.List; /** * @author <NAME> * @author <NAME> */ public class StudySegmentDao extends ChangeableDao<StudySegment> { @Override public Class<StudySegment> domainClass() { return StudySegment.class; } /** * Deletes the given study segment * * @param segment the study segment to delete */ public void delete(StudySegment segment) { getHibernateTemplate().delete(segment); } public void deleteOrphans() { deleteOrphans("StudySegment", "epoch", "EpochDelta", "epoch"); } public void deleteAll(List<StudySegment> t) { getHibernateTemplate().deleteAll(t); } }
itsdaniellucas/digishop
src/server-node/src/graphql/resolvers/order.js
const { getOrders, getOrder, addOrder, removeOrder } = require('../../services/orderService') const resolver = { Query: { orders: (_, { pagination }, { user }) => getOrders(pagination, user), order: (_, { id }, { user }) => getOrder(id, user) }, Mutation: { addOrder: (_, { order }, { user }) => addOrder(order, user), removeOrder: (_, { id }, { user }) => removeOrder(id, user) } } module.exports = resolver
mitring/cuba
modules/gui/src/com/haulmont/cuba/gui/components/HasPresentations.java
/* * Copyright (c) 2008-2018 Haulmont. * * 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.haulmont.cuba.gui.components; import com.haulmont.cuba.gui.presentations.Presentations; /** * Component having presentations. */ public interface HasPresentations extends HasSettings { void usePresentations(boolean b); boolean isUsePresentations(); void resetPresentation(); void loadPresentations(); Presentations getPresentations(); void applyPresentation(Object id); void applyPresentationAsDefault(Object id); Object getDefaultPresentationId(); }
griffithlab/civic-client
src/app/views/events/common/entityTabs.js
(function() { 'use strict'; /** * Permits declarative (and dynamic) definitions of tab links with full routes. * * requires 'ui.router' and 'ui.bootstrap' * (uses ui-tabset and tab directives in ui.bootstrap and route changes in ui.router) * * You can define (for styling) the attributes type="pills" and vertical="true | false" and justified="true | false" * * Watches the $stateChangeXX events so it can update the parent tab(s) when using $state.go or ui-sref anchors. * * See ui-router-tabs.spec.js for tests. * * Author: <NAME> (<EMAIL>) * License: MIT * */ angular.module('civic.events.common') .directive('entityTabs', entityTabsDirective) .controller('EntityTabsController', EntityTabsController); // @ngInject function entityTabsDirective() { return /* @ngInject */ { restrict: 'E', scope: { justified: '=', vertical: '=' }, require: '^^entityView', link: entityTabsLink, controller: 'EntityTabsController', templateUrl: 'app/views/events/common/entityTabs.tpl.html' }; } function entityTabsLink(scope, element, attributes, entityView) { var _ = window._; var vm = scope.vm; // todo convert the rest of this controller to vm var entityViewModel = scope.entityViewModel = entityView.entityViewModel; var entityViewRevisions = scope.entityViewRevisions = entityView.entityViewRevisions; var entityViewOptions = scope.entityViewOptions = entityView.entityViewOptions; element.ready(function() { scope.scroll(); }); vm.type = ''; vm.name = ''; vm.status = ''; vm.type = _.map(entityViewModel.data.item.type.replace('_', ' ').split(' '), function(word) { return word.toUpperCase(); }).join(' '); vm.actions = {}; vm.actions = entityViewModel.data.item.lifecycle_actions; var fetchPending = function(){ entityViewRevisions.getPendingFields(entityViewModel.data.item.id) .then(function(fields) { vm.pendingFields = _.keys(entityViewRevisions.data.pendingFields); vm.hasPendingFields = fields.length > 0; }); }; fetchPending(); scope.$on('revisionDecision', function(){ fetchPending(); }); vm.anchorId = _.kebabCase(vm.type); scope.$watch('entityViewModel.data.item.status', function(status) { vm.status = status; }); scope.$watch('entityViewModel.data.item.name', function(name) { vm.name = name; }); scope.$watchCollection('entityViewModel.data.item.lifecycle_actions', function(lifecycle_actions) { vm.actions = lifecycle_actions; }); scope.viewBackground = 'view-' + entityViewOptions.styles.view.backgroundColor; scope.viewForeground = 'view-' + entityViewOptions.styles.view.foregroundColor; scope.tabs = entityViewOptions.tabData; if (!scope.tabs) { throw new Error('entityTabs: \'data\' attribute not defined, please check documentation for how to use this directive.'); } if (!angular.isArray(scope.tabs)) { throw new Error('entityTabs: \'data\' attribute must be an array of tab data with at least one tab defined.'); } var unbindStateChangeSuccess = scope.$on( '$stateChangeSuccess', function () { scope.update_tabs(); } ); scope.$on('$destroy', unbindStateChangeSuccess); } // @ngInject function EntityTabsController($scope, $state, $rootScope, $stateParams, $location, $document, Security, Subscriptions, _) { var vm = $scope.vm = {}; vm.isAuthenticated = Security.isAuthenticated; vm.isEditor = Security.isEditor; vm.isAdmin = Security.isAdmin; vm.subscribed = null; vm.hasSubscription = false; vm.currentUser = Security.currentUser; // revert button stuff init, null values to be populated by // watchCollection function below vm.revertReqObj = { evidenceId: null, organization: null }; vm.showRevertBtn = false; vm.showCoiNotice = false; vm.entityType = null; vm.entityStatus = null; // ideally the entity status & type would be available to this controller // at the time of instantiation, but unfortunately the link function // above adds `entityViewModel` after controller instantiation. So we // need to create a watchCollection function to toggle the revert button $scope.$watchCollection( '[entityViewModel.data.item.status, entityViewModel.data.item.type]', function(updates) { vm.entityStatus = updates[0]; vm.entityType = updates[1]; var coiStatus = vm.currentUser ? vm.currentUser.conflict_of_interest.coi_valid : undefined; var coiValid = coiStatus === 'conflict' || coiStatus === 'valid'; if((vm.isEditor() || vm.isAdmin()) // either editors or admins may revert && vm.entityType == 'evidence' // only evidence may be reverted && vm.entityStatus !== 'submitted') // submitted evidence cannot be reverted { if(coiValid) { // show revert btn, load orgs vm.showRevertBtn = true; vm.showCoiNotice = false; // update current user to ensure most recent org displayed Security.reloadCurrentUser().then(function(u) { vm.currentUser = u; // set org to be sent with reject/accept actions vm.revertReqObj.evidenceId = $stateParams.evidenceId; vm.revertReqObj.organization = u.most_recent_organization; }); } else { // hide revert btn, show COI notice if COI invalid vm.showRevertBtn = false; vm.showCoiNotice = true; } } else { // not an EID, not an editor, show no buttons vm.showRevertBtn = false; vm.showCoiNotice = false; } }); vm.revert = function(reqObj) { $scope.entityViewModel.revert(reqObj) .then(function(response) { // reload current user if org changed if (vm.revertReqObj.organization.id != vm.currentUser.most_recent_organization.id) { Security.reloadCurrentUser(); } }) .catch(function(error) { console.error('revert evidence error!'); }) .finally(function(){ console.log('evidence reverted.'); }); }; vm.switchOrg = function(id) { vm.revertReqObj.organization = _.find(vm.currentUser.organizations, { id: id }); }; vm.toggleSubscription = function(subscription) { console.log('toggling subscription: '); if(_.isObject(subscription)) { console.log('has subscription, unsubscribing.'); Subscriptions.unsubscribe(subscription.id) .then(function() { console.log('unsubscribe successful.');}); } else { console.log('does not have subscription, subscribing'); var subscribableType = _.startCase(_.camelCase($scope.entityViewModel.data.item.type)); Subscriptions.subscribe({subscribable_type: subscribableType, subscribable_id: $scope.entityViewModel.data.item.id}) .then(function() {console.log('subscription successful.');}); } }; $scope.scroll = function() { var loc = $location.hash(); if(!_.isEmpty(loc) && _.kebabCase(vm.type) === loc && $rootScope.prevScroll !== loc) {// if view has already been scrolled, ignore subsequent requests var elem = document.getElementById(loc); $rootScope.prevScroll = $location.hash(); $document.scrollToElementAnimated(elem); } }; // set subscription flag $scope.$watchCollection( function() {return Subscriptions.data.collection; }, function(subscriptions) { console.log('$watch subscriptions called.'); var subscribableType = _.startCase(_.camelCase($scope.entityViewModel.data.item.type)); if(subscribableType === 'Evidence') {subscribableType = 'EvidenceItem';} if(subscribableType === 'Variant Group') {subscribableType = 'VariantGroup';} var paramType = $scope.entityViewModel.data.item.type; if(paramType === 'evidence') {paramType = 'evidence_item';} var entityId = $scope.entityViewModel.data.item.id; $scope.vm.subscription = _.find(subscriptions, function(sub) { return sub.subscribable.type === subscribableType && sub.subscribable.state_params[paramType].id === entityId; }); $scope.vm.hasSubscription = _.isObject($scope.vm.subscription); }); // store latest stateParams on rootscope, primarily so the Add Evidence button can // include gene and variantIds in the URL $rootScope.stateParams = $stateParams; // TODO not sure why this watch is necessary for tabs to be properly set to active on 1st load var unwatch = $scope.$watchCollection('entityViewModel', function() { var currentStateEqualTo = function (tab) { var isEqual = $state.is(tab.route, tab.params, tab.options); return isEqual; }; $scope.go = function (tab) { if (!currentStateEqualTo(tab) && !tab.disabled) { var promise = $state.go(tab.route, tab.params, tab.options); /* until the $stateChangeCancel event is released in ui-router, will use this to update tabs if the $stateChangeEvent is cancelled before it finishes loading the state, see https://github.com/rpocklin/ui-router-tabs/issues/19 and https://github.com/angular-ui/ui-router/pull/1090 for further information and https://github.com/angular-ui/ui-router/pull/1844 $stateChangeCancel is better since it will handle ui-sref and external $state.go(..) calls */ promise.catch(function () { $scope.update_tabs(); }); } }; /* whether to highlight given route as part of the current state */ $scope.active = function (tab) { var route = tab.route; // TODO: this is a kludge to fix misbehaving sub-tabs that we have in talk views, almost certainly not the most elegant solution. if (_.includes(tab.route, 'talk')) { // drop the last route element so all talk ancestor $state.includes() evaluates to true //lodash change route = _(tab.route.split('.')).dropRightWhile(function(r) { return r !== 'talk'; }).value().join('.'); } var isAncestorOfCurrentRoute = $state.includes(route, _.omit(tab.params, '#'), tab.options); return isAncestorOfCurrentRoute; }; $scope.update_tabs = function () { // sets which tab is active (used for highlighting) angular.forEach($scope.tabs, function (tab) { tab.params = tab.params || {}; tab.options = tab.options || {}; tab.active = $scope.active(tab); }); }; // this always selects the first tab currently - fixed in ui-bootstrap master but not yet released // see https://github.com/angular-ui/bootstrap/commit/91b5fb62eedbb600d6a6abe32376846f327a903d $scope.update_tabs(); unwatch(); }); } })();
aps337/unum-sdk
src/gdb/gdb-8.3/gdb/unittests/optional-selftests.c
/* Self tests for optional for GDB, the GNU debugger. Copyright (C) 2017-2019 Free Software Foundation, Inc. This file is part of GDB. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "defs.h" #include "common/selftest.h" #include "common/gdb_optional.h" /* Used by the included .cc files below. Included here because the included test files are wrapped in a namespace. */ #include <vector> #include <string> #include <memory> /* libstdc++'s testsuite uses VERIFY. */ #define VERIFY SELF_CHECK /* Used to disable testing features not supported by gdb::optional. */ #define GDB_OPTIONAL namespace selftests { namespace optional { /* The actual tests live in separate files, which were originally copied over from libstdc++'s testsuite. To preserve the structure and help with comparison with the original tests, the file names have been preserved, and only minimal modification was done to have them compile against gdb::optional instead of std::optional: - std::optional->gdb:optional, etc. - ATTRIBUTE_UNUSED in a few places - wrap each file in a namespace so they can all be compiled as a single unit. - libstdc++'s license and formatting style was preserved. */ #include "optional/assignment/1.cc" #include "optional/assignment/2.cc" #include "optional/assignment/3.cc" #include "optional/assignment/4.cc" #include "optional/assignment/5.cc" #include "optional/assignment/6.cc" #include "optional/assignment/7.cc" #include "optional/cons/copy.cc" #include "optional/cons/default.cc" #include "optional/cons/move.cc" #include "optional/cons/value.cc" #include "optional/in_place.cc" #include "optional/observers/1.cc" #include "optional/observers/2.cc" static void run_tests () { assign_1::test (); assign_2::test (); assign_3::test (); assign_4::test (); assign_5::test (); assign_6::test (); assign_7::test (); cons_copy::test (); cons_default::test (); cons_move::test (); cons_value::test (); in_place::test (); observers_1::test (); observers_2::test (); } } /* namespace optional */ } /* namespace selftests */ void _initialize_optional_selftests () { selftests::register_test ("optional", selftests::optional::run_tests); }
systemok/xlauch
xlauch-web/src/main/java/com/xlauch/web/config/captcha/KaptchaConfig.java
<reponame>systemok/xlauch package com.xlauch.web.config.captcha; import com.google.code.kaptcha.impl.DefaultKaptcha; import com.google.code.kaptcha.util.Config; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.Properties; /** * 类描述 : 图形验证码配置 <br/> * 项目名称 : xlauch 项目<br/> * 类名称 : KaptchaConfig <br/> * * @author 伊凡 <EMAIL><br/> * 创建日期: 2017/11/8 14:53 <br/> * @version 0.1 */ @Configuration public class KaptchaConfig { @Value(value = "${kaptcha.border:yes}") String isBorder; @Value(value = "${kaptcha.border.color:105,179,90}") String borderColor; @Value(value = "${kaptcha.textproducer.font.color:blue}") String fontColor; @Value(value = "${kaptcha.image.width:125}") String imgWidth; @Value(value = "${kaptcha.image.height:45}") String imgHeight; @Value(value = "${kaptcha.textproducer.font.size:45}") String fontSize; @Value(value = "${kaptcha.session.key:code}") String sessionKey; @Value(value = "${kaptcha.textproducer.char.string:0123456789}") String charString; @Value(value = "${kaptcha.textproducer.char.length:4}") String charLength; @Value(value = "${kaptcha.textproducer.font.names:宋体,楷体,微软雅黑}") String fontName; @Bean("codeConfig") public Config getCodeConfig(){ Properties kaptchaProperties = new Properties(); kaptchaProperties.setProperty("kaptcha.border", isBorder); kaptchaProperties.setProperty("kaptcha.border.color", borderColor); kaptchaProperties.setProperty("kaptcha.textproducer.font.color", fontColor); kaptchaProperties.setProperty("kaptcha.image.width", imgWidth); kaptchaProperties.setProperty("kaptcha.image.height", imgHeight); kaptchaProperties.setProperty("kaptcha.textproducer.font.size", fontSize); kaptchaProperties.setProperty("kaptcha.session.key", sessionKey); kaptchaProperties.setProperty("kaptcha.textproducer.char.string", charString); kaptchaProperties.setProperty("kaptcha.textproducer.char.length", charLength); kaptchaProperties.setProperty("kaptcha.textproducer.font.names", fontName); Config config = new Config(kaptchaProperties); return config; } @Bean public DefaultKaptcha getDefaultKaptcha(){ DefaultKaptcha defaultKaptcha = new DefaultKaptcha(); defaultKaptcha.setConfig(getCodeConfig()); return defaultKaptcha; } }
Hveen8/Firebase-Mobile-App-Tests
app/build/tmp/kapt3/stubs/alphaDebug/org/wikipedia/navtab/NavTabFragmentPagerAdapter.java
package org.wikipedia.navtab; import java.lang.System; @kotlin.Metadata(mv = {1, 6, 0}, k = 1, d1 = {"\u0000\u001a\n\u0002\u0018\u0002\n\u0002\u0018\u0002\n\u0000\n\u0002\u0018\u0002\n\u0002\b\u0003\n\u0002\u0010\b\n\u0002\b\u0002\u0018\u00002\u00020\u0001B\r\u0012\u0006\u0010\u0002\u001a\u00020\u0003\u00a2\u0006\u0002\u0010\u0004J\u0010\u0010\u0005\u001a\u00020\u00032\u0006\u0010\u0006\u001a\u00020\u0007H\u0016J\b\u0010\b\u001a\u00020\u0007H\u0016\u00a8\u0006\t"}, d2 = {"Lorg/wikipedia/navtab/NavTabFragmentPagerAdapter;", "Lorg/wikipedia/views/PositionAwareFragmentStateAdapter;", "fragment", "Landroidx/fragment/app/Fragment;", "(Landroidx/fragment/app/Fragment;)V", "createFragment", "position", "", "getItemCount", "app_alphaDebug"}) public final class NavTabFragmentPagerAdapter extends org.wikipedia.views.PositionAwareFragmentStateAdapter { public NavTabFragmentPagerAdapter(@org.jetbrains.annotations.NotNull() androidx.fragment.app.Fragment fragment) { super(null); } @org.jetbrains.annotations.NotNull() @java.lang.Override() public androidx.fragment.app.Fragment createFragment(int position) { return null; } @java.lang.Override() public int getItemCount() { return 0; } }
floryst/ITK
Examples/Statistics/ListSample.cxx
<filename>Examples/Statistics/ListSample.cxx /*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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. * *=========================================================================*/ // Software Guide : BeginLatex // // This example illustrates the common interface of the \code{Sample} class // in Insight. // // \index{itk::Sample!Interfaces} // \index{itk::Statistics::ListSample} // // Different subclasses of \subdoxygen{Statistics}{Sample} expect different // sets of template arguments. In this example, we use the // \subdoxygen{Statistics}{ListSample} class that requires the type of // measurement vectors. The ListSample uses // \href{http://www.sgi.com/tech/stl/}{STL} \code{vector} to store // measurement vectors. This class conforms to the common interface of Sample. // Most methods of the Sample class interface are for retrieving measurement // vectors, the size of a container, and the total frequency. In this // example, we will see those information retrieving methods in addition to // methods specific to the ListSample class for data input. // // To use the ListSample class, we include the header file for the class. // // We need another header for measurement vectors. We are going to use // the \doxygen{Vector} class which is a subclass of the \doxygen{FixedArray} // class. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet #include "itkListSample.h" #include "itkVector.h" // Software Guide : EndCodeSnippet int main() { // Software Guide : BeginLatex // // The following code snippet defines the measurement vector type as a // three component \code{float} \doxygen{Vector}. The // \code{MeasurementVectorType} is the measurement vector type in the // \code{SampleType}. An object is instantiated at the third line. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet using MeasurementVectorType = itk::Vector< float, 3 >; using SampleType = itk::Statistics::ListSample< MeasurementVectorType >; SampleType::Pointer sample = SampleType::New(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // In the above code snippet, the namespace // specifier for ListSample is \code{itk::Statistics::} instead of the // usual namespace specifier for other ITK classes, \code{itk::}. // // The newly instantiated object does not have any data in it. We // have two different ways of storing data elements. The first method // is using the \code{PushBack} method. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet MeasurementVectorType mv; mv[0] = 1.0; mv[1] = 2.0; mv[2] = 4.0; sample->PushBack(mv); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The previous code increases the size of the container by one and // stores \code{mv} as the first data element in it. // // The other way to store data elements is calling the \code{Resize} method // and then calling the \code{SetMeasurementVector()} method with a // measurement vector. The following code snippet increases the size of the // container to three and stores two measurement vectors at the second and // the third slot. The measurement vector stored using the \code{PushBack} // method above is still at the first slot. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet sample->Resize(3); mv[0] = 2.0; mv[1] = 4.0; mv[2] = 5.0; sample->SetMeasurementVector(1, mv); mv[0] = 3.0; mv[1] = 8.0; mv[2] = 6.0; sample->SetMeasurementVector(2, mv); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We have seen how to create an ListSample object and store // measurement vectors using the ListSample-specific interface. The // following code shows the common interface of the Sample class. The // \code{Size} method returns the number of measurement vectors in the // sample. The primary data stored in Sample subclasses are measurement // vectors. However, each measurement vector has its associated frequency // of occurrence within the sample. For the // ListSample and the adaptor classes (see Section // \ref{sec:SampleAdaptors}), the frequency value is always one. // \subdoxygen{Statistics}{Histogram} can have a varying frequency // (\code{float} type) for each measurement vector. We retrieve measurement // vectors using the \code{GetMeasurementVector(unsigned long instance // identifier)}, and frequency using the \code{GetFrequency(unsigned long // instance identifier)}. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet for ( unsigned long i = 0; i < sample->Size(); ++i ) { std::cout << "id = " << i << "\t measurement vector = " << sample->GetMeasurementVector(i) << "\t frequency = " << sample->GetFrequency(i) << std::endl; } // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The output should look like the following:\newline // \code{id = 0 measurement vector = 1 2 4 frequency = 1}\newline // \code{id = 1 measurement vector = 2 4 5 frequency = 1}\newline // \code{id = 2 measurement vector = 3 8 6 frequency = 1}\newline // // We can get the same result with its iterator. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet SampleType::Iterator iter = sample->Begin(); while( iter != sample->End() ) { std::cout << "id = " << iter.GetInstanceIdentifier() << "\t measurement vector = " << iter.GetMeasurementVector() << "\t frequency = " << iter.GetFrequency() << std::endl; ++iter; } // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The last method defined in the Sample class // is the \code{GetTotalFrequency()} method that returns the sum of // frequency values associated with every measurement vector in a // container. In the case of ListSample and the // adaptor classes, the return value should be exactly the same as that of // the \code{Size()} method, because the frequency values are always one // for each measurement vector. However, for the // \subdoxygen{Statistics}{Histogram}, the frequency values can vary. // Therefore, if we want to develop a general algorithm to calculate the // sample mean, we must use the \code{GetTotalFrequency()} method instead of // the \code{Size()} method. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet std::cout << "Size = " << sample->Size() << std::endl; std::cout << "Total frequency = " << sample->GetTotalFrequency() << std::endl; // Software Guide : EndCodeSnippet return EXIT_SUCCESS; }
muralitaws/cbmc
src/util/std_code.cpp
/*******************************************************************\ Module: Data structures representing statements in a program Author: <NAME>, <EMAIL> \*******************************************************************/ /// \file /// Data structure representing different types of statements in a program #include "std_code.h" #include "arith_tools.h" #include "c_types.h" #include "pointer_expr.h" #include "std_expr.h" #include "string_constant.h" /// In the case of a `codet` type that represents multiple statements, return /// the first of them. Otherwise return the `codet` itself. codet &codet::first_statement() { const irep_idt &statement=get_statement(); if(has_operands()) { if(statement==ID_block) return to_code(op0()).first_statement(); else if(statement==ID_label) return to_code(op0()).first_statement(); } return *this; } /// \copydoc first_statement() const codet &codet::first_statement() const { const irep_idt &statement=get_statement(); if(has_operands()) { if(statement==ID_block) return to_code(op0()).first_statement(); else if(statement==ID_label) return to_code(op0()).first_statement(); } return *this; } /// In the case of a `codet` type that represents multiple statements, return /// the last of them. Otherwise return the `codet` itself. codet &codet::last_statement() { const irep_idt &statement=get_statement(); if(has_operands()) { if(statement==ID_block) return to_code(operands().back()).last_statement(); else if(statement==ID_label) return to_code(operands().back()).last_statement(); } return *this; } /// \copydoc last_statement() const codet &codet::last_statement() const { const irep_idt &statement=get_statement(); if(has_operands()) { if(statement==ID_block) return to_code(operands().back()).last_statement(); else if(statement==ID_label) return to_code(operands().back()).last_statement(); } return *this; } /// Add all the codets from extra_block to the current code_blockt /// \param extra_block: The input code_blockt void code_blockt::append(const code_blockt &extra_block) { statements().reserve(statements().size() + extra_block.statements().size()); for(const auto &statement : extra_block.statements()) { add(statement); } } codet &code_blockt::find_last_statement() { codet *last=this; while(true) { const irep_idt &statement=last->get_statement(); if(statement==ID_block && !to_code_block(*last).statements().empty()) { last=&to_code_block(*last).statements().back(); } else if(statement==ID_label) { last = &(to_code_label(*last).code()); } else break; } return *last; } code_blockt create_fatal_assertion( const exprt &condition, const source_locationt &loc) { code_blockt result({code_assertt(condition), code_assumet(condition)}); for(auto &op : result.statements()) op.add_source_location() = loc; result.add_source_location() = loc; return result; } std::vector<irep_idt> code_function_bodyt::get_parameter_identifiers() const { const auto &sub = find(ID_parameters).get_sub(); std::vector<irep_idt> result; result.reserve(sub.size()); for(const auto &s : sub) result.push_back(s.get(ID_identifier)); return result; } void code_function_bodyt::set_parameter_identifiers( const std::vector<irep_idt> &parameter_identifiers) { auto &sub = add(ID_parameters).get_sub(); sub.reserve(parameter_identifiers.size()); for(const auto &id : parameter_identifiers) { sub.push_back(irept(ID_parameter)); sub.back().set(ID_identifier, id); } } code_inputt::code_inputt( std::vector<exprt> arguments, optionalt<source_locationt> location) : codet{ID_input, std::move(arguments)} { if(location) add_source_location() = std::move(*location); check(*this, validation_modet::INVARIANT); } code_inputt::code_inputt( const irep_idt &description, exprt expression, optionalt<source_locationt> location) : code_inputt{{address_of_exprt(index_exprt( string_constantt(description), from_integer(0, index_type()))), std::move(expression)}, std::move(location)} { } void code_inputt::check(const codet &code, const validation_modet vm) { DATA_CHECK( vm, code.operands().size() >= 2, "input must have at least two operands"); } code_outputt::code_outputt( std::vector<exprt> arguments, optionalt<source_locationt> location) : codet{ID_output, std::move(arguments)} { if(location) add_source_location() = std::move(*location); check(*this, validation_modet::INVARIANT); } code_outputt::code_outputt( const irep_idt &description, exprt expression, optionalt<source_locationt> location) : code_outputt{{address_of_exprt(index_exprt( string_constantt(description), from_integer(0, index_type()))), std::move(expression)}, std::move(location)} { } void code_outputt::check(const codet &code, const validation_modet vm) { DATA_CHECK( vm, code.operands().size() >= 2, "output must have at least two operands"); } code_fort code_fort::from_index_bounds( exprt start_index, exprt end_index, symbol_exprt loop_index, codet body, source_locationt location) { PRECONDITION(start_index.type() == loop_index.type()); PRECONDITION(end_index.type() == loop_index.type()); side_effect_expr_assignt inc( loop_index, plus_exprt(loop_index, from_integer(1, loop_index.type())), location); return code_fort{ code_assignt{loop_index, std::move(start_index)}, binary_relation_exprt{loop_index, ID_lt, std::move(end_index)}, std::move(inc), std::move(body)}; }
sveinbjornt/snowman
lib/universal-detect-stream.cpp
<filename>lib/universal-detect-stream.cpp #include <frame-info.h> #include <limits> #include <math.h> #include <nnet-lib.h> #include <snowboy-debug.h> #include <snowboy-io.h> #include <snowboy-options.h> #include <universal-detect-stream.h> namespace snowboy { void UniversalDetectStreamOptions::Register(const std::string& prefix, OptionsItf* opts) { opts->Register(prefix, "slide-step", "Step size for sliding window in frames.", &slide_step); opts->Register(prefix, "sensitivity-str", "String that contains the sensitivity value for each hotword, separated by comma.", &sensitivity_str); opts->Register(prefix, "high-sensitivity-str", "String that contains the higher sensitivity value for each hotword, separated by comma.", &high_sensitivity_str); opts->Register(prefix, "model-str", "String that contains hotword models, separated by comma. Note that each universal model may contain more than one hotword.", &model_str); opts->Register(prefix, "smooth-window-str", "String that contains smoothing window size in frames for each model, separated by comma.", &smooth_window_str); opts->Register(prefix, "slide-window-str", "String that contains sliding window size in frames for each model, separated by comma.", &slide_window_str); opts->Register(prefix, "min-detection-interval", "Minimal number of frames between two consecutive detections.", &min_detection_interval); opts->Register(prefix, "debug-mode", "If true, turns off things like order enforcing, and will print out more info.", &debug_mode); opts->Register(prefix, "min-num-frames-per-phone", "Minimal number of frames on each phone.", &min_num_frames_per_phone); opts->Register(prefix, "num-repeats", "For search method 4 only, number of repeats when search the hotword.", &num_repeats); } UniversalDetectStream::UniversalDetectStream(const UniversalDetectStreamOptions& options) { m_options = options; if (m_options.model_str == "") { SNOWBOY_ERROR() << "please specify models through --model-str."; return; } if (m_options.slide_step < 1) { SNOWBOY_ERROR() << "slide step size should be positive."; return; } field_x58 = m_options.min_detection_interval; field_x5c = m_options.min_detection_interval; // Note: in the original code there are resize(0) calls for each vector, // but this is not needed since they are constructed empty anyway. ReadHotwordModel(m_options.model_str); if (!m_options.smooth_window_str.empty()) SetSmoothWindowSize(m_options.smooth_window_str); if (!m_options.slide_window_str.empty()) SetSlideWindowSize(m_options.slide_window_str); if (!m_options.sensitivity_str.empty()) SetSensitivity(m_options.sensitivity_str); if (m_options.high_sensitivity_str.empty()) { if (!m_options.sensitivity_str.empty()) SetHighSensitivity(m_options.sensitivity_str); } else SetHighSensitivity(m_options.high_sensitivity_str); for (size_t i = 0; i < field_x70.size(); i++) CheckLicense(i); field_x60 = false; field_x64 = 0; field_x68 = false; field_x6c = 0; } int UniversalDetectStream::Read(Matrix* mat, std::vector<FrameInfo>* info) { mat->Resize(0, 0); if (info) info->clear(); Matrix read_mat; std::vector<FrameInfo> read_info; auto read_res = m_connectedStream->Read(&read_mat, &read_info); if ((read_res & 0xc2) != 0) return read_res; for (size_t file = 0; file < field_x70.size(); file++) { Matrix nnet_out_mat; std::vector<FrameInfo> nnet_out_info; if ((read_res & 0x18) == 0) field_x70[file].Compute(read_mat, read_info, &nnet_out_mat, &nnet_out_info); else field_x70[file].FlushOutput(read_mat, read_info, &nnet_out_mat, &nnet_out_info); SmoothPosterior(file, &nnet_out_mat); for (size_t r = 0; r < nnet_out_mat.m_rows; r += m_options.slide_step) { auto max = 0; if (r + m_options.slide_step > nnet_out_mat.m_rows) max = nnet_out_mat.m_rows; else max = r + m_options.slide_step; PushSlideWindow(file, nnet_out_mat.RowRange(r, max - r)); const auto max_frame_id = nnet_out_info[max - 1].frame_id; float fVar8 = 0.0f; int local_130 = -1; for (size_t i = 0; i < field_x88[file].size(); i++) { auto posterior = GetHotwordPosterior(file, i, max_frame_id); if (!field_x68 || max_frame_id - field_x6c < 0x33) { if (field_x60) { if (3000 < max_frame_id - field_x64) { field_x60 = false; } if (1.0f - field_xb8[file][i] <= posterior && m_options.min_detection_interval < max_frame_id - field_x58) { if (fVar8 < posterior) { local_130 = i; fVar8 = posterior; } field_x64 = max_frame_id; } } else { if (posterior < 1.0f - field_xa0[file][i] || max_frame_id - field_x58 <= m_options.min_detection_interval) { if (!field_x68 && 1.0f - field_xb8[file][i] <= posterior && posterior < 1.0f - field_xa0[file][i] && max_frame_id - field_x58 <= m_options.min_detection_interval) { field_x68 = true; field_x6c = max_frame_id; } } else { if (fVar8 < posterior) { local_130 = i; fVar8 = posterior; } if (!field_x68 && field_xa0[file][i] < field_xb8[file][i]) { field_x68 = true; field_x6c = max_frame_id; } } } } else { field_x68 = false; field_x60 = true; field_x64 = max_frame_id; if (1.0f - field_xb8[file][i] <= posterior && m_options.min_detection_interval < max_frame_id - field_x58) { if (fVar8 < posterior) { local_130 = i; fVar8 = posterior; } field_x64 = max_frame_id; } } } if (local_130 != -1) { CheckLicense(file); field_x58 = max_frame_id; field_x5c = max_frame_id; ResetDetection(); mat->Resize(1, 1); mat->m_data[0] = field_xd0[file][local_130]; if (info != nullptr) { auto i = nnet_out_info[r]; info->push_back(i); return read_res; } } } } if ((read_res & 0x18) != 0) { this->Reset(); } return read_res; } bool UniversalDetectStream::Reset() { for (auto& e : field_x70) e.ResetComputation(); ResetDetection(); return true; } std::string UniversalDetectStream::Name() const { return "UniversalDetectStream"; } UniversalDetectStream::~UniversalDetectStream() {} void UniversalDetectStream::CheckLicense(int param_1) const { if (field_x1a8[param_1] > 0.0f) { time_t t; time(&t); auto diff = difftime(t, field_x190[param_1]); auto expires = field_x1a8[param_1]; if (expires < (diff / 86400.0f)) { SNOWBOY_ERROR() << "Your license for Snowboy has been expired. Please contact KITT.AI at <EMAIL>"; return; } } } float UniversalDetectStream::GetHotwordPosterior(int param_1, int param_2, int param_3) { switch (field_xe8[param_1][param_2]) { case 1: return HotwordNaiveSearch(param_1, param_2); case 2: return HotwordDtwSearch(param_1, param_2); case 3: return HotwordViterbiSearch(param_1, param_2); case 4: return HotwordPiecewiseSearch(param_1, param_2); case 5: return HotwordViterbiSearchReduplication(param_1, param_2, param_3); case 6: return HotwordViterbiSearchSoftFloor(param_1, param_2); case 7: return HotwordViterbiSearchTraceback(param_1, param_2); case 8: return HotwordViterbiSearchTracebackLog(param_1, param_2); default: { SNOWBOY_ERROR() << "search method has not been implemented."; return 0.0f; } } } std::string UniversalDetectStream::GetSensitivity() const { std::stringstream res; for (size_t i = 0; i < field_xa0.size(); i++) { for (size_t x = 0; x < field_xa0[i].size(); x++) { if (i != 0 || x != 0) { res << ", "; } res << field_xa0[i][x]; } } return res.str(); } float UniversalDetectStream::HotwordDtwSearch(int, int) const { SNOWBOY_ERROR() << "Not implemented"; return 0.0f; // TODO:: This is unused in all models I have, but we should still implement it at some point } float UniversalDetectStream::HotwordNaiveSearch(int param_1, int param_2) const { float sum = 0.0f; for (size_t i = 0; i < field_x88[param_1][param_2].size(); i++) { auto& x = field_x250[param_1][field_x88[param_1][param_2][i]]; if (field_x160[param_1][param_2][i] > x.front()) return 0.0f; sum += logf(std::max(x.front(), std::numeric_limits<float>::min())); } return expf(sum / static_cast<float>(field_x88[param_1][param_2].size())); } float UniversalDetectStream::HotwordPiecewiseSearch(int, int) const { SNOWBOY_ERROR() << "Not implemented"; return 0.0f; // TODO:: This is unused in all models I have, but we should still implement it at some point } float UniversalDetectStream::HotwordViterbiSearch(int param_1, int param_2) const { return HotwordNaiveSearch(param_1, param_2); // TODO: Implement Viterbi search std::vector<float> x; x.resize(field_x88[param_1][param_2].size(), -std::numeric_limits<float>::max()); x[0] = 0.0f; std::vector<float> x2; x2.resize(field_x88[param_1][param_2].size(), 0); auto& f250 = field_x250[param_1][0]; int i = f250.size() - field_x148[param_1][param_2].back(); do { if (f250.size() <= i) { auto fVar2 = field_x160[param_1][param_2].back(); if (fVar2 <= x2.back()) { if (field_x178[param_1][param_2] && !x.empty()) { for (auto& e : x) { fVar2 = std::max(e, fVar2); } return fVar2 / static_cast<float>(field_x148[param_1][param_2].back()); } } } if (!x.empty()) { } i++; } while (true); // TODO: Implement Viterbi search } float UniversalDetectStream::HotwordViterbiSearch(int, int, int, const PieceInfo&) const { SNOWBOY_ERROR() << "Not implemented"; return 0.0f; // TODO:: This is unused in all models I have, but we should still implement it at some point } float UniversalDetectStream::HotwordViterbiSearchReduplication(int, int, int) { SNOWBOY_ERROR() << "Not implemented"; return 0.0f; // TODO:: This is unused in all models I have, but we should still implement it at some point } float UniversalDetectStream::HotwordViterbiSearchSoftFloor(int, int) const { SNOWBOY_ERROR() << "Not implemented"; return 0.0f; // TODO:: This is unused in all models I have, but we should still implement it at some point } float UniversalDetectStream::HotwordViterbiSearchTraceback(int, int) const { SNOWBOY_ERROR() << "Not implemented"; return 0.0f; // TODO:: This is unused in all models I have, but we should still implement it at some point } float UniversalDetectStream::HotwordViterbiSearchTracebackLog(int param_1, int param_2) const { // TODO: Implement this return HotwordNaiveSearch(param_1, param_2); } int UniversalDetectStream::NumHotwords(int model_id) const { if (model_id < field_x88.size() && model_id >= 0) { return field_x88[model_id].size(); } else { SNOWBOY_ERROR() << "model_id runs out of range, expecting a value between [0," << field_x88.size() << "], got " << model_id << " instead."; return 0; } } void UniversalDetectStream::PushSlideWindow(int param_1, const MatrixBase& param_2) { // TODO: Optimize this by calculating offsets and doing a memcpy for (size_t r = 0; r < param_2.m_rows; r++) { for (size_t c = 0; c < param_2.m_cols; c++) { field_x250[param_1][c].push_back(param_2.m_data[r * param_2.m_stride + c]); if (field_x250[param_1][c].size() > field_x220.size()) { field_x250[param_1][c].pop_front(); } } } } void UniversalDetectStream::ReadHotwordModel(const std::string& filename) { std::vector<std::string> files; SplitStringToVector(filename, global_snowboy_string_delimiter, &files); if (files.empty()) { SNOWBOY_ERROR() << "no model can be extracted from --model-str: " << filename; return; } auto s = files.size(); field_x88.resize(s); field_x70.resize(s); field_x190.resize(s); field_x1a8.resize(s); field_xa0.resize(s); field_xb8.resize(s); field_xd0.resize(s); field_xe8.resize(s); field_x100.resize(s); field_x118.resize(s); field_x130.resize(s); field_x148.resize(s); field_x160.resize(s); field_x178.resize(s); field_x208.resize(s); field_x220.resize(s); field_x238.resize(s); field_x250.resize(s); field_x268.resize(s); field_x1c0.resize(s); field_x1d8.resize(s); field_x1f0.resize(s); field_x280.resize(s); field_x298.resize(s); field_x2b0.resize(s); int hotword_id = 1; for (size_t f = 0; f < files.size(); f++) { Input in{files[f]}; auto binary = in.is_binary(); auto is = in.Stream(); ExpectToken(binary, "<UniversalModel>", is); if (PeekToken(binary, is) == 'L') { ExpectToken(binary, "<LicenseStart>", is); ReadBasicType<long>(binary, &field_x190[f], is); ExpectToken(binary, "<LicenseDays>", is); ReadBasicType<float>(binary, &field_x1a8[f], is); } else { field_x190[f] = 0; field_x1a8[f] = 0.0f; } ExpectToken(binary, "<KwInfo>", is); ExpectToken(binary, "<SmoothWindow>", is); ReadBasicType<int>(binary, &field_x208[f], is); ExpectToken(binary, "<SlideWindow>", is); ReadBasicType<int>(binary, &field_x220[f], is); ExpectToken(binary, "<NumKws>", is); int num_kws; ReadBasicType<int>(binary, &num_kws, is); field_x88[f].resize(num_kws); field_xa0[f].resize(num_kws); field_xb8[f].resize(num_kws); field_xd0[f].resize(num_kws); field_xe8[f].resize(num_kws, 1); field_x100[f].resize(num_kws); field_x118[f].resize(num_kws); field_x130[f].resize(num_kws); field_x148[f].resize(num_kws); field_x160[f].resize(num_kws); field_x178[f].resize(num_kws); field_x1c0[f].resize(num_kws, m_options.num_repeats); field_x1d8[f].resize(num_kws, 1); field_x280[f].resize(num_kws); field_x298[f].resize(num_kws); for (size_t kw = 0; kw < num_kws; kw++) { ExpectToken(binary, "<Kw>", is); ReadIntegerVector(binary, &field_x88[f][kw], is); ExpectToken(binary, "<Sensitivity>", is); ReadBasicType<float>(binary, &field_xa0[f][kw], is); field_xb8[f][kw] = 0.0f; field_x160[f][kw].resize(field_x88[f][kw].size()); // TODO: I think there is a bug here. // If SearchMax is present, but SearchMethod is not, the code would branch into the first // if and throw on the ExpectToken. It might be possible that SearchMethod is *required* // if SearchMax is present, but I dont know for sure. if (PeekToken(binary, is) == 'S') { ExpectToken(binary, "<SearchMethod>", is); ReadBasicType<int>(binary, &field_xe8[f][kw], is); ExpectToken(binary, "<SearchNeighbour>", is); ReadBasicType<int>(binary, &field_x100[f][kw], is); ExpectToken(binary, "<SearchMask>", is); ReadIntegerVector<int>(binary, &field_x148[f][kw], is); ExpectToken(binary, "<SearchFloor>", is); Vector tvec; tvec.Read(binary, is); field_x160[f][kw].resize(tvec.m_size); for (size_t i = 0; i < tvec.m_size; i++) field_x160[f][kw][i] = tvec.m_data[i]; } else { field_x148[f][kw].resize(field_x88[f][kw].size()); for (size_t i = 0; i < field_x148[f][kw].size(); i++) { field_x148[f][kw][i] = (static_cast<float>(i) / static_cast<float>(field_x148[f][kw].size())) * static_cast<float>(field_x220[f]); } } if (PeekToken(binary, is) == 'S') { ExpectToken(binary, "<SearchMax>", is); bool tbool; ReadBasicType<bool>(binary, &tbool, is); field_x178[f][kw] = tbool; } if (PeekToken(binary, is) == 'N') { ExpectToken(binary, "<NumPieces>", is); ReadBasicType<int>(binary, &field_x1d8[f][kw], is); } if (PeekToken(binary, is) == 'D') { ExpectToken(binary, "<DurationPass>", is); ReadBasicType<int>(binary, &field_x118[f][kw], is); ExpectToken(binary, "<FloorPass>", is); ReadBasicType<int>(binary, &field_x130[f][kw], is); } field_xd0[f][kw] = hotword_id++; } ExpectToken(binary, "</KwInfo>", is); field_x70[f].Read(binary, is); field_x238[f].resize(field_x238[f].size() + field_x70[f].OutputDim()); field_x250[f].resize(field_x250[f].size() + field_x70[f].OutputDim()); field_x268[f].resize(field_x268[f].size() + field_x70[f].OutputDim()); if (field_xe8[f][0] == 4) { SNOWBOY_ERROR() << "Not implemented!"; // TODO } } } void UniversalDetectStream::ResetDetection() { for (size_t i = 0; i < field_x70.size(); i++) { for (size_t x = 0; x < field_x238[i].size(); x++) { field_x238[i][x].clear(); } for (size_t x = 0; x < field_x250[i].size(); x++) { field_x250[i][x].clear(); } for (size_t x = 0; x < field_x268[i].size(); x++) { field_x268[i][x] = 0.0f; } for (size_t x = 0; x < field_x280[i].size(); x++) { field_x280[i][x] = false; } for (size_t x = 0; x < field_x2b0[i].size(); x++) { field_x2b0[i][x] = 0.0f; } for (size_t x = 0; x < field_x298[i].size(); x++) { field_x298[i][x] = -1000; } } } void UniversalDetectStream::SetHighSensitivity(const std::string& param_1) { std::vector<float> parts; SplitStringToFloats(param_1, global_snowboy_string_delimiter, &parts); if (parts.size() == 1) { for (auto& e : field_xb8) { for (auto& e2 : e) { e2 = parts[0]; } } } else if (parts.size() == field_xb8.size()) { for (size_t i = 0; i < field_xb8.size(); i++) { for (auto& e : field_xb8[i]) { e = parts[i]; } } } else { SNOWBOY_ERROR() << "Number of sensitivities does not match number of hotwords (" << parts.size() << " v.s. " << field_xb8.size() << "). Note that each universal model may have multiple hotwords."; return; } } void UniversalDetectStream::SetSensitivity(const std::string& param_1) { std::vector<float> parts; SplitStringToFloats(param_1, global_snowboy_string_delimiter, &parts); if (parts.size() == 1) { for (auto& e : field_xa0) { for (auto& e2 : e) { e2 = parts[0]; } } } else if (parts.size() == field_xa0.size()) { for (size_t i = 0; i < field_xa0.size(); i++) { for (auto& e : field_xa0[i]) { e = parts[i]; } } } else { SNOWBOY_ERROR() << "Number of sensitivities does not match number of hotwords (" << parts.size() << " v.s. " << field_xa0.size() << "). Note that each universal model may have multiple hotwords."; return; } } void UniversalDetectStream::SetSlideWindowSize(const std::string& param_1) { SplitStringToIntegers<int>(param_1, global_snowboy_string_delimiter, &field_x220); } void UniversalDetectStream::SetSmoothWindowSize(const std::string& param_1) { SplitStringToIntegers<int>(param_1, global_snowboy_string_delimiter, &field_x208); } void UniversalDetectStream::SmoothPosterior(int param_1, Matrix* param_2) { for (size_t r = 0; r < param_2->m_rows; r++) { for (size_t c = 0; c < param_2->m_cols; c++) { auto val = param_2->m_data[r * param_2->m_stride + c]; field_x268[param_1][c] += val; field_x238[param_1][c].push_back(val); if (field_x238[param_1][c].size() > field_x208[param_1]) { field_x238[param_1][c].pop_front(); } param_2->m_data[r * param_2->m_stride + c] = field_x268[param_1][c] / field_x208[param_1]; } } } void UniversalDetectStream::UpdateLicense(int param_1, long param_2, float param_3) { field_x190[param_1] = param_2; field_x1a8[param_1] = param_3; } void UniversalDetectStream::UpdateModel() const { WriteHotwordModel(true, m_options.model_str); } void UniversalDetectStream::WriteHotwordModel(bool binary, const std::string& filename) const { std::vector<std::string> parts; SplitStringToVector(filename, global_snowboy_string_delimiter, &parts); for (size_t file = 0; file < parts.size(); file++) { Output out{parts[file], binary}; auto os = out.Stream(); WriteToken(binary, "<UniversalModel>", os); WriteToken(binary, "<LicenseStart>", os); WriteBasicType<long>(binary, field_x190[file], os); WriteToken(binary, "<LicenseDays>", os); WriteBasicType<float>(binary, field_x1a8[file], os); WriteToken(binary, "<KwInfo>", os); WriteToken(binary, "<SmoothWindow>", os); WriteBasicType<int>(binary, field_x208[file], os); WriteToken(binary, "<SlideWindow>", os); WriteBasicType<int>(binary, field_x220[file], os); WriteToken(binary, "<NumKws>", os); WriteBasicType<int>(binary, field_x88[file].size(), os); for (size_t kw = 0; kw < field_x88[file].size(); kw++) { WriteToken(binary, "<Kw>", os); WriteIntegerVector<int>(binary, field_x88[file][kw], os); WriteToken(binary, "<Sensitivity>", os); WriteBasicType<float>(binary, field_xa0[file][kw], os); WriteToken(binary, "<SearchMethod>", os); WriteBasicType<int>(binary, field_xe8[file][kw], os); WriteToken(binary, "<SearchNeighbour>", os); WriteBasicType<int>(binary, field_x100[file][kw], os); WriteToken(binary, "<SearchMask>", os); WriteIntegerVector<int>(binary, field_x148[file][kw], os); WriteToken(binary, "<SearchFloor>", os); Vector tvec; tvec.Resize(field_x160[file][kw].size()); // TODO: This could be a memcpy, or even better implement writing for vector for (size_t i = 0; i < tvec.m_size; i++) { tvec.m_data[i] = field_x160[file][kw][i]; } tvec.Write(binary, os); WriteToken(binary, "<SearchMax>", os); WriteBasicType<bool>(binary, field_x178[file][kw], os); WriteToken(binary, "<NumPieces>", os); WriteBasicType<int>(binary, field_x1d8[file][kw], os); WriteToken(binary, "<DurationPass>", os); WriteBasicType<int>(binary, field_x118[file][kw], os); WriteToken(binary, "<FloorPass>", os); WriteBasicType<int>(binary, field_x130[file][kw], os); } WriteToken(binary, "</KwInfo>", os); field_x70[file].Write(binary, os); } } } // namespace snowboy
thai97hl/Fast-Flashlight
app/src/main/java/com/smobileteam/flashlight/view/OnColorPickerListener.java
<gh_stars>1-10 package com.smobileteam.flashlight.view; /** * Created by <NAME> on 3/21/2017. * FlashlightBitbucket */ public interface OnColorPickerListener { void updateColor(int color); void OnInnerWheelClick(); }
fy310518/MyLibrary
baseLibrary/src/main/java/com/fy/baselibrary/application/ioc/ConfigUtils.java
package com.fy.baselibrary.application.ioc; import android.content.Context; import android.support.annotation.NonNull; import android.text.TextUtils; import com.fy.baselibrary.dress.DressColor; import com.fy.baselibrary.statuslayout.OnStatusAdapter; import java.util.ArrayList; import java.util.List; import okhttp3.Interceptor; /** * 应用框架基础配置工具类 (应用启动时候初始化) * Created by fangs on 2018/7/13. */ public class ConfigUtils { static ConfigComponent configComponent; public ConfigUtils(Context context, ConfigBiuder biuder) { configComponent = DaggerConfigComponent.builder() .configModule(new ConfigModule(context, biuder)) .build(); } public static Context getAppCtx() { return configComponent.getContext(); } public static String getFilePath() { return configComponent.getConfigBiuder().filePath; } public static int getType() { return configComponent.getConfigBiuder().type; } public static boolean isDEBUG() { return configComponent.getConfigBiuder().DEBUG; } public static boolean isFontDefault() { return configComponent.getConfigBiuder().isFontDefault; } public static boolean isEnableCacheInterceptor() { return configComponent.getConfigBiuder().isEnableCacheInterceptor; } public static String getBaseUrl() { return configComponent.getConfigBiuder().BASE_URL; } public static String getAddCookieKey(){return configComponent.getConfigBiuder().addCookieKey;} public static String getCookieDataKey(){return configComponent.getConfigBiuder().cookieData;} public static String getTokenKey(){return configComponent.getConfigBiuder().token;} public static List<Interceptor> getInterceptor(){return configComponent.getConfigBiuder().interceptors;} public static DressColor getDressColor(){return configComponent.getConfigBiuder().dressColors;} public static OnStatusAdapter getOnStatusAdapter(){return configComponent.getConfigBiuder().statusAdapter;} public static String getCer() { return configComponent.getConfigBiuder().cer; } public static List<String> getCerFileName() { return configComponent.getConfigBiuder().cerFileNames; } public static int getTitleColor(){ return configComponent.getConfigBiuder().titleColor; } public static int getBgColor(){ return configComponent.getConfigBiuder().bgColor; } public static boolean isTitleCenter(){ return configComponent.getConfigBiuder().isTitleCenter; } public static int getBackImg(){ return configComponent.getConfigBiuder().backImg; } public static class ConfigBiuder { /** 是否 DEBUG 环境*/ boolean DEBUG; /** 是否 跟随系统字体大小 默认跟随*/ boolean isFontDefault = true; /** 应用 文件根目录 名称(文件夹) */ String filePath = ""; int type = 0; /** 标题栏背景色 */ int bgColor; /** 标题是否居中 */ boolean isTitleCenter; /** 标题字体颜色 */ int titleColor; /** 标题栏 返回按钮 图片 */ int backImg; /** 网络请求 服务器地址 url */ String BASE_URL = ""; /** https 公钥证书字符串 */ String cer = ""; /** https 公钥证书 文件名字符串【带后缀名】集合(放在 assets 目录下) */ List<String> cerFileNames = new ArrayList<>(); /** 是否 启用缓存拦截器 */ boolean isEnableCacheInterceptor; /** 向网络请求 添加 cookie 数据 的 key */ String addCookieKey = "cookie"; /** 从网络请求 响应数据中拿到返回的 cookie数据 的 key */ String cookieData = "set-cookie"; /** token key */ String token = "X-<PASSWORD>"; /** 添加 自定义拦截器;如:token 拦截器 */ List<Interceptor> interceptors = new ArrayList<>(); /** 添加 自定义 色彩处理 对象【相当于 给app 穿衣服,从而改变app 界面 展示样式】DressColor 对象的完整类路径*/ DressColor dressColors; /** 多状态布局 适配器 */ OnStatusAdapter statusAdapter; public ConfigBiuder setDEBUG(boolean DEBUG) { this.DEBUG = DEBUG; return this; } public ConfigBiuder setFontDefault(boolean fontDefault) { isFontDefault = fontDefault; return this; } public ConfigBiuder setEnableCacheInterceptor(boolean enableCacheInterceptor) { isEnableCacheInterceptor = enableCacheInterceptor; return this; } public ConfigBiuder setBASE_URL(String BASE_URL) { this.BASE_URL = BASE_URL; return this; } public ConfigBiuder addCerFileName(@NonNull String cerFileName) { this.cerFileNames.add(cerFileName); return this; } public ConfigBiuder setCer(String cer) { this.cer = cer; return this; } public ConfigBiuder setBgColor(int bgColor) { this.bgColor = bgColor; return this; } public ConfigBiuder setTitleColor(int titleColor) { this.titleColor = titleColor; return this; } public ConfigBiuder setTitleCenter(boolean titleCenter) { isTitleCenter = titleCenter; return this; } public ConfigBiuder setBackImg(int backImg) { this.backImg = backImg; return this; } public ConfigBiuder setBaseFile(String filePath, int type) { this.filePath = filePath == null ? "" : filePath; this.type = type; return this; } public ConfigBiuder setCookie(String addCookieKey, String cookieData) { this.addCookieKey = TextUtils.isEmpty(addCookieKey) ? "" : addCookieKey; this.cookieData = TextUtils.isEmpty(cookieData) ? "" : cookieData; return this; } public ConfigBiuder setToken(String token) { this.token = token == null ? "" : token; return this; } public ConfigBiuder addInterceptor(Interceptor interceptor) { interceptors.add(interceptor); return this; } public ConfigBiuder addDressColor(DressColor dressColor) { this.dressColors = dressColor; return this; } public ConfigBiuder setStatusAdapter(OnStatusAdapter statusAdapter) { this.statusAdapter = statusAdapter; return this; } public ConfigUtils create(Context context){ return new ConfigUtils(context, this); } } }
kevoese/Epic-mail-react-app
src/components/HOC/withUser.js
<reponame>kevoese/Epic-mail-react-app import React, { Component } from 'react'; import { connect } from 'react-redux'; import { setUserAction } from '@actions/Auth'; const withUser = (WrappedComponent) => { class HOC extends Component { componentDidMount() { this.props.setUser(); } render() { return ( this.props.isStarting ? ('loading') : (<WrappedComponent />) ); } } const mapStateToProps = ({ authReducer }) => ({ isStarting: authReducer.isStarting, }); return connect(mapStateToProps, { setUser: setUserAction })(HOC); }; export default withUser;
paullewallencom/node-978-1-8392-1411-0
_/07-creational-design-patterns/02-factory-dynamic-class/imageJpeg.js
import { Image } from './image.js' export class ImageJpeg extends Image { constructor (path) { if (!path.match(/\.jpe?g$/)) { throw new Error(`${path} is not a JPEG image`) } super(path) } }
benoitc/pypy
pypy/translator/backendopt/test/test_support.py
<reponame>benoitc/pypy from pypy.translator.translator import TranslationContext, graphof from pypy.translator.backendopt.support import \ find_loop_blocks, find_backedges, compute_reachability #__________________________________________________________ # test compute_reachability def test_simple_compute_reachability(): def f(x): if x < 0: if x == -1: return x+1 else: return x+2 else: if x == 1: return x-1 else: return x-2 t = TranslationContext() g = t.buildflowgraph(f) reach = compute_reachability(g) assert len(reach[g.startblock]) == 7 assert len(reach[g.startblock.exits[0].target]) == 3 assert len(reach[g.startblock.exits[1].target]) == 3 #__________________________________________________________ # test loop detection def test_find_backedges(): def f(k): result = 0 for i in range(k): result += 1 for j in range(k): result += 1 return result t = TranslationContext() t.buildannotator().build_types(f, [int]) t.buildrtyper().specialize() graph = graphof(t, f) backedges = find_backedges(graph) assert len(backedges) == 2 def test_find_loop_blocks(): def f(k): result = 0 for i in range(k): result += 1 for j in range(k): result += 1 return result t = TranslationContext() t.buildannotator().build_types(f, [int]) t.buildrtyper().specialize() graph = graphof(t, f) loop_blocks = find_loop_blocks(graph) assert len(loop_blocks) == 4 def test_find_loop_blocks_simple(): def f(a): if a <= 0: return 1 return f(a - 1) t = TranslationContext() t.buildannotator().build_types(f, [int]) t.buildrtyper().specialize() graph = graphof(t, f) backedges = find_backedges(graph) assert backedges == [] loop_blocks = find_loop_blocks(graph) assert len(loop_blocks) == 0 def test_find_loop_blocks2(): class A: pass def f(n): a1 = A() a1.x = 1 a2 = A() a2.x = 2 if n > 0: a = a1 else: a = a2 return a.x t = TranslationContext() t.buildannotator().build_types(f, [int]) t.buildrtyper().specialize() graph = graphof(t, f) backedges = find_backedges(graph) assert backedges == [] loop_blocks = find_loop_blocks(graph) assert len(loop_blocks) == 0 def test_find_loop_blocks3(): import os def ps(loops): return 42.0, 42.1 def f(loops): benchtime, stones = ps(abs(loops)) s = '' # annotator happiness if loops >= 0: s = ("RPystone(%s) time for %d passes = %f" % (23, loops, benchtime) + '\n' + ( "This machine benchmarks at %f pystones/second" % stones)) os.write(1, s) if loops == 12345: f(loops-1) t = TranslationContext() t.buildannotator().build_types(f, [int]) t.buildrtyper().specialize() graph = graphof(t, f) backedges = find_backedges(graph) assert backedges == [] loop_blocks = find_loop_blocks(graph) assert len(loop_blocks) == 0
keva-dev/keva
core/src/main/java/dev/keva/core/command/impl/zset/ZScore.java
package dev.keva.core.command.impl.zset; import dev.keva.core.command.annotation.CommandImpl; import dev.keva.core.command.annotation.Execute; import dev.keva.core.command.annotation.ParamLength; import dev.keva.ioc.annotation.Autowired; import dev.keva.ioc.annotation.Component; import dev.keva.protocol.resp.reply.BulkReply; import dev.keva.storage.KevaDatabase; @Component @CommandImpl("zscore") @ParamLength(type = ParamLength.Type.EXACT, value = 2) public final class ZScore extends ZBase { private final KevaDatabase database; @Autowired public ZScore(KevaDatabase database) { super(database); this.database = database; } @Execute public BulkReply execute(byte[] key, byte[] member) { Double result = this.score(key, member); if (result == null) { return BulkReply.NIL_REPLY; } if (result.equals(Double.POSITIVE_INFINITY)) { return BulkReply.POSITIVE_INFINITY_REPLY; } if (result.equals(Double.NEGATIVE_INFINITY)) { return BulkReply.NEGATIVE_INFINITY_REPLY; } return new BulkReply(result.toString()); } }
CommandPost/FinalCutProFrameworks
Headers/Frameworks/Flexo/FFHGObjectInfo.h
<reponame>CommandPost/FinalCutProFrameworks // // Generated by class-dump 3.5 (64 bit) (Debug version compiled Mar 11 2021 20:53:35). // // Copyright (C) 1997-2019 <NAME>. // #import <objc/NSObject.h> @class FFRendererInfo; __attribute__((visibility("hidden"))) @interface FFHGObjectInfo : NSObject { struct HGObject *_hgObject; FFRendererInfo *_rendererInfo; } - (void)dealloc; - (id)initWithHGObject:(struct HGObject *)arg1 rendererInfo:(id)arg2; - (id)rendererInfo; - (struct HGObject *)hgObject; @end
UK-Export-Finance/dtfs2
azure-functions/acbs-function/acbs-http/test.js
const df = require('durable-functions'); const httpFunction = require('./index'); const context = require('../testing/defaultContext'); test('Http trigger should return known text', async () => { const request = { params: { functionName: 'mockDurableFunction', }, body: { mock: 1, }, }; await httpFunction(context, request); expect(df.mockClient.startNew).toHaveBeenCalledWith(request.params.functionName, undefined, request.body); expect(df.mockClient.createCheckStatusResponse).toHaveBeenCalledWith(context.bindingData.req, 'mockInstanceId'); });
LEGO-Robotics/SPIKE-Prime
decompiler/disassemble.py
#!/usr/bin/python3 import argparse import os import importlib import io import sys MP_BC_MASK_FORMAT = 0xf0 MP_BC_MASK_EXTRA_BYTE = 0x9e MP_BC_FORMAT_BYTE = 0 MP_BC_FORMAT_QSTR = 1 MP_BC_FORMAT_VAR_UINT = 2 MP_BC_FORMAT_OFFSET = 3 #MP_BC_BASE_RESERVED = 0x00 # ---------------- MP_BC_BASE_QSTR_O = 0x10 # LLLLLLSSSDDII--- MP_BC_BASE_VINT_E = 0x20 # MMLLLLSSDDBBBBBB MP_BC_BASE_VINT_O = 0x30 # UUMMCCCC-------- MP_BC_BASE_JUMP_E = 0x40 # J-JJJJJEEEEF---- MP_BC_BASE_BYTE_O = 0x50 # LLLLSSDTTTTTEEFF MP_BC_BASE_BYTE_E = 0x60 # --BREEEYYI------ MP_BC_LOAD_CONST_SMALL_INT_MULTI = 0x70 # LLLLLLLLLLLLLLLL MP_BC_LOAD_FAST_MULTI = 0xb0 # LLLLLLLLLLLLLLLL MP_BC_STORE_FAST_MULTI = 0xc0 # SSSSSSSSSSSSSSSS MP_BC_UNARY_OP_MULTI = 0xd0 # OOOOOOO MP_BC_BINARY_OP_MULTI = 0xd7 # OOOOOOOOO ################################################################################ importmap = { "MP_BC_LOAD_CONST_FALSE": (MP_BC_BASE_BYTE_O + 0x00), "MP_BC_LOAD_CONST_NONE": (MP_BC_BASE_BYTE_O + 0x01), "MP_BC_LOAD_CONST_TRUE": (MP_BC_BASE_BYTE_O + 0x02), "MP_BC_LOAD_CONST_SMALL_INT": (MP_BC_BASE_VINT_E + 0x02), # signed var-int "MP_BC_LOAD_CONST_STRING": (MP_BC_BASE_QSTR_O + 0x00), # qstr "MP_BC_LOAD_CONST_OBJ": (MP_BC_BASE_VINT_E + 0x03), # ptr "MP_BC_LOAD_NULL": (MP_BC_BASE_BYTE_O + 0x03), "MP_BC_LOAD_FAST_N": (MP_BC_BASE_VINT_E + 0x04), # uint "MP_BC_LOAD_DEREF": (MP_BC_BASE_VINT_E + 0x05), # uint "MP_BC_LOAD_NAME": (MP_BC_BASE_QSTR_O + 0x01), # qstr "MP_BC_LOAD_GLOBAL": (MP_BC_BASE_QSTR_O + 0x02), # qstr "MP_BC_LOAD_ATTR": (MP_BC_BASE_QSTR_O + 0x03), # qstr "MP_BC_LOAD_METHOD": (MP_BC_BASE_QSTR_O + 0x04), # qstr "MP_BC_LOAD_SUPER_METHOD": (MP_BC_BASE_QSTR_O + 0x05), # qstr "MP_BC_LOAD_BUILD_CLASS": (MP_BC_BASE_BYTE_O + 0x04), "MP_BC_LOAD_SUBSCR": (MP_BC_BASE_BYTE_O + 0x05), "MP_BC_STORE_FAST_N": (MP_BC_BASE_VINT_E + 0x06), # uint "MP_BC_STORE_DEREF": (MP_BC_BASE_VINT_E + 0x07), # uint "MP_BC_STORE_NAME": (MP_BC_BASE_QSTR_O + 0x06), # qstr "MP_BC_STORE_GLOBAL": (MP_BC_BASE_QSTR_O + 0x07), # qstr "MP_BC_STORE_ATTR": (MP_BC_BASE_QSTR_O + 0x08), # qstr "MP_BC_STORE_SUBSCR": (MP_BC_BASE_BYTE_O + 0x06), "MP_BC_DELETE_FAST": (MP_BC_BASE_VINT_E + 0x08), # uint "MP_BC_DELETE_DEREF": (MP_BC_BASE_VINT_E + 0x09), # uint "MP_BC_DELETE_NAME": (MP_BC_BASE_QSTR_O + 0x09), # qstr "MP_BC_DELETE_GLOBAL": (MP_BC_BASE_QSTR_O + 0x0a), # qstr "MP_BC_DUP_TOP": (MP_BC_BASE_BYTE_O + 0x07), "MP_BC_DUP_TOP_TWO": (MP_BC_BASE_BYTE_O + 0x08), "MP_BC_POP_TOP": (MP_BC_BASE_BYTE_O + 0x09), "MP_BC_ROT_TWO": (MP_BC_BASE_BYTE_O + 0x0a), "MP_BC_ROT_THREE": (MP_BC_BASE_BYTE_O + 0x0b), "MP_BC_JUMP": (MP_BC_BASE_JUMP_E + 0x02), # rel byte code offset, 16-bit signed, in excess "MP_BC_POP_JUMP_IF_TRUE": (MP_BC_BASE_JUMP_E + 0x03), # rel byte code offset, 16-bit signed, in excess "MP_BC_POP_JUMP_IF_FALSE": (MP_BC_BASE_JUMP_E + 0x04), # rel byte code offset, 16-bit signed, in excess "MP_BC_JUMP_IF_TRUE_OR_POP": (MP_BC_BASE_JUMP_E + 0x05), # rel byte code offset, 16-bit signed, in excess "MP_BC_JUMP_IF_FALSE_OR_POP": (MP_BC_BASE_JUMP_E + 0x06), # rel byte code offset, 16-bit signed, in excess "MP_BC_UNWIND_JUMP": (MP_BC_BASE_JUMP_E + 0x00), # rel byte code offset, 16-bit signed, in excess; then a byte "MP_BC_SETUP_WITH": (MP_BC_BASE_JUMP_E + 0x07), # rel byte code offset, 16-bit unsigned "MP_BC_SETUP_EXCEPT": (MP_BC_BASE_JUMP_E + 0x08), # rel byte code offset, 16-bit unsigned "MP_BC_SETUP_FINALLY": (MP_BC_BASE_JUMP_E + 0x09), # rel byte code offset, 16-bit unsigned "MP_BC_POP_EXCEPT_JUMP": (MP_BC_BASE_JUMP_E + 0x0a), # rel byte code offset, 16-bit unsigned "MP_BC_FOR_ITER": (MP_BC_BASE_JUMP_E + 0x0b), # rel byte code offset, 16-bit unsigned "MP_BC_WITH_CLEANUP": (MP_BC_BASE_BYTE_O + 0x0c), "MP_BC_END_FINALLY": (MP_BC_BASE_BYTE_O + 0x0d), "MP_BC_GET_ITER": (MP_BC_BASE_BYTE_O + 0x0e), "MP_BC_GET_ITER_STACK": (MP_BC_BASE_BYTE_O + 0x0f), "MP_BC_BUILD_TUPLE": (MP_BC_BASE_VINT_E + 0x0a), # uint "MP_BC_BUILD_LIST": (MP_BC_BASE_VINT_E + 0x0b), # uint "MP_BC_BUILD_MAP": (MP_BC_BASE_VINT_E + 0x0c), # uint "MP_BC_STORE_MAP": (MP_BC_BASE_BYTE_E + 0x02), "MP_BC_BUILD_SET": (MP_BC_BASE_VINT_E + 0x0d), # uint "MP_BC_BUILD_SLICE": (MP_BC_BASE_VINT_E + 0x0e), # uint "MP_BC_STORE_COMP": (MP_BC_BASE_VINT_E + 0x0f), # uint "MP_BC_UNPACK_SEQUENCE": (MP_BC_BASE_VINT_O + 0x00), # uint "MP_BC_UNPACK_EX": (MP_BC_BASE_VINT_O + 0x01), # uint "MP_BC_RETURN_VALUE": (MP_BC_BASE_BYTE_E + 0x03), "MP_BC_RAISE_LAST": (MP_BC_BASE_BYTE_E + 0x04), "MP_BC_RAISE_OBJ": (MP_BC_BASE_BYTE_E + 0x05), "MP_BC_RAISE_FROM": (MP_BC_BASE_BYTE_E + 0x06), "MP_BC_YIELD_VALUE": (MP_BC_BASE_BYTE_E + 0x07), "MP_BC_YIELD_FROM": (MP_BC_BASE_BYTE_E + 0x08), "MP_BC_MAKE_FUNCTION": (MP_BC_BASE_VINT_O + 0x02), # uint "MP_BC_MAKE_FUNCTION_DEFARGS": (MP_BC_BASE_VINT_O + 0x03), # uint "MP_BC_MAKE_CLOSURE": (MP_BC_BASE_VINT_E + 0x00), # uint; extra byte "MP_BC_MAKE_CLOSURE_DEFARGS": (MP_BC_BASE_VINT_E + 0x01), # uint; extra byte "MP_BC_CALL_FUNCTION": (MP_BC_BASE_VINT_O + 0x04), # uint "MP_BC_CALL_FUNCTION_VAR_KW": (MP_BC_BASE_VINT_O + 0x05), # uint "MP_BC_CALL_METHOD": (MP_BC_BASE_VINT_O + 0x06), # uint "MP_BC_CALL_METHOD_VAR_KW": (MP_BC_BASE_VINT_O + 0x07), # uint "MP_BC_IMPORT_NAME": (MP_BC_BASE_QSTR_O + 0x0b), # qstr "MP_BC_IMPORT_FROM": (MP_BC_BASE_QSTR_O + 0x0c), # qstr "MP_BC_IMPORT_STAR": (MP_BC_BASE_BYTE_E + 0x09), "UNOP_POSITIVE": (0xd0), "UNOP_NEGATIVE": (0xd1), "UNOP_INVERT": (0xd2), "UNOP_NOT": (0xd3), "BINOP_LESS": 0xd7, "BINOP_MORE": 0xd8, "BINOP_EQUAL": 0xd9, "BINOP_LESS_EQUAL": 0xda, "BINOP_MORE_EQUAL": 0xdb, "BINOP_NOT_EQUAL": 0xdc, "BINOP_IN": 0xdd, "BINOP_IS": 0xde, "BINOP_EXCEPTION_MATCH": 0xdf, "BINOP_INPLACE_OR": 0xe0, "BINOP_INPLACE_XOR": 0xe1, "BINOP_INPLACE_AND": 0xe2, "BINOP_INPLACE_LSHIFT": 0xe3, "BINOP_INPLACE_RSHIFT": 0xe4, "BINOP_INPLACE_ADD": 0xe5, "BINOP_INPLACE_SUBTRACT": 0xe6, "BINOP_INPLACE_MULTIPLY": 0xe7, "BINOP_INPLACE_MAT_MULTIPLY": 0xe8, "BINOP_INPLACE_FLOOR_DIVIDE": 0xe9, "BINOP_INPLACE_TRUE_DIVIDE": 0xea, "BINOP_INPLACE_MODULO": 0xeb, "BINOP_INPLACE_POWER": 0xec, "BINOP_OR": 0xed, "BINOP_XOR": 0xee, "BINOP_AND": 0xef, "BINOP_LSHIFT": 0xf0, "BINOP_RSHIFT": 0xf1, "BINOP_ADD": 0xf2, "BINOP_SUBTRACT": 0xf3, "BINOP_MULTIPLY": 0xf4, "BINOP_MAT_MULTIPLY": 0xf5, "BINOP_FLOOR_DIVIDE": 0xf6, "BINOP_TRUE_DIVIDE": 0xf7, "BINOP_MODULO": 0xf8, "BINOP_POWER": 0xf9, "BINOP_DIVMOD": 0xfa, "BINOP_CONTAINS": 0xfb, "BINOP_REVERSE_OR": 0xfc, "BINOP_REVERSE_XOR": 0xfd, "BINOP_REVERSE_AND": 0xfe, "BINOP_REVERSE_LSHIFT": 0xff, "BINOP_REVERSE_RSHIFT": 0x100, "BINOP_REVERSE_ADD": 0x101, "BINOP_REVERSE_SUBTRACT": 0x102, "BINOP_REVERSE_MULTIPLY": 0x103, "BINOP_REVERSE_MAT_MULTIPLY": 0x104, "BINOP_REVERSE_FLOOR_DIVIDE": 0x105, "BINOP_REVERSE_TRUE_DIVIDE": 0x106, "BINOP_REVERSE_MODULO": 0x107, "BINOP_REVERSE_POWER": 0x108, } optypes = { op_value: op_name for op_name, op_value in importmap.items() } opsnm = { "MP_BC_LOAD_CONST_FALSE": "false", "MP_BC_LOAD_CONST_NONE": "none", "MP_BC_LOAD_CONST_TRUE": "true", "MP_BC_LOAD_CONST_SMALL_INT": "int", "MP_BC_LOAD_CONST_STRING": "str", "MP_BC_LOAD_CONST_OBJ": "constobj", "MP_BC_LOAD_NULL": "null", "MP_BC_LOAD_FAST_N": "MP_BC_LOAD_FAST_N", "MP_BC_LOAD_DEREF": "deref", "MP_BC_LOAD_NAME": "loadname", "MP_BC_LOAD_GLOBAL": "glbl", "MP_BC_LOAD_ATTR": "attr", "MP_BC_LOAD_METHOD": "method", "MP_BC_LOAD_SUPER_METHOD": "supermethod", "MP_BC_LOAD_BUILD_CLASS": "buildclass", "MP_BC_LOAD_SUBSCR": "ld.arrsub", "MP_BC_STORE_FAST_N": "MP_BC_STORE_FAST_N", "MP_BC_STORE_DEREF": "st.deref", "MP_BC_STORE_NAME": "st.name", "MP_BC_STORE_GLOBAL": "st.glbl", "MP_BC_STORE_ATTR": "st.attr", "MP_BC_STORE_SUBSCR": "st.arrsub", "MP_BC_DELETE_FAST": "del.fast", "MP_BC_DELETE_DEREF": "del.deref", "MP_BC_DELETE_NAME": "del.name", "MP_BC_DELETE_GLOBAL": "del.glbl", "MP_BC_DUP_TOP": "dup", "MP_BC_DUP_TOP_TWO": "dup2", "MP_BC_POP_TOP": "pop", "MP_BC_ROT_TWO": "rot", "MP_BC_ROT_THREE": "rot3", "MP_BC_JUMP": "jmp", "MP_BC_POP_JUMP_IF_TRUE": "btrue", "MP_BC_POP_JUMP_IF_FALSE": "bfalse", "MP_BC_JUMP_IF_TRUE_OR_POP": "btrue.pop", "MP_BC_JUMP_IF_FALSE_OR_POP": "bfalse.pop", "MP_BC_UNWIND_JUMP": "jmp.unwind", "MP_BC_SETUP_WITH": "with.setup", "MP_BC_SETUP_EXCEPT": "except.setup", "MP_BC_SETUP_FINALLY": "finally.setup", "MP_BC_POP_EXCEPT_JUMP": "except.jump", "MP_BC_FOR_ITER": "for.iter", "MP_BC_WITH_CLEANUP": "with.chleanup", "MP_BC_END_FINALLY": "finally.end", "MP_BC_GET_ITER": "ld.iter", "MP_BC_GET_ITER_STACK": "ld.iterstack", "MP_BC_BUILD_TUPLE": "tuple", "MP_BC_BUILD_LIST": "list", "MP_BC_BUILD_MAP": "map", "MP_BC_STORE_MAP": "st.map", "MP_BC_BUILD_SET": "MP_BC_BUILD_SET", "MP_BC_BUILD_SLICE": "slice", "MP_BC_STORE_COMP": "MP_BC_STORE_COMP", "MP_BC_UNPACK_SEQUENCE": "MP_BC_UNPACK_SEQUENCE", "MP_BC_UNPACK_EX": "MP_BC_UNPACK_EX", "MP_BC_RETURN_VALUE": "ret", "MP_BC_RAISE_LAST": "rethrow", "MP_BC_RAISE_OBJ": "raiseobj", "MP_BC_RAISE_FROM": "throwfrom", "MP_BC_YIELD_VALUE": "yield", "MP_BC_YIELD_FROM": "yieldfrom", "MP_BC_MAKE_FUNCTION": "mkfun", "MP_BC_MAKE_FUNCTION_DEFARGS": "mkfun.defargs", "MP_BC_MAKE_CLOSURE": "mkclosure", "MP_BC_MAKE_CLOSURE_DEFARGS": "mkclosure.defargs", "MP_BC_CALL_FUNCTION": "call", "MP_BC_CALL_FUNCTION_VAR_KW": "call.kw", "MP_BC_CALL_METHOD": "call.meth", "MP_BC_CALL_METHOD_VAR_KW": "call.kvmeth", "MP_BC_IMPORT_NAME": "import.nm", "MP_BC_IMPORT_FROM": "import.from", "MP_BC_IMPORT_STAR": "import.all", "UNOP_POSITIVE": "assertint", "UNOP_NEGATIVE": "neg", "UNOP_INVERT": "invert", "UNOP_NOT": "not", "BINOP_LESS": "lt", "BINOP_MORE": "qt", "BINOP_EQUAL": "eq", "BINOP_LESS_EQUAL": "le", "BINOP_MORE_EQUAL": "qe", "BINOP_NOT_EQUAL": "ne", "BINOP_IN": "in", "BINOP_IS": "is", "BINOP_EXCEPTION_MATCH": "ematch", "BINOP_INPLACE_OR": "or.in", "BINOP_INPLACE_XOR": "xor.in", "BINOP_INPLACE_AND": "and.in", "BINOP_INPLACE_LSHIFT": "shl.in", "BINOP_INPLACE_RSHIFT": "shr.in", "BINOP_INPLACE_ADD": "add.in", "BINOP_INPLACE_SUBTRACT": "sub.in", "BINOP_INPLACE_MULTIPLY": "mul.in", "BINOP_INPLACE_MAT_MULTIPLY": "matmul.in", "BINOP_INPLACE_FLOOR_DIVIDE": "floordiv.in", "BINOP_INPLACE_TRUE_DIVIDE": "div.in", "BINOP_INPLACE_MODULO": "mod.in", "BINOP_INPLACE_POWER": "pow.in", "BINOP_OR": "or", "BINOP_XOR": "xor", "BINOP_AND": "and", "BINOP_LSHIFT": "shl", "BINOP_RSHIFT": "shr", "BINOP_ADD": "add", "BINOP_SUBTRACT": "sub", "BINOP_MULTIPLY": "mul", "BINOP_MAT_MULTIPLY": "matmul", "BINOP_FLOOR_DIVIDE": "floordiv", "BINOP_TRUE_DIVIDE": "truediv", "BINOP_MODULO": "mod", "BINOP_POWER": "pow", "BINOP_DIVMOD": "divmod", "BINOP_CONTAINS": "in", "BINOP_REVERSE_OR": "or.rev", "BINOP_REVERSE_XOR": "xor.rev", "BINOP_REVERSE_AND": "and.rev", "BINOP_REVERSE_LSHIFT": "shl.rev", "BINOP_REVERSE_RSHIFT": "shr.rev", "BINOP_REVERSE_ADD": "add.rev", "BINOP_REVERSE_SUBTRACT": "sub.rev", "BINOP_REVERSE_MULTIPLY": "mul.rev", "BINOP_REVERSE_MAT_MULTIPLY": "matmul.rev", "BINOP_REVERSE_FLOOR_DIVIDE": "floordiv.rev", "BINOP_REVERSE_TRUE_DIVIDE": "truediv.rev", "BINOP_REVERSE_MODULO": "mod.rev", "BINOP_REVERSE_POWER": "pow.rev", } branches = [ "jmp", "btrue", "bfalse", "btrue.pop", "bfalse.pop", "jmp.unwind" ] branches2 = [ "with.setup", "except.setup", "finally.setup", "except.jump", "for.iter" ] class capturing(list): def __enter__(self): self._stdout = sys.stdout sys.stdout = self._stringio = io.StringIO() return self def __exit__(self, *args): self.extend(self._stringio.getvalue().splitlines()) del self._stringio sys.stdout = self._stdout def flatten(x, it = None): try: if type(x) in (str, bytes): yield x else: if not it: it = iter(x) yield from flatten(next(it)) if type(x) not in (str, bytes): yield from flatten(x, it) except StopIteration: pass except Exception: yield x def flat(x): return [e for e in flatten(x)] def disassemblefrom_c_opinput(opinput0, p): globals()['outg'].append(p[opinput0[1].split('& 0xff')[0].strip()] + ':') globals()['off'] = 0 globals()['usedAdderesses'] = set() def process_opinput1(line): stage0 = line.strip().split(",") stage1 = stage0 stage1 = [e.strip() for e in stage1] stage1 = [e for e in stage1 if e] globals()['off'] += len(stage1) stage1.append(str(globals()['off'])) def stage2_lbd(e): if (e.startswith('0x')): return int(e, 16) elif (e.endswith('>> 8')): return '' elif (e.endswith('& 0xff')): return p[e.split(' ')[0]] else: return e stage2 = stage1 stage2 = [stage2_lbd(e) for e in stage2] stage2 = [e for e in stage2 if e != ''] def stage3_lbd(e, i): if ((type(e) is int) and (i == 0)): if ((e in optypes) and (optypes[e] in opsnm)): return opsnm[optypes[e]] elif ((type(e) is int) and (e >= MP_BC_LOAD_FAST_MULTI) and (e < MP_BC_STORE_FAST_MULTI) and (i == 0)): return 'ldloc.{}'.format(e - MP_BC_LOAD_FAST_MULTI) elif ((type(e) is int) and (e >= MP_BC_STORE_FAST_MULTI) and (e < MP_BC_UNARY_OP_MULTI) and (i == 0)): return 'stloc.{}'.format(e - MP_BC_STORE_FAST_MULTI) elif ((type(e) is int) and (e >= 0x80) and (e < 0x90) and (i == 0)): return 'int {}'.format(e - 0x80) else: print('Unknown opcode: {}'.format(e)) return e else: #print('Opcode: {} position {}'.format(e, i)) return e stage3 = stage2 stage3 = [stage3_lbd(e, i) for e, i in zip(stage3, range(len(stage3)))] def stage4_lbd(e, i, a): if (a[0] in branches): address = (a[1] | (int(a[2]) << 8)) - 0x8000 + globals()['off'] globals()['usedAdderesses'].add(address) return flat([e, '.L' + str(address), [], e, e][i]) elif (a[0] in branches2): address = (a[1] | (int(a[2]) << 8)) + globals()['off'] globals()['usedAdderesses'].add(address) return flat([e, '.L' + str(address), [], e, e][i]) else: return [e] stage4 = stage3 stage4 = [stage4_lbd(e, i, stage4) for e, i in zip(stage4, range(len(stage4)))] return flat(stage4) opinput1 = opinput0 opinput1 = [process_opinput1(e) for e in opinput1] globals()['off'] = 0 def process_opinput2(e, i, a): def comma_test(e, i): if (i > 1): return ', {}'.format(e) else: return str(e) e2 = [comma_test(e1, i1) for e1, i1 in zip(e[:-1], range(len(e[:-1])))] e3 = ' '.join(e2) e4 = e3.replace(' , ', ', ') if ((i >= 1) and (int(a[i - 1][-1]) in globals()['usedAdderesses'])): return '.L' + a[i - 1][len(a[i - 1]) - 1] + ':\n\t' + e4 else: return '\t' + e4 opinput2 = opinput1[4:] opinput2 = [process_opinput2(e, i, opinput2) for e, i in zip(opinput2, range(len(opinput2)))] globals()['outg'].append('\n'.join(opinput2)); def get_enums(dotc_content): enum_keys = [] num_lines = len(dotc_content) found_pos = -1 for i in range(num_lines): line = dotc_content[i] if line == 'enum {': found_pos = i break if found_pos == -1: return enum_keys for i in range(found_pos+1, num_lines): line = dotc_content[i] if line == '};': break enum_keys.append(line.split(',')[0].split('=')[0].strip()) return enum_keys def get_values(dotc_content): enum_values = [] num_lines = len(dotc_content) found_pos = -1 for i in range(num_lines): line = dotc_content[i] if 'mp_qstr_frozen_const_pool' in line: found_pos = i break if found_pos == -1: return enum_values for i in range(found_pos+6, num_lines): line = dotc_content[i] if line.strip() == '},': break enum_values.append(line.split('"')[3].strip()) return enum_values ################################################################################ if (__name__ == "__main__"): print("Initialising disassembler...") print("Parsing arguments...") parser = argparse.ArgumentParser(description="Disassembles an '.mpy' micropython script.") parser.add_argument("script_path", help="Script file name to disassemble.") parser.add_argument("output_path", nargs='?', help="Output file to used for disassembled output.", default="") arguments = parser.parse_args() print("Checking script...") if (os.path.isfile(arguments.script_path) != True): raise FileNotFoundError("Failed to find the script file at the given path.") if (os.access(arguments.script_path, os.R_OK) != True): raise PermissionError("Do not have permission to read the script file.") if (arguments.output_path != ""): print("Checking output...") if (os.path.isfile(arguments.output_path) != False): raise FileNotFoundError("Found an existing file at the output file path.") print("Running mpy-tool on script...") root_dir = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, root_dir + '/micropython/tools') mpy_tool = importlib.import_module("mpy-tool") mpy_tool.config.MICROPY_LONGINT_IMPL = { "none": mpy_tool.config.MICROPY_LONGINT_IMPL_NONE, "longlong": mpy_tool.config.MICROPY_LONGINT_IMPL_LONGLONG, "mpz": mpy_tool.config.MICROPY_LONGINT_IMPL_MPZ, }["mpz"] mpy_tool.config.MPZ_DIG_SIZE = 16 mpy_tool.config.native_arch = mpy_tool.MP_NATIVE_ARCH_NONE mpy_tool.config.MICROPY_QSTR_BYTES_IN_LEN = 1 mpy_tool.config.MICROPY_QSTR_BYTES_IN_HASH = 1 base_qstrs = {} raw_codes = [mpy_tool.read_mpy(arguments.script_path)] try: with capturing() as captured_output: mpy_tool.freeze_mpy(base_qstrs, raw_codes) except mpy_tool.FreezeError as er: print(er, file=sys.stderr) sys.exit(1) print("Processing output of mpy-tool...") keys = get_enums(captured_output) values = get_values(captured_output) # Double check we have extracted the map correctly. assert(len(keys) == len(values)) entries = dict((key, value) for key, value in zip(keys, values)) data = [[line, index] for line, index in zip(captured_output, range(len(captured_output))) if line.startswith('STATIC const byte fun_data_')] globals()['outg'] = [] functions_raw = [('\n'.join(captured_output[line_index[1] + 1:])).split('};')[0].split('\n') for line_index in data] functions = [[function_line.strip() for function_line in function] for function in functions_raw] for function in functions: disassemblefrom_c_opinput(function, entries) if (arguments.output_path != ""): print("Writing output...") output_file = open(arguments.output_path, 'w') output_file.write('\n'.join(globals()['outg'])) else: print("Disassembled output...") print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") print('\n'.join(globals()['outg'])) print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") print("Finished.")
rbeucher/underworld2
underworld/libUnderworld/Underworld/Utils/AdvectionDiffusion/src/Timestep.c
<gh_stars>0 /*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~* ** ** ** This file forms part of the Underworld geophysics modelling application. ** ** ** ** For full license and copyright information, please refer to the LICENSE.md file ** ** located at the project root, or contact the authors. ** ** ** **~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/ #include "mpi.h" #include <StGermain/libStGermain/src/StGermain.h> #include <StgDomain/libStgDomain/src/StgDomain.h> #include <StgFEM/libStgFEM/src/StgFEM.h> #include "types.h" #include "Timestep.h" #include "AdvectionDiffusionSLE.h" #include "Residual.h" #include <math.h> #include <assert.h> #include <string.h> #include <float.h> double AdvectionDiffusionSLE_CalculateDt( void* advectionDiffusionSLE, FiniteElementContext* context ) { AdvectionDiffusionSLE* self = (AdvectionDiffusionSLE*) advectionDiffusionSLE; double advectionTimestep; double diffusionTimestep; double advectionTimestepGlobal; double diffusionTimestepGlobal; double timestep; Journal_DPrintf( self->debug, "In func: %s\n", __func__ ); /* It would be useful to introduce a limit to the change of step in here ... to prevent timesteps from becoming arbitrarily large in a single step */ /* Calculate Courant Number */ if(self->pureDiffusion) advectionTimestep = DBL_MAX; else advectionTimestep = AdvectionDiffusionSLE_AdvectiveTimestep( self ); diffusionTimestep = AdvectionDiffusionSLE_DiffusiveTimestep( self ); (void)MPI_Allreduce( &advectionTimestep, &advectionTimestepGlobal, 1, MPI_DOUBLE, MPI_MIN, MPI_COMM_WORLD ); (void)MPI_Allreduce( &diffusionTimestep, &diffusionTimestepGlobal, 1, MPI_DOUBLE, MPI_MIN, MPI_COMM_WORLD ); Journal_DPrintf( self->debug, "%s Dominating. - Advective Timestep = %g - Diffusive Timestep = %g\n", advectionTimestepGlobal < diffusionTimestepGlobal ? "Advection" : "Diffusion", advectionTimestepGlobal, diffusionTimestepGlobal); /* Calculate Time Step */ timestep = MIN( advectionTimestepGlobal, diffusionTimestepGlobal ); return timestep; } double AdvectionDiffusionSLE_DiffusiveTimestep( void* advectionDiffusionSLE ) { AdvectionDiffusionSLE* self = (AdvectionDiffusionSLE*) advectionDiffusionSLE; double minSeparation; double minSeparationEachDim[3]; Journal_DPrintf( self->debug, "In func: %s\n", __func__ ); FeVariable_GetMinimumSeparation( self->phiField, &minSeparation, minSeparationEachDim ); self->maxDiffusivity = AdvDiffResidualForceTerm_GetMaxDiffusivity( self->advDiffResidualForceTerm); /* This is quite a conservative estimate */ return self->courantFactor * minSeparation * minSeparation / self->maxDiffusivity; } double AdvectionDiffusionSLE_AdvectiveTimestep( void* advectionDiffusionSLE ) { AdvectionDiffusionSLE* self = (AdvectionDiffusionSLE*) advectionDiffusionSLE; AdvDiffResidualForceTerm* residualForceTerm = self->advDiffResidualForceTerm; FeVariable* velocityField = residualForceTerm->velocityField; Node_LocalIndex nodeLocalCount = FeMesh_GetNodeLocalSize( self->phiField->feMesh ); Node_LocalIndex node_I; Dimension_Index dim = self->dim; Dimension_Index dim_I; double timestep = HUGE_VAL; XYZ velocity; double minSeparation; double minSeparationEachDim[3]; double* meshCoord; Journal_DPrintf( self->debug, "In func: %s\n", __func__ ); FeVariable_GetMinimumSeparation( self->phiField, &minSeparation, minSeparationEachDim ); for( node_I = 0 ; node_I < nodeLocalCount ; node_I++ ){ if( self->phiField->feMesh == velocityField->feMesh){ FeVariable_GetValueAtNode( velocityField, node_I, velocity ); } else { meshCoord = Mesh_GetVertex( self->phiField->feMesh, node_I ); FieldVariable_InterpolateValueAt( velocityField, meshCoord, velocity ); } for ( dim_I = 0 ; dim_I < dim ; dim_I++ ) { if( velocity[ dim_I ] == 0.0 ) continue; timestep = MIN( timestep, fabs( minSeparationEachDim[ dim_I ]/velocity[ dim_I ] ) ); } } return self->courantFactor * timestep; }
jstastny-cz/appformer
uberfire-workbench/uberfire-workbench-processors-tests/src/test/resources/org/uberfire/annotations/processors/PerspectiveTest17.java
package org.uberfire.annotations.processors; import javax.annotation.PostConstruct; import javax.enterprise.context.ApplicationScoped; import com.google.gwt.user.client.ui.FlowPanel; import org.uberfire.client.workbench.panels.impl.MultiTabWorkbenchPanelPresenter; import org.uberfire.client.annotations.WorkbenchPanel; import org.uberfire.client.annotations.WorkbenchPerspective; import org.jboss.errai.common.client.dom.Div; import org.jboss.errai.ui.client.local.api.IsElement; import javax.inject.Inject; @ApplicationScoped @WorkbenchPerspective( identifier = "HomePerspective", isDefault = true) public class PerspectiveTest17 implements IsElement { @Inject @WorkbenchPanel(panelType = MultiTabWorkbenchPanelPresenter.class, isDefault = true, parts = "TesteScreen") Div teste1; @Inject @WorkbenchPanel(parts = "TesteScreen1") Div teste2; @PostConstruct public void setup() { } }
group4BCS1/BCS-2021
src/chapter8/exercise4.py
list = [] fhand = open('romeo.txt') for line in fhand: x = line.split() for y in x: if y in list: continue list.append(y) print(sorted(list))
metincansiper/Paxtools
psimi-converter/src/main/java/org/biopax/paxtools/converter/psi/package-info.java
/** * @author rodche * */ package org.biopax.paxtools.converter.psi;
todhm/wicarproject
wicarproject/static/wicar_dashboard/src/carbasicsetting/CarBasicSetting.js
<reponame>todhm/wicarproject<gh_stars>1-10 import React, { Component } from 'react'; import { Link } from 'react-router-dom' import PropTypes from 'prop-types' import serializeForm from 'form-serialize' import AddressForm from '../utils/AddressForm' import SelectField from '../utils/SelectField' import SmallField from '../utils/SmallField' import LargeField from '../utils/LargeField' import * as api from '../utils/api' import * as SettingAction from './action' import '../utils/styles/selectfield.css' import {TextField,Grid,Select} from '@material-ui/core'; import {BasicSettingStateToProps} from '../utils/reducerutils' import {connect} from 'react-redux' class CarBasicSetting extends Component{ static contextTypes = { router: PropTypes.object } componentDidMount=()=>{ var pathList = this.context.router.history.location.pathname.split("/",-1) var carid = pathList[pathList.length-1]; if(carid &&carid !="car_registeration"){ this.props.getCarInfo(carid) } this.props.getCarBrand(); } onChange = (val)=>{ const address = val ===null ? '' : val this.props.updateBasicSettingReducer({address, valueObj:address.addressObj}) } checkNumber=(num)=>{ let thisYear = new Date().getFullYear(); if (!isNaN(num)){ if( num > thisYear){ this.props.updateBasicSettingReducer({yearError:"숫자가 너무 큽니다."}); return false; } else if(num < 1900 ){ this.props.updateBasicSettingReducer({yearError:"숫자가 너무 작습니다."}); return false; } else{ this.props.updateBasicSettingReducer({yearError:""}); return true; } } else{ this.props.updateBasicSettingReducer({yearError:"년도를 입력해주세요."}); return false; } } checkDistance=(distance)=>{ if (!isNaN(distance)){ if(distance < 50){ this.props.updateBasicSettingReducer({distanceError:"최소 50km이상이 필요합니다."}); return false; } else{ this.props.updateBasicSettingReducer({distanceError:""}); return true; } } else{ this.props.updateBasicSettingReducer({distanceError:"주행거리를 입력해주세요."}); return false; } } checkVariable=(val,errorName,errorMessage)=>{ if (val == null){ this.props.updateSetting(errorName,errorMessage) return false; } else{ this.props.updateSetting(errorName,"") return true; } } handleSubmit = (e)=>{ e.preventDefault() const values = serializeForm(e.target, { hash: true }) let addressCheck = this.checkVariable(values.address,"addressError",'주소를 입력해주세요'); let detailAddressCheck = this.checkVariable(values.detail_address,"detailAddressError",'상세주소를 입력해주세요.'); let yearCheck = this.checkNumber(values.year); let brandCheck = this.checkVariable(values.brandName,"brandError","브랜드를 선택해주세요."); let classCheck = this.checkVariable(values.className,"classError","모델을 선택해주세요.") let modelCheck = this.checkVariable(values.model,"modelError","상세 모델을 선택해주세요."); let distanceCheck = this.checkDistance(values.distance); if(addressCheck && detailAddressCheck && yearCheck && brandCheck && modelCheck && distanceCheck){ values.address = this.props.valueObj; values.email = (window.email)? window.email:'<EMAIL>'; var pathList = this.context.router.history.location.pathname.split("/",-1) var carid = (pathList.length>=3) ? pathList[pathList.length-1]:""; this.props.addCarBasicInfo(carid,values) } } handleInputChange = (e)=>{ let name = e.target.name; let value = e.target.value; this.props.updateSetting(name,value) } handleBrandChange = (e)=>{ const query ={}; const name = e.target.name; const brandName = e.target.value; if(brandName){ this.props.updateBasicSettingReducer({ showClass:true, showModel:false, brandName:brandName, className:"", model:"", modelList:[]}) query['brandName'] =brandName; this.props.getClassList(query) } else{ this.props.updateBasicSettingReducer({showClass:false, showModel:false, brandName:"", className:"", model:"", classList:[], modelList:[]}); } } handleClassChange = (e)=>{ let query ={}; let name = e.target.name; let className = e.target.value; if(className){ this.props.updateBasicSettingReducer({showModel:true,className:className,model:""}) query['className'] =className; this.props.getModelList(query) } else{ this.props.updateBasicSettingReducer({showModel:false,className:"",model:"",modelList:[]}); } } render(){ const {brandList,address,valueObj} = this.props return( <div className="layoutSingleColumn js-listingEligibilityPage"> <h5>자동차정보를 입력해주세요</h5> <form className="js-listingEligibilityForm form" onSubmit={this.handleSubmit} > <AddressForm label={"차의 위치를 입력해주세요"} error={this.props.addressError} value={address} valueObj={valueObj} onChange={this.onChange} /> <Grid container> <TextField name="detail_address" placeholder="고객들이 자동차를 가져갈 위치를 상세히 설명해주세요." label="주차위치" multiline={true} rows={10} id="js-detailAddressInput" onChange={this.handleInputChange} error={this.props.detailAddressError?true:false} helperText={this.props.detailAddressError} value={this.props.detail_address} fullWidth={true} /> </Grid> <Grid container spacing={16}> <Grid item xs={12} sm={3}> <SelectField label="브랜드" value={this.props.brandName} defaultLabel="브랜드선택" onChange = {this.handleBrandChange} optionList={this.props.brandList} error={this.props.brandError} name="brandName" labelEqual={true} /> </Grid> <Grid item xs={12} sm={3}> {this.props.showClass? <SelectField label="모델" value={this.props.className} defaultLabel="모델선택" onChange={this.handleClassChange} optionList={this.props.classList} error={this.props.classError} name="className" labelEqual={true} />:null } </Grid> <Grid item xs={12} sm={3}> {this.props.showModel? <SelectField label="상세모델" value={this.props.model} defaultLabel="상세모델선택" onChange = {this.handleInputChange} optionList={this.props.modelList} error={this.props.modelError} name="model" labelEqual={true} />:null } </Grid> <Grid item xs={12} sm={3}> <SelectField name="year" defaultLabel="차량연도선택" label="차량연도" labelEqual={false} optionList={this.props.yearList} onChange={this.handleInputChange} error={this.props.yearError} value={this.props.year} noDefault={true} /> </Grid> </Grid> <Grid container spacing={16}> <Grid item xs={12} sm={4}> <SelectField label="자동차종류" value={this.props.cartype} defaultLabel="차량종류선택" onChange = {this.handleInputChange} optionList={this.props.carTypeJson} error={this.props.carTypeError} name="cartype" labelEqual={false} noDefault={true} /> </Grid> <Grid item xs={12} sm={4}> <SelectField label="변속선택" value={this.props.transmission} defaultLabel="변속선택" onChange = {this.handleInputChange} optionList={this.props.transmissionList} error={this.props.transmissionError} name="transmission" labelEqual={false} noDefault={true} /> </Grid> <Grid item xs={12} sm={4}> <TextField name="distance" placeholder="100" multiline={true} rows={1} label="일일거리제한(KM)" onChange={this.handleInputChange} error={this.props.distanceError?true:false} helperText={this.props.distanceError} value={this.props.distance} fullWidth={true}/> </Grid> </Grid> <div className="buttonWrapper buttonWrapper--largeTopMargin"> <button type="submit" className="button button--purple js-submitButton">저장하기</button> </div> </form> </div> ) } } export default connect(BasicSettingStateToProps,SettingAction)(CarBasicSetting);
liexusong/fuchsia
src/camera/bin/factory/streamer.h
<filename>src/camera/bin/factory/streamer.h // Copyright 2019 The Fuchsia 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 SRC_CAMERA_BIN_FACTORY_STREAMER_H_ #define SRC_CAMERA_BIN_FACTORY_STREAMER_H_ #include <fuchsia/camera3/cpp/fidl.h> #include <fuchsia/sysmem/cpp/fidl.h> #include <lib/async-loop/cpp/loop.h> #include <lib/sys/cpp/component_context.h> #include <map> #include "src/camera/bin/factory/capture.h" namespace camera { // A class that manages a video stream from a camera class Streamer { public: Streamer(); ~Streamer(); // Make a streamer and start its thread static fit::result<std::unique_ptr<Streamer>, zx_status_t> Create( fuchsia::sysmem::AllocatorHandle allocator, fuchsia::camera3::DeviceWatcherHandle watcher, fit::closure stop_callback = nullptr); // once connected to device, return the number of available configs uint32_t NumConfigs(); // if connected, return the connected config index uint32_t ConnectedConfig(); // if connected to a config, return the number of currently connected streams (all are attempted) uint32_t NumConnectedStreams(); // request a switch to another config index void RequestConfig(uint32_t config); // request a frame capture; the next available frame will be written to flash void RequestCapture(uint32_t stream, const std::string& path, bool wantImage, CaptureResponse response); private: // Start the event loop zx_status_t Start(); // Chain of calls to connect to streams and start receiving frames void WatchDevicesCallback(std::vector<fuchsia::camera3::WatchDevicesEvent> events); void WatchCurrentConfigurationCallback(uint32_t config_index); void ConnectToAllStreams(); void ConnectToStream(uint32_t config_index, uint32_t stream_index); void OnNextFrame(uint32_t stream_index, fuchsia::camera3::FrameInfo frame_info); void DisconnectStream(uint32_t stream_index); void WatchBufferCollectionCallback(uint32_t config_index, uint32_t stream_index, fuchsia::sysmem::BufferCollectionTokenHandle token_back); void SyncCallback(uint32_t stream_index, fuchsia::sysmem::BufferCollectionTokenHandle token_back); void WaitForBuffersAllocatedCallback(uint32_t stream_index, zx_status_t status, fuchsia::sysmem::BufferCollectionInfo_2 buffers); async::Loop loop_; fit::closure stop_callback_; fuchsia::sysmem::AllocatorPtr allocator_; fuchsia::camera3::DeviceWatcherPtr watcher_; fuchsia::camera3::DevicePtr device_; std::vector<fuchsia::camera3::Configuration> configurations_; uint32_t config_count_ = 0; uint32_t connected_stream_count_ = 0; uint32_t connected_config_index_ = 0; uint32_t frame_count_ = 0; struct StreamInfo { fuchsia::sysmem::BufferCollectionTokenPtr token_ptr; fuchsia::sysmem::BufferCollectionPtr collection; fuchsia::sysmem::BufferCollectionInfo_2 collection_info; fuchsia::camera3::StreamPtr stream; }; // stream_infos_ uses the same index as the corresponding stream index in configurations_. std::map<uint32_t, StreamInfo> stream_infos_; std::unique_ptr<Capture> capture_; }; } // namespace camera #endif // SRC_CAMERA_BIN_FACTORY_STREAMER_H_
Junvary/gin-quasar-admin
GQA-BACKEND/service/system/sys_dict.go
package system import ( "errors" "github.com/Junvary/gin-quasar-admin/GQA-BACKEND/global" "github.com/Junvary/gin-quasar-admin/GQA-BACKEND/model/system" "gorm.io/gorm" ) type ServiceDict struct {} func (s *ServiceDict) GetDictList(requestDictList system.RequestDictList) (err error, role interface{}, total int64, parentCode string) { pageSize := requestDictList.PageSize offset := requestDictList.PageSize * (requestDictList.Page - 1) db := global.GqaDb.Where("parent_code = ?", requestDictList.ParentCode).Find(&system.SysDict{}) var dictList []system.SysDict //配置搜索 if requestDictList.DictCode != ""{ db = db.Where("dict_code like ?", "%" + requestDictList.DictCode + "%") } if requestDictList.DictLabel != ""{ db = db.Where("dict_label like ?", "%" + requestDictList.DictLabel + "%") } err = db.Count(&total).Error if err != nil { return } err = db.Limit(pageSize).Offset(offset).Order(global.OrderByColumn(requestDictList.SortBy, requestDictList.Desc)).Find(&dictList).Error return err, dictList, total, requestDictList.ParentCode } func (s *ServiceDict) EditDict(toEditDict system.SysDict) (err error) { var sysDict system.SysDict if err = global.GqaDb.Where("id = ?", toEditDict.Id).First(&sysDict).Error; err != nil { return err } if sysDict.Stable == "yes" { return errors.New("系统内置不允许编辑:" + toEditDict.DictCode) } //err = global.GqaDb.Updates(&toEditDict).Error err = global.GqaDb.Save(&toEditDict).Error return err } func (s *ServiceDict) AddDict(toAddDict system.SysDict) (err error) { var dict system.SysDict if !errors.Is(global.GqaDb.Where("dict_code = ?", toAddDict.DictCode).First(&dict).Error, gorm.ErrRecordNotFound) { return errors.New("此字典已存在:" + toAddDict.DictCode) } err = global.GqaDb.Create(&toAddDict).Error return err } func (s *ServiceDict) DeleteDict(id uint) (err error) { var dict system.SysDict if err = global.GqaDb.Where("id = ?", id).First(&dict).Error; err != nil { return err } if dict.Stable == "yes" { return errors.New("系统内置不允许删除:" + dict.DictCode) } err = global.GqaDb.Where("id = ?", id).Unscoped().Delete(&dict).Error return err } func (s *ServiceDict) QueryDictById(id uint) (err error, dictInfo system.SysDict) { var dict system.SysDict err = global.GqaDb.Preload("CreatedByUser").Preload("UpdatedByUser").First(&dict, "id = ?", id).Error return err, dict }
csell5/RadonFanMobile
source/radonFan/app/tns_modules/ui/border/border.android.js
<reponame>csell5/RadonFanMobile<filename>source/radonFan/app/tns_modules/ui/border/border.android.js<gh_stars>1-10 var __extends = this.__extends || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } __.prototype = b.prototype; d.prototype = new __(); }; var borderCommon = require("ui/border/border-common"); var color = require("color"); require("utils/module-merge").merge(borderCommon, exports); function onCornerRadiusPropertyChanged(data) { var view = data.object; if (!view._nativeView) { return; } if (view._nativeView instanceof android.view.ViewGroup) { var gd = new android.graphics.drawable.GradientDrawable(); gd.setCornerRadius(data.newValue); gd.setStroke(view.borderWidth, view.borderColor.android); view._nativeView.setBackgroundDrawable(gd); } } borderCommon.cornerRadiusProperty.metadata.onSetNativeValue = onCornerRadiusPropertyChanged; function onBorderWidthPropertyChanged(data) { var view = data.object; if (!view._nativeView) { return; } if (view._nativeView instanceof android.view.ViewGroup) { var gd = new android.graphics.drawable.GradientDrawable(); gd.setCornerRadius(view.cornerRadius); gd.setStroke(data.newValue, view.borderColor.android); view._nativeView.setBackgroundDrawable(gd); } } borderCommon.borderWidthProperty.metadata.onSetNativeValue = onBorderWidthPropertyChanged; function onBorderColorPropertyChanged(data) { var view = data.object; if (!view._nativeView) { return; } if (view._nativeView instanceof android.view.ViewGroup && data.newValue instanceof color.Color) { var gd = new android.graphics.drawable.GradientDrawable(); gd.setCornerRadius(view.cornerRadius); gd.setStroke(view.borderWidth, data.newValue.android); view._nativeView.setBackgroundDrawable(gd); } } borderCommon.borderColorProperty.metadata.onSetNativeValue = onBorderColorPropertyChanged; var Border = (function (_super) { __extends(Border, _super); function Border() { _super.apply(this, arguments); } return Border; })(borderCommon.Border); exports.Border = Border;
phlegx/uvue
tests/utils/e2e.js
const request = require('request'); const cheerio = require('cheerio'); const baseURL = 'http://localhost:7357'; /** * Do a HTTP request */ const doRequest = async (url, options) => { return new Promise(resolve => { request( { url, ...options, }, (error, response, body) => { resolve({ error, response, body, }); }, ); }); }; const goto = async url => { await page.goto(`${baseURL}${url}`); }; /** * Go to a page in SSR mode and get HTML content */ const gotoSSR = async url => { const response = await page.goto(`${baseURL}${url}`); const responseBody = await response.text(); const $ = cheerio.load(responseBody); let scriptContent; const dataScript = $('script[data-vue-ssr-data]'); if (dataScript.length) { scriptContent = dataScript.html().replace(/^window\.__DATA__=/, ''); } if (scriptContent && scriptContent !== 'undefined') { $.DATA = JSON.parse(scriptContent); } else { $.DATA = {}; } return $; }; /** * Do a SPA navigation */ const gotoSPA = async name => { await page.goto(`${baseURL}/`); await isMounted(); const link = await page.$(`a[data-route-name="${name}"]`); await link.click(); await wait(100); }; /** * Check the current page is in SPA mode */ const isSPA = async () => { return (await page.$('script[data-vue-spa]')) !== null; }; /** * Check Vue app is mounted */ const isMounted = async () => { return page.waitForFunction('document.querySelector("#mounted") != null'); }; /** * Get text in DOM element */ const getText = selector => { return page.$eval(selector, el => el.textContent); }; /** * Check text in DOM element */ const checkText = async (selector, value) => { expect(await page.$eval(selector, el => el.textContent)).toBe(value); }; /** * Run tests contained in page */ const pageRunTests = async (selector = '.test') => { const tests = await page.evaluate(selector => { const elements = Array.from(document.querySelectorAll(selector)); return elements.map(item => { return { expected: item.querySelector('.expected .value').textContent, result: item.querySelector('.result .value').textContent, }; }); }, selector); for (const test of tests) { expect(test.result).toBe(test.expected); } }; /** * Run tests contained in page (SSR mode, with HTML source code) */ const pageRunTestsSSR = ($, selector = '.test') => { $(selector).each((_, element) => { const expected = $('.expected .value', element).text(); const result = $('.result .value', element).text(); expect(result).toBe(expected); }); }; const testContext = async (path, selector = '.context') => { const contexts = await page.evaluate(selector => { const elements = Array.from(document.querySelectorAll(selector)); return elements.map(item => { try { return JSON.parse(item.textContent); } catch (err) { return {}; } }); }, selector); for (const data of contexts) { for (const key in data) { if (key === 'route') { const route = data[key]; if (route.hook && /^route/.test(route.hook)) { if (route.url) { expect(route.url).toBe(`${path}/bar?bar=baz`); } if (route.query) { expect(route.query).toEqual({ bar: 'baz', }); } if (route.params) { expect(route.params).toEqual({ foo: 'bar', }); } } } else { expect(data[key]).toBe(true); } } } }; const testContextSSR = ($, path) => { $('.context').each((index, element) => { let data; try { data = JSON.parse($(element).text()); } catch (err) { data = {}; } for (const key in data) { if (key === 'route') { const route = data[key]; if (route.hook && /^route/.test(route.hook)) { if (route.url) { expect(route.url).toBe(`${path}/bar?bar=baz`); } if (route.query) { expect(route.query).toEqual({ bar: 'baz', }); } if (route.params) { expect(route.params).toEqual({ foo: 'bar', }); } } } else { expect(data[key]).toBe(true); } } }); }; /** * Simple function to wait */ const wait = time => new Promise(resolve => setTimeout(resolve, time)); module.exports = { wait, goto, gotoSSR, gotoSPA, baseURL, doRequest, isSPA, isMounted, getText, checkText, pageRunTests, pageRunTestsSSR, testContext, testContextSSR, };
Sebastian-Rostock/java.bee-creative
src/main/java/bee/creative/util/HashMapII.java
package bee.creative.util; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Map; import bee.creative.emu.EMU; import bee.creative.lang.Objects; /** Diese Klasse implementiert eine auf {@link AbstractHashMap} aufbauende {@link Map} mit {@link Integer}-Schlüsseln und -Werten sowie geringem * {@link AbstractHashData Speicherverbrauch}. * * @author [cc-by] 2020 <NAME> [http://creativecommons.org/licenses/by/3.0/de/] */ public class HashMapII extends AbstractHashMap<Integer, Integer> implements Serializable, Cloneable { /** Dieses Feld speichert das serialVersionUID. */ private static final long serialVersionUID = -5580543670395051911L; /** Dieses Feld bildet vom Index eines Eintrags auf dessen Schlüssel ab. */ transient int[] keys = AbstractHashData.EMPTY_INTEGERS; /** Dieses Feld bildet vom Index eines Eintrags auf dessen Wert ab. */ transient int[] values = AbstractHashData.EMPTY_INTEGERS; /** Dieser Konstruktor initialisiert die Kapazität mit {@code 0}. */ public HashMapII() { } /** Dieser Konstruktor initialisiert die Kapazität. * * @param capacity Kapazität. */ public HashMapII(final int capacity) { this.allocateImpl(capacity); } /** Dieser Konstruktor initialisiert die {@link HashMapII} mit dem Inhalt der gegebenen {@link Map}. * * @param source gegebene Einträge. */ public HashMapII(final Map<? extends Integer, ? extends Integer> source) { this(source.size()); this.putAll(source); } private void readObject(final ObjectInputStream stream) throws IOException, ClassNotFoundException { final int count = stream.readInt(); this.allocateImpl(count); for (int i = 0; i < count; i++) { final int key = stream.readInt(); final int value = stream.readInt(); this.putImpl(key, value); } } private void writeObject(final ObjectOutputStream stream) throws IOException { stream.writeInt(this.countImpl()); for (final Entry<Integer, Integer> entry: this.newEntriesImpl()) { stream.writeInt(entry.getKey()); stream.writeInt(entry.getValue()); } } @Override protected Integer customGetKey(final int entryIndex) { return this.keys[entryIndex]; } @Override protected Integer customGetValue(final int entryIndex) { return this.values[entryIndex]; } @Override protected void customSetKey(final int entryIndex, final Integer key, final int keyHash) { this.keys[entryIndex] = key; } @Override protected Integer customSetValue(final int entryIndex, final Integer value) { final int[] values = this.values; final Integer result = values[entryIndex]; values[entryIndex] = value; return result; } @Override protected int customHash(final Object key) { return Objects.hash(key); } @Override protected int customHashKey(final int entryIndex) { return this.keys[entryIndex]; } @Override protected int customHashValue(final int entryIndex) { return Objects.hash(this.values[entryIndex]); } @Override protected boolean customEqualsKey(final int entryIndex, final Object key) { return (key instanceof Integer) && (((Integer)key).intValue() == this.keys[entryIndex]); } @Override protected boolean customEqualsValue(final int entryIndex, final Object value) { return Objects.equals(this.values[entryIndex], value); } @Override protected HashAllocator customAllocator(final int capacity) { final int[] keys2; final int[] values2; if (capacity == 0) { keys2 = AbstractHashData.EMPTY_INTEGERS; values2 = AbstractHashData.EMPTY_INTEGERS; } else { keys2 = new int[capacity]; values2 = new int[capacity]; } return new HashAllocator() { @Override public void copy(final int sourceIndex, final int targetIndex) { keys2[targetIndex] = HashMapII.this.keys[sourceIndex]; values2[targetIndex] = HashMapII.this.values[sourceIndex]; } @Override public void apply() { HashMapII.this.keys = keys2; HashMapII.this.values = values2; } }; } @Override public Integer put(final Integer key, final Integer value) { return super.put(Objects.notNull(key), Objects.notNull(value)); } /** Diese Methode erhöht den zum gegebenen Schlüssel hinterlegten Wert um das gegebene Inkrement. Wenn noch kein Wert hinterlegt ist, wird das Inkrement * hinterlegt. * * @param key Schlüssel. * @param value Inklement */ public void add(final Integer key, final int value) { final int count = this.countImpl(), index = this.putIndexImpl(key), start = (count != this.countImpl()) ? 0 : this.values[index]; this.values[index] = start + value; } @Override public long emu() { return super.emu() + EMU.fromArray(this.keys) + EMU.fromArray(this.values); } @Override public HashMapII clone() throws CloneNotSupportedException { try { final HashMapII result = (HashMapII)super.clone(); if (this.capacityImpl() == 0) return result; result.keys = this.keys.clone(); result.values = this.values.clone(); return result; } catch (final Exception cause) { throw new CloneNotSupportedException(cause.getMessage()); } } }
springdev-projects/spring-ldap
core/src/test/java/org/springframework/ldap/core/LdapTemplateLookupTest.java
<reponame>springdev-projects/spring-ldap<filename>core/src/test/java/org/springframework/ldap/core/LdapTemplateLookupTest.java /* * Copyright 2005-2016 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 org.springframework.ldap.core; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.Collections; import javax.naming.Name; import javax.naming.NamingException; import javax.naming.directory.BasicAttributes; import javax.naming.directory.DirContext; import javax.naming.ldap.LdapContext; import javax.naming.ldap.LdapName; import org.junit.Before; import org.junit.Test; import org.springframework.ldap.NameNotFoundException; import org.springframework.ldap.odm.core.ObjectDirectoryMapper; import org.springframework.ldap.support.LdapUtils; public class LdapTemplateLookupTest { private static final String DEFAULT_BASE_STRING = "o=example.com"; private ContextSource contextSourceMock; private DirContext dirContextMock; private AttributesMapper attributesMapperMock; private Name nameMock; private ContextMapper contextMapperMock; private LdapTemplate tested; private ObjectDirectoryMapper odmMock; @Before public void setUp() throws Exception { // Setup ContextSource mock contextSourceMock = mock(ContextSource.class); // Setup LdapContext mock dirContextMock = mock(LdapContext.class); // Setup Name mock nameMock = mock(Name.class); contextMapperMock = mock(ContextMapper.class); attributesMapperMock = mock(AttributesMapper.class); odmMock = mock(ObjectDirectoryMapper.class); tested = new LdapTemplate(contextSourceMock); tested.setObjectDirectoryMapper(odmMock); } private void expectGetReadOnlyContext() { when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); } // Tests for lookup(name) @Test public void testLookup() throws Exception { expectGetReadOnlyContext(); Object expected = new Object(); when(dirContextMock.lookup(nameMock)).thenReturn(expected); Object actual = tested.lookup(nameMock); verify(dirContextMock).close(); assertThat(actual).isSameAs(expected); } @Test public void testLookup_String() throws Exception { expectGetReadOnlyContext(); Object expected = new Object(); when(dirContextMock.lookup(DEFAULT_BASE_STRING)).thenReturn(expected); Object actual = tested.lookup(DEFAULT_BASE_STRING); verify(dirContextMock).close(); assertThat(actual).isSameAs(expected); } @Test public void testLookup_NamingException() throws Exception { expectGetReadOnlyContext(); javax.naming.NameNotFoundException ne = new javax.naming.NameNotFoundException(); when(dirContextMock.lookup(nameMock)).thenThrow(ne); try { tested.lookup(nameMock); fail("NameNotFoundException expected"); } catch (NameNotFoundException expected) { assertThat(true).isTrue(); } verify(dirContextMock).close(); } // Tests for lookup(name, AttributesMapper) @Test public void testLookup_AttributesMapper() throws Exception { expectGetReadOnlyContext(); BasicAttributes expectedAttributes = new BasicAttributes(); when(dirContextMock.getAttributes(nameMock)).thenReturn(expectedAttributes); Object expected = new Object(); when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expected); Object actual = tested.lookup(nameMock, attributesMapperMock); verify(dirContextMock).close(); assertThat(actual).isSameAs(expected); } @Test public void testLookup_String_AttributesMapper() throws Exception { expectGetReadOnlyContext(); BasicAttributes expectedAttributes = new BasicAttributes(); when(dirContextMock.getAttributes(DEFAULT_BASE_STRING)).thenReturn(expectedAttributes); Object expected = new Object(); when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expected); Object actual = tested .lookup(DEFAULT_BASE_STRING, attributesMapperMock); verify(dirContextMock).close(); assertThat(actual).isSameAs(expected); } @Test public void testLookup_AttributesMapper_NamingException() throws Exception { expectGetReadOnlyContext(); javax.naming.NameNotFoundException ne = new javax.naming.NameNotFoundException(); when(dirContextMock.getAttributes(nameMock)).thenThrow(ne); try { tested.lookup(nameMock, attributesMapperMock); fail("NameNotFoundException expected"); } catch (NameNotFoundException expected) { assertThat(true).isTrue(); } verify(dirContextMock).close(); } // Tests for lookup(name, ContextMapper) @Test public void testLookup_ContextMapper() throws Exception { expectGetReadOnlyContext(); Object transformed = new Object(); Object expected = new Object(); when(dirContextMock.lookup(nameMock)).thenReturn(expected); when(contextMapperMock.mapFromContext(expected)).thenReturn(transformed); Object actual = tested.lookup(nameMock, contextMapperMock); verify(dirContextMock).close(); assertThat(actual).isSameAs(transformed); } @Test public void testFindByDn() throws NamingException { expectGetReadOnlyContext(); Object transformed = new Object(); Class<Object> expectedClass = Object.class; DirContextAdapter expectedContext = new DirContextAdapter(); when(dirContextMock.lookup(nameMock)).thenReturn(expectedContext); when(odmMock.mapFromLdapDataEntry(expectedContext, expectedClass)).thenReturn(transformed); when(nameMock.getAll()).thenReturn(Collections.<String> enumeration(Collections.<String> emptyList())); // Perform test Object result = tested.findByDn(nameMock, expectedClass); assertThat(result).isSameAs(transformed); verify(odmMock).manageClass(expectedClass); } @Test public void testLookup_String_ContextMapper() throws Exception { expectGetReadOnlyContext(); Object transformed = new Object(); Object expected = new Object(); when(dirContextMock.lookup(DEFAULT_BASE_STRING)).thenReturn(expected); when(contextMapperMock.mapFromContext(expected)).thenReturn(transformed); Object actual = tested.lookup(DEFAULT_BASE_STRING, contextMapperMock); verify(dirContextMock).close(); assertThat(actual).isSameAs(transformed); } @Test public void testLookup_ContextMapper_NamingException() throws Exception { expectGetReadOnlyContext(); javax.naming.NameNotFoundException ne = new javax.naming.NameNotFoundException(); when(dirContextMock.lookup(nameMock)).thenThrow(ne); try { tested.lookup(nameMock, contextMapperMock); fail("NameNotFoundException expected"); } catch (NameNotFoundException expected) { assertThat(true).isTrue(); } verify(dirContextMock).close(); } // Tests for lookup(name, attributes, AttributesMapper) @Test public void testLookup_ReturnAttributes_AttributesMapper() throws Exception { expectGetReadOnlyContext(); String[] attributeNames = new String[] { "cn" }; BasicAttributes expectedAttributes = new BasicAttributes(); expectedAttributes.put("cn", "Some Name"); when(dirContextMock.getAttributes(nameMock, attributeNames)).thenReturn(expectedAttributes); Object expected = new Object(); when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expected); Object actual = tested.lookup(nameMock, attributeNames, attributesMapperMock); verify(dirContextMock).close(); assertThat(actual).isSameAs(expected); } @Test public void testLookup_String_ReturnAttributes_AttributesMapper() throws Exception { expectGetReadOnlyContext(); String[] attributeNames = new String[] { "cn" }; BasicAttributes expectedAttributes = new BasicAttributes(); expectedAttributes.put("cn", "Some Name"); when(dirContextMock.getAttributes(DEFAULT_BASE_STRING, attributeNames)).thenReturn(expectedAttributes); Object expected = new Object(); when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expected); Object actual = tested.lookup(DEFAULT_BASE_STRING, attributeNames, attributesMapperMock); verify(dirContextMock).close(); assertThat(actual).isSameAs(expected); } // Tests for lookup(name, attributes, ContextMapper) @Test public void testLookup_ReturnAttributes_ContextMapper() throws Exception { expectGetReadOnlyContext(); String[] attributeNames = new String[] { "cn" }; BasicAttributes expectedAttributes = new BasicAttributes(); expectedAttributes.put("cn", "<NAME>"); LdapName name = LdapUtils.newLdapName(DEFAULT_BASE_STRING); DirContextAdapter adapter = new DirContextAdapter(expectedAttributes, name); when(dirContextMock.getAttributes(name,attributeNames)).thenReturn(expectedAttributes); Object transformed = new Object(); when(contextMapperMock.mapFromContext(adapter)).thenReturn(transformed); Object actual = tested.lookup(name, attributeNames, contextMapperMock); verify(dirContextMock).close(); assertThat(actual).isSameAs(transformed); } @Test public void testLookup_String_ReturnAttributes_ContextMapper() throws Exception { expectGetReadOnlyContext(); String[] attributeNames = new String[] { "cn" }; BasicAttributes expectedAttributes = new BasicAttributes(); expectedAttributes.put("cn", "Some Name"); when(dirContextMock.getAttributes(DEFAULT_BASE_STRING, attributeNames)).thenReturn(expectedAttributes); LdapName name = LdapUtils.newLdapName(DEFAULT_BASE_STRING); DirContextAdapter adapter = new DirContextAdapter(expectedAttributes, name); Object transformed = new Object(); when(contextMapperMock.mapFromContext(adapter)).thenReturn(transformed); Object actual = tested.lookup(DEFAULT_BASE_STRING, attributeNames, contextMapperMock); verify(dirContextMock).close(); assertThat(actual).isSameAs(transformed); } }
anatolse/beam
3rdparty/libbitcoin/include/bitcoin/bitcoin/machine/script_pattern.hpp
/** * Copyright (c) 2011-2017 libbitcoin developers (see AUTHORS) * * This file is part of libbitcoin. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef LIBBITCOIN_MACHINE_SCRIPT_PATTERN_HPP #define LIBBITCOIN_MACHINE_SCRIPT_PATTERN_HPP namespace libbitcoin { namespace machine { /// Script patterms. /// Comments from: bitcoin.org/en/developer-guide#signature-hash-types enum class script_pattern { /// Null Data /// Pubkey Script: OP_RETURN <0 to 80 bytes of data> (formerly 40 bytes) /// Null data scripts cannot be spent, so there's no signature script. null_data, /// Pay to Multisig [BIP11] /// Pubkey script: <m> <A pubkey>[B pubkey][C pubkey...] <n> OP_CHECKMULTISIG /// Signature script: OP_0 <A sig>[B sig][C sig...] pay_multisig, /// Pay to Public Key (obsolete) pay_public_key, /// Pay to Public Key Hash [P2PKH] /// Pubkey script: OP_DUP OP_HASH160 <PubKeyHash> OP_EQUALVERIFY OP_CHECKSIG /// Signature script: <sig> <pubkey> pay_key_hash, /// Pay to Script Hash [P2SH/BIP16] /// The redeem script may be any pay type, but only multisig makes sense. /// Pubkey script: OP_HASH160 <Hash160(redeemScript)> OP_EQUAL /// Signature script: <sig>[sig][sig...] <redeemScript> pay_script_hash, /// Sign Multisig script [BIP11] sign_multisig, /// Sign Public Key (obsolete) sign_public_key, /// Sign Public Key Hash [P2PKH] sign_key_hash, /// Sign Script Hash [P2SH/BIP16] sign_script_hash, /// Witness coinbase reserved value [BIP141]. witness_reservation, /// The script may be valid but does not conform to the common templates. /// Such scripts are always accepted if they are mined into blocks, but /// transactions with uncommon scripts may not be forwarded by peers. non_standard }; } // namespace machine } // namespace libbitcoin #endif
mcombell/tuscany-sca
modules/implementation-node-runtime/src/main/java/org/apache/tuscany/sca/implementation/node/provider/NodeImplementationProvider.java
<reponame>mcombell/tuscany-sca<gh_stars>1-10 /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.tuscany.sca.implementation.node.provider; import org.apache.tuscany.sca.implementation.node.NodeImplementation; import org.apache.tuscany.sca.interfacedef.Operation; import org.apache.tuscany.sca.invocation.Invoker; import org.apache.tuscany.sca.provider.ImplementationProvider; import org.apache.tuscany.sca.runtime.RuntimeComponent; import org.apache.tuscany.sca.runtime.RuntimeComponentService; /** * An implementation provider for node component implementations. * * @version $Rev$ $Date$ */ class NodeImplementationProvider implements ImplementationProvider { private NodeImplementation implementation; /** * Constructs a new node implementation provider. * * @param component * @param implementation */ NodeImplementationProvider(RuntimeComponent component, NodeImplementation implementation) { this.implementation = implementation; } public Invoker createInvoker(RuntimeComponentService service, Operation operation) { NodeImplementationInvoker invoker = new NodeImplementationInvoker(implementation.getComposite()); return invoker; } public boolean supportsOneWayInvocation() { return false; } public void start() { } public void stop() { } }
SamuelNovak/GJAR_IoT
Frontend/src/hoc/Transitions/FlyIn.js
import React from "react"; import { motion } from "framer-motion"; const FlyIn = ({ children, slideUp = 0, delay = 0, className }) => { return ( <motion.div className={className} transition={{ delay: delay, duration: 0.5, times: [0.3, 0.6, 1] }} initial={{ opacity: 0, y: slideUp }} animate={{ opacity: [0, 1, 1], y: [slideUp, slideUp / 2, 0] }} > {children} </motion.div> ); }; export default FlyIn;
khuctrang/aha
src/pages/404.js
import React from 'react'; import { Button, SafeAnchor } from '@ahaui/react'; import pkg from '../../aha-react/package.json'; import withLayout from '../withLayout'; export default withLayout( class HomePage extends React.Component { render() { return ( <div className="u-flex u-marginTopMedium lg:u-marginTopLarge u-flexColumn"> <div className="Grid"> <div className="u-sizeFull lg:u-size10of12 lg:u-offset1of12"> <div className="u-textCenter"> <div className="u-textPrimary u-text800 u-fontMedium u-textUppercase"> Page not found </div> <div className="u-text400 u-marginTopMedium"> Oops! The page you are looking for has been removed or relocated </div> </div> </div> </div> </div> ); } }, );
DaviVianna/CRUDs
skintrade/crud/backend/api/src/controllers/excluir.js
//required Model const db = require('../models/excluir'); const express = require('express'); const app = express(); app.use(express.json()); const exclude = async (req, res) => { const data = { id: req.params.id } console.log(data); //Instanciando a Model await db.excluirDados(data); res.status(201).send({ codigo: 1, msg: 'Dado excluído corretamente.' }); } module.exports = { exclude }
peintune/springboot-study
spring-bean-post-processor/src/main/java/spring/study/beanpostproessor/embedded/BeanForMethodValidation.java
<filename>spring-bean-post-processor/src/main/java/spring/study/beanpostproessor/embedded/BeanForMethodValidation.java package spring.study.beanpostproessor.embedded; import org.hibernate.validator.constraints.NotEmpty; import org.springframework.stereotype.Component; import org.springframework.validation.annotation.Validated; import javax.validation.constraints.Min; /** * Created by Format on 2017/6/23. */ @Component @Validated public class BeanForMethodValidation { public void validate(@NotEmpty String name, @Min(10) int age) { System.err.println("validate, name: " + name + ", age: " + age); } }
akquinet/drools
drools-verifier/src/main/java/org/drools/verifier/misc/DrlPackageParser.java
<filename>drools-verifier/src/main/java/org/drools/verifier/misc/DrlPackageParser.java /* * Copyright 2010 JBoss 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 org.drools.verifier.misc; import java.text.ParseException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; public class DrlPackageParser { private static final String packageExpr = "(^\\s*#.*?\\n)?(^\\s*package.*?$)(.*?)"; private static final Pattern finder = Pattern.compile( packageExpr, Pattern.DOTALL | Pattern.MULTILINE ); private static final Pattern globalFinder = Pattern.compile( "(^\\s*global.*?$)", Pattern.DOTALL | Pattern.MULTILINE ); private final String name; private final List<DrlRuleParser> rules; private final String description; private final List<String> metadata; private final Map<String, List<String>> otherInformation; private final List<String> globals; public DrlPackageParser(String packageName, String description, List<DrlRuleParser> rules, List<String> globals, List<String> metadata, Map<String, List<String>> otherInformation) { this.name = packageName; this.description = description; this.rules = rules; this.globals = globals; this.metadata = metadata; this.otherInformation = otherInformation; } public static DrlPackageParser findPackageDataFromDrl(String drl) throws ParseException { // Remove block comments int start = drl.indexOf( "/*" ); while ( start > 0 ) { if ( start >= 0 ) { drl = drl.replace( drl.substring( start, drl.indexOf( "*/", start ) ), "" ); start = drl.indexOf( "/*" ); } } final Matcher m = finder.matcher( drl ); m.find(); String packageNameRow; try { packageNameRow = m.group( 2 ); } catch ( IllegalStateException e ) { throw new ParseException( "DRL string contained no package data.", 0 ); } int indexOfPackage = packageNameRow.indexOf( "package" ); String packageName = packageNameRow.substring( indexOfPackage + "package".length() ).trim(); Comment comment = DrlRuleParser.processComment( m.group( 1 ) ); return new DrlPackageParser( packageName, comment.description, DrlRuleParser.findRulesDataFromDrl( drl ), findGlobals( drl ), comment.metadata, new HashMap<String, List<String>>() ); } public static List<String> findGlobals(String drl) { List<String> globals = new ArrayList<String>(); Matcher gm = globalFinder.matcher( drl ); while ( gm.find() ) { String row = gm.group(); globals.add( row.substring( row.indexOf( "global" ) + "global".length() ).trim() ); } return globals; } static Comment processComment(String text) { Comment comment = new Comment(); if ( text == null ) { comment.description = ""; comment.metadata = new ArrayList<String>(); return comment; } comment.description = text.replaceAll( "#", "" ).trim(); comment.metadata = findMetaData( text ); return comment; } private static List<String> findMetaData(String text) { List<String> list = new ArrayList<String>(); while ( text.contains( "@" ) ) { int start = text.indexOf( '@' ); text = text.substring( start + 1 ); int end = text.indexOf( "\n" ); list.add( text.substring( 0, end ) ); text = text.substring( end ); } return list; } public String getName() { return name; } public List<DrlRuleParser> getRules() { return rules; } public String getDescription() { return description; } public List<String> getMetadata() { return metadata; } public Map<String, List<String>> getOtherInformation() { return otherInformation; } public List<String> getGlobals() { return globals; } }
billwert/azure-sdk-for-java
sdk/policyinsights/azure-resourcemanager-policyinsights/src/samples/java/com/azure/resourcemanager/policyinsights/generated/PolicyEventsListQueryResultsForSubscriptionLevelPolicyAssignmentSamples.java
<gh_stars>1000+ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.policyinsights.generated; import com.azure.core.util.Context; /** Samples for PolicyEvents ListQueryResultsForSubscriptionLevelPolicyAssignment. */ public final class PolicyEventsListQueryResultsForSubscriptionLevelPolicyAssignmentSamples { /* * x-ms-original-file: specification/policyinsights/resource-manager/Microsoft.PolicyInsights/stable/2019-10-01/examples/PolicyEvents_QuerySubscriptionLevelPolicyAssignmentScope.json */ /** * Sample code: Query at subscription level policy assignment scope. * * @param manager Entry point to PolicyInsightsManager. */ public static void queryAtSubscriptionLevelPolicyAssignmentScope( com.azure.resourcemanager.policyinsights.PolicyInsightsManager manager) { manager .policyEvents() .listQueryResultsForSubscriptionLevelPolicyAssignment( "fffedd8f-ffff-fffd-fffd-fffed2f84852", "ec8f9645-8ecb-4abb-9c0b-5292f19d4003", null, null, null, null, null, null, null, null, Context.NONE); } /* * x-ms-original-file: specification/policyinsights/resource-manager/Microsoft.PolicyInsights/stable/2019-10-01/examples/PolicyEvents_QuerySubscriptionLevelPolicyAssignmentScopeNextLink.json */ /** * Sample code: Query at subscription level policy assignment scope with next link. * * @param manager Entry point to PolicyInsightsManager. */ public static void queryAtSubscriptionLevelPolicyAssignmentScopeWithNextLink( com.azure.resourcemanager.policyinsights.PolicyInsightsManager manager) { manager .policyEvents() .listQueryResultsForSubscriptionLevelPolicyAssignment( "fffedd8f-ffff-fffd-fffd-fffed2f84852", "ec8f9645-8ecb-4abb-9c0b-5292f19d4003", null, null, null, null, null, null, null, "WpmWfBSvPhkAK6QD", Context.NONE); } }
SINTEF/simapy
src/sima/simo/wasimresultexport.py
# This an autogenerated file # # Generated with WasimResultExport from __future__ import annotations from typing import Dict,Sequence,List from dmt.entity import Entity from dmt.blueprint import Blueprint from .blueprints.wasimresultexport import WasimResultExportBlueprint from typing import Dict from sima.sima.moao import MOAO from sima.sima.scriptablevalue import ScriptableValue from sima.simo.bodyforcecomponentreference import BodyForceComponentReference from typing import TYPE_CHECKING if TYPE_CHECKING: from sima.simo.simobody import SIMOBody class WasimResultExport(MOAO): """ Keyword arguments ----------------- name : str (default "") description : str (default "") _id : str (default "") scriptableValues : List[ScriptableValue] floaterBody : SIMOBody pointForces : List[BodyForceComponentReference] maxNumberOfWaveComponents : int Limit the number of wave components exported to file(default 0) """ def __init__(self , name="", description="", _id="", maxNumberOfWaveComponents=0, **kwargs): super().__init__(**kwargs) self.name = name self.description = description self._id = _id self.scriptableValues = list() self.floaterBody = None self.pointForces = list() self.maxNumberOfWaveComponents = maxNumberOfWaveComponents for key, value in kwargs.items(): if not isinstance(value, Dict): setattr(self, key, value) @property def blueprint(self) -> Blueprint: """Return blueprint that this entity represents""" return WasimResultExportBlueprint() @property def name(self) -> str: """""" return self.__name @name.setter def name(self, value: str): """Set name""" self.__name = str(value) @property def description(self) -> str: """""" return self.__description @description.setter def description(self, value: str): """Set description""" self.__description = str(value) @property def _id(self) -> str: """""" return self.___id @_id.setter def _id(self, value: str): """Set _id""" self.___id = str(value) @property def scriptableValues(self) -> List[ScriptableValue]: """""" return self.__scriptableValues @scriptableValues.setter def scriptableValues(self, value: List[ScriptableValue]): """Set scriptableValues""" if not isinstance(value, Sequence): raise Exception("Expected sequense, but was " , type(value)) self.__scriptableValues = value @property def floaterBody(self) -> SIMOBody: """""" return self.__floaterBody @floaterBody.setter def floaterBody(self, value: SIMOBody): """Set floaterBody""" self.__floaterBody = value @property def pointForces(self) -> List[BodyForceComponentReference]: """""" return self.__pointForces @pointForces.setter def pointForces(self, value: List[BodyForceComponentReference]): """Set pointForces""" if not isinstance(value, Sequence): raise Exception("Expected sequense, but was " , type(value)) self.__pointForces = value @property def maxNumberOfWaveComponents(self) -> int: """Limit the number of wave components exported to file""" return self.__maxNumberOfWaveComponents @maxNumberOfWaveComponents.setter def maxNumberOfWaveComponents(self, value: int): """Set maxNumberOfWaveComponents""" self.__maxNumberOfWaveComponents = int(value)
isabella232/tessapi
4.0.0/a03438.js
var a03438 = [ [ "base", "a03438.html#a7b43dfaccfaccaaf09d7e957b8504435", null ], [ "FunctionSignature", "a03438.html#a46f407132044b55d0848b71a57a3c922", null ], [ "_TessFunctionResultCallback_1_3", "a03438.html#a0b896d13eaa9374abdd337aa51ba0d74", null ], [ "Run", "a03438.html#a98f1d7285c6f2002f77c2a4f063efd16", null ] ];
Y-D-Lu/rr_frameworks_base
services/tests/uiservicestests/src/com/android/server/notification/ZenModeHelperTest.java
<filename>services/tests/uiservicestests/src/com/android/server/notification/ZenModeHelperTest.java<gh_stars>0 /* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distriZenbuted 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.android.server.notification; import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_BADGE; import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_FULL_SCREEN_INTENT; import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_LIGHTS; import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_PEEK; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertEquals; import static junit.framework.TestCase.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import android.app.AppGlobals; import android.app.AppOpsManager; import android.app.NotificationManager; import android.content.ComponentName; import android.content.ContentResolver; import android.content.Context; import android.content.res.Resources; import android.media.AudioAttributes; import android.media.AudioManager; import android.media.AudioManagerInternal; import android.media.VolumePolicy; import android.media.AudioSystem; import android.net.Uri; import android.provider.Settings; import android.provider.Settings.Global; import android.service.notification.Condition; import android.service.notification.ZenModeConfig; import android.service.notification.ZenModeConfig.ScheduleInfo; import android.test.suitebuilder.annotation.SmallTest; import android.testing.AndroidTestingRunner; import android.testing.TestableLooper; import android.util.ArrayMap; import android.util.Xml; import com.android.internal.R; import com.android.internal.messages.nano.SystemMessageProto.SystemMessage; import com.android.server.notification.ManagedServices.UserProfiles; import com.android.internal.util.FastXmlSerializer; import com.android.server.UiServiceTestCase; import android.util.Slog; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlSerializer; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @SmallTest @RunWith(AndroidTestingRunner.class) @TestableLooper.RunWithLooper public class ZenModeHelperTest extends UiServiceTestCase { ConditionProviders mConditionProviders; @Mock NotificationManager mNotificationManager; @Mock private Resources mResources; private TestableLooper mTestableLooper; private ZenModeHelper mZenModeHelperSpy; private Context mContext; private ContentResolver mContentResolver; @Before public void setUp() { MockitoAnnotations.initMocks(this); mTestableLooper = TestableLooper.get(this); mContext = spy(getContext()); mContentResolver = mContext.getContentResolver(); when(mContext.getResources()).thenReturn(mResources); when(mResources.getString(R.string.zen_mode_default_every_night_name)).thenReturn("night"); when(mResources.getString(R.string.zen_mode_default_events_name)).thenReturn("events"); when(mContext.getSystemService(NotificationManager.class)).thenReturn(mNotificationManager); mConditionProviders = new ConditionProviders(mContext, new UserProfiles(), AppGlobals.getPackageManager()); mConditionProviders.addSystemProvider(new CountdownConditionProvider()); mZenModeHelperSpy = spy(new ZenModeHelper(mContext, mTestableLooper.getLooper(), mConditionProviders)); } private ByteArrayOutputStream writeXmlAndPurge(boolean forBackup, Integer version) throws Exception { XmlSerializer serializer = new FastXmlSerializer(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); serializer.setOutput(new BufferedOutputStream(baos), "utf-8"); serializer.startDocument(null, true); mZenModeHelperSpy.writeXml(serializer, forBackup, version); serializer.endDocument(); serializer.flush(); mZenModeHelperSpy.setConfig(new ZenModeConfig(), null, "writing xml"); return baos; } @Test public void testZenOff_NoMuteApplied() { mZenModeHelperSpy.mZenMode = Settings.Global.ZEN_MODE_OFF; assertTrue(mZenModeHelperSpy.mConfig.allowAlarms); mZenModeHelperSpy.applyRestrictions(); doNothing().when(mZenModeHelperSpy).applyRestrictions(anyBoolean(), anyInt()); verify(mZenModeHelperSpy, atLeastOnce()).applyRestrictions(false, AudioAttributes.USAGE_ALARM); verify(mZenModeHelperSpy, atLeastOnce()).applyRestrictions(false, AudioAttributes.USAGE_MEDIA); } @Test public void testZenOn_AllowAlarmsMedia_NoAlarmMediaMuteApplied() { mZenModeHelperSpy.mZenMode = Settings.Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS; assertTrue(mZenModeHelperSpy.mConfig.allowAlarms); assertTrue(mZenModeHelperSpy.mConfig.allowMedia); mZenModeHelperSpy.applyRestrictions(); verify(mZenModeHelperSpy, atLeastOnce()).applyRestrictions(false, AudioAttributes.USAGE_ALARM); verify(mZenModeHelperSpy, atLeastOnce()).applyRestrictions(false, AudioAttributes.USAGE_MEDIA); } @Test public void testZenOn_DisallowAlarmsMedia_AlarmMediaMuteApplied() { mZenModeHelperSpy.mZenMode = Settings.Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS; mZenModeHelperSpy.mConfig.allowAlarms = false; mZenModeHelperSpy.mConfig.allowMedia = false; mZenModeHelperSpy.mConfig.allowSystem = false; assertFalse(mZenModeHelperSpy.mConfig.allowAlarms); assertFalse(mZenModeHelperSpy.mConfig.allowMedia); assertFalse(mZenModeHelperSpy.mConfig.allowSystem); mZenModeHelperSpy.applyRestrictions(); verify(mZenModeHelperSpy, atLeastOnce()).applyRestrictions(true, AudioAttributes.USAGE_ALARM); // Media is a catch-all that includes games verify(mZenModeHelperSpy, atLeastOnce()).applyRestrictions(true, AudioAttributes.USAGE_MEDIA); verify(mZenModeHelperSpy, atLeastOnce()).applyRestrictions(true, AudioAttributes.USAGE_GAME); } @Test public void testTotalSilence() { mZenModeHelperSpy.mZenMode = Settings.Global.ZEN_MODE_NO_INTERRUPTIONS; mZenModeHelperSpy.applyRestrictions(); // Total silence will silence alarms, media and system noises (but not vibrations) verify(mZenModeHelperSpy, atLeastOnce()).applyRestrictions(true, AudioAttributes.USAGE_ALARM); verify(mZenModeHelperSpy, atLeastOnce()).applyRestrictions(true, AudioAttributes.USAGE_MEDIA); verify(mZenModeHelperSpy, atLeastOnce()).applyRestrictions(true, AudioAttributes.USAGE_GAME); verify(mZenModeHelperSpy, atLeastOnce()).applyRestrictions(true, AudioAttributes.USAGE_ASSISTANCE_SONIFICATION, AppOpsManager.OP_PLAY_AUDIO); verify(mZenModeHelperSpy, atLeastOnce()).applyRestrictions(false, AudioAttributes.USAGE_ASSISTANCE_SONIFICATION, AppOpsManager.OP_VIBRATE); verify(mZenModeHelperSpy, atLeastOnce()).applyRestrictions(true, AudioAttributes.USAGE_UNKNOWN); } @Test public void testAlarmsOnly_alarmMediaMuteNotApplied() { mZenModeHelperSpy.mZenMode = Settings.Global.ZEN_MODE_ALARMS; mZenModeHelperSpy.mConfig.allowAlarms = false; mZenModeHelperSpy.mConfig.allowSystem = false; mZenModeHelperSpy.mConfig.allowMedia = false; assertFalse(mZenModeHelperSpy.mConfig.allowAlarms); assertFalse(mZenModeHelperSpy.mConfig.allowMedia); mZenModeHelperSpy.applyRestrictions(); // Alarms only mode will not silence alarms verify(mZenModeHelperSpy, atLeastOnce()).applyRestrictions(false, AudioAttributes.USAGE_ALARM); // Alarms only mode will not silence media verify(mZenModeHelperSpy, atLeastOnce()).applyRestrictions(false, AudioAttributes.USAGE_MEDIA); verify(mZenModeHelperSpy, atLeastOnce()).applyRestrictions(false, AudioAttributes.USAGE_GAME); verify(mZenModeHelperSpy, atLeastOnce()).applyRestrictions(false, AudioAttributes.USAGE_UNKNOWN); // Alarms only will silence system noises (but not vibrations) verify(mZenModeHelperSpy, atLeastOnce()).applyRestrictions(true, AudioAttributes.USAGE_ASSISTANCE_SONIFICATION, AppOpsManager.OP_PLAY_AUDIO); } @Test public void testAlarmsOnly_callsMuteApplied() { mZenModeHelperSpy.mZenMode = Settings.Global.ZEN_MODE_ALARMS; mZenModeHelperSpy.mConfig.allowCalls = true; assertTrue(mZenModeHelperSpy.mConfig.allowCalls); mZenModeHelperSpy.applyRestrictions(); // Alarms only mode will silence calls despite priority-mode config verify(mZenModeHelperSpy, atLeastOnce()).applyRestrictions(true, AudioAttributes.USAGE_NOTIFICATION_RINGTONE); verify(mZenModeHelperSpy, atLeastOnce()).applyRestrictions(true, AudioAttributes.USAGE_NOTIFICATION_COMMUNICATION_REQUEST); } @Test public void testAlarmsOnly_allZenConfigToggledCannotBypass_alarmMuteNotApplied() { // Only audio attributes with SUPPRESIBLE_NEVER can bypass mZenModeHelperSpy.mZenMode = Settings.Global.ZEN_MODE_ALARMS; mZenModeHelperSpy.mConfig.allowAlarms = false; mZenModeHelperSpy.mConfig.allowMedia = false; mZenModeHelperSpy.mConfig.allowSystem = false; mZenModeHelperSpy.mConfig.allowReminders = false; mZenModeHelperSpy.mConfig.allowCalls = false; mZenModeHelperSpy.mConfig.allowMessages = false; mZenModeHelperSpy.mConfig.allowEvents = false; mZenModeHelperSpy.mConfig.allowRepeatCallers= false; assertFalse(mZenModeHelperSpy.mConfig.allowAlarms); assertFalse(mZenModeHelperSpy.mConfig.allowMedia); assertFalse(mZenModeHelperSpy.mConfig.allowReminders); assertFalse(mZenModeHelperSpy.mConfig.allowCalls); assertFalse(mZenModeHelperSpy.mConfig.allowMessages); assertFalse(mZenModeHelperSpy.mConfig.allowEvents); assertFalse(mZenModeHelperSpy.mConfig.allowRepeatCallers); mZenModeHelperSpy.applyRestrictions(); verify(mZenModeHelperSpy, atLeastOnce()).applyRestrictions(false, AudioAttributes.USAGE_ALARM); } @Test public void testZenAllCannotBypass() { // Only audio attributes with SUPPRESIBLE_NEVER can bypass // with special case USAGE_ASSISTANCE_SONIFICATION mZenModeHelperSpy.mZenMode = Settings.Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS; mZenModeHelperSpy.mConfig.allowAlarms = false; mZenModeHelperSpy.mConfig.allowMedia = false; mZenModeHelperSpy.mConfig.allowSystem = false; mZenModeHelperSpy.mConfig.allowReminders = false; mZenModeHelperSpy.mConfig.allowCalls = false; mZenModeHelperSpy.mConfig.allowMessages = false; mZenModeHelperSpy.mConfig.allowEvents = false; mZenModeHelperSpy.mConfig.allowRepeatCallers= false; assertFalse(mZenModeHelperSpy.mConfig.allowAlarms); assertFalse(mZenModeHelperSpy.mConfig.allowMedia); assertFalse(mZenModeHelperSpy.mConfig.allowReminders); assertFalse(mZenModeHelperSpy.mConfig.allowCalls); assertFalse(mZenModeHelperSpy.mConfig.allowMessages); assertFalse(mZenModeHelperSpy.mConfig.allowEvents); assertFalse(mZenModeHelperSpy.mConfig.allowRepeatCallers); mZenModeHelperSpy.applyRestrictions(); for (int usage : AudioAttributes.SDK_USAGES) { if (usage == AudioAttributes.USAGE_ASSISTANCE_SONIFICATION) { // only mute audio, not vibrations verify(mZenModeHelperSpy, atLeastOnce()).applyRestrictions(true, usage, AppOpsManager.OP_PLAY_AUDIO); verify(mZenModeHelperSpy, atLeastOnce()).applyRestrictions(false, usage, AppOpsManager.OP_VIBRATE); } else { boolean shouldMute = AudioAttributes.SUPPRESSIBLE_USAGES.get(usage) != AudioAttributes.SUPPRESSIBLE_NEVER; verify(mZenModeHelperSpy, atLeastOnce()).applyRestrictions(shouldMute, usage); } } } @Test public void testZenUpgradeNotification() { // shows zen upgrade notification if stored settings says to shows, boot is completed // and we're setting zen mode on Settings.Global.putInt(mContentResolver, Settings.Global.SHOW_ZEN_UPGRADE_NOTIFICATION, 1); mZenModeHelperSpy.mIsBootComplete = true; mZenModeHelperSpy.setZenModeSetting(Settings.Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS); verify(mZenModeHelperSpy, times(1)).createZenUpgradeNotification(); verify(mNotificationManager, times(1)).notify(eq(ZenModeHelper.TAG), eq(SystemMessage.NOTE_ZEN_UPGRADE), any()); assertEquals(0, Settings.Global.getInt(mContentResolver, Settings.Global.SHOW_ZEN_UPGRADE_NOTIFICATION, -1)); } @Test public void testNoZenUpgradeNotification() { // doesn't show upgrade notification if stored settings says don't show Settings.Global.putInt(mContentResolver, Settings.Global.SHOW_ZEN_UPGRADE_NOTIFICATION, 0); mZenModeHelperSpy.mIsBootComplete = true; mZenModeHelperSpy.setZenModeSetting(Settings.Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS); verify(mZenModeHelperSpy, never()).createZenUpgradeNotification(); verify(mNotificationManager, never()).notify(eq(ZenModeHelper.TAG), eq(SystemMessage.NOTE_ZEN_UPGRADE), any()); } @Test public void testZenSetInternalRinger_AllPriorityNotificationSoundsMuted() { AudioManagerInternal mAudioManager = mock(AudioManagerInternal.class); mZenModeHelperSpy.mAudioManager = mAudioManager; Global.putString(mContext.getContentResolver(), Global.ZEN_MODE_RINGER_LEVEL, Integer.toString(AudioManager.RINGER_MODE_NORMAL)); // 1. Current ringer is normal when(mAudioManager.getRingerModeInternal()).thenReturn(AudioManager.RINGER_MODE_NORMAL); // Set zen to priority-only with all notification sounds muted (so ringer will be muted) mZenModeHelperSpy.mZenMode = Settings.Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS; mZenModeHelperSpy.mConfig.allowReminders = false; mZenModeHelperSpy.mConfig.allowCalls = false; mZenModeHelperSpy.mConfig.allowMessages = false; mZenModeHelperSpy.mConfig.allowEvents = false; mZenModeHelperSpy.mConfig.allowRepeatCallers= false; // 2. apply priority only zen - verify ringer is unchanged mZenModeHelperSpy.applyZenToRingerMode(); verify(mAudioManager, never()).setRingerModeInternal(AudioManager.RINGER_MODE_SILENT, mZenModeHelperSpy.TAG); // 3. apply zen off - verify zen is set to previous ringer (normal) when(mAudioManager.getRingerModeInternal()).thenReturn(AudioManager.RINGER_MODE_SILENT); mZenModeHelperSpy.mZenMode = Global.ZEN_MODE_OFF; mZenModeHelperSpy.applyZenToRingerMode(); verify(mAudioManager, atLeastOnce()).setRingerModeInternal(AudioManager.RINGER_MODE_NORMAL, mZenModeHelperSpy.TAG); } @Test public void testRingerAffectedStreamsTotalSilence() { // in total silence: // ringtone, notification, system, alarm, streams, music are affected by ringer mode mZenModeHelperSpy.mZenMode = Settings.Global.ZEN_MODE_NO_INTERRUPTIONS; ZenModeHelper.RingerModeDelegate ringerModeDelegate = mZenModeHelperSpy.new RingerModeDelegate(); int ringerModeAffectedStreams = ringerModeDelegate.getRingerModeAffectedStreams(0); assertTrue((ringerModeAffectedStreams & (1 << AudioSystem.STREAM_RING)) != 0); assertTrue((ringerModeAffectedStreams & (1 << AudioSystem.STREAM_NOTIFICATION)) != 0); assertTrue((ringerModeAffectedStreams & (1 << AudioSystem.STREAM_SYSTEM)) != 0); assertTrue((ringerModeAffectedStreams & (1 << AudioSystem.STREAM_ALARM)) != 0); assertTrue((ringerModeAffectedStreams & (1 << AudioSystem.STREAM_MUSIC)) != 0); } @Test public void testRingerAffectedStreamsPriorityOnly() { // in priority only mode: // ringtone, notification and system streams are affected by ringer mode // UNLESS ringer is muted due to all the other priority only dnd sounds being muted mZenModeHelperSpy.mConfig.allowAlarms = true; mZenModeHelperSpy.mConfig.allowReminders = true; mZenModeHelperSpy.mZenMode = Settings.Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS; ZenModeHelper.RingerModeDelegate ringerModeDelegateRingerMuted = mZenModeHelperSpy.new RingerModeDelegate(); int ringerModeAffectedStreams = ringerModeDelegateRingerMuted.getRingerModeAffectedStreams(0); assertTrue((ringerModeAffectedStreams & (1 << AudioSystem.STREAM_RING)) != 0); assertTrue((ringerModeAffectedStreams & (1 << AudioSystem.STREAM_NOTIFICATION)) != 0); assertTrue((ringerModeAffectedStreams & (1 << AudioSystem.STREAM_SYSTEM)) != 0); assertTrue((ringerModeAffectedStreams & (1 << AudioSystem.STREAM_ALARM)) == 0); assertTrue((ringerModeAffectedStreams & (1 << AudioSystem.STREAM_MUSIC)) == 0); // special case: if ringer is muted (since all notification sounds cannot bypass) // then system stream is not affected by ringer mode mZenModeHelperSpy.mConfig.allowReminders = false; mZenModeHelperSpy.mConfig.allowCalls = false; mZenModeHelperSpy.mConfig.allowMessages = false; mZenModeHelperSpy.mConfig.allowEvents = false; mZenModeHelperSpy.mConfig.allowRepeatCallers= false; ZenModeHelper.RingerModeDelegate ringerModeDelegateRingerNotMuted = mZenModeHelperSpy.new RingerModeDelegate(); int ringerMutedRingerModeAffectedStreams = ringerModeDelegateRingerNotMuted.getRingerModeAffectedStreams(0); assertTrue((ringerMutedRingerModeAffectedStreams & (1 << AudioSystem.STREAM_RING)) != 0); assertTrue((ringerMutedRingerModeAffectedStreams & (1 << AudioSystem.STREAM_NOTIFICATION)) != 0); assertTrue((ringerMutedRingerModeAffectedStreams & (1 << AudioSystem.STREAM_SYSTEM)) == 0); assertTrue((ringerMutedRingerModeAffectedStreams & (1 << AudioSystem.STREAM_ALARM)) == 0); assertTrue((ringerMutedRingerModeAffectedStreams & (1 << AudioSystem.STREAM_MUSIC)) == 0); } @Test public void testZenSetInternalRinger_NotAllPriorityNotificationSoundsMuted_StartNormal() { AudioManagerInternal mAudioManager = mock(AudioManagerInternal.class); mZenModeHelperSpy.mAudioManager = mAudioManager; Global.putString(mContext.getContentResolver(), Global.ZEN_MODE_RINGER_LEVEL, Integer.toString(AudioManager.RINGER_MODE_NORMAL)); // 1. Current ringer is normal when(mAudioManager.getRingerModeInternal()).thenReturn(AudioManager.RINGER_MODE_NORMAL); mZenModeHelperSpy.mZenMode = Settings.Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS; mZenModeHelperSpy.mConfig.allowReminders = true; // 2. apply priority only zen - verify ringer is normal mZenModeHelperSpy.applyZenToRingerMode(); verify(mAudioManager, atLeastOnce()).setRingerModeInternal(AudioManager.RINGER_MODE_NORMAL, mZenModeHelperSpy.TAG); // 3. apply zen off - verify ringer remains normal when(mAudioManager.getRingerModeInternal()).thenReturn(AudioManager.RINGER_MODE_NORMAL); mZenModeHelperSpy.mZenMode = Global.ZEN_MODE_OFF; mZenModeHelperSpy.applyZenToRingerMode(); verify(mAudioManager, atLeastOnce()).setRingerModeInternal(AudioManager.RINGER_MODE_NORMAL, mZenModeHelperSpy.TAG); } @Test public void testZenSetInternalRinger_NotAllPriorityNotificationSoundsMuted_StartSilent() { AudioManagerInternal mAudioManager = mock(AudioManagerInternal.class); mZenModeHelperSpy.mAudioManager = mAudioManager; Global.putString(mContext.getContentResolver(), Global.ZEN_MODE_RINGER_LEVEL, Integer.toString(AudioManager.RINGER_MODE_SILENT)); // 1. Current ringer is silent when(mAudioManager.getRingerModeInternal()).thenReturn(AudioManager.RINGER_MODE_SILENT); mZenModeHelperSpy.mZenMode = Settings.Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS; mZenModeHelperSpy.mConfig.allowReminders = true; // 2. apply priority only zen - verify ringer is silent mZenModeHelperSpy.applyZenToRingerMode(); verify(mAudioManager, atLeastOnce()).setRingerModeInternal(AudioManager.RINGER_MODE_SILENT, mZenModeHelperSpy.TAG); // 3. apply zen-off - verify ringer is still silent when(mAudioManager.getRingerModeInternal()).thenReturn(AudioManager.RINGER_MODE_SILENT); mZenModeHelperSpy.mZenMode = Global.ZEN_MODE_OFF; mZenModeHelperSpy.applyZenToRingerMode(); verify(mAudioManager, atLeastOnce()).setRingerModeInternal(AudioManager.RINGER_MODE_SILENT, mZenModeHelperSpy.TAG); } @Test public void testZenSetInternalRinger_NotAllPriorityNotificationSoundsMuted_RingerChanges() { AudioManagerInternal mAudioManager = mock(AudioManagerInternal.class); mZenModeHelperSpy.mAudioManager = mAudioManager; Global.putString(mContext.getContentResolver(), Global.ZEN_MODE_RINGER_LEVEL, Integer.toString(AudioManager.RINGER_MODE_NORMAL)); // 1. Current ringer is normal when(mAudioManager.getRingerModeInternal()).thenReturn(AudioManager.RINGER_MODE_NORMAL); // Set zen to priority-only with all notification sounds muted (so ringer will be muted) mZenModeHelperSpy.mZenMode = Settings.Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS; mZenModeHelperSpy.mConfig.allowReminders = true; // 2. apply priority only zen - verify zen will still be normal mZenModeHelperSpy.applyZenToRingerMode(); verify(mAudioManager, atLeastOnce()).setRingerModeInternal(AudioManager.RINGER_MODE_NORMAL, mZenModeHelperSpy.TAG); // 3. change ringer from normal to silent, verify previous ringer set to new ringer (silent) ZenModeHelper.RingerModeDelegate ringerModeDelegate = mZenModeHelperSpy.new RingerModeDelegate(); ringerModeDelegate.onSetRingerModeInternal(AudioManager.RINGER_MODE_NORMAL, AudioManager.RINGER_MODE_SILENT, "test", AudioManager.RINGER_MODE_NORMAL, VolumePolicy.DEFAULT); assertEquals(AudioManager.RINGER_MODE_SILENT, Global.getInt(mContext.getContentResolver(), Global.ZEN_MODE_RINGER_LEVEL, AudioManager.RINGER_MODE_NORMAL)); // 4. apply zen off - verify ringer still silenced when(mAudioManager.getRingerModeInternal()).thenReturn(AudioManager.RINGER_MODE_SILENT); mZenModeHelperSpy.mZenMode = Global.ZEN_MODE_OFF; mZenModeHelperSpy.applyZenToRingerMode(); verify(mAudioManager, atLeastOnce()).setRingerModeInternal(AudioManager.RINGER_MODE_SILENT, mZenModeHelperSpy.TAG); } @Test public void testSilentRingerSavedInZenOff_startsZenOff() { AudioManagerInternal mAudioManager = mock(AudioManagerInternal.class); mZenModeHelperSpy.mAudioManager = mAudioManager; // apply zen off multiple times - verify ringer is not set to normal when(mAudioManager.getRingerModeInternal()).thenReturn(AudioManager.RINGER_MODE_SILENT); mZenModeHelperSpy.mZenMode = Global.ZEN_MODE_OFF; mZenModeHelperSpy.mConfig = null; // will evaluate config to zen mode off for (int i = 0; i < 3; i++) { // if zen doesn't change, zen should not reapply itself to the ringer mZenModeHelperSpy.evaluateZenMode("test", true); } verify(mZenModeHelperSpy, never()).applyZenToRingerMode(); verify(mAudioManager, never()).setRingerModeInternal(AudioManager.RINGER_MODE_NORMAL, mZenModeHelperSpy.TAG); } @Test public void testSilentRingerSavedOnZenOff_startsZenOn() { AudioManagerInternal mAudioManager = mock(AudioManagerInternal.class); mZenModeHelperSpy.mAudioManager = mAudioManager; mZenModeHelperSpy.mZenMode = Global.ZEN_MODE_OFF; // previously set silent ringer ZenModeHelper.RingerModeDelegate ringerModeDelegate = mZenModeHelperSpy.new RingerModeDelegate(); ringerModeDelegate.onSetRingerModeInternal(AudioManager.RINGER_MODE_NORMAL, AudioManager.RINGER_MODE_SILENT, "test", AudioManager.RINGER_MODE_NORMAL, VolumePolicy.DEFAULT); assertEquals(AudioManager.RINGER_MODE_SILENT, Global.getInt(mContext.getContentResolver(), Global.ZEN_MODE_RINGER_LEVEL, AudioManager.RINGER_MODE_NORMAL)); // apply zen off multiple times - verify ringer is not set to normal when(mAudioManager.getRingerModeInternal()).thenReturn(AudioManager.RINGER_MODE_SILENT); mZenModeHelperSpy.mZenMode = Settings.Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS; mZenModeHelperSpy.mConfig = null; // will evaluate config to zen mode off for (int i = 0; i < 3; i++) { // if zen doesn't change, zen should not reapply itself to the ringer mZenModeHelperSpy.evaluateZenMode("test", true); } verify(mZenModeHelperSpy, times(1)).applyZenToRingerMode(); verify(mAudioManager, never()).setRingerModeInternal(AudioManager.RINGER_MODE_NORMAL, mZenModeHelperSpy.TAG); } @Test public void testVibrateRingerSavedOnZenOff_startsZenOn() { AudioManagerInternal mAudioManager = mock(AudioManagerInternal.class); mZenModeHelperSpy.mAudioManager = mAudioManager; mZenModeHelperSpy.mZenMode = Global.ZEN_MODE_OFF; // previously set silent ringer ZenModeHelper.RingerModeDelegate ringerModeDelegate = mZenModeHelperSpy.new RingerModeDelegate(); ringerModeDelegate.onSetRingerModeInternal(AudioManager.RINGER_MODE_NORMAL, AudioManager.RINGER_MODE_VIBRATE, "test", AudioManager.RINGER_MODE_NORMAL, VolumePolicy.DEFAULT); assertEquals(AudioManager.RINGER_MODE_VIBRATE, Global.getInt(mContext.getContentResolver(), Global.ZEN_MODE_RINGER_LEVEL, AudioManager.RINGER_MODE_NORMAL)); // apply zen off multiple times - verify ringer is not set to normal when(mAudioManager.getRingerModeInternal()).thenReturn(AudioManager.RINGER_MODE_VIBRATE); mZenModeHelperSpy.mZenMode = Settings.Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS; mZenModeHelperSpy.mConfig = null; // will evaluate config to zen mode off for (int i = 0; i < 3; i++) { // if zen doesn't change, zen should not reapply itself to the ringer mZenModeHelperSpy.evaluateZenMode("test", true); } verify(mZenModeHelperSpy, times(1)).applyZenToRingerMode(); verify(mAudioManager, never()).setRingerModeInternal(AudioManager.RINGER_MODE_NORMAL, mZenModeHelperSpy.TAG); } @Test public void testParcelConfig() { mZenModeHelperSpy.mZenMode = Settings.Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS; mZenModeHelperSpy.mConfig.allowAlarms = false; mZenModeHelperSpy.mConfig.allowMedia = false; mZenModeHelperSpy.mConfig.allowSystem = false; mZenModeHelperSpy.mConfig.allowReminders = true; mZenModeHelperSpy.mConfig.allowCalls = true; mZenModeHelperSpy.mConfig.allowMessages = true; mZenModeHelperSpy.mConfig.allowEvents = true; mZenModeHelperSpy.mConfig.allowRepeatCallers= true; mZenModeHelperSpy.mConfig.suppressedVisualEffects = SUPPRESSED_EFFECT_BADGE; mZenModeHelperSpy.mConfig.manualRule = new ZenModeConfig.ZenRule(); mZenModeHelperSpy.mConfig.manualRule.component = new ComponentName("a", "a"); mZenModeHelperSpy.mConfig.manualRule.enabled = true; mZenModeHelperSpy.mConfig.manualRule.snoozing = true; ZenModeConfig actual = mZenModeHelperSpy.mConfig.copy(); assertEquals(mZenModeHelperSpy.mConfig, actual); } @Test public void testWriteXml() throws Exception { mZenModeHelperSpy.mZenMode = Settings.Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS; mZenModeHelperSpy.mConfig.allowAlarms = false; mZenModeHelperSpy.mConfig.allowMedia = false; mZenModeHelperSpy.mConfig.allowSystem = false; mZenModeHelperSpy.mConfig.allowReminders = true; mZenModeHelperSpy.mConfig.allowCalls = true; mZenModeHelperSpy.mConfig.allowMessages = true; mZenModeHelperSpy.mConfig.allowEvents = true; mZenModeHelperSpy.mConfig.allowRepeatCallers= true; mZenModeHelperSpy.mConfig.suppressedVisualEffects = SUPPRESSED_EFFECT_BADGE; mZenModeHelperSpy.mConfig.manualRule = new ZenModeConfig.ZenRule(); mZenModeHelperSpy.mConfig.manualRule.zenMode = Settings.Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS; mZenModeHelperSpy.mConfig.manualRule.component = new ComponentName("a", "a"); mZenModeHelperSpy.mConfig.manualRule.enabled = true; mZenModeHelperSpy.mConfig.manualRule.snoozing = true; ZenModeConfig expected = mZenModeHelperSpy.mConfig.copy(); ByteArrayOutputStream baos = writeXmlAndPurge(false, null); XmlPullParser parser = Xml.newPullParser(); parser.setInput(new BufferedInputStream( new ByteArrayInputStream(baos.toByteArray())), null); parser.nextTag(); mZenModeHelperSpy.readXml(parser, false); assertEquals(expected, mZenModeHelperSpy.mConfig); } @Test public void testReadXml() throws Exception { setupZenConfig(); // automatic zen rule is enabled on upgrade so rules should not be overriden by default ArrayMap<String, ZenModeConfig.ZenRule> enabledAutoRule = new ArrayMap<>(); ZenModeConfig.ZenRule customRule = new ZenModeConfig.ZenRule(); final ScheduleInfo weeknights = new ScheduleInfo(); customRule.enabled = true; customRule.name = "Custom Rule"; customRule.zenMode = Settings.Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS; customRule.conditionId = ZenModeConfig.toScheduleConditionId(weeknights); enabledAutoRule.put("customRule", customRule); mZenModeHelperSpy.mConfig.automaticRules = enabledAutoRule; ZenModeConfig expected = mZenModeHelperSpy.mConfig.copy(); // set previous version ByteArrayOutputStream baos = writeXmlAndPurge(false, 5); XmlPullParser parser = Xml.newPullParser(); parser.setInput(new BufferedInputStream( new ByteArrayInputStream(baos.toByteArray())), null); parser.nextTag(); mZenModeHelperSpy.readXml(parser, false); assertTrue(mZenModeHelperSpy.mConfig.automaticRules.containsKey("customRule")); setupZenConfigMaintained(); } @Test public void testMigrateSuppressedVisualEffects_oneExistsButOff() throws Exception { String xml = "<zen version=\"6\" user=\"0\">\n" + "<allow calls=\"false\" repeatCallers=\"false\" messages=\"true\" " + "reminders=\"false\" events=\"false\" callsFrom=\"1\" messagesFrom=\"2\" " + "visualScreenOff=\"false\" alarms=\"true\" " + "media=\"true\" system=\"false\" />\n" + "<disallow visualEffects=\"511\" />" + "</zen>"; XmlPullParser parser = Xml.newPullParser(); parser.setInput(new BufferedInputStream( new ByteArrayInputStream(xml.getBytes())), null); parser.nextTag(); mZenModeHelperSpy.readXml(parser, false); assertEquals(0, mZenModeHelperSpy.mConfig.suppressedVisualEffects); xml = "<zen version=\"6\" user=\"0\">\n" + "<allow calls=\"false\" repeatCallers=\"false\" messages=\"true\" " + "reminders=\"false\" events=\"false\" callsFrom=\"1\" messagesFrom=\"2\" " + "visualScreenOn=\"false\" alarms=\"true\" " + "media=\"true\" system=\"false\" />\n" + "<disallow visualEffects=\"511\" />" + "</zen>"; parser = Xml.newPullParser(); parser.setInput(new BufferedInputStream( new ByteArrayInputStream(xml.getBytes())), null); parser.nextTag(); mZenModeHelperSpy.readXml(parser, false); assertEquals(0, mZenModeHelperSpy.mConfig.suppressedVisualEffects); } @Test public void testMigrateSuppressedVisualEffects_bothExistButOff() throws Exception { String xml = "<zen version=\"6\" user=\"0\">\n" + "<allow calls=\"false\" repeatCallers=\"false\" messages=\"true\" " + "reminders=\"false\" events=\"false\" callsFrom=\"1\" messagesFrom=\"2\" " + "visualScreenOff=\"false\" visualScreenOn=\"false\" alarms=\"true\" " + "media=\"true\" system=\"false\" />\n" + "<disallow visualEffects=\"511\" />" + "</zen>"; XmlPullParser parser = Xml.newPullParser(); parser.setInput(new BufferedInputStream( new ByteArrayInputStream(xml.getBytes())), null); parser.nextTag(); mZenModeHelperSpy.readXml(parser, false); assertEquals(0, mZenModeHelperSpy.mConfig.suppressedVisualEffects); } @Test public void testMigrateSuppressedVisualEffects_bothExistButOn() throws Exception { String xml = "<zen version=\"6\" user=\"0\">\n" + "<allow calls=\"false\" repeatCallers=\"false\" messages=\"true\" " + "reminders=\"false\" events=\"false\" callsFrom=\"1\" messagesFrom=\"2\" " + "visualScreenOff=\"true\" visualScreenOn=\"true\" alarms=\"true\" " + "media=\"true\" system=\"false\" />\n" + "<disallow visualEffects=\"511\" />" + "</zen>"; XmlPullParser parser = Xml.newPullParser(); parser.setInput(new BufferedInputStream( new ByteArrayInputStream(xml.getBytes())), null); parser.nextTag(); mZenModeHelperSpy.readXml(parser, false); assertEquals(SUPPRESSED_EFFECT_FULL_SCREEN_INTENT | SUPPRESSED_EFFECT_LIGHTS | SUPPRESSED_EFFECT_PEEK, mZenModeHelperSpy.mConfig.suppressedVisualEffects); xml = "<zen version=\"6\" user=\"0\">\n" + "<allow calls=\"false\" repeatCallers=\"false\" messages=\"true\" " + "reminders=\"false\" events=\"false\" callsFrom=\"1\" messagesFrom=\"2\" " + "visualScreenOff=\"false\" visualScreenOn=\"true\" alarms=\"true\" " + "media=\"true\" system=\"false\" />\n" + "<disallow visualEffects=\"511\" />" + "</zen>"; parser = Xml.newPullParser(); parser.setInput(new BufferedInputStream( new ByteArrayInputStream(xml.getBytes())), null); parser.nextTag(); mZenModeHelperSpy.readXml(parser, false); assertEquals(SUPPRESSED_EFFECT_PEEK, mZenModeHelperSpy.mConfig.suppressedVisualEffects); xml = "<zen version=\"6\" user=\"0\">\n" + "<allow calls=\"false\" repeatCallers=\"false\" messages=\"true\" " + "reminders=\"false\" events=\"false\" callsFrom=\"1\" messagesFrom=\"2\" " + "visualScreenOff=\"true\" visualScreenOn=\"false\" alarms=\"true\" " + "media=\"true\" system=\"false\" />\n" + "<disallow visualEffects=\"511\" />" + "</zen>"; parser = Xml.newPullParser(); parser.setInput(new BufferedInputStream( new ByteArrayInputStream(xml.getBytes())), null); parser.nextTag(); mZenModeHelperSpy.readXml(parser, false); assertEquals(SUPPRESSED_EFFECT_FULL_SCREEN_INTENT | SUPPRESSED_EFFECT_LIGHTS, mZenModeHelperSpy.mConfig.suppressedVisualEffects); } @Test public void testReadXmlResetDefaultRules() throws Exception { setupZenConfig(); // no enabled automatic zen rule, so rules should be overriden by default rules mZenModeHelperSpy.mConfig.automaticRules = new ArrayMap<>(); // set previous version ByteArrayOutputStream baos = writeXmlAndPurge(false, 5); XmlPullParser parser = Xml.newPullParser(); parser.setInput(new BufferedInputStream( new ByteArrayInputStream(baos.toByteArray())), null); parser.nextTag(); mZenModeHelperSpy.readXml(parser, false); // check default rules ArrayMap<String, ZenModeConfig.ZenRule> rules = mZenModeHelperSpy.mConfig.automaticRules; assertTrue(rules.size() != 0); for (String defaultId : ZenModeConfig.DEFAULT_RULE_IDS) { assertTrue(rules.containsKey(defaultId)); } setupZenConfigMaintained(); } @Test public void testReadXmlAllDisabledRulesResetDefaultRules() throws Exception { setupZenConfig(); // all automatic zen rules are diabled on upgrade so rules should be overriden by default // rules ArrayMap<String, ZenModeConfig.ZenRule> enabledAutoRule = new ArrayMap<>(); ZenModeConfig.ZenRule customRule = new ZenModeConfig.ZenRule(); final ScheduleInfo weeknights = new ScheduleInfo(); customRule.enabled = false; customRule.name = "Custom Rule"; customRule.zenMode = Settings.Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS; customRule.conditionId = ZenModeConfig.toScheduleConditionId(weeknights); enabledAutoRule.put("customRule", customRule); mZenModeHelperSpy.mConfig.automaticRules = enabledAutoRule; // set previous version ByteArrayOutputStream baos = writeXmlAndPurge(false, 5); XmlPullParser parser = Xml.newPullParser(); parser.setInput(new BufferedInputStream( new ByteArrayInputStream(baos.toByteArray())), null); parser.nextTag(); mZenModeHelperSpy.readXml(parser, false); // check default rules ArrayMap<String, ZenModeConfig.ZenRule> rules = mZenModeHelperSpy.mConfig.automaticRules; assertTrue(rules.size() != 0); for (String defaultId : ZenModeConfig.DEFAULT_RULE_IDS) { assertTrue(rules.containsKey(defaultId)); } assertFalse(rules.containsKey("customRule")); setupZenConfigMaintained(); } @Test public void testCountdownConditionSubscription() throws Exception { ZenModeConfig config = new ZenModeConfig(); mZenModeHelperSpy.mConfig = config; mZenModeHelperSpy.mConditions.evaluateConfig(mZenModeHelperSpy.mConfig, null, true); assertEquals(0, mZenModeHelperSpy.mConditions.mSubscriptions.size()); mZenModeHelperSpy.mConfig.manualRule = new ZenModeConfig.ZenRule(); Uri conditionId = ZenModeConfig.toCountdownConditionId(9000000, false); mZenModeHelperSpy.mConfig.manualRule.conditionId = conditionId; mZenModeHelperSpy.mConfig.manualRule.component = new ComponentName("android", CountdownConditionProvider.class.getName()); mZenModeHelperSpy.mConfig.manualRule.condition = new Condition(conditionId, "", "", "", 0, Condition.STATE_TRUE, Condition.FLAG_RELEVANT_NOW); mZenModeHelperSpy.mConfig.manualRule.enabled = true; ZenModeConfig originalConfig = mZenModeHelperSpy.mConfig.copy(); mZenModeHelperSpy.mConditions.evaluateConfig(mZenModeHelperSpy.mConfig, null, true); assertEquals(true, ZenModeConfig.isValidCountdownConditionId(conditionId)); assertEquals(originalConfig, mZenModeHelperSpy.mConfig); assertEquals(1, mZenModeHelperSpy.mConditions.mSubscriptions.size()); } private void setupZenConfig() { mZenModeHelperSpy.mZenMode = Settings.Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS; mZenModeHelperSpy.mConfig.allowAlarms = false; mZenModeHelperSpy.mConfig.allowMedia = false; mZenModeHelperSpy.mConfig.allowSystem = false; mZenModeHelperSpy.mConfig.allowReminders = true; mZenModeHelperSpy.mConfig.allowCalls = true; mZenModeHelperSpy.mConfig.allowMessages = true; mZenModeHelperSpy.mConfig.allowEvents = true; mZenModeHelperSpy.mConfig.allowRepeatCallers= true; mZenModeHelperSpy.mConfig.suppressedVisualEffects = SUPPRESSED_EFFECT_BADGE; mZenModeHelperSpy.mConfig.manualRule = new ZenModeConfig.ZenRule(); mZenModeHelperSpy.mConfig.manualRule.zenMode = Settings.Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS; mZenModeHelperSpy.mConfig.manualRule.component = new ComponentName("a", "a"); mZenModeHelperSpy.mConfig.manualRule.enabled = true; mZenModeHelperSpy.mConfig.manualRule.snoozing = true; } private void setupZenConfigMaintained() { // config is still the same as when it was setup (setupZenConfig) assertFalse(mZenModeHelperSpy.mConfig.allowAlarms); assertFalse(mZenModeHelperSpy.mConfig.allowMedia); assertFalse(mZenModeHelperSpy.mConfig.allowSystem); assertTrue(mZenModeHelperSpy.mConfig.allowReminders); assertTrue(mZenModeHelperSpy.mConfig.allowCalls); assertTrue(mZenModeHelperSpy.mConfig.allowMessages); assertTrue(mZenModeHelperSpy.mConfig.allowEvents); assertTrue(mZenModeHelperSpy.mConfig.allowRepeatCallers); assertEquals(SUPPRESSED_EFFECT_BADGE, mZenModeHelperSpy.mConfig.suppressedVisualEffects); } }
Daornit/affliate-qraphql-admin
src/components/Category/ShortCategory.js
import React from "react"; import PropTypes from "prop-types"; import { withStyles } from "@material-ui/core/styles"; import Card from '@material-ui/core/Card'; import CardContent from '@material-ui/core/CardContent'; import CardMedia from '@material-ui/core/CardMedia'; import Typography from '@material-ui/core/Typography'; import GridItem from "components/Grid/GridItem.js"; import GridContainer from "components/Grid/GridContainer.js"; import Link from "@material-ui/core/Link"; const styles = (theme) => ({ root: { width: '100%', display: 'flex', marginTop: '10px' }, details: { display: 'flex', flexDirection: 'column', width: '100%' }, content: { flex: '1 0 auto', }, cover: { width: '180px !important', }, controls: { display: 'flex', alignItems: 'center', }, action: { marginTop: '15px' }, snap: { color: 'white', borderRadius: '5px', padding: '5px', background: '#3f51b5', marginRight: '10px' }, button: { color: '#3f51b5' }, floatLeft: { float: 'left' }, floatRight: { float: 'right' }, block: { display: 'block' }, short: { color: '#263238' } }); function ShortCategory(props) { const { classes, category }= props; return ( <Card className={classes.root}> <div className={classes.details}> <CardContent className={classes.content}> <Typography component="h5" variant="h5"> <Link color="inherit" href={'/admin/category/' + category._id}> {category.name} </Link> </Typography> <GridContainer> <GridItem xs={12} sm={12} md={12}> {category.description ? category.description: 'Тайлбар өгөөгүй байна.'} </GridItem> </GridContainer> <div className={classes.action}> <span className={classes.snap}>СY {category.isVisibleInMainMenu ? 'Үндсэн цэс': 'Үндсэн цэс биш'}</span> </div> </CardContent> </div> <CardMedia className={classes.cover} image={category.coverImg ? category.coverImg : '/cover.jpeg'} title="coverImg" /> </Card> ); } ShortCategory.propTypes = { classes: PropTypes.object.isRequired } const styledComp = withStyles(styles)(ShortCategory); export default styledComp;
iklasky/timemachines
tests/dlm/test_dlm_exogenous.py
<reponame>iklasky/timemachines from timemachines.skaters.dlm.dlmunivariate import using_dlm if using_dlm: from timemachines.skaters.dlm.dlmexogenous import dlm_exogenous_r3, dlm_exogenous_b from timemachines.skatertools.evaluation.evaluators import hospital_mean_square_error_with_sporadic_fit, hospital_exog_mean_square_error_with_sporadic_fit import numpy as np def test_dlm_exogenous(): print(hospital_exog_mean_square_error_with_sporadic_fit(f=dlm_exogenous_r3, k=1, n=150, fit_frequency=100, n_test=1, r=np.random.rand())) print(hospital_exog_mean_square_error_with_sporadic_fit(f=dlm_exogenous_b, k=1, n=150, fit_frequency=100, n_test=1)) def test_dlm_exogenous_on_univariate(): print(hospital_mean_square_error_with_sporadic_fit(f=dlm_exogenous_b, k=1, n=150, fit_frequency=100, n_test=1)) if __name__=='__main__': test_dlm_exogenous_on_univariate()
chenleizhaoEdinboro/chenleizhaoedinboro.github.io
NemoJava-2.0/src/test/java/FactoryAndData/FE/SWAT564.java
package FactoryAndData.FE; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import CommonFunction.Common; import TestData.PropsUtils; import TestScript.FE.SWAT564Test; public class SWAT564 { @DataProvider(name = "test") public static Object[][] Data564() { return Common.getFactoryData(new Object[][] { { "US" } }, PropsUtils.getTargetStore("SWAT564")); } @Factory(dataProvider = "test") public Object[] createTest(String store) { Object[] tests = new Object[1]; tests[0] = new SWAT564Test(store); return tests; } }