repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
LukasGasior1/crypto-tool
src/main/scala/cryptotool/cli/service/ProfitCalcCliService.scala
<reponame>LukasGasior1/crypto-tool package cryptotool.cli.service import cryptotool.domain.Exchange import cryptotool.ext.binance.service.{BinanceService, Trade} import cryptotool.{domain, profitcalc} import cryptotool.profitcalc.{ProfitCalc, TradeProfitsResult, TradeType} import de.vandermeer.asciitable.{AT_Row, AsciiTable} import de.vandermeer.skb.interfaces.transformers.textformat.TextAlignment import scala.concurrent.{ExecutionContext, Future} object ProfitCalcCliService { val TableWidth = 100 } class ProfitCalcCliService(binanceService: BinanceService)(implicit ec: ExecutionContext) { import ProfitCalcCliService._ def profitCalc(exchange: Exchange, currencies: Seq[String]): Future[Unit] = { require(exchange == Exchange.Binance, "only binance supported") val resultsF = Future.traverse(currencies) { currency => val resF = binanceService.getFullTradeList(currency) zip binanceService.getTickerPrice(s"${currency}BTC") resF.map { case (tr, price) => (currency, tr, price) } }.map { tradeListsWithPrices => tradeListsWithPrices.map { case (currency, tradeList, price) => val profitCalc = new ProfitCalc(tradeList.trades.map(toCalcTrade), price) (currency, profitCalc.calculateProfit()) } } for { results <- resultsF btcPriceInUsd <- binanceService.getTickerPrice("BTCUSDT") } yield printResults(results, btcPriceInUsd) } private def printResults(results: Seq[(String, TradeProfitsResult)], btcPriceInUsd: Double): Unit = { val table = new AsciiTable table.addRule() alignRow(table.addRow("Currency", "Gross profit", "Commissions", "Net profit", "Unrealized profit", "Unrealized profit (USD)")) table.addRule() results.toArray.foreach { case (currency, r) => alignRow(table.addRow( currency, r.realizedProfitGross.formatCrypto, r.totalCommissions.formatCrypto, r.realizedProfitNet.formatCrypto, r.unrealizedProfit.formatCrypto, (r.unrealizedProfit * btcPriceInUsd).formatUsd)) table.addRule() } println(table.render(TableWidth)) } private def toCalcTrade(trade: Trade): profitcalc.Trade = { if (trade.isBuyer) { require(trade.commissionAsset != domain.BTC) profitcalc.Trade( id = trade.id.toString, price = trade.price, quantity = trade.netQty, commission = trade.commission * trade.price, timestamp = trade.time, tradeType = TradeType.Buy) } else { require(trade.commissionAsset == domain.BTC) profitcalc.Trade( id = trade.id.toString, price = trade.price, quantity = trade.netQty, commission = trade.commission, timestamp = trade.time, tradeType = TradeType.Sell) } } private def alignRow(row: AT_Row): Unit = { row.getCells.get(0).getContext.setTextAlignment(TextAlignment.LEFT) (1 until row.getCells.size).foreach { i => row.getCells.get(i).getContext.setTextAlignment(TextAlignment.RIGHT) } } }
deynesonborba/SmallBI
SmallBI_WebService/SmallBI_WebService/src/br/com/smallbi/entity/Plano.java
<gh_stars>1-10 package br.com.smallbi.entity; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Plano { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer idPlano; private Date dataCadastro; private Integer usuarioId; @Column(name = "descricao",length=30) private String nomePlano; private boolean status; public boolean isStatus() { return status; } public void setStatus(boolean status) { this.status = status; } public Integer getIdPlano() { return idPlano; } public void setIdPlano(Integer idPlano) { this.idPlano = idPlano; } public Date getDataCadastro() { return dataCadastro; } public void setDataCadastro(Date dataCadastro) { this.dataCadastro = dataCadastro; } public Integer getUsuarioId() { return usuarioId; } public void setUsuarioId(Integer usuarioId) { this.usuarioId = usuarioId; } public String getNomePlano() { return nomePlano; } public void setNomePlano(String descricao) { this.nomePlano = descricao; } }
fredmorcos/attic
Projects/PlantMaker/plantmaker-2/src/benchmark/evaluatorperf.py
<filename>Projects/PlantMaker/plantmaker-2/src/benchmark/evaluatorperf.py from time import time from benchmark.benchmark import Benchmark from optimizer.optimizer import Optimizer from optimizer.simulator import Simulator from optimizer.evaluator import Evaluator from extra.printer import pprint, BLUE class EvaluatorPerf(Benchmark): def __init__(self, plant, orderList, testNumber): Benchmark.__init__(self, plant, orderList, testNumber) self.prefix = "evaluator" class EvaluatorMachinesPerf(EvaluatorPerf): def __init__(self, plant, orderList, testNumber): EvaluatorPerf.__init__(self, plant, orderList, testNumber) self.testName = "NumberOfMachines" self.startValue = 1 def bench(self): recipes = [] for o in self.orderList.orders: recipes.append(o.recipe.recipe[:]) o.recipe.recipe = [] machines = self.plant.machines[:] self.plant.machines = [] i = self.startValue while i <= len(machines): pprint("PERF Number of machines = " + str(i), BLUE) self.plant.machines = machines[:i] for j, o in enumerate(self.orderList.orders): o.recipe.recipe = recipes[j][:i] optimizer = Optimizer(self.plant, self.orderList, Simulator(self.plant), Evaluator(self.plant)) optimizer.populationSize = 2 optimizer.iterations = 2 optimizer.indivMutationRate = 0.5 optimizer.selectionRate = 0.5 optimizer.mutationRange = 10 schedules = optimizer.run() evaluator = Evaluator(self.plant) t = time() evaluator.evaluate(schedules[0]) t = time() - t self.addCairoPlotTime(t) self.addGnuPlotTime(i, t) i += 1 class EvaluatorOrdersPerf(EvaluatorPerf): def __init__(self, plant, orderList, testNumber): EvaluatorPerf.__init__(self, plant, orderList, testNumber) self.testName = "NumberOfOrders" self.startValue = 2 def bench(self): orders = self.orderList.orders[:] self.orderList.orders = [] i = self.startValue while i <= len(orders): pprint("PERF Number of orders = " + str(i), BLUE) self.orderList.orders = orders[:i] optimizer = Optimizer(self.plant, self.orderList, Simulator(self.plant), Evaluator(self.plant)) optimizer.populationSize = 2 optimizer.iterations = 2 optimizer.indivMutationRate = 0.5 optimizer.selectionRate = 0.5 optimizer.mutationRange = 10 schedules = optimizer.run() evaluator = Evaluator(self.plant) t = time() evaluator.evaluate(schedules[0]) t = time() - t self.addCairoPlotTime(t) self.addGnuPlotTime(i, t) i += 1 class EvaluatorLargeValuesPerf(EvaluatorPerf): def __init__(self, plant, orderList, testNumber): EvaluatorPerf.__init__(self, plant, orderList, testNumber) self.testName = "LargeValuesMultiplier" def bench(self): val = 2 i = self.startValue while i < 10: pprint("PERF Large Value = " + str(i * val), BLUE) for o in self.orderList.orders: o.deadline *= val for r in o.recipe.recipe: r[1] *= val optimizer = Optimizer(self.plant, self.orderList, Simulator(self.plant), Evaluator(self.plant)) optimizer.populationSize = 2 optimizer.iterations = 2 optimizer.indivMutationRate = 0.5 optimizer.selectionRate = 0.5 optimizer.mutationRange = 500 schedules = optimizer.run() evaluator = Evaluator(self.plant) t = time() evaluator.evaluate(schedules[0]) t = time() - t self.addCairoPlotTime(t) self.addGnuPlotTime((i + 1) * val, t) i += 1
ColdMatter/PhotonBEC
FianiumController/probably_out_of_date/fianium_main.py
#!/usr/bin/env python import sys import socket if socket.gethostname().lower()=="ph-photonbec": fianium_comport=4 sys.path.append("Z:\\Control\\PythonPackages\\") sys.path.append("Z:\\Control\\FianiumController\\") elif socket.gethostname().lower()=="ph-photonbec3": fianium_comport=6 sys.path.append("D:\\Control\\PythonPackages\\") sys.path.append("D:\\Control\\FianiumController\\") import __main__ from serial import * import time, threading import pbec_ipc from InterfaceGUI_fianium import * app = QtGui.QApplication(sys.argv) mw = QtGui.QMainWindow() ui = Ui_MainWindow() ui.setupUi(mw) #--------------------------------- #SERIAL PORT UTILITIES #--------------------------------- from fianium import * fia = FianiumLaser() fia_lock = threading.Lock() def updateSetPulseEnergyGUI(newSetValue): ui.setLCD_pulse_energy.display(newSetValue) ui.setText_pulse_energy.setText(str(newSetValue)) #--------------------------------- #ADDITIONAL SETUP #--------------------------------- def enableUpdate(newValue): ui.enable_checkBox print "enableUpdate: called with "+str(newValue) #Called every time the enable tickbox is toggled. with fia_lock: #fia = FianiumLaser() if newValue==True: fia.enable() ui.currentLCD_alarms.setText("") else: fia.disable() ui.currentLCD_alarms.setText("Enable first before setting the parameters.") ui.enable_checkBox.setChecked(newValue) #---Enable tick box------ ui.enable_checkBox.clicked.connect(enableUpdate) def setValueUpdate_pe(newValue): #Called every time the pulse is set. with fia_lock: #fia = FianiumLaser() p = fia.setPulseEnergy(newValue) LaserSafetyAlarms() updateSetPulseEnergyGUI(newValue) #---Text control for pulse energy------ def setValueChangedByText_pe(): try: newValue = float(ui.setText_pulse_energy.text()) except: pass else: ui.setLCD_pulse_energy.display(newValue) setValueUpdate_pe(newValue) # ui.setTextButton_pulse_energy.clicked.connect(setValueChangedByText_pe) ui.setText_pulse_energy.returnPressed.connect(setValueChangedByText_pe) def updateSetRepetitionRateGUI(newSetValue): ui.setLCD_rr.display(newSetValue) ui.setText_rr.setText(str(newSetValue)) #--------------------------------- #ADDITIONAL SETUP #--------------------------------- def setValueUpdate_rr(newValue): #Called every time the power is set. with fia_lock: #fia = FianiumLaser() p = fia.setRepetitionRate(newValue) LaserSafetyAlarms() updateSetRepetitionRateGUI(newValue) #---Text control for pulse energy------ def setValueChangedByText_rr(): try: newValue = float(ui.setText_rr.text()) except: pass else: ui.currentLCD_rr.display(newValue) setValueUpdate_rr(newValue) # ui.setTextButton_rr.clicked.connect(setValueChangedByText_rr) ui.setText_rr.returnPressed.connect(setValueChangedByText_rr) #----CURRENT VALUE BOX PULSE ENERGY----- def getCurrentPulseEnergy(): with fia_lock: #fia = FianiumLaser() p = fia.getPulseEnergy() if p==None: p="ERR" print 'got current pulse energy = ' + str(p) ui.currentLCD_pulse_energy.display(p) return p def getData(self): pass #ui.currentLCD.connect(getCurrentPower) ui.getDataPushButton.clicked.connect(getData) #----CURRENT VALUE BOX REPETITION RATE----- def getCurrentRepetitionRate(): with fia_lock: #fia = FianiumLaser() p = fia.getRepetitionRate() if p==None: p="ERR" print 'got current repetition rate = ' + str(p) ui.currentLCD_rr.display(p) return p def LaserSafetyAlarms(): power=fia.getPower() pe=fia.getPulseEnergy() if power>=15 or pe>=6: ui.currentLCD_alarms.setText('NOT SAFE. LASER GOOGLES ON.') ui.currentLCD_pulse_energy.palette.setColor(QtGui.Palette.WindowText,QtGui.QColor(85,85,255)) ui.currentLCD_pulse_energy.palette.setColor(QtGui.Palette.Background,QtGui.QColor(85,85,255)) ui.setPalette(palette) else: ui.currentLCD_alarms.setText('SAFE. LASER GOOGLES OFF.') return None ######################################################################### class PollPowerThread(threading.Thread): def run(self): #self.daemon = True time.sleep(2) while True: time.sleep(0.2) if ui.power_timer_checkBox.isChecked(): getCurrentPulseEnergy() getCurrentRepetitionRate() return None #if FianiumLaser().isEnabled(): if fia.isEnabled(): ui.enable_checkBox.setCheckState(QtCore.Qt.Checked) else: ui.enable_checkBox.setCheckState(QtCore.Qt.Unchecked) ui.currentLCD_alarms.setText("Enable first before setting up the parameters.") mw.show() #--------------------------------- #FINAL COMMANDS FOR RUNNING IN NON-INTERACTIVE MODE #--------------------------------- def isInteractive(): return not(hasattr(__main__, '__file__')) if ~isInteractive(): bind_success = pbec_ipc.start_server(globals(), port = pbec_ipc.PORT_NUMBERS['fianium_controller']) if not bind_success: print 'Laser Controller already running, quitting...' ppt = PollPowerThread() ppt.daemon = True ppt.start() ui.power_timer_checkBox.setCheckState(QtCore.Qt.Checked) sys.exit(app.exec_()) ########################################################################### #EOF
andresmundoweb/prueba
prestashop/analytics/plugins/TagManager/Template/Tag/FacebookPixelTag.web.js
(function () { return function (parameters, TagManager) { var setup = {}; var isLibLoaded = false; this.fire = function () { if (!isLibLoaded) { isLibLoaded = true; !function(f,b,e,v,n,t,s) {if(f.fbq)return;n=f.fbq=function(){n.callMethod? n.callMethod.apply(n,arguments):n.queue.push(arguments)}; if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0'; n.queue=[];t=b.createElement(e);t.async=!0; t.src=v;s=b.getElementsByTagName(e)[0]; s.parentNode.insertBefore(t,s)}(parameters.window,parameters.document,'script', 'https://connect.facebook.net/en_US/fbevents.js'); } var pixelId = parameters.get('pixelId'); if (!(pixelId in setup)) { setup[pixelId] = true; fbq('init', pixelId); } fbq('track', 'PageView'); }; }; })();
SingingBush/ldap-browser-idea-plugin
src/org/majki/intellij/ldapbrowser/editor/LdapFileIconProvider.java
<gh_stars>0 package org.majki.intellij.ldapbrowser.editor; import com.intellij.ide.FileIconProvider; import com.intellij.openapi.fileEditor.impl.EditorTabTitleProvider; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Iconable; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; public class LdapFileIconProvider implements FileIconProvider, EditorTabTitleProvider { @Nullable @Override public Icon getIcon(@NotNull VirtualFile virtualFile, @Iconable.IconFlags int i, @Nullable Project project) { if (virtualFile instanceof LdapNodeVirtualFile) { return ((LdapNodeVirtualFile) virtualFile).getLdapTreeNode().getIcon(); } return null; } @Nullable @Override public String getEditorTabTitle(@NotNull Project project, @NotNull VirtualFile virtualFile) { if (virtualFile instanceof LdapNodeVirtualFile) { return "RDN: " + ((LdapNodeVirtualFile) virtualFile).getLdapTreeNode().toString(); } return null; } }
wgnet/wds_qt
qtmultimedia/src/plugins/windowsaudio/qwindowsaudiodeviceinfo.cpp
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ // // W A R N I N G // ------------- // // This file is not part of the Qt API. It exists for the convenience // of other Qt classes. This header file may change from version to // version without notice, or even be removed. // // INTERNAL USE ONLY: Do NOT use for any other purpose. // #include <QtCore/qt_windows.h> #include <QtCore/QDataStream> #include <mmsystem.h> #include "qwindowsaudiodeviceinfo.h" #include "qwindowsaudioutils.h" #if defined(Q_CC_MINGW) && !defined(__MINGW64_VERSION_MAJOR) struct IBaseFilter; // Needed for strmif.h from stock MinGW. struct _DDPIXELFORMAT; typedef struct _DDPIXELFORMAT* LPDDPIXELFORMAT; #endif #include <strmif.h> #if !defined(Q_CC_MINGW) || defined(__MINGW64_VERSION_MAJOR) # include <uuids.h> #else extern GUID CLSID_AudioInputDeviceCategory; extern GUID CLSID_AudioRendererCategory; extern GUID IID_ICreateDevEnum; extern GUID CLSID_SystemDeviceEnum; #ifndef __ICreateDevEnum_INTERFACE_DEFINED__ #define __ICreateDevEnum_INTERFACE_DEFINED__ DECLARE_INTERFACE_(ICreateDevEnum, IUnknown) { STDMETHOD(CreateClassEnumerator)(REFCLSID clsidDeviceClass, IEnumMoniker **ppEnumMoniker, DWORD dwFlags) PURE; }; #endif // __ICreateDevEnum_INTERFACE_DEFINED__ #ifndef __IErrorLog_INTERFACE_DEFINED__ #define __IErrorLog_INTERFACE_DEFINED__ DECLARE_INTERFACE_(IErrorLog, IUnknown) { STDMETHOD(AddError)(THIS_ LPCOLESTR, EXCEPINFO *) PURE; }; #endif /* __IErrorLog_INTERFACE_DEFINED__ */ #ifndef __IPropertyBag_INTERFACE_DEFINED__ #define __IPropertyBag_INTERFACE_DEFINED__ const GUID IID_IPropertyBag = {0x55272A00, 0x42CB, 0x11CE, {0x81, 0x35, 0x00, 0xAA, 0x00, 0x4B, 0xB8, 0x51}}; DECLARE_INTERFACE_(IPropertyBag, IUnknown) { STDMETHOD(Read)(THIS_ LPCOLESTR, VARIANT *, IErrorLog *) PURE; STDMETHOD(Write)(THIS_ LPCOLESTR, VARIANT *) PURE; }; #endif /* __IPropertyBag_INTERFACE_DEFINED__ */ #endif // defined(Q_CC_MINGW) && !defined(__MINGW64_VERSION_MAJOR) QT_BEGIN_NAMESPACE // For mingw toolchain mmsystem.h only defines half the defines, so add if needed. #ifndef WAVE_FORMAT_44M08 #define WAVE_FORMAT_44M08 0x00000100 #define WAVE_FORMAT_44S08 0x00000200 #define WAVE_FORMAT_44M16 0x00000400 #define WAVE_FORMAT_44S16 0x00000800 #define WAVE_FORMAT_48M08 0x00001000 #define WAVE_FORMAT_48S08 0x00002000 #define WAVE_FORMAT_48M16 0x00004000 #define WAVE_FORMAT_48S16 0x00008000 #define WAVE_FORMAT_96M08 0x00010000 #define WAVE_FORMAT_96S08 0x00020000 #define WAVE_FORMAT_96M16 0x00040000 #define WAVE_FORMAT_96S16 0x00080000 #endif QWindowsAudioDeviceInfo::QWindowsAudioDeviceInfo(QByteArray dev, QAudio::Mode mode) { QDataStream ds(&dev, QIODevice::ReadOnly); ds >> devId >> device; this->mode = mode; updateLists(); } QWindowsAudioDeviceInfo::~QWindowsAudioDeviceInfo() { close(); } bool QWindowsAudioDeviceInfo::isFormatSupported(const QAudioFormat& format) const { return testSettings(format); } QAudioFormat QWindowsAudioDeviceInfo::preferredFormat() const { QAudioFormat nearest; if (mode == QAudio::AudioOutput) { nearest.setSampleRate(44100); nearest.setChannelCount(2); nearest.setByteOrder(QAudioFormat::LittleEndian); nearest.setSampleType(QAudioFormat::SignedInt); nearest.setSampleSize(16); nearest.setCodec(QLatin1String("audio/pcm")); } else { nearest.setSampleRate(11025); nearest.setChannelCount(1); nearest.setByteOrder(QAudioFormat::LittleEndian); nearest.setSampleType(QAudioFormat::SignedInt); nearest.setSampleSize(8); nearest.setCodec(QLatin1String("audio/pcm")); } return nearest; } QString QWindowsAudioDeviceInfo::deviceName() const { return device; } QStringList QWindowsAudioDeviceInfo::supportedCodecs() { return QStringList() << QStringLiteral("audio/pcm"); } QList<int> QWindowsAudioDeviceInfo::supportedSampleRates() { updateLists(); return sampleRatez; } QList<int> QWindowsAudioDeviceInfo::supportedChannelCounts() { updateLists(); return channelz; } QList<int> QWindowsAudioDeviceInfo::supportedSampleSizes() { updateLists(); return sizez; } QList<QAudioFormat::Endian> QWindowsAudioDeviceInfo::supportedByteOrders() { return QList<QAudioFormat::Endian>() << QAudioFormat::LittleEndian; } QList<QAudioFormat::SampleType> QWindowsAudioDeviceInfo::supportedSampleTypes() { updateLists(); return typez; } bool QWindowsAudioDeviceInfo::open() { return true; } void QWindowsAudioDeviceInfo::close() { } bool QWindowsAudioDeviceInfo::testSettings(const QAudioFormat& format) const { WAVEFORMATEXTENSIBLE wfx; if (qt_convertFormat(format, &wfx)) { // query only, do not open device if (mode == QAudio::AudioOutput) { return (waveOutOpen(NULL, UINT_PTR(devId), &wfx.Format, 0, 0, WAVE_FORMAT_QUERY) == MMSYSERR_NOERROR); } else { // AudioInput return (waveInOpen(NULL, UINT_PTR(devId), &wfx.Format, 0, 0, WAVE_FORMAT_QUERY) == MMSYSERR_NOERROR); } } return false; } void QWindowsAudioDeviceInfo::updateLists() { if (!sizez.isEmpty()) return; bool hasCaps = false; DWORD fmt = 0; if(mode == QAudio::AudioOutput) { WAVEOUTCAPS woc; if (waveOutGetDevCaps(devId, &woc, sizeof(WAVEOUTCAPS)) == MMSYSERR_NOERROR) { hasCaps = true; fmt = woc.dwFormats; } } else { WAVEINCAPS woc; if (waveInGetDevCaps(devId, &woc, sizeof(WAVEINCAPS)) == MMSYSERR_NOERROR) { hasCaps = true; fmt = woc.dwFormats; } } sizez.clear(); sampleRatez.clear(); channelz.clear(); typez.clear(); if (hasCaps) { // Check sample size if ((fmt & WAVE_FORMAT_1M08) || (fmt & WAVE_FORMAT_1S08) || (fmt & WAVE_FORMAT_2M08) || (fmt & WAVE_FORMAT_2S08) || (fmt & WAVE_FORMAT_4M08) || (fmt & WAVE_FORMAT_4S08) || (fmt & WAVE_FORMAT_48M08) || (fmt & WAVE_FORMAT_48S08) || (fmt & WAVE_FORMAT_96M08) || (fmt & WAVE_FORMAT_96S08)) { sizez.append(8); } if ((fmt & WAVE_FORMAT_1M16) || (fmt & WAVE_FORMAT_1S16) || (fmt & WAVE_FORMAT_2M16) || (fmt & WAVE_FORMAT_2S16) || (fmt & WAVE_FORMAT_4M16) || (fmt & WAVE_FORMAT_4S16) || (fmt & WAVE_FORMAT_48M16) || (fmt & WAVE_FORMAT_48S16) || (fmt & WAVE_FORMAT_96M16) || (fmt & WAVE_FORMAT_96S16)) { sizez.append(16); } // Check sample rate if ((fmt & WAVE_FORMAT_1M08) || (fmt & WAVE_FORMAT_1S08) || (fmt & WAVE_FORMAT_1M16) || (fmt & WAVE_FORMAT_1S16)) { sampleRatez.append(11025); } if ((fmt & WAVE_FORMAT_2M08) || (fmt & WAVE_FORMAT_2S08) || (fmt & WAVE_FORMAT_2M16) || (fmt & WAVE_FORMAT_2S16)) { sampleRatez.append(22050); } if ((fmt & WAVE_FORMAT_4M08) || (fmt & WAVE_FORMAT_4S08) || (fmt & WAVE_FORMAT_4M16) || (fmt & WAVE_FORMAT_4S16)) { sampleRatez.append(44100); } if ((fmt & WAVE_FORMAT_48M08) || (fmt & WAVE_FORMAT_48S08) || (fmt & WAVE_FORMAT_48M16) || (fmt & WAVE_FORMAT_48S16)) { sampleRatez.append(48000); } if ((fmt & WAVE_FORMAT_96M08) || (fmt & WAVE_FORMAT_96S08) || (fmt & WAVE_FORMAT_96M16) || (fmt & WAVE_FORMAT_96S16)) { sampleRatez.append(96000); } // Check channel count if (fmt & WAVE_FORMAT_1M08 || fmt & WAVE_FORMAT_1M16 || fmt & WAVE_FORMAT_2M08 || fmt & WAVE_FORMAT_2M16 || fmt & WAVE_FORMAT_4M08 || fmt & WAVE_FORMAT_4M16 || fmt & WAVE_FORMAT_48M08 || fmt & WAVE_FORMAT_48M16 || fmt & WAVE_FORMAT_96M08 || fmt & WAVE_FORMAT_96M16) { channelz.append(1); } if (fmt & WAVE_FORMAT_1S08 || fmt & WAVE_FORMAT_1S16 || fmt & WAVE_FORMAT_2S08 || fmt & WAVE_FORMAT_2S16 || fmt & WAVE_FORMAT_4S08 || fmt & WAVE_FORMAT_4S16 || fmt & WAVE_FORMAT_48S08 || fmt & WAVE_FORMAT_48S16 || fmt & WAVE_FORMAT_96S08 || fmt & WAVE_FORMAT_96S16) { channelz.append(2); } typez.append(QAudioFormat::SignedInt); typez.append(QAudioFormat::UnSignedInt); // WAVEOUTCAPS and WAVEINCAPS contains information only for the previously tested parameters. // WaveOut and WaveInt might actually support more formats, the only way to know is to try // opening the device with it. QAudioFormat testFormat; testFormat.setCodec(QStringLiteral("audio/pcm")); testFormat.setByteOrder(QAudioFormat::LittleEndian); testFormat.setSampleType(QAudioFormat::SignedInt); testFormat.setChannelCount(channelz.first()); testFormat.setSampleRate(sampleRatez.at(sampleRatez.size() / 2)); testFormat.setSampleSize(sizez.last()); const QAudioFormat defaultTestFormat(testFormat); // Check if float samples are supported testFormat.setSampleType(QAudioFormat::Float); testFormat.setSampleSize(32); if (testSettings(testFormat)) typez.append(QAudioFormat::Float); // Check channel counts > 2 testFormat = defaultTestFormat; for (int i = 3; i < 19; ++i) { // <mmreg.h> defines 18 different channels testFormat.setChannelCount(i); if (testSettings(testFormat)) channelz.append(i); } // Check more sample sizes testFormat = defaultTestFormat; QList<int> testSampleSizes = QList<int>() << 24 << 32 << 48 << 64; Q_FOREACH (int s, testSampleSizes) { testFormat.setSampleSize(s); if (testSettings(testFormat)) sizez.append(s); } // Check more sample rates testFormat = defaultTestFormat; QList<int> testSampleRates = QList<int>() << 8000 << 16000 << 32000 << 88200 << 192000; Q_FOREACH (int r, testSampleRates) { testFormat.setSampleRate(r); if (testSettings(testFormat)) sampleRatez.append(r); } std::sort(sampleRatez.begin(), sampleRatez.end()); } } QList<QByteArray> QWindowsAudioDeviceInfo::availableDevices(QAudio::Mode mode) { Q_UNUSED(mode) QList<QByteArray> devices; #ifndef Q_OS_WINCE //enumerate device fullnames through directshow api CoInitialize(NULL); ICreateDevEnum *pDevEnum = NULL; IEnumMoniker *pEnum = NULL; // Create the System device enumerator HRESULT hr = CoCreateInstance(CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER, IID_ICreateDevEnum, reinterpret_cast<void **>(&pDevEnum)); unsigned long iNumDevs = mode == QAudio::AudioOutput ? waveOutGetNumDevs() : waveInGetNumDevs(); if (SUCCEEDED(hr)) { // Create the enumerator for the audio input/output category if (pDevEnum->CreateClassEnumerator( mode == QAudio::AudioOutput ? CLSID_AudioRendererCategory : CLSID_AudioInputDeviceCategory, &pEnum, 0) == S_OK) { pEnum->Reset(); // go through and find all audio devices IMoniker *pMoniker = NULL; while (pEnum->Next(1, &pMoniker, NULL) == S_OK) { IPropertyBag *pPropBag; hr = pMoniker->BindToStorage(0,0,IID_IPropertyBag, reinterpret_cast<void **>(&pPropBag)); if (FAILED(hr)) { pMoniker->Release(); continue; // skip this one } // Find if it is a wave device VARIANT var; VariantInit(&var); hr = pPropBag->Read(mode == QAudio::AudioOutput ? L"WaveOutID" : L"WaveInID", &var, 0); if (SUCCEEDED(hr)) { LONG waveID = var.lVal; if (waveID >= 0 && waveID < LONG(iNumDevs)) { VariantClear(&var); // Find the description hr = pPropBag->Read(L"FriendlyName", &var, 0); if (SUCCEEDED(hr)) { QByteArray device; QDataStream ds(&device, QIODevice::WriteOnly); ds << quint32(waveID) << QString::fromWCharArray(var.bstrVal); devices.append(device); } } } pPropBag->Release(); pMoniker->Release(); } pEnum->Release(); } pDevEnum->Release(); } CoUninitialize(); #else // Q_OS_WINCE if (mode == QAudio::AudioOutput) { WAVEOUTCAPS woc; unsigned long iNumDevs,i; iNumDevs = waveOutGetNumDevs(); for (i=0;i<iNumDevs;i++) { if (waveOutGetDevCaps(i, &woc, sizeof(WAVEOUTCAPS)) == MMSYSERR_NOERROR) { QByteArray device; QDataStream ds(&device, QIODevice::WriteOnly); ds << quint32(i) << QString::fromWCharArray(woc.szPname); devices.append(device); } } } else { WAVEINCAPS woc; unsigned long iNumDevs,i; iNumDevs = waveInGetNumDevs(); for (i=0;i<iNumDevs;i++) { if (waveInGetDevCaps(i, &woc, sizeof(WAVEINCAPS)) == MMSYSERR_NOERROR) { QByteArray device; QDataStream ds(&device, QIODevice::WriteOnly); ds << quint32(i) << QString::fromWCharArray(woc.szPname); devices.append(device); } } } #endif // !Q_OS_WINCE return devices; } QByteArray QWindowsAudioDeviceInfo::defaultOutputDevice() { QByteArray defaultDevice; QDataStream ds(&defaultDevice, QIODevice::WriteOnly); ds << quint32(WAVE_MAPPER) // device ID for default device << QStringLiteral("Default Output Device"); return defaultDevice; } QByteArray QWindowsAudioDeviceInfo::defaultInputDevice() { QByteArray defaultDevice; QDataStream ds(&defaultDevice, QIODevice::WriteOnly); ds << quint32(WAVE_MAPPER) // device ID for default device << QStringLiteral("Default Input Device"); return defaultDevice; } QT_END_NAMESPACE
shixiongjing/DeepRobust
deeprobust/graph/global_attack/__init__.py
<gh_stars>100-1000 from .base_attack import BaseAttack from .dice import DICE from .mettack import MetaApprox, Metattack from .random_attack import Random from .topology_attack import MinMax, PGDAttack from .node_embedding_attack import NodeEmbeddingAttack, OtherNodeEmbeddingAttack from .nipa import NIPA __all__ = ['BaseAttack', 'DICE', 'MetaApprox', 'Metattack', 'Random', 'MinMax', 'PGDAttack', 'NIPA', 'NodeEmbeddingAttack', 'OtherNodeEmbeddingAttack']
eckberg/ferenda
test/integrationLagen.py
<filename>test/integrationLagen.py<gh_stars>0 # -*- coding: utf-8 -*- # This fixture does a bunch of real HTTP request against a selected # server (determined by the environment variable FERENDA_TESTURL, # which is http://localhost:8000/ by default) # # When running against a local instance, it's important that this has # been initialized with the documents in lagen/nu/res/scripts/testdata.txt from __future__ import (absolute_import, division, print_function, unicode_literals) from builtins import * # sys import os import unittest import codecs import re from urllib.parse import urljoin from datetime import datetime # 3rdparty import requests from bs4 import BeautifulSoup from rdflib import Graph, URIRef from rdflib.namespace import DCTERMS # own from ferenda.elements import Link, serialize from ferenda.testutil import FerendaTestCase from ferenda.sources.legal.se import RPUBL from lagen.nu import SFS, LNKeyword from lagen.nu.wsgiapp import WSGIApp class TestLagen(unittest.TestCase, FerendaTestCase): baseurl = os.environ.get("FERENDA_TESTURL", "http://localhost:8000/") def assert_status(self, url, code): res = requests.get(url, headers={'Accept': 'text/html'}) self.assertEqual(res.status_code, code, url) return res def assert200(self, url): return self.assert_status(url, 200) def assert404(self, url): return self.assert_status(url, 404) def get(self, url, raise_for_status=False, **kwargs): if 'headers' not in kwargs: kwargs['headers']={'Accept': 'text/html'} res = requests.get(url, **kwargs) if raise_for_status: res.raise_for_status() return res class TestPaths(TestLagen): def test_frontpage(self): self.assert200(self.baseurl) def test_nonexist(self): self.assert404(self.baseurl + "this-resource-does-not-exist") def test_specific_sfs(self): self.assert200(self.baseurl + "1999:175") def test_specific_dv(self): self.assert200(self.baseurl + "dom/nja/2015s180") # basefile HDO/Ö6229-14 def test_specific_sou(self): self.assert200(self.baseurl + "sou/1997:39") # test old-style URI (for a while) self.assert200(self.baseurl + "utr/sou/1997:39") def test_specific_prop(self): self.assert200(self.baseurl + "prop/1997/98:44") def test_specific_keyword(self): self.assert200(self.baseurl + "begrepp/Personuppgift") def test_specific_keyword_tricky(self): self.assert200(self.baseurl + "begrepp/Sekundär_sekretessbestämmelse") def test_facsimile_page(self): res = self.get(self.baseurl + "sou/1997:39/sid557.png") self.assertEqual(200, res.status_code) self.assertEqual("image/png", res.headers["Content-Type"]) # assert trough first 8 bytes (magic number) that this really # is a legit png import binascii self.assertEqual(b"89504e470d0a1a0a", binascii.hexlify(res.content[:8])) # assert that the old-style URI still works (for a time) res = self.get(self.baseurl + "utr/sou/1997:39/sid557.png") self.assertEqual(200, res.status_code) def test_feed_html(self): self.assert200(self.baseurl + "dataset/sitenews/feed") self.assert200(self.baseurl + "dataset/sfs/feed?rdf_type=type/forordning") def test_feed_atom(self): self.assert200(self.baseurl + "dataset/sitenews/feed.atom") self.assert200(self.baseurl + "dataset/sfs/feed.atom?rdf_type=type/forordning") def test_attached_css(self): res = self.get(self.baseurl + "bolfs/2008:1") self.assertEqual(200, res.status_code) self.assertEqual("text/html; charset=utf-8", res.headers["Content-Type"]) self.assertIn('<link rel="stylesheet" href="/bolfs/2008:1?dir=parsed&amp;attachment=index.css"/>', res.text[:1200]) res = self.get(self.baseurl + "bolfs/2008:1?dir=parsed&attachment=index.css") self.assertEqual(200, res.status_code) self.assertEqual("text/css", res.headers["Content-Type"]) class TestPages(TestLagen): def test_doctype(self): for doc in ("", "1999:175", "dom/nja/2015s180", "sou/1997:39", "prop/1997/98:44", "begrepp/Personuppgift", "begrepp/Sekundär_sekretessbestämmelse"): resp = self.get(self.baseurl + doc) self.assertEqual('<!DOCTYPE html SYSTEM "about:legacy-compat">', resp.text[:44], "Wrong doctype for %s" % doc) def test_frontpage_links(self): # <a> elements should have a href attribute (you'd think that # was obvious, but it's not) res = self.get(self.baseurl) soup = BeautifulSoup(res.text, "lxml") firstlink = soup.article.a self.assertTrue(firstlink.get("href")) def test_frontpage_disabled_links(self): res = self.get(self.baseurl) soup = BeautifulSoup(res.text, "lxml") local = not os.environ.get("FERENDA_TESTURL") if local: # don't test for broken links in the main content area # since there will be many (in local testing we only # download a small subset of laws and other resources, and # the main content area contains links to other # resources. Thus, in this testing scenario, they're # expected to be missing soup.find("div", "section-wrapper").decompose() for link in soup.find_all("a"): self.assertNotIn("invalid-link", link.attrs.get('class', []), "Link %s marked as invalid (not in DB)" % link.text) def test_css_link(self): for link in ("", "dom/nja/2015s180", "dom/hfd/2015/not/1"): url = self.baseurl + link res = self.get(url) soup = BeautifulSoup(res.text, "lxml") cssref = soup.find("link", rel="stylesheet", href=re.compile("ferenda.css$"))['href'] cssurl = urljoin(url, cssref) self.assertEqual(self.baseurl + "rsrc/css/ferenda.css", cssurl, "Error for %s" % url) def test_sfs_outline(self): res = self.get(self.baseurl + "1999:175") soup = BeautifulSoup(res.text, "lxml") outlines = soup.find("nav", id="toc").find_all("li") # make sure the outline navigation is as expected and hasn't # been mangled. self.assertIn('Ett offentligt rättsinformationssystem', outlines[0].a.text) subheadings = outlines[1].find_all("li") self.assertEqual(9, len(subheadings)) self.assertIn('Personuppgifter', subheadings[-1].a.text) def test_paragrafbeteckning(self): for doc in ("1949:105", "1999:175"): res = self.get(self.baseurl + doc) soup = BeautifulSoup(res.text, "lxml") self.assertTrue(soup.find("a", "paragrafbeteckning"), "%s lacks marked-up paragrafbeteckning" % doc) class TestPatching(TestLagen): def test_file_has_been_patched(self): # the encoding parameter might be a py3-ism needle = codecs.encode("Fjrebgrp", encoding="rot13")# rot13 of a sensitive name res = self.get(self.baseurl + "dom/nja/2002s35") # case containing sensitive info res.raise_for_status() # req succeded self.assertEqual(-1, res.text.find(needle)) # sensitive name is removed self.assertTrue(res.text.index("alert alert-warning patchdescription")) # patching is advertised class TestConNeg(TestLagen): # this basically mirrors testWSGI.ConNeg def test_basic(self): res = self.get(self.baseurl + "1999:175") self.assertEqual(200, res.status_code) self.assertEqual("text/html; charset=utf-8", res.headers['Content-Type']) def test_xhtml(self): res = self.get(self.baseurl + "1999:175", headers={'Accept': 'application/xhtml+xml'}) self.assertEqual(200, res.status_code) self.assertEqual("application/xhtml+xml", res.headers['Content-Type']) # variation: use file extension res = self.get(self.baseurl + "1999:175.xhtml") self.assertEqual(200, res.status_code) self.assertEqual("application/xhtml+xml", res.headers['Content-Type']) def test_rdf(self): # basic test 3: accept: application/rdf+xml -> RDF statements (in XML) res = self.get(self.baseurl + "1999:175", headers={'Accept': 'application/rdf+xml'}) self.assertEqual(200, res.status_code) self.assertEqual("application/rdf+xml", res.headers['Content-Type']) # variation: use file extension res = self.get(self.baseurl + "1999:175.rdf") self.assertEqual(200, res.status_code) self.assertEqual("application/rdf+xml", res.headers['Content-Type']) def test_ntriples(self): # transform test 4: accept: application/n-triples -> RDF statements (in NTriples) # get the untransformed data to compare with g = Graph().parse(data=self.get(self.baseurl + "1999:175.rdf", raise_for_status=True).text) res = self.get(self.baseurl + "1999:175", headers={'Accept': 'application/n-triples'}) self.assertEqual(200, res.status_code) self.assertEqual("application/n-triples", res.headers['Content-Type']) got = Graph().parse(data=res.content, format="nt") self.assertEqualGraphs(g, got) # variation: use file extension res = self.get(self.baseurl + "1999:175.nt", raise_for_status=True) self.assertEqual(200, res.status_code) self.assertEqual("application/n-triples", res.headers['Content-Type']) got = Graph() got.parse(data=res.content, format="nt") self.assertEqualGraphs(g, got) def test_turtle(self): # transform test 5: accept: text/turtle -> RDF statements (in Turtle) g = Graph().parse(data=self.get(self.baseurl + "1999:175.rdf", raise_for_status=True).text) res = self.get(self.baseurl + "1999:175", headers={'Accept': 'text/turtle'}) self.assertEqual(200, res.status_code) self.assertEqual("text/turtle", res.headers['Content-Type']) got = Graph().parse(data=res.content, format="turtle") self.assertEqualGraphs(g, got) # variation: use file extension res = self.get(self.baseurl + "1999:175.ttl") self.assertEqual(200, res.status_code) self.assertEqual("text/turtle", res.headers['Content-Type']) got = Graph() got.parse(data=res.content, format="turtle") self.assertEqualGraphs(g, got) def test_json(self): # transform test 6: accept: application/json -> RDF statements (in JSON-LD) g = Graph().parse(data=self.get(self.baseurl + "1999:175.rdf").text) res = self.get(self.baseurl + "1999:175", headers={'Accept': 'application/json'}) self.assertEqual(200, res.status_code) self.assertEqual("application/json", res.headers['Content-Type']) got = Graph().parse(data=res.text, format="json-ld") self.assertEqualGraphs(g, got) # variation: use file extension res = self.get(self.baseurl + "1999:175.json") self.assertEqual(200, res.status_code) self.assertEqual("application/json", res.headers['Content-Type']) got = Graph() got.parse(data=res.text, format="json-ld") self.assertEqualGraphs(g, got) def test_unacceptable(self): res = self.get(self.baseurl + "1999:175", headers={'Accept': 'application/pdf'}) self.assertEqual(res.status_code, 406) self.assertEqual("text/html; charset=utf-8", res.headers['Content-Type']) # variation: unknown file extension should also be unacceptable res = self.get(self.baseurl + "1999:175.pdf") self.assertEqual(res.status_code, 406) self.assertEqual("text/html; charset=utf-8", res.headers['Content-Type']) def test_extended_rdf(self): # extended test 6: accept: "/data" -> extended RDF statements g = Graph().parse(data=self.get(self.baseurl + "1999:175/data.rdf").text) res = self.get(self.baseurl + "1999:175/data", headers={'Accept': 'application/rdf+xml'}) self.assertEqual(200, res.status_code) self.assertEqual("application/rdf+xml", res.headers['Content-Type']) got = Graph().parse(data=res.text) self.assertEqualGraphs(g, got) def test_extended_ntriples(self): # extended test 7: accept: "/data" + "application/n-triples" -> extended # RDF statements in NTriples g = Graph().parse(data=self.get(self.baseurl + "1999:175/data.rdf").text) res = self.get(self.baseurl + "1999:175/data", headers={'Accept': 'application/n-triples'}) self.assertEqual(200, res.status_code) self.assertEqual("application/n-triples", res.headers['Content-Type']) got = Graph().parse(data=res.text, format="nt") self.assertEqualGraphs(g, got) # variation: use file extension res = self.get(self.baseurl + "1999:175/data.nt") self.assertEqual(200, res.status_code) self.assertEqual("application/n-triples", res.headers['Content-Type']) got = Graph().parse(data=res.text, format="nt") self.assertEqualGraphs(g, got) def test_extended_turtle(self): # extended test 7: accept: "/data" + "text/turtle" -> extended # RDF statements in Turtle g = Graph().parse(data=self.get(self.baseurl + "1999:175/data.rdf").text) res = self.get(self.baseurl + "1999:175/data", headers={'Accept': 'text/turtle'}) self.assertEqual(200, res.status_code) self.assertEqual("text/turtle", res.headers['Content-Type']) got = Graph().parse(data=res.content, format="turtle") self.assertEqualGraphs(g, got) # variation: use file extension res = self.get(self.baseurl + "1999:175/data.ttl") self.assertEqual(200, res.status_code) self.assertEqual("text/turtle", res.headers['Content-Type']) got = Graph().parse(data=res.content, format="turtle") self.assertEqualGraphs(g, got) def test_dataset_html(self): res = self.get(self.baseurl + "dataset/sfs") self.assertTrue(res.status_code, 200) self.assertEqual("text/html; charset=utf-8", res.headers['Content-Type']) def test_dataset_html_param(self): res = self.get(self.baseurl + "dataset/sfs?titel=P") self.assertTrue(res.status_code, 200) self.assertEqual("text/html; charset=utf-8", res.headers['Content-Type']) self.assertIn('Författningar som börjar på "P"', res.text) def test_dataset_ntriples(self): res = self.get(self.baseurl + "dataset/sitenews", headers={'Accept': 'application/n-triples'}) self.assertTrue(res.status_code, 200) self.assertEqual("application/n-triples", res.headers['Content-Type']) Graph().parse(data=res.text, format="nt") res = self.get(self.baseurl + "dataset/sitenews.nt") self.assertTrue(res.status_code, 200) self.assertEqual("application/n-triples", res.headers['Content-Type']) Graph().parse(data=res.text, format="nt") def test_dataset_turtle(self): res = self.get(self.baseurl + "dataset/sitenews", headers={'Accept': 'text/turtle'}) self.assertTrue(res.status_code, 200) self.assertEqual("text/turtle", res.headers['Content-Type']) Graph().parse(data=res.text, format="turtle") res = self.get(self.baseurl + "dataset/sitenews.ttl") self.assertTrue(res.status_code, 200) self.assertEqual("text/turtle", res.headers['Content-Type']) Graph().parse(data=res.text, format="turtle") def test_dataset_xml(self): res = self.get(self.baseurl + "dataset/sitenews", headers={'Accept': 'application/rdf+xml'}) self.assertTrue(res.status_code, 200) self.assertEqual("application/rdf+xml", res.headers['Content-Type']) Graph().parse(data=res.text) res = self.get(self.baseurl + "dataset/sitenews.rdf") self.assertTrue(res.status_code, 200) self.assertEqual("application/rdf+xml", res.headers['Content-Type']) Graph().parse(data=res.text) def test_facsimile_page_ie_accept(self): # IE uses this accept header, which triggered a 406 error from wsgiapp # res = self.get(self.baseurl + "utr/sou/1997:39/sid557.png", res = self.get(self.baseurl + "dir/2016:15/sid1.png", headers={'Accept': "text/html, application/xhtml+xml, image/jxr, */*"}) self.assertEqual(200, res.status_code) self.assertEqual("image/png", res.headers["Content-Type"]) # assert trough first 8 bytes (magic number) that this really # is a legit png import binascii self.assertEqual(b"89504e470d0a1a0a", binascii.hexlify(res.content[:8])) class TestAnnotations(TestLagen): def test_inbound_links(self): res = self.get(self.baseurl + "1949:105/data", True, headers={'Accept': 'application/rdf+xml'}) graph = Graph().parse(data=res.text, format="xml") resource = graph.resource(URIRef("https://lagen.nu/1949:105")) self.assertEqual(str(resource.value(DCTERMS.title)), "Tryckfrihetsförordning (1949:105)") # Assert a few things about inbound relations resource = graph.resource(URIRef("https://lagen.nu/1949:105#K3P3")) # see if an expected legal case + inbound statute reference is # as expected resource2 = next(x for x in resource.objects(RPUBL.isLagrumFor) if x._identifier == URIRef("https://lagen.nu/dom/nja/2015s166")) self.assertEqual("NJA 2015 s. 166", str(resource2.value(DCTERMS.identifier))) resource2 = next(x for x in resource.objects(DCTERMS.isReferencedBy) if x._identifier == URIRef("https://lagen.nu/1991:1469#K10P1S5")) self.assertEqual("10 kap. 1 § 5 st Yttrandefrihetsgrundlag (1991:1469)", str(resource2.value(DCTERMS.identifier))) self.assertIn("Anonymiteten skyddas genom att", resource.value(DCTERMS.description)) def test_wiki_comments(self): res = self.get(self.baseurl + "1949:105") # make sure the wiki commentary is weaved in. NOTE: if the # wiki commentary changes, this test has to be updated. self.assertIn("Hemsidor, bloggar och innehållet i andra databaser", res.text) def test_wiki_concept(self): res = self.get(self.baseurl + "begrepp/Sekundär_sekretessbestämmelse") self.assertNotIn("Beskrivning saknas!", res.text) class TestSearch(TestLagen): def totalhits(self, soup): return int(soup.find("h1").text.split()[0]) def test_basic_search(self): # assert that left nav contains a number of results with at least x hits res = self.get(self.baseurl + "search/?q=personuppgift", raise_for_status=True) soup = BeautifulSoup(res.text, "lxml") self.assertGreaterEqual(self.totalhits(soup), 14) nav = soup.find("nav", id="toc") for repo, minhits in (("dv", 3), ("prop", 3), ("myndfs", 2), ("sou", 2), ("ds", 1), ("mediawiki", 1), ("sfs", 1), ("static", 1)): link = nav.find("a", href=re.compile("type=%s" % repo)) self.assertIsNotNone(link, "Found no nav link of type=%s" % repo) hits = int(link.parent.span.text) # a <span class="badge pull-right">42</span> self.assertGreaterEqual(hits, minhits, "Expected more hits for %s" % repo) def test_faceted_search(self): res = self.get(self.baseurl + "search/?q=personuppgift", raise_for_status=True) totalhits = self.totalhits(BeautifulSoup(res.text, "lxml")) soup = BeautifulSoup(self.get(self.baseurl + "search/?q=personuppgift&type=dv").text, "lxml") self.assertLess(self.totalhits(soup), totalhits) # for some reason, this search keyword yields ghost hits when using faceting totalhits = self.totalhits(BeautifulSoup(self.get( self.baseurl + "search/?q=avtal").text, "lxml")) soup = BeautifulSoup(self.get(self.baseurl + "search/?q=avtal&type=dv").text, "lxml") self.assertLess(self.totalhits(soup), totalhits) # go on and test that the facets in the navbar is as they should def test_sfs_title(self): soup = BeautifulSoup(self.get(self.baseurl + "search/?q=personuppgiftslag").text, "lxml") # examine if the first hit is the SFS with that exact title # (well, actually a title that starts with the exact same # string). NB: The SFS should rank above prop 1997/98:44 which # has the exact same title. We do this by boosting the sfs # index. hits = soup.find_all("section", "hit") hit = hits[0] self.assertEqual(hit.b.a.get("href"), "/1998:204") for hit in hits: self.assertNotRegex(hit.b.a.text, "SFS \d+:\d+", "placeholder title used instead of real SFS title") def test_stemming(self): # "bulvanutredning" never occurs in the plain text, but # "bulvanutredningen" does. Check if proper stemming has been # applied when indexing soup = BeautifulSoup(self.get(self.baseurl + "search/?q=bulvanutredning").text, "lxml") hit = soup.find("section", "hit") self.assertTrue(hit) # also, check that the query itself is properly stemmed. It'd # be weird if "bulvanutredningen" yielded no hits as the exact # word occurs in the text. soup = BeautifulSoup(self.get(self.baseurl + "search/?q=bulvanutredningen").text, "lxml") hit = soup.find("section", "hit") self.assertTrue(hit) def test_scoring(self): # really a regression test -- this query should never match anything other than prop/sou/ds/dir soup = BeautifulSoup(self.get(self.baseurl + "search/?q=bulvanutredningen").text, "lxml") hits = soup.find_all("section", "hit") self.assertTrue(hits) for hit in hits: self.assertTrue(hit.b.a.get("href").startswith(("/prop/", "/dir/", "/sou/", "/ds/")), "%s isn't prop/dir/sou/ds" % hit.b.a.get("href")) def test_innerhits(self): soup = BeautifulSoup(self.get(self.baseurl + "search/?q=personuppgiftsbiträde&type=sou&issued=2016").text, "lxml") # should match SOU 2016:41 firsthit = soup.find_all("section", "hit")[0] # assert that the hit has no content apart FROM innerhits maintext = "".join([x.get_text().strip() for x in firsthit.find_all("p", class_=False)]) self.assertEqual("", maintext) innerhits = soup.find_all("p", "innerhit") self.assertTrue(len(innerhits)) for innerhit in innerhits: link = innerhit.a.get("href") self.assertTrue("#S" in link or "#B" in link or "#kommentar" in link, "link %s doesn't look section-y" % link) self.assertNotIn("(beteckning saknas)", innerhit.a.text) class TestAutocomplete(TestLagen): def test_basic_sfs(self): res = self.get(self.baseurl + "api/?q=3+§+personuppgiftslag&_ac=true", headers={'Accept': 'application/json'}) # returns eg [{'url': 'http://localhost:8000/1998:204#P3', # 'label': '3 § personuppgiftslagen', # 'desc': 'I denna lag används följande ' # 'beteckningar med nedan angiven...'}, # {'url': 'http://localhost:8000/dom/nja/2015s180', # 'desc': 'NJA 2015 s. 180', # NB! Is :identifier not :title # 'label': 'Lagring av personuppgifter ' # '(domstols dagboksblad) i dator har' # ' ansetts inte omfattad av ...'}] self.assertEqual('application/json', res.headers['Content-Type']) hits = res.json() self.assertEqual(hits[0]['url'], self.baseurl + "1998:204#P3") self.assertTrue(hits[0]['desc'].startswith("I denna lag")) self.assertGreaterEqual(len(hits), 1) # "3 § # Personuppgiftslagen" # only matches one thing # ("personuppgiftslagen # 3" matches several) def test_shortform_sfs(self): res = self.get(self.baseurl + "api/?q=TF+2:&_ac=true", headers={'Accept': 'application/json'}) hits = res.json() # for idx, h in enumerate(hits): # print(idx+1, h['url']) # We assume that the first section retrieved will be section 1 # ("2 kap 1 §"). This requires that the search returns hits in # the same order that they were indexed in, which might not # always be guaranteed. self.assertEqual(hits[0]['url'], self.baseurl + "1949:105#K2P1") self.assertEqual(hits[0]['label'], "2 kap. 1 § Tryckfrihetsförordning (1949:105)") self.assertTrue(hits[0]['desc'].startswith("Till främjande av ett fritt meningsutbyte")) def test_incomplete_lawname(self): res = self.get(self.baseurl + "api/?q=personuppgiftsl&_ac=true", headers={'Accept': 'application/json'}) hits = res.json() self.assertEqual(hits[0]['url'], self.baseurl + "1998:204") self.assertEqual(hits[0]['label'], "Personuppgiftslag (1998:204)") res = self.get(self.baseurl + "api/?q=TRYCK&_ac=true", # check that case insensitivity works headers={'Accept': 'application/json'}) hits = res.json() self.assertEqual(hits[0]['url'], self.baseurl + "1949:105") self.assertEqual(hits[0]['label'], "Tryckfrihetsförordning (1949:105)") def test_basic_dv(self): res = self.get(self.baseurl + "api/?q=NJA+2015+s+16&_ac=true", headers={'Accept': 'application/json'}) hits = res.json() wantedhit = None for hit in hits: if hit['url'] == self.baseurl + "dom/nja/2015s166": wantedhit = hit self.assertTrue(wantedhit) self.assertEqual(wantedhit['label'], "NJA 2015 s. 166") self.assertEqual(wantedhit['desc'], "Brott mot tystnadsplikten enligt tryckfrihetsförordningen.") def test_basic_prop(self): res = self.get(self.baseurl + "api/?q=prop+1997/98:4&_ac=true", headers={'Accept': 'application/json'}) hits = res.json() wantedhit = None self.assertLessEqual(len(hits), 10) # return at most 10 hits for hit in hits: if hit['url'] == self.baseurl + "prop/1997/98:44": wantedhit = hit # for this kind of query, only documents, not doc # fragments (pages) should be returned self.assertFalse("#sid" in hit['url'], "%s is page fragment not doc" % hit['url']) # make sure the doc we want is among the 10 self.assertTrue(wantedhit) self.assertEqual(wantedhit['label'], "Prop. 1997/98:44") self.assertEqual(wantedhit['desc'], "Personuppgiftslag") # this is a local test, don't need to run it if we're running the test # suite against a remote server @unittest.skipIf(os.environ.get("FERENDA_TESTURL"), "Not testing against local dev server") class TestACExpand(unittest.TestCase): def setUp(self): self.wsgiapp = WSGIApp(repos=[SFS(datadir="tng.lagen.nu/data")]) def test_expand_shortname(self): self.assertEqual("https://lagen.nu/1949:105#K", self.wsgiapp.expand_partial_ref("TF")) def test_expand_chapters(self): self.assertEqual("https://lagen.nu/1949:105#K1", self.wsgiapp.expand_partial_ref("TF 1")) def test_expand_all_sections(self): self.assertEqual("https://lagen.nu/1949:105#K1P", self.wsgiapp.expand_partial_ref("TF 1:")) def test_expand_prefixed_sections(self): self.assertEqual("https://lagen.nu/1949:105#K1P1", self.wsgiapp.expand_partial_ref("TF 1:1")) def test_chapterless_expand_all_sections(self): self.assertTrue(os.path.exists("tng.lagen.nu/data/sfs/distilled/1998/204.rdf")) self.assertEqual("https://lagen.nu/1998:204#P", self.wsgiapp.expand_partial_ref("PUL")) def test_chapterless_expand_prefixed_sections(self): self.assertTrue(os.path.exists("tng.lagen.nu/data/sfs/distilled/1998/204.rdf")) self.assertEqual("https://lagen.nu/1998:204#P3", self.wsgiapp.expand_partial_ref("PUL 3")) def test_prop_start(self): self.assertEqual("https://lagen.nu/prop/", self.wsgiapp.expand_partial_ref("prop")) def test_prop_incomplete_year(self): self.assertEqual("https://lagen.nu/prop/199", self.wsgiapp.expand_partial_ref("prop 199")) def test_prop_year(self): self.assertEqual("https://lagen.nu/prop/1997", self.wsgiapp.expand_partial_ref("prop 1997")) def test_prop_missing_num(self): self.assertEqual("https://lagen.nu/prop/1997/98:", self.wsgiapp.expand_partial_ref("prop 1997/98:")) def test_prop_complete(self): self.assertEqual("https://lagen.nu/prop/1997/98:44", self.wsgiapp.expand_partial_ref("prop 1997/98:44")) def test_prop_missing_page(self): self.assertEqual("https://lagen.nu/prop/1997/98:44#sid", self.wsgiapp.expand_partial_ref("prop 1997/98:44 s")) def test_prop_complete(self): self.assertEqual("https://lagen.nu/prop/1997/98:44#sid12", self.wsgiapp.expand_partial_ref("prop 1997/98:44 s. 12")) @unittest.skipIf(":8000" in os.environ.get("FERENDA_TESTURL", "http://localhost:8000"), "Not testing against dev server") class TestNginxServing(TestLagen): def assertNginx(self, url): res = self.get(url) self.assertIsNone(res.headers.get("X-WSGI-app"), "%s wasn't served by nginx directly" % url) def assertWsgi(self, url): res = self.get(url) self.assertEqual("ferenda", res.headers.get("X-WSGI-app"), "%s wasn't served by the WSGI app" % url) def test_frontpage(self): self.assertNginx(self.baseurl) def test_doc(self): self.assertNginx(self.baseurl + "dom/nja/2015s180") def test_toc(self): self.assertNginx(self.baseurl + "dataset/dv") def test_search(self): self.assertWsgi(self.baseurl + "search/?q=personuppgift") class TestKeywordToc(unittest.TestCase): maxDiff = None def makeitem(self, text): return [Link(text, uri="https://lagen.nu/begrepp/" + text.replace("»", "//").replace(" ", "_"))] def do_test(self, keywords, want): repo = LNKeyword() body = repo.toc_generate_page_body(map(self.makeitem, keywords), None) got = serialize(body[1]) self.assertEqual(want, got) def test_prefix_segmentation(self): self.do_test(["Abc", "Abd", "Abe", "Afg", "Ahi", "Ahj", "Ahk"], """<Div class="threecol"> <H2> <str>Ab</str> </H2> <UnorderedList> <ListItem> <Link uri="https://lagen.nu/begrepp/Abc">Abc</Link> </ListItem><ListItem> <Link uri="https://lagen.nu/begrepp/Abd">Abd</Link> </ListItem><ListItem> <Link uri="https://lagen.nu/begrepp/Abe">Abe</Link> </ListItem> </UnorderedList> <H2> <str>Af</str> </H2> <UnorderedList> <ListItem> <Link uri="https://lagen.nu/begrepp/Afg">Afg</Link> </ListItem> </UnorderedList> <H2> <str>Ah</str> </H2> <UnorderedList> <ListItem> <Link uri="https://lagen.nu/begrepp/Ahi">Ahi</Link> </ListItem><ListItem> <Link uri="https://lagen.nu/begrepp/Ahj">Ahj</Link> </ListItem><ListItem> <Link uri="https://lagen.nu/begrepp/Ahk">Ahk</Link> </ListItem> </UnorderedList> </Div> """) def test_segmentation_casing(self): self.do_test(["Albanien", "ALFA", "Algolean"], """<Div class="threecol"> <H2> <str>Al</str> </H2> <UnorderedList> <ListItem> <Link uri="https://lagen.nu/begrepp/Albanien">Albanien</Link> </ListItem><ListItem> <Link uri="https://lagen.nu/begrepp/ALFA">ALFA</Link> </ListItem><ListItem> <Link uri="https://lagen.nu/begrepp/Algolean">Algolean</Link> </ListItem> </UnorderedList> </Div> """) def test_nested(self): self.do_test(["Abc", "Abc»D", "Abc»D»Efg", "Abc»D»Hij", # Note that there is no "Abc»K" entry -- the test should create a non-linked "phantom" entry "Abc»K»Lmn", "Abc»K»Opq", "Ars"], """<Div class="threecol"> <H2> <str>Ab</str> </H2> <UnorderedList> <ListItem> <Link uri="https://lagen.nu/begrepp/Abc">Abc</Link> <UnorderedList> <ListItem> <Link uri="https://lagen.nu/begrepp/Abc//D">D</Link> <UnorderedList> <ListItem> <Link uri="https://lagen.nu/begrepp/Abc//D//Efg">Efg</Link> </ListItem><ListItem> <Link uri="https://lagen.nu/begrepp/Abc//D//Hij">Hij</Link> </ListItem> </UnorderedList> </ListItem><ListItem> <str>K</str> <UnorderedList> <ListItem> <Link uri="https://lagen.nu/begrepp/Abc//K//Lmn">Lmn</Link> </ListItem><ListItem> <Link uri="https://lagen.nu/begrepp/Abc//K//Opq">Opq</Link> </ListItem> </UnorderedList> </ListItem> </UnorderedList> </ListItem> </UnorderedList> <H2> <str>Ar</str> </H2> <UnorderedList> <ListItem> <Link uri="https://lagen.nu/begrepp/Ars">Ars</Link> </ListItem> </UnorderedList> </Div> """) def test_nested_mixed(self): self.do_test(["Abc", "Abc»D", "Abf", "Abf»G"], """<Div class="threecol"> <H2> <str>Ab</str> </H2> <UnorderedList> <ListItem> <Link uri="https://lagen.nu/begrepp/Abc">Abc</Link> <UnorderedList> <ListItem> <Link uri="https://lagen.nu/begrepp/Abc//D">D</Link> </ListItem> </UnorderedList> </ListItem><ListItem> <Link uri="https://lagen.nu/begrepp/Abf">Abf</Link> <UnorderedList> <ListItem> <Link uri="https://lagen.nu/begrepp/Abf//G">G</Link> </ListItem> </UnorderedList> </ListItem> </UnorderedList> </Div> """) def test_phantoms(self): self.do_test(["Alkoholdryck»Sprit", "Allmän försäkring»Sjukpenninggrundande inkomst"], """<Div class="threecol"> <H2> <str>Al</str> </H2> <UnorderedList> <ListItem> <str>Alkoholdryck</str> <UnorderedList> <ListItem> <Link uri="https://lagen.nu/begrepp/Alkoholdryck//Sprit">Sprit</Link> </ListItem> </UnorderedList> </ListItem><ListItem> <str>Allmän försäkring</str> <UnorderedList> <ListItem> <Link uri="https://lagen.nu/begrepp/Allmän_försäkring//Sjukpenninggrundande_inkomst">Sjukpenninggrundande inkomst</Link> </ListItem> </UnorderedList> </ListItem> </UnorderedList> </Div> """) def test_threelevels_phantom(self): self.do_test(["Analysmetod", "Analys»Principalkomponentanalys»Sensorisk analys"], """<Div class="threecol"> <H2> <str>An</str> </H2> <UnorderedList> <ListItem> <Link uri="https://lagen.nu/begrepp/Analysmetod">Analysmetod</Link> </ListItem><ListItem> <str>Analys</str> <UnorderedList> <ListItem> <str>Principalkomponentanalys</str> <UnorderedList> <ListItem> <Link uri="https://lagen.nu/begrepp/Analys//Principalkomponentanalys//Sensorisk_analys">Sensorisk analys</Link> </ListItem> </UnorderedList> </ListItem> </UnorderedList> </ListItem> </UnorderedList> </Div> """) def test_nested_wat(self): # Some corner cases that broke the previous version of # toc_generate_page_body_thread self.do_test(['Allmän försäkring»Sjukpenninggrundande inkomst', 'Allmän försäkring vårdbidrag', 'Allmän försäkring»Återbetalning av sjukpenning'], """<Div class="threecol"> <H2> <str>Al</str> </H2> <UnorderedList> <ListItem> <str>Allmän försäkring</str> <UnorderedList> <ListItem> <Link uri="https://lagen.nu/begrepp/Allmän_försäkring//Sjukpenninggrundande_inkomst">Sjukpenninggrundande inkomst</Link> </ListItem> </UnorderedList> </ListItem><ListItem> <Link uri="https://lagen.nu/begrepp/Allmän_försäkring_vårdbidrag">Allmän försäkring vårdbidrag</Link> </ListItem><ListItem> <str>Allmän försäkring</str> <UnorderedList> <ListItem> <Link uri="https://lagen.nu/begrepp/Allmän_försäkring//Återbetalning_av_sjukpenning">Återbetalning av sjukpenning</Link> </ListItem> </UnorderedList> </ListItem> </UnorderedList> </Div> """) self.do_test(['Allmän försäkring vårdbidrag', 'Allmän försäkring»Återbetalning av sjukpenning'], """<Div class="threecol"> <H2> <str>Al</str> </H2> <UnorderedList> <ListItem> <Link uri="https://lagen.nu/begrepp/Allmän_försäkring_vårdbidrag">Allmän försäkring vårdbidrag</Link> </ListItem><ListItem> <str>Allmän försäkring</str> <UnorderedList> <ListItem> <Link uri="https://lagen.nu/begrepp/Allmän_försäkring//Återbetalning_av_sjukpenning">Återbetalning av sjukpenning</Link> </ListItem> </UnorderedList> </ListItem> </UnorderedList> </Div> """) class MetadataOnly(TestLagen): # a document marked as "metadataonly" in options.py should return # a 404 when requested, but the response should still be a custom # page (saved to disk as eg sou/generated/2008/5.html.404) with # proper title, links to source, explanation etc def test_404_status(self): res = self.get(self.baseurl + "sou/2008:5") self.assertEqual(res.status_code, 404) # should have a proper header self.assertIn("Könsdiskriminerande reklam", res.text) # should have an explaination self.assertIn("<h2>Dokumenttext saknas</h2>", res.text) # should have links to source self.assertIn('<a href="https://www.regeringen.se/rattsliga-dokument/statens-offentliga-utredningar/2008/01/sou-20085/">Källa</a>', res.text) # should be generated by wsgi app self.assertEqual("ferenda", res.headers.get("X-WSGI-app"), "%s wasn't served by the WSGI app" % self.baseurl + "sou/2008:5") # the local dev environment, as specified by # lagen/nu/res/scripts/testdata.txt, doesn't have all these documents @unittest.skipIf(":8000" in os.environ.get("FERENDA_TESTURL", "http://localhost:8000"), "Not testing against dev server") class Regressions(TestLagen): # this is really a testcase built from a extensive bug report, # containing 9 numbered issues. Some of those are suggestions or # otherwise untestable, but the testable things are written as # test cases here def test_sfs_source(self): # issue 1 b res = self.get(self.baseurl + "2002:562") soup = BeautifulSoup(res.text, "lxml") dep = soup.find("dt", text="Departement").find_next_sibling("dd") self.assertEqual("Näringsdepartementet RS N", dep.text) def test_facsimiles(self): # issue 3 for urlseg, pages in (("prop/1915:83", [29]), # new kind of repo ("prop/2004/05:147", [36, 48]), ("prop/1997/98:177", [18, 30, 32]), ("prop/1997/98:179", [57, 58, 43]), ("prop/2007/08:95", [56, 295, 296]), ("prop/1998/99:90", [18, 23]), ("prop/1996/97:141", [19]), ("prop/1996/97:106", [22]), # based on index.wpd, not a PDF ("sou/1944:59", [15]), ("sou/1944:49", [15]), ("prop/1978/79:11", [15]), ("prop/2008/09:14", [15]), ("prop/2011/12:115", [15]), ("prop/1980/81:44", [15]), ("prop/1996/97:9", [1]), ): for page in pages: url = self.baseurl + urlseg + "/sid%s.png" % page self.assert200(url) def test_format(self): # issue 4 for urlseg in ("prop/1994/95:76", "prop/1994/95:93", "prop/1994/95:89", "prop/1994/95:102", "prop/1994/95:115", "prop/1993/94:65", "prop/1993/94:67", "prop/1993/94:242"): res = self.get(self.baseurl + urlseg) res.raise_for_status() self.assertTrue("<pre>" not in res.text) def test_missing_pages(self): # issue 5: "I prop. 1992/93:30 saknas s. 18–30. Prop. 1996/97:106 är ofullständig (har bara två sidor)" # # added: I SOU 2002:18 saknas s. 6–15. I SOU 1997:58 saknas s. 6 och 7. for urlseg, expected_missing in ( ("prop/1992/93:30", []), ("prop/1996/97:106", [3, ]), ("sou/2002:18", []), # should be [6,7,8,9,10,11,12,13,14] once we identify and omit the TOC ("sou/1997:58", [1,2,6,7]) # more to do: # Prop. 1995/96:115 är ofullständig. # I prop. 1983/84:78 är sidnumreringen fel fr.o.m. s. 12 (som har fått sidnummer 21). # I prop. 2008/09:67 är sidnumreringen fel och saknas s. 4–7. # I Ds 2002:56 är sidnumreringen fel. # I prop. 1996/97:9 saknas bildfiler och verkar det vara något konstigt med sidnumreringen. # I SOU 1997:44 är det fel på s. 5 (den skannade texten är annan än den på bilden) och s. 6–9 saknas. ): res = self.get(self.baseurl + urlseg) res.raise_for_status() soup = BeautifulSoup(res.text, "lxml") pages = soup.find_all("div", "sida") # any prop should have at least 10 pages self.assertGreater(len(pages), 10) # make sure there are no missing pages (except those we # expect to be missing, due to them being TOC pages) pagenum = 1 for page in pages: while pagenum in expected_missing: pagenum += 1 self.assertEqual(str(pagenum), page.get("id")[3:], urlseg) pagenum += 1 def test_missing_docs(self): # issue 6 for urlseg in ("prop/1992/93:40", # left out by design since noone refers to it "prop/1991/92:155", # left out by design since noone refers to it "prop/1973:90", "prop/1996/97:72", "prop/1995/96:79", # left out by design since noone refers to it # "prop/2007/08:85", # does this one even exist? "dir/1989:50", # requested, but had parsing errors "prop/2004/05:17", # requested, but had parsing errors ): self.assert200(self.baseurl + urlseg) def test_doc_version(self): # Av SOU 2009:44 fanns tidigare bara den engelska sammanfattningen med. for urlseg, expected_title in ( ("sou/2009:44", "Integritetsskydd i arbetslivet"), ): res = self.get(self.baseurl + urlseg + ".rdf") res.raise_for_status() # once that gets working: # 1 load into a rdflib graph, # 2 find root, # 3 get dcterms:title, # 4 compare to expected_title def test_identifier_formats(self): # issue 7 for urlseg in ("dir/1987:42", "dir/1987:7"): res = self.get(self.baseurl + urlseg) res.raise_for_status() soup = BeautifulSoup(res.text, "lxml") # directly underneath <article> there should be no nodes w/o class "row" for node in soup.find("article").children: if isinstance(node, str): continue self.assertIn("row", node.get("class", [])) tocs = (("dir", 1987, "^Dir\. (19|20)\d{2}:[1-9]\d{,2}$"), ("ds", 2001, "^Ds (19|20)\d{2}:[1-9]\d{,2}$"), # first published is from 1995 but published coverage the first few years is spotty ("sou", 1922, "^SOU (19|20)\d{2}:[1-9]\d{,2}$"), ("prop", 1971, "^Prop\. (19|20)\d{2}(|/\d{2}|/2000):[1-9]\d{,2}$")) def test_toc(self): # issue 8 errors = [] for doctype, startyear, regex in self.tocs: for year in range(startyear, 2018): if doctype == "prop" and year > 1975: nextyear = "2000" if year == 2000 else str(year)[2:] year = "%s/%s" % (year - 1, nextyear) url = "dataset/forarbeten?%s=%s" % (doctype, year) res = self.get(self.baseurl + url) res.raise_for_status() soup = BeautifulSoup(res.text, "lxml") links = 0 for idx, link in enumerate(soup.find("article").find_all("a")): # self.assertRegexpMatches(link.text, regex) if not re.match(regex, link.text): errors.append("%s/%s: %s (%s)" % (doctype, year, link.text, link.get("href"))) self.maxDiff = None self.assertEqual([], errors) def test_toc_coverage(self): errors = [] for doctype, startyear, regex in self.tocs: for year in range(startyear, 2018): if doctype == "prop" and year > 1975: nextyear = "2000" if year == 2000 else str(year)[2:] year = "%s/%s" % (year - 1, nextyear) url = "dataset/forarbeten?%s=%s" % (doctype, year) res = self.get(self.baseurl + url) res.raise_for_status() soup = BeautifulSoup(res.text, "lxml") links = soup.find("article").find_all("a") link = links[-1] maxidx = int(re.search("\:(\d+)$", link.text).group(1)) # no more than 10 % of indexes may be missing coverage = (len(links)+1)/maxidx # propositioner shares a ordinal series with # skrivelser (which we don't include, and which can be # up to a third of total output per year), so we need to # lower our coverage expectations expected_coverage = 0.65 if doctype == "prop" else 0.9 if coverage < expected_coverage: errors.append("%s/%s: coverage %s" % (doctype, year, coverage)) # self.assertGreaterEqual(coverage, 0.9, url) self.maxDiff = None self.assertEqual([], errors) # and some other bugs described in a second mail. # 1. SOU 1995:149, SOU 2004:23, SOU 2006:22, SOU 2014:49, # prop. 2009/10:165, prop. 2013/14:198 och prop. 2009/10:160 # saknar bildfiler, t.ex. s. 15. # # the issue is that links to facsimile pages are # incorrectly-relative ("2014:49/sid3.png" instead of # "/sou/2014:49/sid3.png") def test_facsimile_links(self): for urlseg in ("sou/1995:149", "sou/2004:23", "sou/2006:22", "sou/2014:49", "prop/2009/10:165", "prop/2013/14:198", "prop/2009/10:160"): res = self.get(self.baseurl + urlseg) res.raise_for_status() soup = BeautifulSoup(res.text, "lxml") found = False for a in soup.find_all("a", "facsimile"): found = True self.assertIn(urlseg, a.get("href")) self.assertIn(urlseg, a.img.get("data-src")) self.assertTrue(found, urlseg) class AcceptableStatus(TestLagen): def test_status(self): def assert_stats(line, maxfail, maxwarn, repo="toplevel"): m = re.match(r"(\d+) % failed,\s*(\d+) % warnings", line) fail, warn = m.groups() self.assertLessEqual(int(fail), maxfail, "%s has more than %s %% fails" % (repo, maxfail)) self.assertLessEqual(int(warn), maxwarn, "%s has more than %s %% warns" % (repo, maxwarn)) res = self.get(self.baseurl + "status/status.html") soup = BeautifulSoup(res.text, "lxml") # 1 make sure h1.small is at most a day old gentime = datetime.strptime(soup.find("h1").small.text.strip()[:19], "%Y-%m-%dT%H:%M:%S") days = (datetime.now() - gentime).days self.assertLessEqual(days, 76) # 2 make sure total fail < 3 %, warnings < 20 % stats = soup.select("p > small") assert_stats(stats.pop(0).text, 3, 20) # 3 make sure that for each repo, fail < 6 %, warnings < 65 % (yeah this should be lower but myndfs...) for s in stats: repo = s.parent.find_previous_sibling("h2").text assert_stats(s.text, 6, 65, repo)
songyuyuyu/x-pipe
redis/redis-checker/src/main/java/com/ctrip/xpipe/redis/checker/healthcheck/actions/interaction/event/InstanceHalfSick.java
package com.ctrip.xpipe.redis.checker.healthcheck.actions.interaction.event; import com.ctrip.xpipe.redis.checker.healthcheck.RedisHealthCheckInstance; import com.ctrip.xpipe.utils.ObjectUtils; public class InstanceHalfSick extends AbstractInstanceEvent { public InstanceHalfSick(RedisHealthCheckInstance instance) { super(instance); } @Override public int hashCode() { return ObjectUtils.hashCode(instance.getCheckInfo().getHostPort()); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof InstanceHalfSick)) { return false; } InstanceHalfSick other = (InstanceHalfSick) obj; return other.instance.getCheckInfo().getHostPort().equals(this.instance.getCheckInfo().getHostPort()); } }
JavaQualitasCorpus/cayenne-3.0.1
framework/cayenne-modeler/src/main/java/org/apache/cayenne/modeler/util/ProjectUtil.java
<gh_stars>0 /***************************************************************** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. ****************************************************************/ package org.apache.cayenne.modeler.util; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import org.apache.cayenne.access.DataDomain; import org.apache.cayenne.access.DataNode; import org.apache.cayenne.conf.Configuration; import org.apache.cayenne.map.Attribute; import org.apache.cayenne.map.DataMap; import org.apache.cayenne.map.DbAttribute; import org.apache.cayenne.map.DbEntity; import org.apache.cayenne.map.DbJoin; import org.apache.cayenne.map.DbRelationship; import org.apache.cayenne.map.Embeddable; import org.apache.cayenne.map.EmbeddableAttribute; import org.apache.cayenne.map.Entity; import org.apache.cayenne.map.EntityResolver; import org.apache.cayenne.map.MappingNamespace; import org.apache.cayenne.map.ObjAttribute; import org.apache.cayenne.map.ObjEntity; import org.apache.cayenne.map.ObjRelationship; import org.apache.cayenne.map.Procedure; import org.apache.cayenne.map.ProcedureParameter; import org.apache.cayenne.map.Relationship; import org.apache.cayenne.query.AbstractQuery; import org.apache.cayenne.query.EJBQLQuery; import org.apache.cayenne.query.Query; import org.apache.cayenne.util.Util; /** * Provides utility methods to perform various manipulations with project objects. */ public class ProjectUtil { public static void setProcedureParameterName( ProcedureParameter parameter, String newName) { String oldName = parameter.getName(); // If name hasn't changed, just return if (Util.nullSafeEquals(oldName, newName)) { return; } Procedure procedure = parameter.getProcedure(); procedure.removeCallParameter(parameter.getName()); parameter.setName(newName); procedure.addCallParameter(parameter); } public static void setDataMapName(DataDomain domain, DataMap map, String newName) { String oldName = map.getName(); // If name hasn't changed, just return if (Util.nullSafeEquals(oldName, newName)) { return; } // must fully relink renamed map List<DataNode> nodes = new ArrayList<DataNode>(); for (DataNode node : domain.getDataNodes()) if (node.getDataMaps().contains(map)) nodes.add(node); domain.removeMap(oldName); map.setName(newName); domain.addMap(map); for (DataNode node : nodes) { node.removeDataMap(oldName); node.addDataMap(map); } } public static void setDataDomainName( Configuration configuration, DataDomain domain, String newName) { String oldName = domain.getName(); // If name hasn't changed, just return if (Util.nullSafeEquals(oldName, newName)) { return; } domain.setName(newName); configuration.removeDomain(oldName); configuration.addDomain(domain); } public static void setDataNodeName(DataDomain domain, DataNode node, String newName) { String oldName = node.getName(); node.setName(newName); domain.removeDataNode(oldName); domain.addNode(node); } public static void setProcedureName(DataMap map, Procedure procedure, String newName) { String oldName = procedure.getName(); // If name hasn't changed, just return if (Util.nullSafeEquals(oldName, newName)) { return; } procedure.setName(newName); map.removeProcedure(oldName); map.addProcedure(procedure); // important - clear parent namespace: MappingNamespace ns = map.getNamespace(); if (ns instanceof EntityResolver) { ((EntityResolver) ns).clearCache(); } } public static void setQueryName(DataMap map, Query query, String newName) { String oldName = query.getName(); // If name hasn't changed, just return if (Util.nullSafeEquals(oldName, newName)) { return; } if (query instanceof AbstractQuery) { ((AbstractQuery) query).setName(newName); } if (query instanceof EJBQLQuery) { ((EJBQLQuery) query).setName(newName); } map.removeQuery(oldName); map.addQuery(query); // important - clear parent namespace: MappingNamespace ns = map.getNamespace(); if (ns instanceof EntityResolver) { ((EntityResolver) ns).clearCache(); } } public static void setObjEntityName(DataMap map, ObjEntity entity, String newName) { String oldName = entity.getName(); // If name hasn't changed, just return if (Util.nullSafeEquals(oldName, newName)) { return; } entity.setName(newName); map.removeObjEntity(oldName, false); map.addObjEntity(entity); // important - clear parent namespace: MappingNamespace ns = map.getNamespace(); if (ns instanceof EntityResolver) { ((EntityResolver) ns).clearCache(); } } /** * Renames a DbEntity and changes the name of all references. */ public static void setDbEntityName(DbEntity entity, String newName) { String oldName = entity.getName(); // If name hasn't changed, just return if (Util.nullSafeEquals(oldName, newName)) { return; } entity.setName(newName); DataMap map = entity.getDataMap(); if (map != null) { map.removeDbEntity(oldName, false); map.addDbEntity(entity); // important - clear parent namespace: MappingNamespace ns = map.getNamespace(); if (ns instanceof EntityResolver) { ((EntityResolver) ns).clearCache(); } } } /** * Changes the name of the attribute and all references to this attribute. */ public static void setAttributeName(Attribute attribute, String newName) { String oldName = attribute.getName(); attribute.setName(newName); Entity entity = attribute.getEntity(); if (entity != null) { entity.removeAttribute(oldName); entity.addAttribute(attribute); } } /** * Changes the name of the embeddable attribute and all references to this embeddable attribute. */ public static void setEmbeddableAttributeName(EmbeddableAttribute attribute, String newName) { String oldName = attribute.getName(); attribute.setName(newName); Embeddable embeddable = attribute.getEmbeddable(); if (embeddable != null) { embeddable.removeAttribute(oldName); embeddable.addAttribute(attribute); } } /** Changes the name of the attribute in all places in DataMap. */ public static void setRelationshipName(Entity entity, Relationship rel, String newName) { if (rel == null || rel != entity.getRelationship(rel.getName())) { return; } entity.removeRelationship(rel.getName()); rel.setName(newName); entity.addRelationship(rel); } /** * Cleans any mappings of ObjEntities, ObjAttributes, ObjRelationship to the * corresponding Db* objects that not longer exist. */ public static void cleanObjMappings(DataMap map) { for (ObjEntity entity : map.getObjEntities()) { DbEntity dbEnt = entity.getDbEntity(); // the whole entity mapping is invalid if (dbEnt != null && map.getDbEntity(dbEnt.getName()) != dbEnt) { clearDbMapping(entity); continue; } // check individual attributes for (ObjAttribute att : entity.getAttributes()) { // If flattenet atribute if (att.getDbAttributePath() != null && att.getDbAttributePath().contains(".")) { String[] pathSplit = att.getDbAttributePath().split("\\."); // If flattened attribute if (pathSplit.length > 1) { DbEntity currentEnt = dbEnt; StringBuilder pathBuf = new StringBuilder(); boolean isTruePath = true; if (currentEnt != null) { for (int j = 0; j < pathSplit.length; j++) { if (j == pathSplit.length - 1 && isTruePath) { DbAttribute dbAttribute = (DbAttribute) currentEnt .getAttribute(pathSplit[j]); if (dbAttribute != null) { pathBuf.append(dbAttribute.getName()); } else { isTruePath = false; } } else if (isTruePath) { DbRelationship dbRelationship = (DbRelationship) currentEnt .getRelationship(pathSplit[j]); if (dbRelationship != null) { currentEnt = (DbEntity) dbRelationship .getTargetEntity(); pathBuf.append(dbRelationship.getName()); pathBuf.append("."); } else { isTruePath = false; } } } } if (!isTruePath) { att.setDbAttributePath(null); } } } else { DbAttribute dbAtt = att.getDbAttribute(); if (dbAtt != null) { if (dbEnt.getAttribute(dbAtt.getName()) != dbAtt) { att.setDbAttributePath(null); } } } } // check individual relationships for (ObjRelationship rel : entity.getRelationships()) { List<DbRelationship> dbRelList = new ArrayList<DbRelationship>(rel .getDbRelationships()); for (DbRelationship dbRel : dbRelList) { Entity srcEnt = dbRel.getSourceEntity(); if (srcEnt == null || map.getDbEntity(srcEnt.getName()) != srcEnt || srcEnt.getRelationship(dbRel.getName()) != dbRel) { rel.removeDbRelationship(dbRel); } } } } } /** * Clears all the mapping between this obj entity and its current db entity. Clears * mapping between entities, attributes and relationships. */ public static void clearDbMapping(ObjEntity entity) { DbEntity db_entity = entity.getDbEntity(); if (db_entity == null) { return; } for (ObjAttribute objAttr : entity.getAttributeMap().values()) { DbAttribute dbAttr = objAttr.getDbAttribute(); if (null != dbAttr) { objAttr.setDbAttributePath(null); } } for (ObjRelationship obj_rel : entity.getRelationships()) { obj_rel.clearDbRelationships(); } entity.setDbEntity(null); } /** * Returns true if one of relationship joins uses a given attribute as a source. */ public static boolean containsSourceAttribute( DbRelationship relationship, DbAttribute attribute) { if (attribute.getEntity() != relationship.getSourceEntity()) { return false; } for (DbJoin join : relationship.getJoins()) { if (join.getSource() == attribute) { return true; } } return false; } /** * Returns true if one of relationship joins uses a given attribute as a target. */ public static boolean containsTargetAttribute( DbRelationship relationship, DbAttribute attribute) { if (attribute.getEntity() != relationship.getTargetEntity()) { return false; } for (DbJoin join : relationship.getJoins()) { if (join.getTarget() == attribute) { return true; } } return false; } /** * Returns a collection of DbRelationships that use this attribute as a source. */ public static Collection<DbRelationship> getRelationshipsUsingAttributeAsSource( DbAttribute attribute) { Entity parent = attribute.getEntity(); if (parent == null) { return Collections.EMPTY_LIST; } Collection<DbRelationship> parentRelationships = (Collection<DbRelationship>) parent .getRelationships(); Collection<DbRelationship> relationships = new ArrayList<DbRelationship>( parentRelationships.size()); // Iterator it = parentRelationships.iterator(); // while (it.hasNext()) { // DbRelationship relationship = (DbRelationship) it.next(); for (DbRelationship relationship : parentRelationships) { if (ProjectUtil.containsSourceAttribute(relationship, attribute)) { relationships.add(relationship); } } return relationships; } /** * Returns a collection of DbRelationships that use this attribute as a source. */ public static Collection<DbRelationship> getRelationshipsUsingAttributeAsTarget( DbAttribute attribute) { Entity parent = attribute.getEntity(); if (parent == null) { return Collections.EMPTY_LIST; } DataMap map = parent.getDataMap(); if (map == null) { return Collections.EMPTY_LIST; } Collection<DbRelationship> relationships = new ArrayList<DbRelationship>(); for (Entity entity : map.getDbEntities()) { if (entity == parent) { continue; } Collection<DbRelationship> entityRelationships = (Collection<DbRelationship>) entity .getRelationships(); for (DbRelationship relationship : entityRelationships) { if (ProjectUtil.containsTargetAttribute(relationship, attribute)) { relationships.add(relationship); } } } return relationships; } }
robfitz273k/incubator-netbeans
hibernate/src/org/netbeans/modules/hibernate/wizards/HibernateCodeGenWizardDescriptor.java
<filename>hibernate/src/org/netbeans/modules/hibernate/wizards/HibernateCodeGenWizardDescriptor.java /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.hibernate.wizards; import java.io.File; import java.net.URL; import java.util.Arrays; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.hibernate.HibernateException; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.JDBCMetaDataConfiguration; import org.hibernate.cfg.reveng.DefaultReverseEngineeringStrategy; import org.hibernate.cfg.reveng.OverrideRepository; import org.hibernate.cfg.reveng.ReverseEngineeringSettings; import org.hibernate.cfg.reveng.ReverseEngineeringStrategy; import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; import org.netbeans.api.db.explorer.DatabaseConnection; import org.netbeans.api.project.Project; import org.netbeans.api.project.SourceGroup; import org.netbeans.modules.hibernate.cfg.model.HibernateConfiguration; import org.netbeans.modules.hibernate.loaders.cfg.HibernateCfgDataObject; import org.netbeans.modules.hibernate.service.api.HibernateEnvironment; import org.netbeans.modules.hibernate.util.CustomJDBCConnectionProvider; import org.netbeans.modules.hibernate.util.HibernateUtil; import org.netbeans.modules.j2ee.core.api.support.SourceGroups; import org.netbeans.modules.j2ee.core.api.support.java.JavaIdentifiers; import org.netbeans.spi.project.ui.templates.support.Templates; import org.openide.WizardDescriptor; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; import org.openide.loaders.DataObject; import org.openide.loaders.DataObjectNotFoundException; import org.openide.util.ChangeSupport; import org.openide.util.Exceptions; import org.openide.util.HelpCtx; import org.openide.util.NbBundle; /** * * @author gowri */ public class HibernateCodeGenWizardDescriptor implements WizardDescriptor.Panel, ChangeListener { private final ChangeSupport changeSupport = new ChangeSupport(this); private Logger logger = Logger.getLogger(HibernateCodeGenWizardDescriptor.class.getName()); private HibernateCodeGenerationPanel component; private boolean componentInitialized; private WizardDescriptor wizardDescriptor; private Project project; private String title; public HibernateCodeGenWizardDescriptor(Project project, String title) { this.project = project; this.title = title; } @Override public HibernateCodeGenerationPanel getComponent() { if (component == null) { component = new HibernateCodeGenerationPanel(); component.addChangeListener(this); } return component; } @Override public void removeChangeListener(ChangeListener listener) { changeSupport.removeChangeListener(listener); } @Override public void addChangeListener(ChangeListener listener) { changeSupport.addChangeListener(listener); } @Override public HelpCtx getHelp() { return new HelpCtx(HibernateCodeGenWizardDescriptor.class); } @Override public void readSettings(Object settings) { wizardDescriptor = (WizardDescriptor) settings; wizardDescriptor.putProperty("NewFileWizard_Title", title); HibernateCodeGenWizardHelper helper = HibernateCodeGenWizard.getHelper(wizardDescriptor); if (!componentInitialized) { componentInitialized = true; project = Templates.getProject(wizardDescriptor); FileObject targetFolder = Templates.getTargetFolder(wizardDescriptor); getComponent().initialize(project, targetFolder); } } @Override public boolean isValid() { SourceGroup sourceGroup = getComponent().getLocationValue(); DataObject cfgDataObject = null; if (getComponent().getConfigurationFile() == null) { wizardDescriptor.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE, NbBundle.getMessage(HibernateCodeGenWizardDescriptor.class, "ERR_ConfFileChooser")); // NOI18N return false; } try { cfgDataObject = DataObject.find(getComponent().getConfigurationFile()); } catch (DataObjectNotFoundException ex) { // } if(cfgDataObject != null){ HibernateCfgDataObject hco = (HibernateCfgDataObject) cfgDataObject; HibernateConfiguration config = hco.getHibernateConfiguration(); String dbDriver = HibernateUtil.getDbConnectionDetails(config, "hibernate.connection.driver_class"); //NOI18N if (dbDriver == null || "".equals(dbDriver)) { dbDriver = HibernateUtil.getDbConnectionDetails(config, "connection.driver_class"); //NOI18N } if (dbDriver == null || "".equals(dbDriver)) { wizardDescriptor.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE, NbBundle.getMessage(HibernateCodeGenWizardDescriptor.class, "ERR_No_DB_ConnectionDriver_Exists")); // NOI18N return false; } } if (getComponent().getRevengFile() == null) { wizardDescriptor.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE, NbBundle.getMessage(HibernateCodeGenWizardDescriptor.class, "ERR_RevengFileChooser")); // NOI18N return false; } try { checkConfig(getComponent().getRevengFile()); } catch (HibernateException e) { logger.log(Level.INFO, "access to hibernate fails.", e);//NOI18N wizardDescriptor.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE, NbBundle.getMessage(HibernateCodeGenWizardDescriptor.class, "ERR_HibernateError", e.getMessage())); // NOI18N return false; } catch (Exception e) { logger.log(Level.INFO, "access to hibernate fails.", e);//NOI18N wizardDescriptor.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE, NbBundle.getMessage(HibernateCodeGenWizardDescriptor.class, "ERR_HibernateError", e.toString())); // NOI18N return false; } String packageName = getComponent().getPackageName(); if (sourceGroup == null) { wizardDescriptor.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE, NbBundle.getMessage(HibernateCodeGenWizardDescriptor.class, "ERR_JavaTargetChooser_SelectSourceGroup")); // NOI18N return false; } if (packageName.trim().equals("")) { // NOI18N wizardDescriptor.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE, NbBundle.getMessage(HibernateCodeGenWizardDescriptor.class, "ERR_JavaTargetChooser_CantUseDefaultPackage")); // NOI18N return false; } if (!JavaIdentifiers.isValidPackageName(packageName)) { wizardDescriptor.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE, NbBundle.getMessage(HibernateCodeGenWizardDescriptor.class, "ERR_JavaTargetChooser_InvalidPackage")); //NOI18N return false; } if (!SourceGroups.isFolderWritable(sourceGroup, packageName)) { wizardDescriptor.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE, NbBundle.getMessage(HibernateCodeGenWizardDescriptor.class, "ERR_JavaTargetChooser_UnwritablePackage")); //NOI18N return false; } wizardDescriptor.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE, ""); //NOI18N return true; } @Override public void storeSettings(Object settings) { Object buttonPressed = ((WizardDescriptor) settings).getValue(); if (buttonPressed.equals(WizardDescriptor.NEXT_OPTION) || buttonPressed.equals(WizardDescriptor.FINISH_OPTION)) { HibernateCodeGenWizardHelper helper = HibernateCodeGenWizard.getHelper(wizardDescriptor); helper.setConfigurationFile(getComponent().getConfigurationFile()); helper.setRevengFile(getComponent().getRevengFile()); helper.setLocation(getComponent().getLocationValue()); helper.setPackageName(getComponent().getPackageName()); helper.setDomainGen(getComponent().getChkDomain()); helper.setHbmGen(getComponent().getChkHbm()); helper.setJavaSyntax(getComponent().getChkJava()); helper.setEjbAnnotation(getComponent().getChkEjb()); } } @Override public void stateChanged(ChangeEvent event) { changeSupport.fireChange(); } private void setErrorMessage(String errorMessage) { wizardDescriptor.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE, errorMessage); // NOI18N } private boolean checkConfig(FileObject revengFile) throws Exception{ JDBCMetaDataConfiguration cfg = null; ReverseEngineeringSettings settings; ClassLoader oldClassLoader = null; File confFile = FileUtil.toFile(getComponent().getConfigurationFile()); try { HibernateEnvironment env = project.getLookup().lookup(HibernateEnvironment.class); DataObject confDataObject = DataObject.find(getComponent().getConfigurationFile()); HibernateCfgDataObject hco = (HibernateCfgDataObject) confDataObject; HibernateConfiguration hibConf = hco.getHibernateConfiguration(); DatabaseConnection dbconn = HibernateUtil.getDBConnection(hibConf); List<URL> urls = env.getProjectClassPath(revengFile); if (dbconn != null) { dbconn.getJDBCConnection(); if(dbconn.getJDBCDriver() != null) { urls.addAll(Arrays.asList(dbconn.getJDBCDriver().getURLs())); } } ClassLoader ccl = env.getProjectClassLoader( urls.toArray(new URL[]{})); oldClassLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(ccl); // Configuring the reverse engineering strategy try { cfg = new JDBCMetaDataConfiguration(); DefaultReverseEngineeringStrategy defaultStrategy = new DefaultReverseEngineeringStrategy(); ReverseEngineeringStrategy revStrategy = defaultStrategy; OverrideRepository or = new OverrideRepository(); Configuration c = cfg.configure(confFile); or.addFile(FileUtil.toFile(revengFile)); revStrategy = or.getReverseEngineeringStrategy(revStrategy); settings = new ReverseEngineeringSettings(revStrategy); settings.setDefaultPackageName("validname");//NOI18N defaultStrategy.setSettings(settings); revStrategy.setSettings(settings); cfg.setReverseEngineeringStrategy(or.getReverseEngineeringStrategy(revStrategy)); cfg.readFromJDBC(); cfg.buildMappings(); } catch(HibernateException e) { throw e; } catch (Exception e) { throw e; } } finally { Thread.currentThread().setContextClassLoader(oldClassLoader); } return true; } }
jimdb-org/jimdb
jimsql/jim-sdk/jim-core/src/main/java/io/jimdb/core/model/meta/Index.java
<gh_stars>10-100 /* * Copyright 2019 The JIMDB 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 io.jimdb.core.model.meta; import java.util.Collections; import java.util.List; import io.jimdb.pb.Metapb.MetaState; import io.jimdb.pb.Metapb.IndexInfo; import io.jimdb.pb.Metapb.IndexType; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; /** * @version V1.0 */ @SuppressFBWarnings({ "EI_EXPOSE_REP", "FCCD_FIND_CLASS_CIRCULAR_DEPENDENCY" }) public final class Index { private final Integer id; private final IndexInfo indexInfo; private final Column[] columns; private final Table table; public Index(Table table, IndexInfo indexInfo) { this.table = table; this.indexInfo = indexInfo; this.id = indexInfo.getId(); List<Integer> indexColumns = indexInfo.getColumnsList() == null ? Collections.EMPTY_LIST : indexInfo.getColumnsList(); Column[] tableColumns = table.getReadableColumns(); this.columns = new Column[indexColumns.size()]; for (int i = 0; i < indexColumns.size(); i++) { int colId = indexColumns.get(i); for (Column column : tableColumns) { if (column.getId() == colId) { this.columns[i] = column; break; } } } } public Integer getId() { return id; } public String getName() { return indexInfo.getName(); } public Column[] getColumns() { return columns; } public boolean isUnique() { return indexInfo.getUnique(); } public boolean isPrimary() { return indexInfo.getPrimary(); } public IndexType getType() { return indexInfo.getType(); } public String getIndexComment() { return indexInfo.getComment(); } public MetaState getState() { return indexInfo.getState(); } public Table getTable() { return table; } }
IBM/scheduler-library
examples/mini-era/src/utils/gen_trace.c
<reponame>IBM/scheduler-library /* * Copyright 2019 IBM * * 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 <stdio.h> #include <stdlib.h> #include <string.h> #include <string.h> #include <unistd.h> typedef enum {success, error} status_t; #include "sim_environs.h" #include "getopt.h" bool output_viz_trace = false; bool output_source_trace = true; char world_desc_file_name[256] = "default_world.desc"; float IMPACT_DISTANCE = 50.0; // Minimum distance at which an obstacle "impacts" MyCar (collision case) unsigned rand_seed = 0; // Only used if -r <N> option set bool all_obstacle_lanes_mode = false; unsigned total_obj; // Total non-'N' obstacle objects across all lanes this time step unsigned obj_in_lane[NUM_LANES]; // Number of obstacle objects in each lane this time step (at least one, 'n') unsigned lane_dist[NUM_LANES][MAX_OBJ_IN_LANE]; // The distance to each obstacle object in each lane char lane_obj[NUM_LANES][MAX_OBJ_IN_LANE]; // The type of each obstacle object in each lane distance_t MAX_DISTANCE = 500.0; // Max resolution distance of radar is < 500.0m distance_t MAX_DIST_STEP_SIZE = 50.0; distance_t INF_DISTANCE = 550.0; // (MAX_DISTANCE + MAX_DIST_STEP_SIZE) char nearest_obj[NUM_LANES] = { 'N', 'N', 'N', 'N', 'N' }; float nearest_dist[NUM_LANES];// = { INF_DISTANCE, INF_DISTANCE, INF_DISTANCE, INF_DISTANCE, INF_DISTANCE }; void print_usage(char *pname) { printf("Usage: %s <OPTIONS>\n", pname); printf(" OPTIONS:\n"); printf(" -h : print this helpful usage info\n"); printf(" -w <wfile> : defines the world environment parameters description file <wfile> to use\n"); printf(" -r <N> : Sets the rand random number seed to N\n"); printf(" -A : Allow obstacle vehciles in All lanes (otherwise not in left or right hazard lanes)\n"); } int main(int argc, char *argv[]) { vehicle_state_t vehicle_state; vehicle_state.active = true; vehicle_state.lane = center; vehicle_state.speed = 50; int opt; while ((opt = getopt(argc, argv, ":hAw:r:")) != -1) { switch (opt) { case 'h': print_usage(argv[0]); exit(0); break; case 'w': snprintf(world_desc_file_name, 255, "%s", optarg); break; case 'A': all_obstacle_lanes_mode = true; break; case 'r': rand_seed = atoi(optarg); break; } } // optind is for the extra arguments which were not parsed for (; optind < argc; optind++) { printf("extra arguments: %s\n", argv[optind]); } printf("Setting up world space from %s\n", world_desc_file_name); if (init_sim_environs(world_desc_file_name, &vehicle_state) == error) { printf("ERROR in init_sim_environs... exiting\n"); exit(-1); } printf("All-Obstacle-Lanes-Mode = %u\n", all_obstacle_lanes_mode); printf("\n"); for (int i = 0; i < 5000; i++) { DEBUG(printf("\n\nTime Step %d\n", i)); iterate_sim_environs(vehicle_state); //visualize_world(); } return 0; }
JohnnyS318/RoyalAfg
services/poker-matchmaker/pkg/lobby/connect.go
<filename>services/poker-matchmaker/pkg/lobby/connect.go package lobby import ( "encoding/json" fmt "fmt" "io/ioutil" "net/http" "github.com/spf13/viper" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/JohnnyS318/RoyalAfgInGo/pkg/log" "github.com/JohnnyS318/RoyalAfgInGo/services/poker-matchmaker/pkg/serviceconfig" ) func (m *Manager) Connect(id string) (*TicketRequestResult, error) { list, err := m.agonesClient.AgonesV1().GameServers("default").List(metav1.ListOptions{ TypeMeta: metav1.TypeMeta{ Kind: "agones.dev/v1", APIVersion: "GameServer", }, LabelSelector: fmt.Sprintf("game=poker,lobbyId=%v", id), Watch: false, AllowWatchBookmarks: false, }) if err != nil { m.logger.Errorw("err during connect", "error", err) return nil, err } m.logger.Infow("Agones list results", "id", id, "list", list) if len(list.Items) < 1 { return nil, fmt.Errorf("no lobbies found with the given id") } addresses := viper.GetStringSlice(serviceconfig.NodeIPAddresses) adr := list.Items[0].Status.Address for _, address := range addresses { if err2 := m.PingHealth(fmt.Sprintf("%s:%v", address, list.Items[0].Status.Ports[0].Port)) ; err2 == nil { log.Logger.Debugf("Poker Address found of addresses %v => %v", addresses, address) adr = address break } log.Logger.Warnf("Poker Address was not valid %v => %v", addresses, address) } return &TicketRequestResult{Address: fmt.Sprintf("%s:%v", adr, list.Items[0].Status.Ports[0].Port), LobbyId: id}, nil } type HealthPingResponse struct { Count int `json:"count"` Running bool `json:"running"` LobbyID string `json:"lobbyId"` } func (m *Manager) PingHealth(addr string) error { res, err := http.Get(fmt.Sprintf("http://%v/api/poker/health", addr)) if err != nil { return err } js, err := ioutil.ReadAll(res.Body) _ = res.Body.Close() if err != nil { return err } var ping HealthPingResponse err = json.Unmarshal(js, &ping) if err != nil { return err } return nil }
ash1247/DocumentsWindows
CodeBlocks/Codeforces/Codeforces141A.cpp
<gh_stars>0 #include <bits/stdc++.h> using namespace std; int main( void ) { string guest, host, pile; cin >> guest >> host >> pile; string mix = guest + host; sort( mix.begin(), mix.end() ); sort( pile.begin(), pile.end() ); if( mix == pile ) { cout << "YES\n"; } else { cout << "NO\n"; } }
curtisjaxon/Landfill
app/src/main/java/com/sqisland/friendspell/dagger/GoogleApiClientBridgeModule.java
package com.sqisland.friendspell.dagger; import com.sqisland.friendspell.api.GoogleApiClientBridge; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; @Module public class GoogleApiClientBridgeModule { @Provides @Singleton GoogleApiClientBridge provideGoogleApiClientBridge() { return new GoogleApiClientBridge(); } }
frankhorv/nym-directory
presence/fixtures/fixtures.go
package fixtures import "github.com/nymtech/nym-directory/models" func MixNodeID() models.MixNodeID { d := models.MixNodeID{ PubKey: "abc123", } return d } func GoodCocoHost() models.CocoHostInfo { good := models.CocoHostInfo{ HostInfo: models.HostInfo{ Location: "foomplandia", Host: ":1789", PubKey: "pubkey", Version: "0.1.0", }, Type: "type", } return good } func GoodMixHost() models.MixHostInfo { good := models.MixHostInfo{ HostInfo: models.HostInfo{ Location: "foomplandia", Host: ":1789", PubKey: "pubkey", Version: "0.7.0", }, Layer: 1, } return good } func GoodGatewayHost() models.GatewayHostInfo { client1 := models.RegisteredClient{PubKey: "client1"} client2 := models.RegisteredClient{PubKey: "client2"} clients := []models.RegisteredClient{client1, client2} good := models.GatewayHostInfo{ Location: "foomplandia", ClientListener: ":1789", MixnetListener: ":1790", PubKey: "pubkey", Version: "0.1.0", RegisteredClients: clients, } return good } func XssCocoHost() models.CocoHostInfo { xss := models.CocoHostInfo{ HostInfo: models.HostInfo{ Location: "foomplandia", Host: ":1789", PubKey: "pubkey<script>alert('gotcha')</script>", Version: "0.1.0", }, Type: "type<script>alert('gotcha')", } return xss } func XssMixHost() models.MixHostInfo { xss := models.MixHostInfo{ HostInfo: models.HostInfo{ Location: "foomplandia", Host: ":1789", PubKey: "pubkey<script>alert('gotcha')</script>", Version: "0.7.0", }, Layer: 1, } return xss } func XssGatewayHost() models.GatewayHostInfo { client1 := models.RegisteredClient{PubKey: "client1<script>alert('gotcha')</script>"} client2 := models.RegisteredClient{PubKey: "client2<script>alert('gotcha')</script>"} clients := []models.RegisteredClient{client1, client2} xss := models.GatewayHostInfo{ Location: "foomplandia", ClientListener: ":1789", MixnetListener: ":1790", PubKey: "pubkey<script>alert('gotcha')</script>", Version: "0.1.0", RegisteredClients: clients, } return xss }
jehovahsays/MMOSOCKETHTML5JSCHAT
examples/chat/node_modules/budo/lib/file-watch.js
//a thin wrapper around chokidar file watching HTML / CSS var log = require('bole')('budo') var watch = require('chokidar').watch var xtend = require('xtend') var Emitter = require('events/') var ignores = [ 'node_modules/**', 'bower_components/**', '.git', '.hg', '.svn', '.DS_Store', '*.swp', 'thumbs.db', 'desktop.ini' ] module.exports = function(glob, opt) { opt = xtend({ ignored: ignores, ignoreInitial: true }, opt) var emitter = new Emitter() var closed = false, ready = false var watcher = watch(glob, opt) watcher.on('add', onWatch.bind(null, 'add')) watcher.on('change', onWatch.bind(null, 'change')) // chokidar@1.0.0-r6 only allows close after ready event watcher.once('ready', function() { ready = true if (closed) watcher.close() }) function onWatch(event, path) { emitter.emit('watch', event, path) log.debug({ type: event, url: path }) } emitter.close = function() { if (closed) return if (ready) watcher.close() closed = true } return emitter } module.exports.ignores = ignores
OresteVisari/alien4cloud
alien4cloud-core/src/main/java/org/alien4cloud/tosca/editor/processors/workflow/RemoveEdgeProcessor.java
package org.alien4cloud.tosca.editor.processors.workflow; import org.alien4cloud.tosca.editor.EditionContextManager; import org.alien4cloud.tosca.editor.operations.workflow.RemoveEdgeOperation; import org.springframework.stereotype.Component; import org.alien4cloud.tosca.model.templates.Topology; import alien4cloud.paas.wf.Workflow; import lombok.extern.slf4j.Slf4j; /** * Process the {@link RemoveEdgeOperation} operation */ @Slf4j @Component public class RemoveEdgeProcessor extends AbstractWorkflowProcessor<RemoveEdgeOperation> { @Override protected void processWorkflowOperation(RemoveEdgeOperation operation, Workflow workflow) { Topology topology = EditionContextManager.getTopology(); log.debug("removing edge from <{}> to <{}> from the workflow <{}> from topology <{}>", operation.getFromStepId(), operation.getToStepId(), workflow.getName(), topology.getId()); workflowBuilderService.removeEdge(topology, workflow.getName(), operation.getFromStepId(), operation.getToStepId()); } }
JianpingZeng/xcc
xcc/java/backend/target/arm/ARMDAGISel.java
package backend.target.arm; /* * Extremely Compiler Collection * Copyright (c) 2015-2020, <NAME>. * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the <organization> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import backend.codegen.EVT; import backend.codegen.MVT; import backend.codegen.MachineMemOperand; import backend.codegen.dagisel.*; import backend.debug.DebugLoc; import backend.mc.MCInstrDesc; import backend.pass.FunctionPass; import backend.pass.Pass; import backend.pass.RegisterPass; import backend.target.TargetMachine; import backend.target.TargetOpcode; import backend.type.Type; import backend.value.ConstantInt; import tools.OutRef; import tools.Util; import tools.commandline.BooleanOpt; import tools.commandline.OptionHidden; import tools.commandline.OptionHiddenApplicator; import java.util.ArrayList; import static backend.intrinsic.Intrinsic.ID.values; import static tools.commandline.Desc.desc; import static tools.commandline.Initializer.init; import static tools.commandline.OptionNameApplicator.optionName; /** * The detailed document of ARM addressing modes can be viewed from the following file. * the chapter A5 of ARM Architecture Reference Manual (2005). * * @author <NAME>. * @version 0.4 */ public abstract class ARMDAGISel extends SelectionDAGISel { static final BooleanOpt DisableShifterOp = new BooleanOpt( optionName("disable-shifter-opt"), new OptionHiddenApplicator(OptionHidden.Hidden), desc("Disable isel of shifter-opt"), init(false)); static final BooleanOpt CheckVMLxHazard = new BooleanOpt( optionName("check-vmlx-hazard"), new OptionHiddenApplicator(OptionHidden.Hidden), desc("Check fp vmla / vmls hazard at isel time"), init(true)); static final BooleanOpt DisableARMIntABS = new BooleanOpt( optionName("disable-arm-int-abs"), new OptionHiddenApplicator(OptionHidden.Hidden), desc("Enable / disable ARM integer abs transform"), init(false)); protected ARMTargetLowering tli; protected ARMSubtarget subtarget; protected ARMDAGISel(ARMTargetMachine tm, TargetMachine.CodeGenOpt optLevel) { super(tm, optLevel); try { new RegisterPass("Instruction Selector based on DAG covering", "dag-isel", Class.forName("backend.target.arm.ARMGenDAGISel").asSubclass(Pass.class)); } catch (ClassNotFoundException e) { e.printStackTrace(); } subtarget = tm.getSubtarget(); tli = subtarget.getTargetLowering(); } @Override public String getPassName() { return "ARM Instruction Selection"; } @Override public SDNode select(SDNode node) { EVT nvt = node.getValueType(0); int opcode = node.getOpcode(); DebugLoc dl = node.getDebugLoc(); if (Util.DEBUG) { System.err.print("Selecting: "); node.dump(curDAG); System.err.println(); } if (node.isMachineOpecode()) { // Already been selected. return null; } switch (opcode) { default: break; case ARMISD.CMOV: return selectCMOVOp(node); case ARMISD.BRCOND: { // Pattern: (ARMbrcond:void (bb:Other):$dst, (imm:i32):$cc) // Emits: (Bcc:void (bb:Other):$dst, (imm:i32):$cc) // Pattern complexity = 6 cost = 1 size = 0 // Pattern: (ARMbrcond:void (bb:Other):$dst, (imm:i32):$cc) // Emits: (tBcc:void (bb:Other):$dst, (imm:i32):$cc) // Pattern complexity = 6 cost = 1 size = 0 // Pattern: (ARMbrcond:void (bb:Other):$dst, (imm:i32):$cc) // Emits: (t2Bcc:void (bb:Other):$dst, (imm:i32):$cc) // Pattern complexity = 6 cost = 1 size = 0 int opc = subtarget.isThumb() ? subtarget.hasThumb2() ? ARMGenInstrNames.t2Bcc : ARMGenInstrNames.tBcc : ARMGenInstrNames.Bcc; SDValue chain = node.getOperand(0); SDValue n1 = node.getOperand(1); SDValue n2 = node.getOperand(2); SDValue n3 = node.getOperand(3); SDValue inFlag = node.getOperand(4); // destination block. Util.assertion(n1.getOpcode() == ISD.BasicBlock); // ARM_CC.CondCodes Util.assertion(n2.getOpcode() == ISD.Constant); // the CPSR register. Util.assertion(n3.getOpcode() == ISD.Register); SDValue temp = curDAG.getTargetConstant(((SDNode.ConstantSDNode) n2.getNode()).getZExtValue(), new EVT(MVT.i32)); SDValue[] ops = new SDValue[]{n1, temp, n3, chain, inFlag}; SDNode resNode = curDAG.getMachineNode(opc, dl, new EVT(MVT.Other), new EVT(MVT.Glue), ops); chain = new SDValue(resNode, 0); if (node.getNumValues() == 2) { inFlag = new SDValue(resNode, 1); replaceUses(new SDValue(node, 1), inFlag); } replaceUses(new SDValue(node, 0), chain); return null; } case ISD.FrameIndex: { // select the frame index to the ADDri, FI, 0 which in turn will become ADDri SP, imm. int fi = ((SDNode.FrameIndexSDNode) node).getFrameIndex(); SDValue fin = curDAG.getTargetFrameIndex(fi, new EVT(tli.getPointerTy())); SDValue al = curDAG.getTargetConstant(ARMCC.CondCodes.AL.ordinal(), new EVT(MVT.i32)); if (subtarget.isThumb1Only()) { SDValue[] ops = {fin, curDAG.getTargetConstant(0, new EVT(MVT.i32)), al, curDAG.getRegister(0, new EVT(MVT.i32)), curDAG.getRegister(0, new EVT(MVT.i32))}; return curDAG.selectNodeTo(node, ARMGenInstrNames.tADDrSPi, new EVT(MVT.i32), ops); } else { int opc = subtarget.isThumb() && subtarget.hasThumb2() ? ARMGenInstrNames.t2ADDri : ARMGenInstrNames.ADDri; SDValue[] ops = {fin, curDAG.getTargetConstant(0, new EVT(MVT.i32)), al, curDAG.getRegister(0, new EVT(MVT.i32)), curDAG.getRegister(0, new EVT(MVT.i32))}; return curDAG.selectNodeTo(node, opc, new EVT(MVT.i32), ops); } } case ISD.XOR: { // Select special operations if XOR node forms integer ABS pattern SDNode resNode = selectABSOp(node); if (resNode != null) return resNode; // Other cases are autogenerated. break; } case ISD.Constant: { int Val = (int) ((SDNode.ConstantSDNode) node).getZExtValue(); boolean UseCP = true; if (subtarget.hasThumb2()) // Thumb2-aware targets have the MOVT instruction, so all immediates can // be done with MOV + MOVT, at worst. UseCP = false; else { if (subtarget.isThumb()) { UseCP = (Val > 255 && // MOV ~Val > 255 && // MOV + MVN !ARM_AM.isThumbImmShiftedVal(Val)); // MOV + LSL } else UseCP = (ARM_AM.getSOImmVal(Val) == -1 && // MOV ARM_AM.getSOImmVal(~Val) == -1 && // MVN !ARM_AM.isSOImmTwoPartVal(Val)); // two instrs. } if (UseCP) { SDValue CPIdx = curDAG.getTargetConstantPool(ConstantInt.get( Type.getInt32Ty(curDAG.getContext()), Val), new EVT(tli.getPointerTy()), 0, 0, 0); SDNode ResNode; if (subtarget.isThumb1Only()) { SDValue Pred = getAL(curDAG); SDValue PredReg = curDAG.getRegister(0, MVT.i32); SDValue ops[] = {CPIdx, Pred, PredReg, curDAG.getEntryNode()}; ResNode = curDAG.getMachineNode(ARMGenInstrNames.tLDRpci, dl, curDAG.getVTList(new EVT(MVT.i32), new EVT(MVT.Other)), ops); } else { SDValue ops[] = { CPIdx, curDAG.getTargetConstant(0, new EVT(MVT.i32)), getAL(curDAG), curDAG.getRegister(0, MVT.i32), curDAG.getEntryNode() }; ResNode = curDAG.getMachineNode(ARMGenInstrNames.LDRcp, dl, curDAG.getVTList(new EVT(MVT.i32), new EVT(MVT.Other)), ops); } replaceUses(new SDValue(node, 0), new SDValue(ResNode, 0)); return null; } // Other cases are autogenerated. break; } case ISD.SRL: { SDNode res = selectV6T2BitfieldExtractOp(node, false); if (res != null) return res; break; } case ISD.SRA: { SDNode res = selectV6T2BitfieldExtractOp(node, true); if (res != null) return res; break; } case ISD.MUL: if (subtarget.isThumb1Only()) break; if (node.getOperand(1).getNode() instanceof SDNode.ConstantSDNode) { SDNode.ConstantSDNode c = (SDNode.ConstantSDNode) node.getOperand(1).getNode(); int rhsv = (int) c.getZExtValue(); if (rhsv == 0) break; if (Util.isPowerOf2(rhsv - 1)) { // 2^n+1? int shImm = Util.log2(rhsv - 1); if (shImm >= 32) break; SDValue v = node.getOperand(0); shImm = (int) ARM_AM.getSORegOpc(ARM_AM.ShiftOpc.lsl, shImm); SDValue shImmOp = curDAG.getTargetConstant(shImm, new EVT(MVT.i32)); SDValue reg0 = curDAG.getRegister(0, MVT.i32); if (subtarget.isThumb()) { SDValue[] ops = {v, v, shImmOp, getAL(curDAG), reg0, reg0}; return curDAG.selectNodeTo(node, ARMGenInstrNames.t2ADDrs, new EVT(MVT.i32), ops); } else { SDValue[] ops = {v, v, shImmOp, getAL(curDAG), reg0, reg0}; return curDAG.selectNodeTo(node, ARMGenInstrNames.ADDrsi, new EVT(MVT.i32), ops); } } if (Util.isPowerOf2(rhsv + 1)) { // 2^n-1? int ShImm = Util.log2(rhsv + 1); if (ShImm >= 32) break; SDValue V = node.getOperand(0); ShImm = (int) ARM_AM.getSORegOpc(ARM_AM.ShiftOpc.lsl, ShImm); SDValue ShImmOp = curDAG.getTargetConstant(ShImm, new EVT(MVT.i32)); SDValue Reg0 = curDAG.getRegister(0, MVT.i32); if (subtarget.isThumb()) { SDValue ops[] = {V, V, ShImmOp, getAL(curDAG), Reg0, Reg0}; return curDAG.selectNodeTo(node, ARMGenInstrNames.t2RSBrs, new EVT(MVT.i32), ops); } else { SDValue ops[] = {V, V, ShImmOp, getAL(curDAG), Reg0, Reg0}; return curDAG.selectNodeTo(node, ARMGenInstrNames.RSBrsi, new EVT(MVT.i32), ops); } } } break; case ISD.AND: { // Check for int bitfield extract SDNode res = selectV6T2BitfieldExtractOp(node, false); if (res != null) return res; // (and (or x, c2), c1) and top 16-bits of c1 and c2 match, lower 16-bits // of c1 are 0xffff, and lower 16-bit of c2 are 0. That is, the top 16-bits // are entirely contributed by c2 and lower 16-bits are entirely contributed // by x. That's equal to (or (and x, 0xffff), (and c1, 0xffff0000)). // Select it to: "movt x, ((c1 & 0xffff) >> 16) EVT vt = node.getValueType(0); if (!vt.equals(new EVT(MVT.i32))) break; int opc = (subtarget.isThumb() && subtarget.hasThumb2()) ? ARMGenInstrNames.t2MOVTi16 : (subtarget.hasV6T2Ops() ? ARMGenInstrNames.MOVTi16 : 0); if (opc == 0) break; SDValue n0 = node.getOperand(0), n1 = node.getOperand(1); if (!(n1.getNode() instanceof SDNode.ConstantSDNode)) break; SDNode.ConstantSDNode n1c = (SDNode.ConstantSDNode) n1.getNode(); if (n0.getOpcode() == ISD.OR && n0.getNode().hasOneUse()) { SDValue n2 = n0.getOperand(1); if (!(n2.getNode() instanceof SDNode.ConstantSDNode)) break; SDNode.ConstantSDNode n2c = (SDNode.ConstantSDNode) n2.getNode(); int N1CVal = (int) n1c.getZExtValue(); int N2CVal = (int) n2c.getZExtValue(); if ((N1CVal & 0xffff0000) == (N2CVal & 0xffff0000) && (N1CVal & 0xffff) == 0xffff && (N2CVal & 0xffff) == 0x0) { SDValue Imm16 = curDAG.getTargetConstant((N2CVal & 0xFFFF0000) >> 16, new EVT(MVT.i32)); SDValue ops[] = {n0.getOperand(0), Imm16, getAL(curDAG), curDAG.getRegister(0, MVT.i32)}; return curDAG.getMachineNode(opc, dl, vt, ops); } } break; } case ARMISD.VMOVRRD: return curDAG.getMachineNode(ARMGenInstrNames.VMOVRRD, dl, new EVT(MVT.i32), new EVT(MVT.i32), node.getOperand(0), getAL(curDAG), curDAG.getRegister(0, MVT.i32)); case ISD.UMUL_LOHI: { if (subtarget.isThumb1Only()) break; if (subtarget.isThumb()) { SDValue ops[] = {node.getOperand(0), node.getOperand(1), getAL(curDAG), curDAG.getRegister(0, MVT.i32), curDAG.getRegister(0, MVT.i32)}; return curDAG.getMachineNode(ARMGenInstrNames.t2UMULL, dl, new EVT(MVT.i32), new EVT(MVT.i32), ops); } else { SDValue ops[] = {node.getOperand(0), node.getOperand(1), getAL(curDAG), curDAG.getRegister(0, MVT.i32), curDAG.getRegister(0, MVT.i32)}; return curDAG.getMachineNode(subtarget.hasV6Ops() ? ARMGenInstrNames.UMULL : ARMGenInstrNames.UMULLv5, dl, new EVT(MVT.i32), new EVT(MVT.i32), ops); } } case ISD.SMUL_LOHI: { if (subtarget.isThumb1Only()) break; if (subtarget.isThumb()) { SDValue ops[] = {node.getOperand(0), node.getOperand(1), getAL(curDAG), curDAG.getRegister(0, MVT.i32)}; return curDAG.getMachineNode(ARMGenInstrNames.t2SMULL, dl, new EVT(MVT.i32), new EVT(MVT.i32), ops); } else { SDValue ops[] = {node.getOperand(0), node.getOperand(1), getAL(curDAG), curDAG.getRegister(0, MVT.i32), curDAG.getRegister(0, MVT.i32)}; return curDAG.getMachineNode(subtarget.hasV6Ops() ? ARMGenInstrNames.SMULL : ARMGenInstrNames.SMULLv5, dl, new EVT(MVT.i32), new EVT(MVT.i32), ops); } } case ISD.LOAD: { SDNode resNode = null; if (subtarget.isThumb() && subtarget.hasThumb2()) resNode = selectT2IndexedLoad(node); else resNode = selectARMIndexedLoad(node); if (resNode != null) return resNode; // Other cases are autogenerated. break; } case ARMISD.VZIP: { int opc = 0; EVT vt = node.getValueType(0); switch (vt.getSimpleVT().simpleVT) { default: return null; case MVT.v8i8: opc = ARMGenInstrNames.VZIPd8; break; case MVT.v4i16: opc = ARMGenInstrNames.VZIPd16; break; case MVT.v2f32: case MVT.v2i32: opc = ARMGenInstrNames.VZIPd32; break; case MVT.v16i8: opc = ARMGenInstrNames.VZIPq8; break; case MVT.v8i16: opc = ARMGenInstrNames.VZIPq16; break; case MVT.v4f32: case MVT.v4i32: opc = ARMGenInstrNames.VZIPq32; break; } SDValue pred = getAL(curDAG); SDValue predReg = curDAG.getRegister(0, MVT.i32); SDValue ops[] = {node.getOperand(0), node.getOperand(1), pred, predReg}; return curDAG.getMachineNode(opc, dl, vt, vt, ops); } case ARMISD.VUZP: { int opc = 0; EVT vt = node.getValueType(0); switch (vt.getSimpleVT().simpleVT) { default: return null; case MVT.v8i8: opc = ARMGenInstrNames.VUZPd8; break; case MVT.v4i16: opc = ARMGenInstrNames.VUZPd16; break; case MVT.v2f32: case MVT.v2i32: opc = ARMGenInstrNames.VUZPd32; break; case MVT.v16i8: opc = ARMGenInstrNames.VUZPq8; break; case MVT.v8i16: opc = ARMGenInstrNames.VUZPq16; break; case MVT.v4f32: case MVT.v4i32: opc = ARMGenInstrNames.VUZPq32; break; } SDValue Pred = getAL(curDAG); SDValue PredReg = curDAG.getRegister(0, MVT.i32); SDValue ops[] = {node.getOperand(0), node.getOperand(1), Pred, PredReg}; return curDAG.getMachineNode(opc, dl, vt, vt, ops); } case ARMISD.VTRN: { int opc = 0; EVT vt = node.getValueType(0); switch (vt.getSimpleVT().simpleVT) { default: return null; case MVT.v8i8: opc = ARMGenInstrNames.VTRNd8; break; case MVT.v4i16: opc = ARMGenInstrNames.VTRNd16; break; case MVT.v2f32: case MVT.v2i32: opc = ARMGenInstrNames.VTRNd32; break; case MVT.v16i8: opc = ARMGenInstrNames.VTRNq8; break; case MVT.v8i16: opc = ARMGenInstrNames.VTRNq16; break; case MVT.v4f32: case MVT.v4i32: opc = ARMGenInstrNames.VTRNq32; break; } SDValue Pred = getAL(curDAG); SDValue PredReg = curDAG.getRegister(0, MVT.i32); SDValue ops[] = {node.getOperand(0), node.getOperand(1), Pred, PredReg}; return curDAG.getMachineNode(opc, dl, vt, vt, ops); } case ARMISD.BUILD_VECTOR: { EVT vecVT = node.getValueType(0); EVT eltVT = vecVT.getVectorElementType(); int numElts = vecVT.getVectorNumElements(); if (eltVT.equals(new EVT(MVT.f64))) { Util.assertion(numElts == 2, "unexpected type for BUILD_VECTOR"); return pairDRegs(vecVT, node.getOperand(0), node.getOperand(1), dl); } Util.assertion(eltVT.equals(new EVT(MVT.f32)), "unexpected type for BUILD_VECTOR"); if (numElts == 2) return pairSRegs(vecVT, node.getOperand(0), node.getOperand(1), dl); Util.assertion(numElts == 4, "unexpected type for BUILD_VECTOR"); return quadSRegs(vecVT, node.getOperand(0), node.getOperand(1), node.getOperand(2), node.getOperand(3), dl); } case ARMISD.VLD2DUP: { int Opcodes[] = {ARMGenInstrNames.VLD2DUPd8Pseudo, ARMGenInstrNames.VLD2DUPd16Pseudo, ARMGenInstrNames.VLD2DUPd32Pseudo}; return selectVLDDup(node, false, 2, Opcodes); } case ARMISD.VLD3DUP: { int Opcodes[] = {ARMGenInstrNames.VLD3DUPd8Pseudo, ARMGenInstrNames.VLD3DUPd16Pseudo, ARMGenInstrNames.VLD3DUPd32Pseudo}; return selectVLDDup(node, false, 3, Opcodes); } case ARMISD.VLD4DUP: { int Opcodes[] = {ARMGenInstrNames.VLD4DUPd8Pseudo, ARMGenInstrNames.VLD4DUPd16Pseudo, ARMGenInstrNames.VLD4DUPd32Pseudo}; return selectVLDDup(node, false, 4, Opcodes); } case ARMISD.VLD2DUP_UPD: { int Opcodes[] = {ARMGenInstrNames.VLD2DUPd8Pseudo_UPD, ARMGenInstrNames.VLD2DUPd16Pseudo_UPD, ARMGenInstrNames.VLD2DUPd32Pseudo_UPD}; return selectVLDDup(node, true, 2, Opcodes); } case ARMISD.VLD3DUP_UPD: { int Opcodes[] = {ARMGenInstrNames.VLD3DUPd8Pseudo_UPD, ARMGenInstrNames.VLD3DUPd16Pseudo_UPD, ARMGenInstrNames.VLD3DUPd32Pseudo_UPD}; return selectVLDDup(node, true, 3, Opcodes); } case ARMISD.VLD4DUP_UPD: { int Opcodes[] = {ARMGenInstrNames.VLD4DUPd8Pseudo_UPD, ARMGenInstrNames.VLD4DUPd16Pseudo_UPD, ARMGenInstrNames.VLD4DUPd32Pseudo_UPD}; return selectVLDDup(node, true, 4, Opcodes); } case ARMISD.VLD1_UPD: { int DOpcodes[] = {ARMGenInstrNames.VLD1d8_UPD, ARMGenInstrNames.VLD1d16_UPD, ARMGenInstrNames.VLD1d32_UPD, ARMGenInstrNames.VLD1d64_UPD}; int QOpcodes[] = {ARMGenInstrNames.VLD1q8Pseudo_UPD, ARMGenInstrNames.VLD1q16Pseudo_UPD, ARMGenInstrNames.VLD1q32Pseudo_UPD, ARMGenInstrNames.VLD1q64Pseudo_UPD}; return selectVLD(node, true, 1, DOpcodes, QOpcodes, null); } case ARMISD.VLD2_UPD: { int DOpcodes[] = {ARMGenInstrNames.VLD2d8Pseudo_UPD, ARMGenInstrNames.VLD2d16Pseudo_UPD, ARMGenInstrNames.VLD2d32Pseudo_UPD, ARMGenInstrNames.VLD1q64Pseudo_UPD}; int QOpcodes[] = {ARMGenInstrNames.VLD2q8Pseudo_UPD, ARMGenInstrNames.VLD2q16Pseudo_UPD, ARMGenInstrNames.VLD2q32Pseudo_UPD}; return selectVLD(node, true, 2, DOpcodes, QOpcodes, null); } case ARMISD.VLD3_UPD: { int DOpcodes[] = {ARMGenInstrNames.VLD3d8Pseudo_UPD, ARMGenInstrNames.VLD3d16Pseudo_UPD, ARMGenInstrNames.VLD3d32Pseudo_UPD, ARMGenInstrNames.VLD1d64TPseudo_UPD}; int QOpcodes0[] = {ARMGenInstrNames.VLD3q8Pseudo_UPD, ARMGenInstrNames.VLD3q16Pseudo_UPD, ARMGenInstrNames.VLD3q32Pseudo_UPD}; int QOpcodes1[] = {ARMGenInstrNames.VLD3q8oddPseudo_UPD, ARMGenInstrNames.VLD3q16oddPseudo_UPD, ARMGenInstrNames.VLD3q32oddPseudo_UPD}; return selectVLD(node, true, 3, DOpcodes, QOpcodes0, QOpcodes1); } case ARMISD.VLD4_UPD: { int DOpcodes[] = {ARMGenInstrNames.VLD4d8Pseudo_UPD, ARMGenInstrNames.VLD4d16Pseudo_UPD, ARMGenInstrNames.VLD4d32Pseudo_UPD, ARMGenInstrNames.VLD1d64QPseudo_UPD}; int QOpcodes0[] = {ARMGenInstrNames.VLD4q8Pseudo_UPD, ARMGenInstrNames.VLD4q16Pseudo_UPD, ARMGenInstrNames.VLD4q32Pseudo_UPD}; int QOpcodes1[] = {ARMGenInstrNames.VLD4q8oddPseudo_UPD, ARMGenInstrNames.VLD4q16oddPseudo_UPD, ARMGenInstrNames.VLD4q32oddPseudo_UPD}; return selectVLD(node, true, 4, DOpcodes, QOpcodes0, QOpcodes1); } case ARMISD.VLD2LN_UPD: { int DOpcodes[] = {ARMGenInstrNames.VLD2LNd8Pseudo_UPD, ARMGenInstrNames.VLD2LNd16Pseudo_UPD, ARMGenInstrNames.VLD2LNd32Pseudo_UPD}; int QOpcodes[] = {ARMGenInstrNames.VLD2LNq16Pseudo_UPD, ARMGenInstrNames.VLD2LNq32Pseudo_UPD}; return selectVLDSTLane(node, true, true, 2, DOpcodes, QOpcodes); } case ARMISD.VLD3LN_UPD: { int DOpcodes[] = {ARMGenInstrNames.VLD3LNd8Pseudo_UPD, ARMGenInstrNames.VLD3LNd16Pseudo_UPD, ARMGenInstrNames.VLD3LNd32Pseudo_UPD}; int QOpcodes[] = {ARMGenInstrNames.VLD3LNq16Pseudo_UPD, ARMGenInstrNames.VLD3LNq32Pseudo_UPD}; return selectVLDSTLane(node, true, true, 3, DOpcodes, QOpcodes); } case ARMISD.VLD4LN_UPD: { int DOpcodes[] = {ARMGenInstrNames.VLD4LNd8Pseudo_UPD, ARMGenInstrNames.VLD4LNd16Pseudo_UPD, ARMGenInstrNames.VLD4LNd32Pseudo_UPD}; int QOpcodes[] = {ARMGenInstrNames.VLD4LNq16Pseudo_UPD, ARMGenInstrNames.VLD4LNq32Pseudo_UPD}; return selectVLDSTLane(node, true, true, 4, DOpcodes, QOpcodes); } case ARMISD.VST1_UPD: { int DOpcodes[] = {ARMGenInstrNames.VST1d8_UPD, ARMGenInstrNames.VST1d16_UPD, ARMGenInstrNames.VST1d32_UPD, ARMGenInstrNames.VST1d64_UPD}; int QOpcodes[] = {ARMGenInstrNames.VST1q8Pseudo_UPD, ARMGenInstrNames.VST1q16Pseudo_UPD, ARMGenInstrNames.VST1q32Pseudo_UPD, ARMGenInstrNames.VST1q64Pseudo_UPD}; return selectVST(node, true, 1, DOpcodes, QOpcodes, null); } case ARMISD.VST2_UPD: { int DOpcodes[] = {ARMGenInstrNames.VST2d8Pseudo_UPD, ARMGenInstrNames.VST2d16Pseudo_UPD, ARMGenInstrNames.VST2d32Pseudo_UPD, ARMGenInstrNames.VST1q64Pseudo_UPD}; int QOpcodes[] = {ARMGenInstrNames.VST2q8Pseudo_UPD, ARMGenInstrNames.VST2q16Pseudo_UPD, ARMGenInstrNames.VST2q32Pseudo_UPD}; return selectVST(node, true, 2, DOpcodes, QOpcodes, null); } case ARMISD.VST3_UPD: { int DOpcodes[] = {ARMGenInstrNames.VST3d8Pseudo_UPD, ARMGenInstrNames.VST3d16Pseudo_UPD, ARMGenInstrNames.VST3d32Pseudo_UPD, ARMGenInstrNames.VST1d64TPseudo_UPD}; int QOpcodes0[] = {ARMGenInstrNames.VST3q8Pseudo_UPD, ARMGenInstrNames.VST3q16Pseudo_UPD, ARMGenInstrNames.VST3q32Pseudo_UPD}; int QOpcodes1[] = {ARMGenInstrNames.VST3q8oddPseudo_UPD, ARMGenInstrNames.VST3q16oddPseudo_UPD, ARMGenInstrNames.VST3q32oddPseudo_UPD}; return selectVST(node, true, 3, DOpcodes, QOpcodes0, QOpcodes1); } case ARMISD.VST4_UPD: { int DOpcodes[] = {ARMGenInstrNames.VST4d8Pseudo_UPD, ARMGenInstrNames.VST4d16Pseudo_UPD, ARMGenInstrNames.VST4d32Pseudo_UPD, ARMGenInstrNames.VST1d64QPseudo_UPD}; int QOpcodes0[] = {ARMGenInstrNames.VST4q8Pseudo_UPD, ARMGenInstrNames.VST4q16Pseudo_UPD, ARMGenInstrNames.VST4q32Pseudo_UPD}; int QOpcodes1[] = {ARMGenInstrNames.VST4q8oddPseudo_UPD, ARMGenInstrNames.VST4q16oddPseudo_UPD, ARMGenInstrNames.VST4q32oddPseudo_UPD}; return selectVST(node, true, 4, DOpcodes, QOpcodes0, QOpcodes1); } case ARMISD.VST2LN_UPD: { int DOpcodes[] = {ARMGenInstrNames.VST2LNd8Pseudo_UPD, ARMGenInstrNames.VST2LNd16Pseudo_UPD, ARMGenInstrNames.VST2LNd32Pseudo_UPD}; int QOpcodes[] = {ARMGenInstrNames.VST2LNq16Pseudo_UPD, ARMGenInstrNames.VST2LNq32Pseudo_UPD}; return selectVLDSTLane(node, false, true, 2, DOpcodes, QOpcodes); } case ARMISD.VST3LN_UPD: { int DOpcodes[] = {ARMGenInstrNames.VST3LNd8Pseudo_UPD, ARMGenInstrNames.VST3LNd16Pseudo_UPD, ARMGenInstrNames.VST3LNd32Pseudo_UPD}; int QOpcodes[] = {ARMGenInstrNames.VST3LNq16Pseudo_UPD, ARMGenInstrNames.VST3LNq32Pseudo_UPD}; return selectVLDSTLane(node, false, true, 3, DOpcodes, QOpcodes); } case ARMISD.VST4LN_UPD: { int DOpcodes[] = {ARMGenInstrNames.VST4LNd8Pseudo_UPD, ARMGenInstrNames.VST4LNd16Pseudo_UPD, ARMGenInstrNames.VST4LNd32Pseudo_UPD}; int QOpcodes[] = {ARMGenInstrNames.VST4LNq16Pseudo_UPD, ARMGenInstrNames.VST4LNq32Pseudo_UPD}; return selectVLDSTLane(node, false, true, 4, DOpcodes, QOpcodes); } case ISD.INTRINSIC_VOID: case ISD.INTRINSIC_W_CHAIN: { int IntNo = (int) ((SDNode.ConstantSDNode) node.getOperand(1).getNode()).getZExtValue(); switch (values()[IntNo]) { default: break; case arm_ldrexd: { SDValue memAddr = node.getOperand(2); SDValue chain = node.getOperand(0); int newOpc = ARMGenInstrNames.LDREXD; if (subtarget.isThumb() && subtarget.hasThumb2()) newOpc = ARMGenInstrNames.t2LDREXD; // arm_ldrexd returns a i64 value in {i32, i32} ArrayList<EVT> resTys = new ArrayList<>(); resTys.add(new EVT(MVT.i32)); resTys.add(new EVT(MVT.i32)); resTys.add(new EVT(MVT.Other)); // place arguments in the right order SDValue[] ops = {memAddr, getAL(curDAG), curDAG.getRegister(0, new EVT(MVT.i32)), chain}; SDNode.MachineSDNode ld = curDAG.getMachineNode(newOpc, dl, curDAG.getVTList(resTys), ops); // Transfer memoperands. ld.setMemRefs(new MachineMemOperand[]{((SDNode.MemIntrinsicSDNode) node).getMemOperand()}); // Until there's support for specifing explicit register constraints // like the use of even/odd register pair, hardcode ldrexd to always // use the pair [R0, R1] to hold the load result. chain = curDAG.getCopyToReg(curDAG.getEntryNode(), dl, ARMGenRegisterNames.R0, new SDValue(ld, 0), new SDValue(null, 0)); chain = curDAG.getCopyToReg(chain, dl, ARMGenRegisterNames.R1, new SDValue(ld, 1), chain.getValue(1)); // Remap uses. SDValue Glue = chain.getValue(1); if (!new SDValue(node, 0).isUseEmpty()) { SDValue Result = curDAG.getCopyFromReg(curDAG.getEntryNode(), dl, ARMGenRegisterNames.R0, new EVT(MVT.i32), Glue); Glue = Result.getValue(2); replaceUses(new SDValue(node, 0), Result); } if (!new SDValue(node, 1).isUseEmpty()) { SDValue Result = curDAG.getCopyFromReg(curDAG.getEntryNode(), dl, ARMGenRegisterNames.R1, new EVT(MVT.i32), Glue); Glue = Result.getValue(2); replaceUses(new SDValue(node, 1), Result); } replaceUses(new SDValue(node, 2), new SDValue(ld, 2)); return null; } case arm_strexd: { SDValue chain = node.getOperand(0); SDValue val0 = node.getOperand(2); SDValue val1 = node.getOperand(3); SDValue memAddr = node.getOperand(4); // Until there's support for specifing explicit register constraints // like the use of even/odd register pair, hardcode strexd to always // use the pair [R2, R3] to hold the i64 (i32, i32) value to be stored. chain = curDAG.getCopyToReg(curDAG.getEntryNode(), dl, ARMGenRegisterNames.R2, val0, new SDValue(null, 0)); chain = curDAG.getCopyToReg(chain, dl, ARMGenRegisterNames.R3, val1, chain.getValue(1)); SDValue Glue = chain.getValue(1); val0 = curDAG.getCopyFromReg(curDAG.getEntryNode(), dl, ARMGenRegisterNames.R2, new EVT(MVT.i32), Glue); Glue = val0.getValue(1); val1 = curDAG.getCopyFromReg(curDAG.getEntryNode(), dl, ARMGenRegisterNames.R3, new EVT(MVT.i32), Glue); // Store exclusive double return a i32 value which is the return status // of the issued store. ArrayList<EVT> resTys = new ArrayList<>(); resTys.add(new EVT(MVT.i32)); resTys.add(new EVT(MVT.Other)); // place arguments in the right order SDValue[] ops = new SDValue[]{val0, val1, memAddr, getAL(curDAG), curDAG.getRegister(0, new EVT(MVT.i32)), chain}; int NewOpc = ARMGenInstrNames.STREXD; if (subtarget.isThumb() && subtarget.hasThumb2()) NewOpc = ARMGenInstrNames.t2STREXD; SDNode.MachineSDNode st = curDAG.getMachineNode(NewOpc, dl, curDAG.getVTList(resTys), ops); // Transfer memoperands. st.setMemRefs(new MachineMemOperand[]{((SDNode.MemIntrinsicSDNode) node).getMemOperand()}); return st; } case arm_neon_vld1: { int DOpcodes[] = {ARMGenInstrNames.VLD1d8, ARMGenInstrNames.VLD1d16, ARMGenInstrNames.VLD1d32, ARMGenInstrNames.VLD1d64}; int QOpcodes[] = {ARMGenInstrNames.VLD1q8Pseudo, ARMGenInstrNames.VLD1q16Pseudo, ARMGenInstrNames.VLD1q32Pseudo, ARMGenInstrNames.VLD1q64Pseudo}; return selectVLD(node, false, 1, DOpcodes, QOpcodes, null); } case arm_neon_vld2: { int DOpcodes[] = {ARMGenInstrNames.VLD2d8Pseudo, ARMGenInstrNames.VLD2d16Pseudo, ARMGenInstrNames.VLD2d32Pseudo, ARMGenInstrNames.VLD1q64Pseudo}; int QOpcodes[] = {ARMGenInstrNames.VLD2q8Pseudo, ARMGenInstrNames.VLD2q16Pseudo, ARMGenInstrNames.VLD2q32Pseudo}; return selectVLD(node, false, 2, DOpcodes, QOpcodes, null); } case arm_neon_vld3: { int DOpcodes[] = {ARMGenInstrNames.VLD3d8Pseudo, ARMGenInstrNames.VLD3d16Pseudo, ARMGenInstrNames.VLD3d32Pseudo, ARMGenInstrNames.VLD1d64TPseudo}; int QOpcodes0[] = {ARMGenInstrNames.VLD3q8Pseudo_UPD, ARMGenInstrNames.VLD3q16Pseudo_UPD, ARMGenInstrNames.VLD3q32Pseudo_UPD}; int QOpcodes1[] = {ARMGenInstrNames.VLD3q8oddPseudo, ARMGenInstrNames.VLD3q16oddPseudo, ARMGenInstrNames.VLD3q32oddPseudo}; return selectVLD(node, false, 3, DOpcodes, QOpcodes0, QOpcodes1); } case arm_neon_vld4: { int DOpcodes[] = {ARMGenInstrNames.VLD4d8Pseudo, ARMGenInstrNames.VLD4d16Pseudo, ARMGenInstrNames.VLD4d32Pseudo, ARMGenInstrNames.VLD1d64QPseudo}; int QOpcodes0[] = {ARMGenInstrNames.VLD4q8Pseudo_UPD, ARMGenInstrNames.VLD4q16Pseudo_UPD, ARMGenInstrNames.VLD4q32Pseudo_UPD}; int QOpcodes1[] = {ARMGenInstrNames.VLD4q8oddPseudo, ARMGenInstrNames.VLD4q16oddPseudo, ARMGenInstrNames.VLD4q32oddPseudo}; return selectVLD(node, false, 4, DOpcodes, QOpcodes0, QOpcodes1); } case arm_neon_vld2lane: { int DOpcodes[] = {ARMGenInstrNames.VLD2LNd8Pseudo, ARMGenInstrNames.VLD2LNd16Pseudo, ARMGenInstrNames.VLD2LNd32Pseudo}; int QOpcodes[] = {ARMGenInstrNames.VLD2LNq16Pseudo, ARMGenInstrNames.VLD2LNq32Pseudo}; return selectVLDSTLane(node, true, false, 2, DOpcodes, QOpcodes); } case arm_neon_vld3lane: { int DOpcodes[] = {ARMGenInstrNames.VLD3LNd8Pseudo, ARMGenInstrNames.VLD3LNd16Pseudo, ARMGenInstrNames.VLD3LNd32Pseudo}; int QOpcodes[] = {ARMGenInstrNames.VLD3LNq16Pseudo, ARMGenInstrNames.VLD3LNq32Pseudo}; return selectVLDSTLane(node, true, false, 3, DOpcodes, QOpcodes); } case arm_neon_vld4lane: { int DOpcodes[] = {ARMGenInstrNames.VLD4LNd8Pseudo, ARMGenInstrNames.VLD4LNd16Pseudo, ARMGenInstrNames.VLD4LNd32Pseudo}; int QOpcodes[] = {ARMGenInstrNames.VLD4LNq16Pseudo, ARMGenInstrNames.VLD4LNq32Pseudo}; return selectVLDSTLane(node, true, false, 4, DOpcodes, QOpcodes); } case arm_neon_vst1: { int DOpcodes[] = {ARMGenInstrNames.VST1d8, ARMGenInstrNames.VST1d16, ARMGenInstrNames.VST1d32, ARMGenInstrNames.VST1d64}; int QOpcodes[] = {ARMGenInstrNames.VST1q8Pseudo, ARMGenInstrNames.VST1q16Pseudo, ARMGenInstrNames.VST1q32Pseudo, ARMGenInstrNames.VST1q64Pseudo}; return selectVST(node, false, 1, DOpcodes, QOpcodes, null); } case arm_neon_vst2: { int DOpcodes[] = {ARMGenInstrNames.VST2d8Pseudo, ARMGenInstrNames.VST2d16Pseudo, ARMGenInstrNames.VST2d32Pseudo, ARMGenInstrNames.VST1q64Pseudo}; int QOpcodes[] = {ARMGenInstrNames.VST2q8Pseudo, ARMGenInstrNames.VST2q16Pseudo, ARMGenInstrNames.VST2q32Pseudo}; return selectVST(node, false, 2, DOpcodes, QOpcodes, null); } case arm_neon_vst3: { int DOpcodes[] = {ARMGenInstrNames.VST3d8Pseudo, ARMGenInstrNames.VST3d16Pseudo, ARMGenInstrNames.VST3d32Pseudo, ARMGenInstrNames.VST1d64TPseudo}; int QOpcodes0[] = {ARMGenInstrNames.VST3q8Pseudo_UPD, ARMGenInstrNames.VST3q16Pseudo_UPD, ARMGenInstrNames.VST3q32Pseudo_UPD}; int QOpcodes1[] = {ARMGenInstrNames.VST3q8oddPseudo, ARMGenInstrNames.VST3q16oddPseudo, ARMGenInstrNames.VST3q32oddPseudo}; return selectVST(node, false, 3, DOpcodes, QOpcodes0, QOpcodes1); } case arm_neon_vst4: { int DOpcodes[] = {ARMGenInstrNames.VST4d8Pseudo, ARMGenInstrNames.VST4d16Pseudo, ARMGenInstrNames.VST4d32Pseudo, ARMGenInstrNames.VST1d64QPseudo}; int QOpcodes0[] = {ARMGenInstrNames.VST4q8Pseudo_UPD, ARMGenInstrNames.VST4q16Pseudo_UPD, ARMGenInstrNames.VST4q32Pseudo_UPD}; int QOpcodes1[] = {ARMGenInstrNames.VST4q8oddPseudo, ARMGenInstrNames.VST4q16oddPseudo, ARMGenInstrNames.VST4q32oddPseudo}; return selectVST(node, false, 4, DOpcodes, QOpcodes0, QOpcodes1); } case arm_neon_vst2lane: { int DOpcodes[] = {ARMGenInstrNames.VST2LNd8Pseudo, ARMGenInstrNames.VST2LNd16Pseudo, ARMGenInstrNames.VST2LNd32Pseudo}; int QOpcodes[] = {ARMGenInstrNames.VST2LNq16Pseudo, ARMGenInstrNames.VST2LNq32Pseudo}; return selectVLDSTLane(node, false, false, 2, DOpcodes, QOpcodes); } case arm_neon_vst3lane: { int DOpcodes[] = {ARMGenInstrNames.VST3LNd8Pseudo, ARMGenInstrNames.VST3LNd16Pseudo, ARMGenInstrNames.VST3LNd32Pseudo}; int QOpcodes[] = {ARMGenInstrNames.VST3LNq16Pseudo, ARMGenInstrNames.VST3LNq32Pseudo}; return selectVLDSTLane(node, false, false, 3, DOpcodes, QOpcodes); } case arm_neon_vst4lane: { int DOpcodes[] = {ARMGenInstrNames.VST4LNd8Pseudo, ARMGenInstrNames.VST4LNd16Pseudo, ARMGenInstrNames.VST4LNd32Pseudo}; int QOpcodes[] = {ARMGenInstrNames.VST4LNq16Pseudo, ARMGenInstrNames.VST4LNq32Pseudo}; return selectVLDSTLane(node, false, false, 4, DOpcodes, QOpcodes); } } break; } case ISD.INTRINSIC_WO_CHAIN: { int IntNo = (int) ((SDNode.ConstantSDNode) node.getOperand(0).getNode()).getZExtValue(); switch (values()[IntNo]) { default: break; case arm_neon_vtbl2: return selectVTBL(node, false, 2, ARMGenInstrNames.VTBL2Pseudo); case arm_neon_vtbl3: return selectVTBL(node, false, 3, ARMGenInstrNames.VTBL3Pseudo); case arm_neon_vtbl4: return selectVTBL(node, false, 4, ARMGenInstrNames.VTBL4Pseudo); case arm_neon_vtbx2: return selectVTBL(node, true, 2, ARMGenInstrNames.VTBX2Pseudo); case arm_neon_vtbx3: return selectVTBL(node, true, 3, ARMGenInstrNames.VTBX3Pseudo); case arm_neon_vtbx4: return selectVTBL(node, true, 4, ARMGenInstrNames.VTBX4Pseudo); } break; } case ARMISD.VTBL1: { EVT vt = node.getValueType(0); ArrayList<SDValue> ops = new ArrayList<>(); ops.add(node.getOperand(0)); ops.add(node.getOperand(1)); ops.add(getAL(curDAG)); // Predicate ops.add(curDAG.getRegister(0, MVT.i32)); // Predicate Register return curDAG.getMachineNode(ARMGenInstrNames.VTBL1, dl, vt); } case ARMISD.VTBL2: { EVT vt = node.getValueType(0); // Form a REG_SEQUENCE to force register allocation. SDValue v0 = node.getOperand(0); SDValue v1 = node.getOperand(1); SDValue RegSeq = new SDValue(pairDRegs(new EVT(MVT.v16i8), v0, v1, dl), 0); ArrayList<SDValue> ops = new ArrayList<>(); ops.add(RegSeq); ops.add(node.getOperand(2)); ops.add(getAL(curDAG)); // Predicate ops.add(curDAG.getRegister(0, MVT.i32)); // Predicate Register return curDAG.getMachineNode(ARMGenInstrNames.VTBL2Pseudo, dl, vt); } case ISD.CONCAT_VECTORS: return selectConcatVector(node); case ARMISD.ATOMOR64_DAG: return selectAtomic64(node, ARMGenInstrNames.ATOMOR6432); case ARMISD.ATOMXOR64_DAG: return selectAtomic64(node, ARMGenInstrNames.ATOMXOR6432); case ARMISD.ATOMADD64_DAG: return selectAtomic64(node, ARMGenInstrNames.ATOMADD6432); case ARMISD.ATOMSUB64_DAG: return selectAtomic64(node, ARMGenInstrNames.ATOMSUB6432); case ARMISD.ATOMNAND64_DAG: return selectAtomic64(node, ARMGenInstrNames.ATOMNAND6432); case ARMISD.ATOMAND64_DAG: return selectAtomic64(node, ARMGenInstrNames.ATOMAND6432); case ARMISD.ATOMSWAP64_DAG: return selectAtomic64(node, ARMGenInstrNames.ATOMSWAP6432); case ARMISD.ATOMCMPXCHG64_DAG: return selectAtomic64(node, ARMGenInstrNames.ATOMCMPXCHG6432); } SDNode resNode = selectCommonCode(node); if (Util.DEBUG) { System.err.print("=> "); if (resNode == null || resNode.equals(node)) node.dump(curDAG); else resNode.dump(curDAG); System.err.println(); } return resNode; } private SDNode selectConcatVector(SDNode node) { // EVT vt = node.getValueType(0); if (!vt.is128BitVector() || node.getNumOperands() != 2) Util.shouldNotReachHere("unexpected CONCAT_VECTORS"); return pairDRegs(vt, node.getOperand(0), node.getOperand(1), node.getDebugLoc()); } private SDNode selectAtomic64(SDNode node, int opc) { ArrayList<SDValue> ops = new ArrayList<>(); ops.add(node.getOperand(1)); // ptr ops.add(node.getOperand(2)); // low part of val1. ops.add(node.getOperand(3)); // high part of val1. if (opc == ARMGenInstrNames.ATOMCMPXCHG6432) { ops.add(node.getOperand(4)); // low part of val2. ops.add(node.getOperand(5)); // high part of val2. } // chain. ops.add(node.getOperand(0)); SDNode.SDVTList vts = curDAG.getVTList(new EVT(MVT.i32), new EVT(MVT.i32), new EVT(MVT.Other)); SDValue[] args = new SDValue[ops.size()]; ops.toArray(args); SDNode.MachineSDNode resNode = curDAG.getMachineNode(opc, node.getDebugLoc(), vts, args); resNode.setMemRefs(new MachineMemOperand[]{((SDNode.MemSDNode)node).getMemOperand()}); return resNode; } /** * Form 4 consecutive S registers. * @param vt * @param v0 * @param v1 * @param v2 * @param v3 * @return */ private SDNode quadSRegs(EVT vt, SDValue v0, SDValue v1, SDValue v2, SDValue v3, DebugLoc dl) { SDValue regClass = curDAG.getTargetConstant(ARMGenRegisterInfo.QPR_VFP2RegClassID, new EVT(MVT.i32)); SDValue subReg0 = curDAG.getTargetConstant(ARMGenRegisterInfo.ssub_0, new EVT(MVT.i32)); SDValue subReg1 = curDAG.getTargetConstant(ARMGenRegisterInfo.ssub_1, new EVT(MVT.i32)); SDValue subReg2 = curDAG.getTargetConstant(ARMGenRegisterInfo.ssub_2, new EVT(MVT.i32)); SDValue subReg3 = curDAG.getTargetConstant(ARMGenRegisterInfo.ssub_3, new EVT(MVT.i32)); SDValue[] ops = {regClass, v0, subReg0, v1, subReg1, v2, subReg2, v3, subReg3}; return curDAG.getMachineNode(TargetOpcode.REG_SEQUENCE, dl, vt, ops); } private SDNode quadDRegs(EVT vt, SDValue v0, SDValue v1, SDValue v2, SDValue v3, DebugLoc dl) { SDValue regClass = curDAG.getTargetConstant(ARMGenRegisterInfo.QQPRRegClassID, new EVT(MVT.i32)); SDValue subReg0 = curDAG.getTargetConstant(ARMGenRegisterInfo.dsub_0, new EVT(MVT.i32)); SDValue subReg1 = curDAG.getTargetConstant(ARMGenRegisterInfo.dsub_1, new EVT(MVT.i32)); SDValue subReg2 = curDAG.getTargetConstant(ARMGenRegisterInfo.dsub_2, new EVT(MVT.i32)); SDValue subReg3 = curDAG.getTargetConstant(ARMGenRegisterInfo.dsub_3, new EVT(MVT.i32)); SDValue[] ops = {regClass, v0, subReg0, v1, subReg1, v2, subReg2, v3, subReg3}; return curDAG.getMachineNode(TargetOpcode.REG_SEQUENCE, dl, vt, ops); } private SDNode quadQRegs(EVT vt, SDValue v0, SDValue v1, SDValue v2, SDValue v3, DebugLoc dl) { SDValue regClass = curDAG.getTargetConstant(ARMGenRegisterInfo.QQQQPRRegClassID, new EVT(MVT.i32)); SDValue subReg0 = curDAG.getTargetConstant(ARMGenRegisterInfo.qsub_0, new EVT(MVT.i32)); SDValue subReg1 = curDAG.getTargetConstant(ARMGenRegisterInfo.qsub_1, new EVT(MVT.i32)); SDValue subReg2 = curDAG.getTargetConstant(ARMGenRegisterInfo.qsub_2, new EVT(MVT.i32)); SDValue subReg3 = curDAG.getTargetConstant(ARMGenRegisterInfo.qsub_3, new EVT(MVT.i32)); SDValue[] ops = {regClass, v0, subReg0, v1, subReg1, v2, subReg2, v3, subReg3}; return curDAG.getMachineNode(TargetOpcode.REG_SEQUENCE, dl, vt, ops); } /** * Form a D register from a pair of S registers. * @param vt * @param v0 * @param v1 * @return */ private SDNode pairSRegs(EVT vt, SDValue v0, SDValue v1, DebugLoc dl) { SDValue regClass = curDAG.getTargetConstant(ARMGenRegisterInfo.DPR_VFP2RegClassID, new EVT(MVT.i32)); SDValue subReg0 = curDAG.getTargetConstant(ARMGenRegisterInfo.ssub_0, new EVT(MVT.i32)); SDValue subReg1 = curDAG.getTargetConstant(ARMGenRegisterInfo.ssub_1, new EVT(MVT.i32)); SDValue[] ops = {regClass, v0, subReg0, v1, subReg1}; return curDAG.getMachineNode(TargetOpcode.REG_SEQUENCE, dl, vt, ops); } /** * Form a quad register from a pair of D registers. * @param vt * @param v0 * @param v1 * @return */ private SDNode pairDRegs(EVT vt, SDValue v0, SDValue v1, DebugLoc dl) { SDValue regClass = curDAG.getTargetConstant(ARMGenRegisterInfo.QPRRegClassID, new EVT(MVT.i32)); SDValue subReg0 = curDAG.getTargetConstant(ARMGenRegisterInfo.dsub_0, new EVT(MVT.i32)); SDValue subReg1 = curDAG.getTargetConstant(ARMGenRegisterInfo.dsub_1, new EVT(MVT.i32)); SDValue[] ops = {regClass, v0, subReg0, v1, subReg1}; return curDAG.getMachineNode(TargetOpcode.REG_SEQUENCE, dl, vt, ops); } /** * Form 4 consecutive D registers from a pair of Q registers. * @param vt * @param v0 * @param v1 * @return */ private SDNode pairQRegs(EVT vt, SDValue v0, SDValue v1, DebugLoc dl) { SDValue regClass = curDAG.getTargetConstant(ARMGenRegisterInfo.QQPRRegClassID, new EVT(MVT.i32)); SDValue subReg0 = curDAG.getTargetConstant(ARMGenRegisterInfo.qsub_0, new EVT(MVT.i32)); SDValue subReg1 = curDAG.getTargetConstant(ARMGenRegisterInfo.qsub_1, new EVT(MVT.i32)); SDValue[] ops = {regClass, v0, subReg0, v1, subReg1}; return curDAG.getMachineNode(TargetOpcode.REG_SEQUENCE, dl, vt, ops); } private boolean selectAddrMode2OffsetImmPre(SDNode op, SDValue n, SDValue[] out) { // op is the base ptr of ld, n is the offset part of address expression. // out = {offset, opc} int opcode = op.getOpcode(); MemIndexedMode am = opcode == ISD.LOAD ? ((SDNode.LoadSDNode)op).getAddressingMode() : ((SDNode.StoreSDNode)op).getAddressingMode(); ARM_AM.AddrOpc addSub = am == MemIndexedMode.PRE_INC || am == MemIndexedMode.POST_INC ? ARM_AM.AddrOpc.add : ARM_AM.AddrOpc.sub; OutRef<Integer> val = new OutRef<>(0); if (isScaledConstantInRange(n, 1, 0, 0x1000, val)) { // 12 bits. if (addSub == ARM_AM.AddrOpc.sub) val.set(-val.get()); out[0] = curDAG.getRegister(0, new EVT(MVT.i32)); out[1] = curDAG.getTargetConstant(val.get(), new EVT(MVT.i32)); return true; } return false; } private SDNode selectARMIndexedLoad(SDNode node) { SDNode.LoadSDNode ld = (SDNode.LoadSDNode) node; DebugLoc dl = ld.getDebugLoc(); MemIndexedMode mim = ld.getAddressingMode(); if (mim == MemIndexedMode.UNINDEXED) return null; EVT loadVT = ld.getMemoryVT(); boolean isPre = mim == MemIndexedMode.PRE_INC || mim == MemIndexedMode.PRE_DEC; int opcode = 0; boolean match = false; SDValue[] args = new SDValue[2]; SDValue offset = new SDValue(), amOpc = new SDValue(); // ldr r0, [r1, +-imm] if (loadVT.equals(new EVT(MVT.i32)) && isPre && selectAddrMode2OffsetImmPre(node, ld.getOffset(), args)) { offset = args[0]; amOpc = args[1]; opcode = ARMGenInstrNames.LDR_PRE_IMM; match = true; } else if (loadVT.equals(new EVT(MVT.i32)) && !isPre && selectAddrMode2OffsetImm(node, ld.getOffset(), args)) { offset = args[0]; amOpc = args[1]; opcode = ARMGenInstrNames.LDR_POST_IMM; match = true; } else if (loadVT.equals(new EVT(MVT.i32)) && selectAddrMode2OffsetReg(node, ld.getOffset(), args)) { offset = args[0]; amOpc = args[1]; opcode = !isPre ? ARMGenInstrNames.LDR_POST_REG : ARMGenInstrNames.LDR_PRE_REG; match = true; } else if (loadVT.equals(new EVT(MVT.i16)) && selectAddrMode3Offset(node, ld.getOffset(), args)) { offset = args[0]; amOpc = args[1]; opcode = ld.getExtensionType() == LoadExtType.SEXTLOAD ? (!isPre ? ARMGenInstrNames.LDRSH_POST : ARMGenInstrNames.LDRSH_PRE) : (!isPre ? ARMGenInstrNames.LDRH_POST : ARMGenInstrNames.LDRH_PRE); match = true; } else if (loadVT.equals(new EVT(MVT.i8)) || loadVT.equals(new EVT(MVT.i1))) { if (ld.getExtensionType() == LoadExtType.SEXTLOAD) { if (selectAddrMode3Offset(node, ld.getOffset(), args)){ offset = args[0]; amOpc = args[1]; match = true; opcode = isPre ? ARMGenInstrNames.LDRSB_PRE : ARMGenInstrNames.LDRSB_POST; } } else { if (isPre && selectAddrMode2OffsetImmPre(node, ld.getOffset(), args)) { offset = args[0]; amOpc = args[1]; match = true; opcode = ARMGenInstrNames.LDRB_PRE_IMM; } else if (!isPre && selectAddrMode2OffsetImm(node, ld.getOffset(), args)) { offset = args[0]; amOpc = args[1]; match = true; opcode = ARMGenInstrNames.LDRB_POST_IMM; } else if (selectAddrMode2OffsetReg(node, ld.getOffset(), args)) { offset = args[0]; amOpc = args[1]; match = true; opcode = isPre ? ARMGenInstrNames.LDRB_PRE_REG : ARMGenInstrNames.LDRB_POST_REG; } } } if (match) { if (opcode == ARMGenInstrNames.LDR_PRE_IMM || opcode == ARMGenInstrNames.LDRB_PRE_IMM) { SDValue chain = ld.getChain(); SDValue base = ld.getBasePtr(); SDValue[] ops = new SDValue[] {base, amOpc, getAL(curDAG), curDAG.getRegister(0, new EVT(MVT.i32)), chain}; // for pre or post, it updates the address base register. return curDAG.getMachineNode(opcode, dl, new EVT(MVT.i32), new EVT(MVT.i32), new EVT(MVT.Other), ops); } else { SDValue chain = ld.getChain(); SDValue base = ld.getBasePtr(); SDValue[] ops = {base, offset, amOpc, getAL(curDAG), curDAG.getRegister(0, new EVT(MVT.i32)), chain}; return curDAG.getMachineNode(opcode, dl, new EVT(MVT.i32), new EVT(MVT.i32), new EVT(MVT.Other), ops); } } return null; } private SDNode selectT2IndexedLoad(SDNode node) { SDNode.LoadSDNode ld = (SDNode.LoadSDNode) node; MemIndexedMode am = ld.getAddressingMode(); if (am == MemIndexedMode.UNINDEXED) return null; EVT loadedVT = ld.getMemoryVT(); boolean isExtLd = ld.getExtensionType() == LoadExtType.SEXTLOAD; boolean isPre = am == MemIndexedMode.PRE_INC || am == MemIndexedMode.PRE_DEC; int opcode = 0; boolean match = false; OutRef<SDValue> offset = new OutRef<>(); if (selectT2AddrModeImm8Offset(node, ld.getOffset(), offset)) { switch (loadedVT.getSimpleVT().simpleVT) { case MVT.i32: opcode = isPre ? ARMGenInstrNames.t2LDR_PRE : ARMGenInstrNames.t2LDR_POST; break; case MVT.i16: opcode = isPre ? ARMGenInstrNames.t2LDRH_PRE : ARMGenInstrNames.t2LDRH_POST; break; case MVT.i8: case MVT.i1: opcode = isPre ? ARMGenInstrNames.t2LDRB_PRE : ARMGenInstrNames.t2LDRB_POST; break; default: return null; } match = true; } if (match) { SDValue chain = ld.getChain(); SDValue base = ld.getBasePtr(); SDValue[] ops = {base, offset.get(), getAL(curDAG), curDAG.getRegister(0, new EVT(MVT.i32)), chain}; return curDAG.getMachineNode(opcode, node.getDebugLoc(), new EVT(MVT.i32), new EVT(MVT.i32), new EVT(MVT.Other), ops); } return null; } private boolean isInt32Immediate(SDNode n, OutRef<Long> imm) { if (n.getOpcode() == ISD.Constant && n.getValueType(0).equals(new EVT(MVT.i32))) { imm.set(((SDNode.ConstantSDNode)n).getZExtValue()); return true; } return false; } private boolean isInt32Immediate(SDValue n, OutRef<Long> imm) { return isInt32Immediate(n.getNode(), imm); } private boolean isOpcWithIntImmediate(SDNode n, int opc, OutRef<Long> imm) { return n.getOpcode() == opc && isInt32Immediate(n.getOperand(1).getNode(), imm); } private SDNode selectV6T2BitfieldExtractOp(SDNode node, boolean isSigned) { if (!subtarget.hasV6T2Ops()) return null; int opc = isSigned ? (subtarget.isThumb() ? ARMGenInstrNames.t2SBFX : ARMGenInstrNames.SBFX) : (subtarget.isThumb()? ARMGenInstrNames.t2UBFX : ARMGenInstrNames.UBFX); // for int extracts, check for a shift right and mask. OutRef<Long> andImm = new OutRef<>(0L); if (node.getOpcode() == ISD.AND) { if (isOpcWithIntImmediate(node, ISD.AND, andImm)) { if ((andImm.get() & (andImm.get() + 1)) != 0) return null; OutRef<Long> srlImm = new OutRef<>(0L); if (isOpcWithIntImmediate(node.getOperand(0).getNode(), ISD.SRL, srlImm)) { Util.assertion(srlImm.get() > 0 && srlImm.get() < 32, "bad acount in shift node!"); int width = Util.countTrailingOnes(andImm.get()) - 1; long lsb = srlImm.get(); SDValue reg0 = curDAG.getRegister(0, new EVT(MVT.i32)); SDValue[] ops = {node.getOperand(0).getOperand(0), curDAG.getTargetConstant(lsb, new EVT(MVT.i32)), curDAG.getTargetConstant(width, new EVT(MVT.i32)), getAL(curDAG)}; return curDAG.selectNodeTo(node, opc, new EVT(MVT.i32), ops); } } return null; } // otherwise, we are looking for a shift of a shift. // (srl|sra, (shl, X, C1), C2) OutRef<Long> shlImm = new OutRef<>(0L); if (isOpcWithIntImmediate(node.getOperand(0).getNode(), ISD.SHL, shlImm)) { Util.assertion(shlImm.get() >0 && shlImm.get() < 32, "bad amount in shift node!"); OutRef<Long> srlImm = new OutRef<>(0L); if (isInt32Immediate(node.getOperand(1), srlImm)) { Util.assertion(srlImm.get() > 0 && srlImm.get() < 32, "bad amount in shift node!"); long width = 32 - srlImm.get() - 1; long lsb = srlImm.get() - shlImm.get(); if (lsb < 0) return null; SDValue reg0 = curDAG.getRegister(0, new EVT(MVT.i32)); SDValue[] ops = {node.getOperand(0).getOperand(0), curDAG.getTargetConstant(lsb, new EVT(MVT.i32)), curDAG.getTargetConstant(width, new EVT(MVT.i32)), getAL(curDAG), reg0}; return curDAG.selectNodeTo(node, opc, new EVT(MVT.i32), ops); } } return null; } /** * Return a constantSDNode with the {@linkplain ARMCC.CondCodes#AL} as an immediate. * @param curDAG * @return */ private static SDValue getAL(SelectionDAG curDAG) { return curDAG.getTargetConstant(ARMCC.CondCodes.AL.ordinal(), new EVT(MVT.i32)); } /** * ARM instruction selection transform the following code * <pre> * Y = sra (X, size(X) - 1); * xor (add (X, Y), Y) * </pre> * into * <pre> * abs(X) * </pre> * {@linkplain ARMGenInstrNames#ABS} or {@linkplain ARMGenInstrNames#t2ABS}. * @param node * @return */ private SDNode selectABSOp(SDNode node) { SDValue xor0 = node.getOperand(0), xor1 = node.getOperand(1); if (DisableARMIntABS.value || subtarget.isThumb1Only()) return null; if (xor0.getOpcode() != ISD.ADD || xor1.getOpcode() != ISD.SRA) return null; SDValue add0 = xor0.getOperand(0), add1 = xor0.getOperand(1); SDValue sra0 = xor1.getOperand(0), sra1 = xor1.getOperand(1); if (!(sra1.getNode() instanceof SDNode.ConstantSDNode)) return null; SDNode.ConstantSDNode sra1Cst = (SDNode.ConstantSDNode) sra1.getNode(); long size = sra0.getValueSizeInBits() - 1; EVT xType = sra0.getValueType(); if (add1.equals(xor1) && add0.equals(sra0) && xType.isInteger() && size == sra1Cst.getZExtValue()) { int opcode = subtarget.isThumb2() ? ARMGenInstrNames.t2ABS : ARMGenInstrNames.ABS; return curDAG.selectNodeTo(node, opcode, node.getValueType(0), add0); } return null; } private SDNode selectCMOVOp(SDNode n) { EVT vt = n.getValueType(0); SDValue falseVal = n.getOperand(0); SDValue trueVal = n.getOperand(1); SDValue cc = n.getOperand(2); SDValue ccr = n.getOperand(3); SDValue inflag = n.getOperand(4); Util.assertion(cc.getOpcode() == ISD.Constant); Util.assertion(ccr.getOpcode() == ISD.Register); ARMCC.CondCodes armcc = ARMCC.CondCodes.values()[(int) ((SDNode.ConstantSDNode) cc.getNode()).getZExtValue()]; if (!subtarget.isThumb1Only() && vt.equals(new EVT(MVT.i32))) { // Pattern: (ARMcmov:i32 GPR:i32:$false, so_reg:i32:$true, (imm:i32):$cc) // Emits: (MOVCCs:i32 GPR:i32:$false, so_reg:i32:$true, (imm:i32):$cc) // Pattern complexity = 18 cost = 1 size = 0 if (subtarget.isThumb()) { SDNode res = selectT2CMOVShiftOp(n, falseVal, trueVal, armcc, ccr, inflag); if (res == null) res = selectT2CMOVShiftOp(n, trueVal, falseVal, ARMCC.getOppositeCondition(armcc), ccr, inflag); if (res != null) return res; } else { SDNode res = selectARMCMOVShiftOp(n, falseVal, trueVal, armcc, ccr, inflag); if (res == null) res = selectARMCMOVShiftOp(n, falseVal, trueVal, ARMCC.getOppositeCondition(armcc), ccr, inflag); if (res != null) return res; } } // Pattern: (ARMcmov:i32 GPR:i32:$false, // (imm:i32)<<P:Pred_so_imm>>:$true, // (imm:i32):$cc) // Emits: (MOVCCi:i32 GPR:i32:$false, // (so_imm:i32 (imm:i32):$true), (imm:i32):$cc) // Pattern complexity = 10 cost = 1 size = 0 if (subtarget.isThumb()) { SDNode res = selectT2CMOVImmOp(n, falseVal, trueVal, armcc, ccr, inflag); if (res == null) res = selectT2CMOVImmOp(n, falseVal, trueVal, ARMCC.getOppositeCondition(armcc), ccr, inflag); if (res != null) return res; } else { SDNode res = selectARMCMOVImmOp(n, falseVal, trueVal, armcc, ccr, inflag); if (res == null) res = selectARMCMOVImmOp(n, falseVal, trueVal, ARMCC.getOppositeCondition(armcc), ccr, inflag); if (res != null) return res; } // Pattern: (ARMcmov:i32 GPR:i32:$false, GPR:i32:$true, (imm:i32):$cc) // Emits: (MOVCCr:i32 GPR:i32:$false, GPR:i32:$true, (imm:i32):$cc) // Pattern complexity = 6 cost = 1 size = 0 // // Pattern: (ARMcmov:i32 GPR:i32:$false, GPR:i32:$true, (imm:i32):$cc) // Emits: (tMOVCCr:i32 GPR:i32:$false, GPR:i32:$true, (imm:i32):$cc) // Pattern complexity = 6 cost = 11 size = 0 // // Also VMOVScc and VMOVDcc. SDValue tmp2 = curDAG.getTargetConstant(armcc.ordinal(), new EVT(MVT.i32)); SDValue[] ops = new SDValue[]{falseVal, trueVal, tmp2, ccr, inflag}; int opc = 0; switch (vt.getSimpleVT().simpleVT) { default: Util.assertion("Illegal conditional move type!"); case MVT.i32: opc = subtarget.isThumb() ? (subtarget.isThumb2() ? ARMGenInstrNames.t2MOVCCr : ARMGenInstrNames.tMOVCCr_pseudo) : ARMGenInstrNames.MOVCCr; break; case MVT.f32: opc = ARMGenInstrNames.VMOVScc; break; case MVT.f64: opc = ARMGenInstrNames.VMOVDcc; break; } return curDAG.selectNodeTo(n, opc, vt, ops); } private SDNode selectT2CMOVShiftOp(SDNode n, SDValue falseVal, SDValue trueVal, ARMCC.CondCodes armcc, SDValue ccr, SDValue inflag) { SDValue[] tmp = new SDValue[2]; if (selectT2ShifterOperandReg(trueVal, tmp)) { SDValue tmp0 = tmp[0], tmp1 = tmp[1]; long soVal = ((SDNode.ConstantSDNode) tmp1.getNode()).getZExtValue(); ARM_AM.ShiftOpc soShOp = ARM_AM.getSORegShOp(soVal); int opc = 0; switch (soShOp) { case lsl: opc = ARMGenInstrNames.t2MOVCClsl; break; case lsr: opc = ARMGenInstrNames.t2MOVCClsr; break; case asr: opc = ARMGenInstrNames.t2MOVCCasr; break; case ror: opc = ARMGenInstrNames.t2MOVCCror; break; default: Util.shouldNotReachHere("Unknown shifter operator"); break; } SDValue soShImm = curDAG.getTargetConstant(ARM_AM.getSORegOffset(soVal), new EVT(MVT.i32)); SDValue cc = curDAG.getTargetConstant(armcc.ordinal(), new EVT(MVT.i32)); SDValue[] ops = new SDValue[]{falseVal, tmp0, soShImm, cc, ccr, inflag}; return curDAG.selectNodeTo(n, opc, new EVT(MVT.i32), ops); } return null; } private SDNode selectARMCMOVShiftOp(SDNode n, SDValue falseVal, SDValue trueVal, ARMCC.CondCodes armcc, SDValue ccr, SDValue inflag) { SDValue[] tmp = new SDValue[2]; if (selectImmShifterOperand(trueVal, tmp)) { SDValue cpTmp0 = tmp[0], cpTmp2 = tmp[1]; SDValue cc = curDAG.getTargetConstant(armcc.ordinal(), new EVT(MVT.i32)); SDValue[] ops = new SDValue[]{falseVal, cpTmp0, cpTmp2, cc, ccr, inflag}; return curDAG.selectNodeTo(n, ARMGenInstrNames.MOVCCsi, new EVT(MVT.i32), ops); } SDValue[] tmp1 = new SDValue[3]; if (selectRegShifterOperand(trueVal, tmp1)) { SDValue cpTmp0 = tmp1[0], cpTmp1 = tmp1[1], cpTmp2 = tmp1[2]; SDValue cc = curDAG.getTargetConstant(armcc.ordinal(), new EVT(MVT.i32)); SDValue[] ops = new SDValue[]{falseVal, cpTmp0, cpTmp1, cpTmp2, cc, ccr, inflag}; return curDAG.selectNodeTo(n, ARMGenInstrNames.MOVCCsr, new EVT(MVT.i32), ops); } return null; } private boolean is_so_imm(long imm) { return ARM_AM.getSOImmVal((int) imm) != -1; } private boolean is_so_imm_not(long imm) { return ARM_AM.getSOImmVal((int) ~imm) != -1; } private boolean is_t2_so_imm(long imm) { return ARM_AM.getT2SOImmVal((int) imm) != -1; } private boolean is_t2_so_imm_not(long imm) { return ARM_AM.getT2SOImmVal((int) ~imm) != -1; } private SDNode selectT2CMOVImmOp(SDNode n, SDValue falseVal, SDValue trueVal, ARMCC.CondCodes armcc, SDValue ccr, SDValue inflag) { if (!(trueVal.getNode() instanceof SDNode.ConstantSDNode)) return null; SDNode.ConstantSDNode t = (SDNode.ConstantSDNode) trueVal.getNode(); int opc = 0; long trueImm = t.getZExtValue(); if (is_t2_so_imm(trueImm)) { opc = ARMGenInstrNames.t2MOVCCi; } else if (trueImm <= 0xffff) { opc = ARMGenInstrNames.t2MOVCCi16; } else if (is_t2_so_imm_not(trueImm)) { trueImm = ~trueImm; opc = ARMGenInstrNames.t2MVNCCi; } else if (trueVal.getNode().hasOneUse() && subtarget.hasV6T2Ops()) { // large immediate can be fitted into t2MOVCCi32imm if the armv6 is enabled. opc = ARMGenInstrNames.t2MOVCCi32imm; } if (opc != 0) { SDValue trueValue = curDAG.getTargetConstant(trueImm, new EVT(MVT.i32)); SDValue cc = curDAG.getTargetConstant(armcc.ordinal(), new EVT(MVT.i32)); SDValue[] ops = {falseVal, trueValue, cc, ccr, inflag}; return curDAG.selectNodeTo(n, opc, new EVT(MVT.i32), ops); } return null; } private SDNode selectARMCMOVImmOp(SDNode n, SDValue falseVal, SDValue trueVal, ARMCC.CondCodes armcc, SDValue ccr, SDValue inflag) { if (!(trueVal.getNode() instanceof SDNode.ConstantSDNode)) return null; SDNode.ConstantSDNode t = (SDNode.ConstantSDNode) trueVal.getNode(); int opc = 0; long trueImm = t.getZExtValue(); if (is_so_imm(trueImm)) { opc = ARMGenInstrNames.MOVCCi; } else if (trueImm <= 0xffff && subtarget.hasV6T2Ops()) { opc = ARMGenInstrNames.t2MOVCCi16; } else if (is_so_imm_not(trueImm)) { trueImm = ~trueImm; opc = ARMGenInstrNames.MVNCCi; } else if (trueVal.getNode().hasOneUse() && (subtarget.hasV6T2Ops() || ARM_AM.isSOImmTwoPartVal((int) trueImm))) { // large immediate can be fitted into t2MOVCCi32imm if the armv6 is enabled. opc = ARMGenInstrNames.MOVCCi32imm; } if (opc != 0) { SDValue trueValue = curDAG.getTargetConstant(trueImm, new EVT(MVT.i32)); SDValue cc = curDAG.getTargetConstant(armcc.ordinal(), new EVT(MVT.i32)); SDValue[] ops = {falseVal, trueValue, cc, ccr, inflag}; return curDAG.selectNodeTo(n, opc, new EVT(MVT.i32), ops); } return null; } /** * register +- 12 bit offset. * * @param root * @param n * @param tmp * @return */ protected boolean selectAddrRegImm(SDNode root, SDValue n, SDValue[] tmp) { // temp = {offset, base} tmp[0] = curDAG.getTargetConstant(0, new EVT(MVT.i32)); if (n.getNode() instanceof SDNode.FrameIndexSDNode) { SDNode.FrameIndexSDNode fi = (SDNode.FrameIndexSDNode) n.getNode(); tmp[1] = curDAG.getTargetFrameIndex(fi.getFrameIndex(), n.getValueType()); } else tmp[1] = n; // any address fits in a register. return true; } /** * Return true if it's desirable to select a FP MLA / MLS * node. VFP / NEON fp VMLA / VMLS instructions have special RAW hazards (at * least on current ARM implementations, cortex-A8 and cortex-A9) which should be avoided. * @param n * @return */ protected boolean hasNoVMLxHazardUse(SDNode n) { if (optLevel == TargetMachine.CodeGenOpt.None) return false; if (!CheckVMLxHazard.value) return false; if (!subtarget.isCortexA8() && !subtarget.isCortexA9()) return true; SDNode use = n.getUse(0).getNode(); if (use.getOpcode() == ISD.CopyToReg) return true; if (use.isMachineOpecode()) { MCInstrDesc mcid = subtarget.getInstrInfo().get(use.getMachineOpcode()); if (mcid.mayStore()) return true; int opcode = mcid.getOpcode(); if (opcode == ARMGenInstrNames.VMOVRS || opcode == ARMGenInstrNames.VMOVRRD) return true; // vmlx feeding into another vmlx. We actually want to unfold // the use later in the MLxExpansion pass. e.g. // vmla // vmla (stall 8 cycles) // // vmul (5 cycles) // vadd (5 cycles) // vmla // This adds up to about 18 - 19 cycles. // // vmla // vmul (stall 4 cycles) // vadd adds up to about 14 cycles. return subtarget.getInstrInfo().isFpMLxInstruction(opcode); } return false; } protected boolean selectRegShifterOperand(SDValue n, SDValue[] tmp) { return selectRegShifterOperand(n, tmp, true); } private boolean isShifterOpProfitable(SDValue shift, ARM_AM.ShiftOpc shOpc, long shAmt) { if (!subtarget.isCortexA9()) return true; if (shift.hasOneUse()) return true; // R << 2 is free. return shOpc == ARM_AM.ShiftOpc.lsl && shAmt == 2; } protected boolean selectRegShifterOperand(SDValue n, SDValue[] tmp, boolean checkProfitability) { if (DisableShifterOp.value) return false; ARM_AM.ShiftOpc shOpcVal = ARM_AM.getShiftOpcForNode(n.getOpcode()); // Don't match base register only case. That is matched to a separate // lower complexity pattern with explicit register operand. if (shOpcVal == ARM_AM.ShiftOpc.no_shift) return false; // base register. SDValue baseReg = n.getOperand(0); int shImmVal = 0; if ((n.getOperand(1).getNode() instanceof SDNode.ConstantSDNode)) return false; // shift register. SDValue shReg = n.getOperand(1); if (checkProfitability && !isShifterOpProfitable(n, shOpcVal, shImmVal)) return false; SDValue opc = curDAG.getTargetConstant(ARM_AM.getSORegOpc(shOpcVal, shImmVal), new EVT(MVT.i32)); tmp[0] = baseReg; tmp[1] = shReg; tmp[2] = opc; return true; } protected boolean selectImmShifterOperand(SDValue n, SDValue[] tmp) { return selectImmShifterOperand(n, tmp, true); } protected boolean selectImmShifterOperand(SDValue n, SDValue[] tmp, boolean checkProfitability) { if (DisableShifterOp.value) return false; ARM_AM.ShiftOpc shOpcVal = ARM_AM.getShiftOpcForNode(n.getOpcode()); // Don't match base register only case. That is matched to a separate // lower complexity pattern with explicit register operand. if (shOpcVal == ARM_AM.ShiftOpc.no_shift) return false; // base register. SDValue baseReg = n.getOperand(0); long shImmVal = 0; if (!(n.getOperand(1).getNode() instanceof SDNode.ConstantSDNode)) return false; shImmVal = ((SDNode.ConstantSDNode) n.getOperand(1).getNode()).getZExtValue() & 31; SDValue opc = curDAG.getTargetConstant(ARM_AM.getSORegOpc(shOpcVal, shImmVal), new EVT(MVT.i32)); tmp[0] = baseReg; tmp[1] = opc; return true; } private SDValue getI32Imm(long imm) { return curDAG.getTargetConstant(imm, new EVT(MVT.i32)); } protected boolean selectT2ShifterOperandReg(SDValue n, SDValue[] tmp) { // tmp = {basereg, opc} if (DisableShifterOp.value) return false; ARM_AM.ShiftOpc shOpcVal = ARM_AM.getShiftOpcForNode(n.getOpcode()); if (shOpcVal == ARM_AM.ShiftOpc.no_shift) return false; tmp[0] = n.getOperand(0); int shImmVal = 0; if (n.getOperand(1).getNode() instanceof SDNode.ConstantSDNode) { shImmVal = (int) (((SDNode.ConstantSDNode)n.getOperand(1).getNode()).getZExtValue() & 31); tmp[1] = getI32Imm(ARM_AM.getSORegOpc(shOpcVal, shImmVal)); return true; } return false; } protected boolean selectShiftRegShifterOperand(SDValue n, SDValue[] tmp) { // disable profitability checking. return selectRegShifterOperand(n, tmp, false); } protected boolean selectShiftImmShifterOperand(SDValue n, SDValue[] tmp) { // disable profitability checking. return selectImmShifterOperand(n, tmp, false); } /** * Check whether a particular node is a constant value representable as * (node * Scale) where (node in [{@code rangeMin}, {@code rangeMax}). * * @param node * @param scale * @param rangeMin * @param rangeMax * @param scaledConstant * @return */ private static boolean isScaledConstantInRange(SDValue node, int scale, int rangeMin, int rangeMax, OutRef<Integer> scaledConstant) { Util.assertion(scale > 0, "invalid scale"); if (!(node.getNode() instanceof SDNode.ConstantSDNode)) return false; SDNode.ConstantSDNode cst = (SDNode.ConstantSDNode) node.getNode(); long c = cst.getZExtValue(); if ((c % scale) != 0) return false; c /= scale; return c >= rangeMin && c < rangeMax; } protected boolean selectLdStSOReg(SDValue n, SDValue[] tmp) { if (n.getOpcode() == ISD.MUL && (!subtarget.isCortexA9() || n.hasOneUse())) { if (n.getOperand(1).getNode() instanceof SDNode.ConstantSDNode) { SDNode.ConstantSDNode cstRHS = (SDNode.ConstantSDNode) n.getOperand(1).getNode(); long rhsc = cstRHS.getZExtValue(); if ((rhsc & 1) != 0) { rhsc = rhsc & ~1; ARM_AM.AddrOpc addsub = ARM_AM.AddrOpc.add; if (rhsc < 0) { addsub = ARM_AM.AddrOpc.sub; rhsc = -rhsc; } if (Util.isPowerOf2(rhsc)) { int shAmt = Util.log2(rhsc); // base = offset = n.getOperand(0); tmp[0] = tmp[1] = n.getOperand(0); // opc tmp[2] = curDAG.getTargetConstant(ARM_AM.getAM2Opc(addsub, shAmt, ARM_AM.ShiftOpc.lsl), new EVT(MVT.i32)); return true; } } } } if (n.getOpcode() != ISD.ADD && n.getOpcode() != ISD.SUB && !curDAG.isBaseWithConstantOffset(n)) { return false; } if (n.getOpcode() == ISD.ADD || n.getOpcode() == ISD.OR) { // simple R +- imm12 for LDRi12. OutRef<Integer> rhsc = new OutRef<>(0); if (isScaledConstantInRange(n.getOperand(1), /*scale*/ 1, -0x100 + 1, 0x1000, rhsc)) return false; } // otherwise R +/- [possibly shifted] R. ARM_AM.AddrOpc addsub = n.getOpcode() == ISD.ADD ? ARM_AM.AddrOpc.add : ARM_AM.AddrOpc.sub; ARM_AM.ShiftOpc shOpc = ARM_AM.getShiftOpcForNode(n.getOperand(1).getOpcode()); long shAmt = 0; // base SDValue base = n.getOperand(0); // offset SDValue offset = n.getOperand(1); if (shOpc != ARM_AM.ShiftOpc.no_shift) { // check to see if the rhs of the shift is a constant, if it is not, we can't fold. if (n.getOperand(1).getOperand(1).getNode() instanceof SDNode.ConstantSDNode) { SDNode.ConstantSDNode sh = (SDNode.ConstantSDNode) n.getOperand(1).getOperand(1).getNode(); shAmt = sh.getZExtValue(); if (isShifterOpProfitable(offset, shOpc, shAmt)) offset = n.getOperand(1).getOperand(0); else { shAmt = 0; shOpc = ARM_AM.ShiftOpc.no_shift; } } else shOpc = ARM_AM.ShiftOpc.no_shift; } // try matching (R shl C) + (R). if (n.getOpcode() != ISD.SUB && shOpc == ARM_AM.ShiftOpc.no_shift && !(subtarget.isCortexA9() || n.getOperand(0).hasOneUse())) { shOpc = ARM_AM.getShiftOpcForNode(n.getOperand(0).getOpcode()); if (shOpc != ARM_AM.ShiftOpc.no_shift) { // check to see if the rhs of the shift is a constant, if it is not, don't fold. if (n.getOperand(0).getOperand(1).getNode() instanceof SDNode.ConstantSDNode) { SDNode.ConstantSDNode sh = (SDNode.ConstantSDNode) n.getOperand(0).getOperand(1).getNode(); shAmt = sh.getZExtValue(); if (isShifterOpProfitable(n.getOperand(0), shOpc, shAmt)) { offset = n.getOperand(0).getOperand(0); base = n.getOperand(1); } else { shAmt = 0; shOpc = ARM_AM.ShiftOpc.no_shift; } } else shOpc = ARM_AM.ShiftOpc.no_shift; } } tmp[0] = base; tmp[1] = offset; // opc tmp[2] = curDAG.getTargetConstant(ARM_AM.getAM2Opc(addsub, (int) shAmt, shOpc), new EVT(MVT.i32)); return true; } protected boolean selectT2AddrModeSoReg(SDValue n, SDValue[] tmp) { // tmp = {base, offReg, shImm} // (R - imm8) should be handled by t2LDRi8. The rest are handled by t2LDRi12. if (n.getOpcode() != ISD.ADD && !curDAG.isBaseWithConstantOffset(n)) return false; // leave (R + imm12) for t2LDRi12, (R - imm8) for t2LDRi8. if (n.getOperand(1).getNode() instanceof SDNode.ConstantSDNode) { SDNode.ConstantSDNode rhs = (SDNode.ConstantSDNode) n.getOperand(1).getNode(); long rhsc = rhs.getZExtValue(); // 12 bits if (rhsc >= 0 && rhsc < 0x1000) { return false; } else if (rhsc < 0 && rhsc >= -255) // 8bits return false; } // look for (R + R) or (R + (R << [1, 2, 3])) SDValue base = n.getOperand(0); SDValue offReg = n.getOperand(1); // swap if it is ((R << C) + R) ARM_AM.ShiftOpc shOpcVal = ARM_AM.getShiftOpcForNode(offReg.getOpcode()); if (shOpcVal != ARM_AM.ShiftOpc.lsl) { shOpcVal = ARM_AM.getShiftOpcForNode(base.getOpcode()); if (shOpcVal == ARM_AM.ShiftOpc.lsl) { SDValue t = base; base = offReg; offReg = t; } } long shAmt = 0; if (shOpcVal == ARM_AM.ShiftOpc.lsl) { // check to see if the rhs of the shift is a constant. if not, we can't fold it. if (offReg.getOperand(1).getNode() instanceof SDNode.ConstantSDNode) { shAmt = ((SDNode.ConstantSDNode)offReg.getOperand(1).getNode()).getZExtValue(); if (shAmt < 4 && isShifterOpProfitable(offReg, shOpcVal, shAmt)) offReg = offReg.getOperand(0); else { shAmt = 0; shOpcVal = ARM_AM.ShiftOpc.no_shift; } } else shOpcVal = ARM_AM.ShiftOpc.no_shift; } tmp[0] = base; tmp[1] = offReg; // shImm tmp[2] = curDAG.getTargetConstant(shAmt, new EVT(MVT.i32)); return true; } protected boolean selectAddrModeImm12(SDValue n, SDValue[] tmp) { // tmp = {base, offImm} // Match simple R + imm12 operands. if (n.getOpcode() != ISD.ADD && n.getOpcode() != ISD.SUB && !curDAG.isBaseWithConstantOffset(n)) { // match frame index. if (n.getOpcode() == ISD.FrameIndex) { int fi = ((SDNode.FrameIndexSDNode) (n.getNode())).getFrameIndex(); tmp[0] = curDAG.getTargetFrameIndex(fi, new EVT(tli.getPointerTy())); tmp[1] = curDAG.getTargetConstant(0, new EVT(MVT.i32)); return true; } if (n.getOpcode() == ARMISD.Wrapper && !(subtarget.useMovt() && n.getOperand(0).getOpcode() == ISD.TargetGlobalAddress)) { tmp[0] = n.getOperand(0); } else tmp[0] = n; tmp[1] = curDAG.getTargetConstant(0, new EVT(MVT.i32)); return true; } if (n.getOperand(1).getNode() instanceof SDNode.ConstantSDNode) { SDNode.ConstantSDNode rhs = (SDNode.ConstantSDNode) n.getOperand(1).getNode(); long rhsc = rhs.getZExtValue(); if (n.getOpcode() == ISD.SUB) rhsc = -rhsc; if (rhsc >= 0 && rhsc < 0x1000) { // 12 bits tmp[0] = n.getOperand(0); if (tmp[0].getOpcode() == ISD.FrameIndex) { int fi = ((SDNode.FrameIndexSDNode) tmp[0].getNode()).getFrameIndex(); tmp[0] = curDAG.getTargetFrameIndex(fi, new EVT(tli.getPointerTy())); } tmp[1] = curDAG.getTargetConstant(rhsc, new EVT(MVT.i32)); return true; } } // Base only. tmp[0] = n; tmp[1] = curDAG.getTargetConstant(0, new EVT(MVT.i32)); return true; } protected boolean selectT2AddrModeImm12(SDValue n, SDValue[] tmp) { // tmp = {base, offImm} // Match simple R + imm12 operands. // Base only if (n.getOpcode() != ISD.ADD && n.getOpcode() != ISD.SUB && !curDAG.isBaseWithConstantOffset(n)) { if (n.getOpcode() == ISD.FrameIndex) { // match frame index. long fi = ((SDNode.FrameIndexSDNode) n.getNode()).getFrameIndex(); tmp[0] = curDAG.getTargetFrameIndex((int) fi, new EVT(tli.getPointerTy())); tmp[1] = curDAG.getTargetConstant(0, new EVT(MVT.i32)); return true; } if (n.getOpcode() == ARMISD.Wrapper && !(subtarget.useMovt() && n.getOperand(0).getOpcode() == ISD.TargetGlobalAddress)) { tmp[0] = n.getOperand(0); if (tmp[0].getOpcode() == ISD.TargetConstantPool) return false; // select t2LDRpci instead. } else { tmp[0] = n; } tmp[1] = curDAG.getTargetConstant(0, new EVT(MVT.i32)); return true; } if (n.getOperand(1).getNode() instanceof SDNode.ConstantSDNode) { SDNode.ConstantSDNode rhs = (SDNode.ConstantSDNode) n.getOperand(1).getNode(); if (selectT2AddrModeImm8(n, tmp)) // select t2LDRi8 for (R - imm8) return false; long rhsC = rhs.getZExtValue(); if (n.getOpcode() == ISD.SUB) rhsC = -rhsC; if (rhsC >= 0 && rhsC <= 0x1000) { tmp[0] = n.getOperand(0); if (tmp[0].getOpcode() == ISD.FrameIndex) { int fi = ((SDNode.FrameIndexSDNode)tmp[0].getNode()).getFrameIndex(); tmp[0] = curDAG.getTargetFrameIndex(fi, new EVT(tli.getPointerTy())); } tmp[1] = curDAG.getTargetConstant(rhsC, new EVT(MVT.i32)); return true; } } // base only. tmp[0] = n; tmp[1] = curDAG.getTargetConstant(0, new EVT(MVT.i32)); return true; } protected boolean selectT2AddrModeImm8(SDValue n, SDValue[] tmp) { // match the simple R - imm8 operands. if (n.getOpcode() != ISD.ADD && n.getOpcode() != ISD.SUB && !curDAG.isBaseWithConstantOffset(n)) { return false; } if ( n.getOperand(1).getNode() instanceof SDNode.ConstantSDNode) { SDNode.ConstantSDNode rhs = (SDNode.ConstantSDNode) n.getOperand(1).getNode(); long rhsC = rhs.getZExtValue(); if (n.getOpcode() == ISD.SUB) rhsC = -rhsC; if (rhsC >= -255 && rhsC < 0) { // 8 bits tmp[0] = n.getOperand(0); if (tmp[0].getOpcode() == ISD.FrameIndex) { int fi = ((SDNode.FrameIndexSDNode)tmp[0].getNode()).getFrameIndex(); tmp[0] = curDAG.getTargetFrameIndex(fi, new EVT(tli.getPointerTy())); } tmp[1] = curDAG.getTargetConstant(rhsC, new EVT(MVT.i32)); return true; } } return false; } protected boolean selectAddrMode2(SDValue n, SDValue[] tmp) { selectAddrMode2Worker(n, tmp); return true; } private enum AddrMode2Type { AM2_BASE, // Simple AM2 (+-imm12) AM2_SHOP // Shifter-op AM2 } private AddrMode2Type selectAddrMode2Worker(SDValue n, SDValue[] tmp) { // tmp = {base, offset, opc} if (n.getOpcode() == ISD.MUL && (!subtarget.isCortexA9() || n.hasOneUse())) { if (n.getOperand(1).getNode() instanceof SDNode.ConstantSDNode) { SDNode.ConstantSDNode rhs = (SDNode.ConstantSDNode) n.getOperand(1).getNode(); // X * (3, 5, 9) -> X + X * (2, 4, 8) long rhsC = rhs.getZExtValue(); if ((rhsC & 1) != 0) { rhsC = rhsC & ~1; ARM_AM.AddrOpc addsub = ARM_AM.AddrOpc.add; if (rhsC < 0) { addsub = ARM_AM.AddrOpc.sub; rhsC = -rhsC; } if (Util.isPowerOf2(rhsC)) { int shAmt = Util.log2(rhsC); tmp[0] = tmp[1] = n.getOperand(0); tmp[2] = curDAG.getTargetConstant(ARM_AM.getAM2Opc(addsub, shAmt, ARM_AM.ShiftOpc.lsl), new EVT(MVT.i32)); return AddrMode2Type.AM2_SHOP; } } } } if (n.getOpcode() != ISD.ADD && n.getOpcode() != ISD.SUB && !curDAG.isBaseWithConstantOffset(n)) { tmp[0] = n; if (n.getOpcode() == ISD.FrameIndex) { int fi = ((SDNode.FrameIndexSDNode)n.getNode()).getFrameIndex(); tmp[0] = curDAG.getTargetFrameIndex(fi, new EVT(tli.getPointerTy())); } else if (n.getOpcode() == ARMISD.Wrapper && !(subtarget.useMovt() && n.getOperand(0).getOpcode() == ISD.TargetGlobalAddress)) { tmp[0] = n.getOperand(0); } tmp[1] = curDAG.getRegister(0, new EVT(MVT.i32)); tmp[2] = curDAG.getTargetConstant(ARM_AM.getAM2Opc(ARM_AM.AddrOpc.add, 0, ARM_AM.ShiftOpc.no_shift), new EVT(MVT.i32)); return AddrMode2Type.AM2_BASE; } // Match simple R +/- imm12 operands. if (n.getOpcode() != ISD.SUB) { OutRef<Integer> rhsc = new OutRef<>(0); if (isScaledConstantInRange(n.getOperand(1), /*scale*/1, -0x1000+1, 0x1000, rhsc)) { tmp[0] = n.getOperand(0); if (tmp[0].getOpcode() == ISD.FrameIndex) { int fi = ((SDNode.FrameIndexSDNode)n.getOperand(0).getNode()).getFrameIndex(); tmp[0] = curDAG.getTargetFrameIndex(fi, new EVT(tli.getPointerTy())); } tmp[1] = curDAG.getRegister(0, new EVT(MVT.i32)); ARM_AM.AddrOpc addsub = ARM_AM.AddrOpc.add; if (rhsc.get() < 0) { rhsc.set(-rhsc.get()); addsub = ARM_AM.AddrOpc.sub; } // opc tmp[2] = curDAG.getTargetConstant(ARM_AM.getAM2Opc(addsub, rhsc.get(), ARM_AM.ShiftOpc.no_shift), new EVT(MVT.i32)); return AddrMode2Type.AM2_BASE; } } if (subtarget.isCortexA9() && !n.hasOneUse()) { // Compute R +/- (R << N) and reuse it. tmp[0] = n; tmp[1] = curDAG.getRegister(0, new EVT(MVT.i32)); tmp[2] = curDAG.getTargetConstant(ARM_AM.getAM2Opc(ARM_AM.AddrOpc.add, 0, ARM_AM.ShiftOpc.no_shift), new EVT(MVT.i32)); return AddrMode2Type.AM2_BASE; } // Otherwise this is R +/- [possibly shifted] R. ARM_AM.AddrOpc addsub = n.getOpcode() != ISD.SUB ? ARM_AM.AddrOpc.add : ARM_AM.AddrOpc.sub; ARM_AM.ShiftOpc shopcVal = ARM_AM.getShiftOpcForNode(n.getOperand(1).getOpcode()); long shAmt = 0; tmp[0] = n.getOperand(0); tmp[1] = n.getOperand(1); if (shopcVal != ARM_AM.ShiftOpc.no_shift) { // check to see if the RHS of the shift is a constant, if not, wew can't fold it. if (n.getOperand(1).getOperand(1).getNode() instanceof SDNode.ConstantSDNode) { shAmt = ((SDNode.ConstantSDNode)n.getOperand(1).getOperand(1).getNode()).getZExtValue(); if (isShifterOpProfitable(tmp[1], shopcVal, shAmt)) tmp[1] = n.getOperand(1).getOperand(0); else { shAmt = 0; shopcVal = ARM_AM.ShiftOpc.no_shift; } } else { shopcVal = ARM_AM.ShiftOpc.no_shift; } } // Try matching (R shl C) + (R). if (n.getOpcode() != ISD.SUB && shopcVal == ARM_AM.ShiftOpc.no_shift && !(subtarget.isCortexA9() || n.getOperand(0).hasOneUse())) { shopcVal = ARM_AM.getShiftOpcForNode(n.getOperand(0).getOpcode()); if (shopcVal != ARM_AM.ShiftOpc.no_shift) { // Check to see if the RHS of the shift is a constant, if not, we can't // fold it. if (n.getOperand(0).getOperand(1).getNode() instanceof SDNode.ConstantSDNode) { shAmt = ((SDNode.ConstantSDNode)n.getOperand(0).getOperand(1).getNode()).getZExtValue(); if (isShifterOpProfitable(n.getOperand(0), shopcVal, shAmt)) { tmp[0] = n.getOperand(1); tmp[1] = n.getOperand(0).getOperand(0); } else { shAmt = 0; shopcVal = ARM_AM.ShiftOpc.no_shift; } } else { shopcVal = ARM_AM.ShiftOpc.no_shift; } } } tmp[2] = curDAG.getTargetConstant(ARM_AM.getAM2Opc(addsub, (int) shAmt, shopcVal), new EVT(MVT.i32)); return AddrMode2Type.AM2_SHOP; } protected boolean selectAddrMode6(SDNode parent, SDValue n, SDValue[] tmp) { // tmp = {add, align} tmp[0] = n; int alignment = 0; if (parent instanceof SDNode.LSBaseSDNode) { SDNode.LSBaseSDNode lsn = (SDNode.LSBaseSDNode) parent; int memSize = lsn.getMemoryVT().getSizeInBits() / 8; int lsnAlign = lsn.getAlignment(); if (lsnAlign > memSize && memSize > 1) alignment = lsnAlign; } else { alignment = ((SDNode.MemIntrinsicSDNode)parent).getAlignment(); } tmp[1] = curDAG.getTargetConstant(alignment, new EVT(MVT.i32)); return true; } protected boolean selectAddrMode6Offset(SDNode op, SDValue n, SDValue[] tmp) { // tmp = {offset} SDNode.LSBaseSDNode ldSt = (SDNode.LSBaseSDNode) op; MemIndexedMode am = ldSt.getAddressingMode(); if (am != MemIndexedMode.POST_INC) return false; tmp[0] = n; if (n.getNode() instanceof SDNode.ConstantSDNode) { SDNode.ConstantSDNode nc = (SDNode.ConstantSDNode) n.getNode(); if (nc.getZExtValue() * 8 == ldSt.getMemoryVT().getSizeInBits()) tmp[0] = curDAG.getRegister(0, new EVT(MVT.i32)); } return true; } protected boolean selectAddrModePC(SDValue n, SDValue[] tmp) { if (n.getOpcode() == ARMISD.PIC_ADD && n.hasOneUse()) { // offset tmp[0] = n.getOperand(0); SDValue n1 = n.getOperand(1); // label. tmp[1] = curDAG.getTargetConstant(((SDNode.ConstantSDNode) n1.getNode()).getZExtValue(), new EVT(MVT.i32)); return true; } return false; } protected boolean selectAddrOffsetNone(SDValue n, SDValue[] tmp) { // tmp[0] = base tmp[0] = n; return true; } protected boolean selectAddrMode3Offset(SDNode op, SDValue n, SDValue[] tmp) { int opc = op.getOpcode(); MemIndexedMode am = opc == ISD.LOAD ? ((SDNode.LoadSDNode) n.getNode()).getAddressingMode() : ((SDNode.StoreSDNode) n.getNode()).getAddressingMode(); ARM_AM.AddrOpc addsub = am == MemIndexedMode.PRE_INC || am == MemIndexedMode.POST_INC ? ARM_AM.AddrOpc.add : ARM_AM.AddrOpc.sub; // tmp[0] = offset tmp[0] = n; // tmp[1] = opc. tmp[1] = curDAG.getTargetConstant(ARM_AM.getAM3Opc(addsub, 0), new EVT(MVT.i32)); return true; } protected boolean selectAddrMode2OffsetReg(SDNode op, SDValue n, SDValue[] tmp) { int opc = op.getOpcode(); MemIndexedMode am = opc == ISD.LOAD ? ((SDNode.LoadSDNode) n.getNode()).getAddressingMode() : ((SDNode.StoreSDNode) n.getNode()).getAddressingMode(); ARM_AM.AddrOpc addsub = am == MemIndexedMode.PRE_INC || am == MemIndexedMode.POST_INC ? ARM_AM.AddrOpc.add : ARM_AM.AddrOpc.sub; OutRef<Integer> val = new OutRef<>(0); // 12 bit, [0, 2^12) if (isScaledConstantInRange(n, 1, 0, 0x1000, val)) { if (addsub == ARM_AM.AddrOpc.sub) val.set(-val.get()); // tmp[0] = offset tmp[0] = curDAG.getRegister(0, new EVT(MVT.i32)); // tmp[1] = opc. tmp[1] = curDAG.getTargetConstant(val.get(), new EVT(MVT.i32)); return true; } return false; } protected boolean selectAddrMode2OffsetImm(SDNode op, SDValue n, SDValue[] tmp) { int opc = op.getOpcode(); MemIndexedMode am = opc == ISD.LOAD ? ((SDNode.LoadSDNode) n.getNode()).getAddressingMode() : ((SDNode.StoreSDNode) n.getNode()).getAddressingMode(); ARM_AM.AddrOpc addsub = am == MemIndexedMode.PRE_INC || am == MemIndexedMode.POST_INC ? ARM_AM.AddrOpc.add : ARM_AM.AddrOpc.sub; OutRef<Integer> val = new OutRef<>(0); // 12 bit, [0, 2^12) if (isScaledConstantInRange(n, 1, 0, 0x1000, val)) { // tmp[0] = offset tmp[0] = curDAG.getRegister(0, new EVT(MVT.i32)); // tmp[1] = opc. tmp[1] = curDAG.getTargetConstant(ARM_AM.getAM2Opc(addsub, val.get(), ARM_AM.ShiftOpc.no_shift), new EVT(MVT.i32)); return true; } return false; } protected boolean selectAddrMode3(SDValue n, SDValue[] tmp) { // Match the address mode 3. // tmp[0] = base, tmp[1] = offset , tmp[2] = opc. if (n.getOpcode() == ISD.SUB) { tmp[0] = n.getOperand(0); tmp[1] = n.getOperand(1); tmp[2] = curDAG.getTargetConstant(ARM_AM.getAM3Opc(ARM_AM.AddrOpc.sub, 0), new EVT(MVT.i32)); return true; } if (!curDAG.isBaseWithConstantOffset(n)) { tmp[0] = n; if (n.getOpcode() == ISD.FrameIndex) { int fi = ((SDNode.FrameIndexSDNode) n.getNode()).getFrameIndex(); tmp[0] = curDAG.getTargetFrameIndex(fi, new EVT(tli.getPointerTy())); } tmp[1] = curDAG.getRegister(0, new EVT(MVT.i32)); tmp[2] = curDAG.getTargetConstant(ARM_AM.getAM3Opc(ARM_AM.AddrOpc.add, 0), new EVT(MVT.i32)); return true; } // If the RHS is +/- imm8, fold into addr mode. OutRef<Integer> rhsc = new OutRef<>(0); if (isScaledConstantInRange(n.getOperand(1), /*scale*/1, -256 + 1, 256, rhsc)) { tmp[0] = n.getOperand(0); if (tmp[0].getOpcode() == ISD.FrameIndex) { int fi = ((SDNode.FrameIndexSDNode) tmp[0].getNode()).getFrameIndex(); tmp[0] = curDAG.getTargetFrameIndex(fi, new EVT(tli.getPointerTy())); } tmp[1] = curDAG.getRegister(0, new EVT(MVT.i32)); ARM_AM.AddrOpc addsub = ARM_AM.AddrOpc.add; if (rhsc.get() < 0) { rhsc.set(-rhsc.get()); addsub = ARM_AM.AddrOpc.sub; } tmp[2] = curDAG.getTargetConstant(ARM_AM.getAM3Opc(addsub, rhsc.get()), new EVT(MVT.i32)); return true; } tmp[0] = n.getOperand(0); tmp[1] = n.getOperand(1); tmp[2] = curDAG.getTargetConstant(ARM_AM.getAM3Opc(ARM_AM.AddrOpc.add, 0), new EVT(MVT.i32)); return true; } protected boolean selectT2AddrModeImm8Offset(SDNode op, SDValue n, SDValue[] offImm) { Util.assertion(offImm.length == 1); OutRef<SDValue> arg = new OutRef<>(); boolean res = selectT2AddrModeImm8Offset(op, n, arg); offImm[0] = arg.get(); return res; } protected boolean selectT2AddrModeImm8Offset(SDNode op, SDValue n, OutRef<SDValue> offImm) { int opcode = op.getOpcode(); MemIndexedMode am = opcode == ISD.LOAD ? ((SDNode.LoadSDNode)op).getAddressingMode() : ((SDNode.StoreSDNode)op).getAddressingMode(); OutRef<Integer> rhsc = new OutRef<>(0); // test if the offset is a constant in 8 bits. if (isScaledConstantInRange(n, 1, 0, 0x100, rhsc)) { offImm.set(am == MemIndexedMode.PRE_INC || am == MemIndexedMode.PRE_DEC ? curDAG.getTargetConstant(rhsc.get(), new EVT(MVT.i32)) : curDAG.getTargetConstant(-rhsc.get(), new EVT(MVT.i32))); return true; } offImm.set(null); return false; } protected boolean selectThumbAddrModeRI5S1(SDValue n, SDValue[] tmp) { return selectThumbAddrModeRI(n, tmp, 1); } protected boolean selectThumbAddrModeRI5S2(SDValue n, SDValue[] tmp) { return selectThumbAddrModeRI(n, tmp, 2); } protected boolean selectThumbAddrModeRI5S4(SDValue n, SDValue[] tmp) { return selectThumbAddrModeRI(n, tmp, 4); } protected boolean selectThumbAddrModeImm5S1(SDValue n, SDValue[] tmp) { return selectThumbAddrModeImm5S(n, 1, tmp); } protected boolean selectThumbAddrModeImm5S2(SDValue n, SDValue[] tmp) { return selectThumbAddrModeImm5S(n, 2, tmp); } protected boolean selectThumbAddrModeImm5S4(SDValue n, SDValue[] tmp) { return selectThumbAddrModeImm5S(n, 4, tmp); } private boolean selectThumbAddrModeRI(SDValue n, SDValue[] tmp, int scale) { if (scale == 4) { SDValue[] tmpRes = new SDValue[2]; // select tLDRspi / tSTRspi instead. if (selectThumbAddrModeSP(n, tmpRes)) return false; // select tLDRpci instead. if (n.getOpcode() == ARMISD.Wrapper && n.getOperand(0).getOpcode() == ISD.TargetConstantPool) return false; } if (!curDAG.isBaseWithConstantOffset(n)) return false; // thumb doens't have [sp, r] address mode. if ((n.getOperand(0).getNode() instanceof SDNode.RegisterSDNode && ((SDNode.RegisterSDNode)n.getOperand(0).getNode()).getReg() == ARMGenRegisterNames.SP) || (n.getOperand(1).getNode() instanceof SDNode.RegisterSDNode && ((SDNode.RegisterSDNode)n.getOperand(1).getNode()).getReg() == ARMGenRegisterNames.SP)) { return false; } OutRef<Integer> rhsc = new OutRef<>(0); if (isScaledConstantInRange(n.getOperand(1), scale, 0, 32, rhsc)) return false; tmp[0] = n.getOperand(0); tmp[1] = n.getOperand(1); return true; } private boolean selectThumbAddrModeImm5S(SDValue n, int scale, SDValue[] tmp) { // tmp = {base, offImm} if (scale == 4) { SDValue[] tmpRes = new SDValue[2]; // select tLDRspi / tSTRspi instead. if (selectThumbAddrModeSP(n, tmpRes)) return false; // select tLDRpci instead. if (n.getOpcode() == ARMISD.Wrapper && n.getOperand(0).getOpcode() == ISD.TargetConstantPool) return false; } if (!curDAG.isBaseWithConstantOffset(n)) { if (n.getOpcode() == ARMISD.Wrapper && !(subtarget.useMovt() && n.getOperand(0).getOpcode() == ISD.TargetGlobalAddress)) { tmp[0] = n.getOperand(0); } else tmp[0] = n; tmp[1] = curDAG.getTargetConstant(0, new EVT(MVT.i32)); return true; } // thumb doens't have [sp, #imm5] address mode for non-zero imm5. if ((n.getOperand(0).getNode() instanceof SDNode.RegisterSDNode && ((SDNode.RegisterSDNode)n.getOperand(0).getNode()).getReg() == ARMGenRegisterNames.SP) || (n.getOperand(1).getNode() instanceof SDNode.RegisterSDNode && ((SDNode.RegisterSDNode)n.getOperand(1).getNode()).getReg() == ARMGenRegisterNames.SP)) { long lhsc = 0; if (n.getOperand(0).getNode() instanceof SDNode.ConstantSDNode) lhsc = ((SDNode.ConstantSDNode)n.getOperand(0).getNode()).getZExtValue(); long rhsc = 0; if (n.getOperand(1).getNode() instanceof SDNode.ConstantSDNode) rhsc = ((SDNode.ConstantSDNode)n.getOperand(1).getNode()).getZExtValue(); if (lhsc != 0 || rhsc != 0) return false; tmp[0] = n; tmp[1] = curDAG.getTargetConstant(0, new EVT(MVT.i32)); return true; } // If the RHS is + imm5 * scale, fold into addr mode. OutRef<Integer> rhsc = new OutRef<>(0); if (isScaledConstantInRange(n.getOperand(1), scale, 0, 32, rhsc)) { tmp[0] = n.getOperand(0); tmp[1] = curDAG.getTargetConstant(rhsc.get(), new EVT(MVT.i32)); return true; } tmp[0] = n.getOperand(0); tmp[1] = curDAG.getTargetConstant(0, new EVT(MVT.i32)); return true; } protected boolean selectThumbAddrModeSP(SDValue n, SDValue[] tmp) { // tmp = {base, offImm} if (n.getOpcode() == ISD.FrameIndex) { int fi = ((SDNode.FrameIndexSDNode)n.getNode()).getFrameIndex(); tmp[0] = curDAG.getTargetFrameIndex(fi, new EVT(tli.getPointerTy())); tmp[1] = curDAG.getTargetConstant(0, new EVT(MVT.i32)); return true; } if (!curDAG.isBaseWithConstantOffset(n)) return false; if (n.getOperand(0).getOpcode() == ISD.FrameIndex || ((n.getOperand(0).getNode() instanceof SDNode.RegisterSDNode) && ((SDNode.RegisterSDNode) n.getOperand(0).getNode()).getReg() == ARMGenRegisterNames.SP)) { // if the rhs is + imm8 * scale, fold into addr mode. OutRef<Integer> rhsc = new OutRef<>(0); if (isScaledConstantInRange(n.getOperand(1), /*scale*/ 4, 0, 256, rhsc)) { tmp[0] = n.getOperand(0); if (tmp[0].getOpcode() == ISD.FrameIndex) { int fi = ((SDNode.FrameIndexSDNode)n.getOperand(0).getNode()).getFrameIndex(); tmp[0] = curDAG.getTargetFrameIndex(fi, new EVT(tli.getPointerTy())); } tmp[1] = curDAG.getTargetConstant(rhsc.get(), new EVT(MVT.i32)); return true; } } return false; } /** * The address mode 5 is designed for Load/Store coprocessor instruction. * @param n * @param tmp * @return */ protected boolean selectAddrMode5(SDValue n, SDValue[] tmp) { // tmp = {base, offset} if (!curDAG.isBaseWithConstantOffset(n)) { tmp[0] = n; if (n.getOpcode() == ISD.FrameIndex) { int fi = ((SDNode.FrameIndexSDNode)n.getNode()).getFrameIndex(); tmp[0] = curDAG.getTargetFrameIndex(fi, new EVT(tli.getPointerTy())); } else if (n.getOpcode() == ARMISD.Wrapper && !(subtarget.useMovt() && n.getOperand(0).getOpcode() == ISD.TargetGlobalAddress)) { tmp[0] = n.getOperand(0); } tmp[1] = curDAG.getTargetConstant(ARM_AM.getAM5Opc(ARM_AM.AddrOpc.add, 0), new EVT(MVT.i32)); return true; } // if the rhs is +/- imm8 (-255 to 256), fold it into the addr mode. OutRef<Integer> rhsc = new OutRef<>(0); if (isScaledConstantInRange(n.getOperand(1), /*scale*/4, -255, 256, rhsc)) { tmp[0] = n.getOperand(0); if (tmp[0].getOpcode() == ISD.FrameIndex) { int fi = ((SDNode.FrameIndexSDNode)tmp[0].getNode()).getFrameIndex(); tmp[0] = curDAG.getTargetFrameIndex(fi, new EVT(tli.getPointerTy())); } ARM_AM.AddrOpc addsub = ARM_AM.AddrOpc.add; if (rhsc.get() < 0) { rhsc.set(-rhsc.get()); addsub = ARM_AM.AddrOpc.sub; } tmp[1] = curDAG.getTargetConstant(ARM_AM.getAM5Opc(addsub, rhsc.get()), new EVT(MVT.i32)); return true; } tmp[0] = n; tmp[1] = curDAG.getTargetConstant(ARM_AM.getAM5Opc(ARM_AM.AddrOpc.add, 0), new EVT(MVT.i32)); return true; } protected boolean selectThumbAddrModeRR(SDValue n, SDValue[] tmp) { // tmp = {base, offset} if (n.getOpcode() != ISD.ADD && !curDAG.isBaseWithConstantOffset(n)) { if (!(n.getNode() instanceof SDNode.ConstantSDNode) || ((SDNode.ConstantSDNode)n.getNode()).isNullValue()) return false; tmp[0] = tmp[1] = n; return true; } tmp[0] = n.getOperand(0); tmp[1] = n.getOperand(1); return true; } private SDNode selectVTBL(SDNode n, boolean isExt, int numVecs, int opc) { Util.assertion(numVecs >= 2 && numVecs <= 4, "VTBL numVecs out of range"); EVT vt = n.getValueType(0); int firstTblReg = isExt ? 2 : 1; DebugLoc dl = n.getDebugLoc(); // form a REG_SEQUENCE to force register allocation. SDValue regSeq; SDValue v0 = n.getOperand(firstTblReg + 0); SDValue v1 = n.getOperand(firstTblReg + 1); if (numVecs == 2) regSeq = new SDValue(pairDRegs(new EVT(MVT.v16i8), v0, v1, dl), 0); else { SDValue v2 = n.getOperand(firstTblReg + 2); SDValue v3 = numVecs == 3 ? new SDValue(curDAG.getMachineNode(TargetOpcode.IMPLICIT_DEF, dl, vt), 0) : n.getOperand(firstTblReg + 3); regSeq = new SDValue(quadDRegs(new EVT(MVT.v4i64), v0, v1, v2, v3, dl), 0); } ArrayList<SDValue> ops = new ArrayList<>(); if (isExt) ops.add(n.getOperand(1)); ops.add(regSeq); ops.add(n.getOperand(firstTblReg + numVecs)); ops.add(getAL(curDAG)); ops.add(curDAG.getRegister(0, new EVT(MVT.i32))); SDValue[] tmp = new SDValue[ops.size()]; ops.toArray(tmp); return curDAG.getMachineNode(opc, dl, vt, tmp); } private SDValue getVLDSTAlign(SDValue align, int numVecs, boolean is64BitVector) { int numRegs = numVecs; if (!is64BitVector && numRegs < 3) numRegs *= 2; long alignment = ((SDNode.ConstantSDNode)align.getNode()).getZExtValue(); if (alignment >= 32 && numRegs == 4) alignment = 32; else if (alignment >= 16 && (numRegs == 2 || numRegs == 4)) alignment = 16; else if (alignment >= 8) alignment = 8; else alignment = 0; return curDAG.getTargetConstant(alignment, new EVT(MVT.i32)); } private SDNode selectVST(SDNode n, boolean isUpdating, int numVecs, int[] dOpcodes, int[] qOpcodes0, int[] qOpcodes1) { Util.assertion(numVecs >= 1 && numVecs <= 4, "VST numVecs out of range!"); DebugLoc dl = n.getDebugLoc(); int addrOpIdx = isUpdating ? 1: 2; int vec0Idx = 3; // addrOpIdx + (isUpdating ? 2 : 1) SDValue[] tmp = new SDValue[2]; if (!selectAddrMode6(n, n.getOperand(addrOpIdx), tmp)) return null; SDValue memAddr = tmp[0], align = tmp[1]; MachineMemOperand mmo = ((SDNode.MemIntrinsicSDNode)n).getMemOperand(); SDValue chain = n.getOperand(0); EVT vt = n.getOperand(vec0Idx).getValueType(); boolean is64BitVector = vt.is64BitVector(); align = getVLDSTAlign(align, numVecs, is64BitVector); int opcodeIndex = 0; switch (vt.getSimpleVT().simpleVT) { // 64 bit registers case MVT.v8i8: opcodeIndex = 0; break; case MVT.v4i16: opcodeIndex = 1; break; case MVT.v2f32: case MVT.v2i32: opcodeIndex = 2; break; case MVT.v1i64: opcodeIndex = 3; break; // 128 bit registers. case MVT.v16i8: opcodeIndex = 0; break; case MVT.v8i16: opcodeIndex = 1; break; case MVT.v4f32: case MVT.v4i32: opcodeIndex = 2; break; case MVT.v2i64: opcodeIndex = 3; Util.assertion(numVecs == 1, "v2i64 only supported for VST1"); break; default: Util.shouldNotReachHere("unhandled vst type!"); } ArrayList<EVT> resTys = new ArrayList<>(); // updating means we have to update the base register after the VLD or VST. if (isUpdating) resTys.add(new EVT(MVT.i32)); resTys.add(new EVT(MVT.Other)); SDValue pred = getAL(curDAG); SDValue reg0 = curDAG.getRegister(0, new EVT(MVT.i32)); ArrayList<SDValue> ops = new ArrayList<>(); // Double registers and VST1/VST2 quad registers are directly supported. if (is64BitVector || numVecs <= 2) { SDValue srcReg; if (numVecs == 1) { srcReg = n.getOperand(vec0Idx); } else if (is64BitVector) { SDValue v0 = n.getOperand(vec0Idx + 0); SDValue v1 = n.getOperand(vec0Idx + 1); if (numVecs == 2) srcReg = new SDValue(pairDRegs(new EVT(MVT.v2i64), v0, v1, dl), 0); else { SDValue v2 = n.getOperand(vec0Idx + 2); SDValue v3 = numVecs == 3 ? new SDValue(curDAG.getMachineNode(TargetOpcode.IMPLICIT_DEF, dl, vt), 0) : n.getOperand(vec0Idx + 3); srcReg = new SDValue(quadDRegs(new EVT(MVT.v4i64), v0, v1, v2, v3, dl), 0); } } else { SDValue q0 = n.getOperand(vec0Idx); SDValue q1 = n.getOperand(vec0Idx + 1); srcReg = new SDValue(pairQRegs(new EVT(MVT.v4i64), q0, q1, dl), 0); } int opc = is64BitVector ? dOpcodes[opcodeIndex] : qOpcodes0[opcodeIndex]; ops.add(memAddr); ops.add(align); if (isUpdating) { SDValue inc = n.getOperand(addrOpIdx + 1); ops.add(inc.getNode() instanceof SDNode.ConstantSDNode ? reg0 : inc); } ops.add(srcReg); ops.add(pred); ops.add(reg0); ops.add(chain); SDValue[] res = new SDValue[ops.size()]; ops.toArray(res); EVT[] vts = new EVT[resTys.size()]; resTys.toArray(vts); SDNode.MachineSDNode vst = curDAG.getMachineNode(opc, dl, curDAG.makeVTList(vts), res); // transfer memory operand. vst.setMemRefs(new MachineMemOperand[] {mmo}); return vst; } // Otherwise, quad registers are stored with two separate instructions, // where one stores the even registers and the other stores the odd registers. // Form the QQQQ REG_SEQUENCE. SDValue v0 = n.getOperand(vec0Idx + 0); SDValue v1 = n.getOperand(vec0Idx + 1); SDValue v2 = n.getOperand(vec0Idx + 2); SDValue v3 = numVecs == 3 ? new SDValue(curDAG.getMachineNode(TargetOpcode.IMPLICIT_DEF, dl, vt), 0) : n.getOperand(vec0Idx + 3); SDValue regSeq = new SDValue(quadQRegs(new EVT(MVT.v8i64), v0, v1, v2, v3, dl), 0); // Store the even D registers. This is always an updating store, so that it // provides the address to the second store for the odd subregs. SDValue[] opsA = new SDValue[] {memAddr, align, reg0, regSeq, pred, reg0, chain}; SDNode.MachineSDNode vsta = (SDNode.MachineSDNode) curDAG.getMachineNode(qOpcodes0[opcodeIndex], dl, memAddr.getValueType(), new EVT(MVT.Other), opsA); vsta.setMemRefs(new MachineMemOperand[] {mmo}); chain = new SDValue(vsta, 1); ops.add(new SDValue(vsta, 0)); ops.add(align); if (isUpdating) { SDValue inc = n.getOperand(addrOpIdx + 1); Util.assertion(inc.getNode() instanceof SDNode.ConstantSDNode, "only constant post-increment update allowed for VST3/4"); ops.add(reg0); } ops.add(regSeq); ops.add(pred); ops.add(reg0); ops.add(chain); SDValue[] res = new SDValue[ops.size()]; ops.toArray(res); EVT[] vts = new EVT[resTys.size()]; resTys.toArray(vts); SDNode.MachineSDNode vstb = curDAG.getMachineNode(qOpcodes1[opcodeIndex], dl, curDAG.makeVTList(vts), res); vstb.setMemRefs(new MachineMemOperand[]{mmo}); return vstb; } private SDNode selectVLD(SDNode n, boolean isUpdating, int numVecs, int[] dOpcodes, int[] qOpcodes0, int[] qOpcodes1) { Util.assertion(numVecs >= 1 && numVecs <= 4, "VST numVecs out of range!"); DebugLoc dl = n.getDebugLoc(); int addrOpIdx = isUpdating ? 1 : 2; SDValue[] tmp = new SDValue[2]; if (!selectAddrMode6(n, n.getOperand(addrOpIdx), tmp)) return null; SDValue memAddr = tmp[0], align = tmp[1]; SDValue chain = n.getOperand(0); EVT vt = n.getValueType(0); boolean is64BitVector = vt.is64BitVector(); align = getVLDSTAlign(align, numVecs, is64BitVector); int opcodeIndex = 0; switch (vt.getSimpleVT().simpleVT) { // 64 bit registers case MVT.v8i8: opcodeIndex = 0; break; case MVT.v4i16: opcodeIndex = 1; break; case MVT.v2f32: case MVT.v2i32: opcodeIndex = 2; break; case MVT.v1i64: opcodeIndex = 3; break; // 128 bit registers. case MVT.v16i8: opcodeIndex = 0; break; case MVT.v8i16: opcodeIndex = 1; break; case MVT.v4f32: case MVT.v4i32: opcodeIndex = 2; break; case MVT.v2i64: opcodeIndex = 3; Util.assertion(numVecs == 1, "v2i64 only supported for VST1"); break; default: Util.shouldNotReachHere("unhandled vst type!"); } EVT resTy; if (numVecs == 1) resTy = vt; else { int numResTyElts = numVecs == 3 ? 4 : numVecs; if (!is64BitVector) numResTyElts *= 2; resTy = EVT.getVectorVT(curDAG.getContext(), new EVT(MVT.i64), numResTyElts); } ArrayList<EVT> resTys = new ArrayList<>(); // updating means we have to update the base register after the VLD or VST. if (isUpdating) resTys.add(new EVT(MVT.i32)); resTys.add(new EVT(MVT.Other)); SDValue pred = getAL(curDAG); SDValue reg0 = curDAG.getRegister(0, new EVT(MVT.i32)); SDNode.MachineSDNode vld = null; ArrayList<SDValue> ops = new ArrayList<>(); // Double registers and VST1/VST2 quad registers are directly supported. if (is64BitVector || numVecs <= 2) { int opc = isUpdating ? dOpcodes[opcodeIndex] : qOpcodes0[opcodeIndex]; ops.add(memAddr); ops.add(align); if (isUpdating) { SDValue inc = n.getOperand(addrOpIdx + 1); ops.add(inc.getNode() instanceof SDNode.ConstantSDNode ? reg0 : inc); } ops.add(pred); ops.add(reg0); ops.add(chain); SDValue[] res = new SDValue[ops.size()]; ops.toArray(res); EVT[] vts = new EVT[resTys.size()]; resTys.toArray(vts); vld = curDAG.getMachineNode(opc, dl, curDAG.makeVTList(vts), res); } else { // Otherwise, quad registers are stored with two separate instructions, // where one stores the even registers and the other stores the odd registers. EVT addrTy = memAddr.getValueType(); // load the even subregs SDValue implDef = new SDValue(curDAG.getMachineNode(TargetOpcode.IMPLICIT_DEF, dl, resTy), 0); SDValue[] opsA = new SDValue[]{memAddr, align, reg0, implDef, pred, reg0, chain}; SDNode.MachineSDNode vlda = (SDNode.MachineSDNode) curDAG.getMachineNode(qOpcodes0[opcodeIndex], dl, resTy, addrTy, new EVT(MVT.Other), opsA); chain = new SDValue(vlda, 2); // load the odd subregs. ops.add(new SDValue(vlda, 0)); ops.add(align); if (isUpdating) { SDValue inc = n.getOperand(addrOpIdx + 1); Util.assertion(inc.getNode() instanceof SDNode.ConstantSDNode, "only constant post-increment update allowed for VST3/4"); ops.add(reg0); } ops.add(new SDValue(vlda, 0)); ops.add(pred); ops.add(reg0); ops.add(chain); SDValue[] res = new SDValue[ops.size()]; ops.toArray(res); EVT[] vts = new EVT[resTys.size()]; resTys.toArray(vts); vld = curDAG.getMachineNode(qOpcodes1[opcodeIndex], dl, curDAG.makeVTList(vts), res); } // transfer memory operands. MachineMemOperand[] mmos = {((SDNode.MemIntrinsicSDNode)n).getMemOperand()}; vld.setMemRefs(mmos); if (numVecs == 1) return vld; // extract out the subregisters. SDValue superReg = new SDValue(vld, 0); int sub0 = is64BitVector ? ARMGenRegisterInfo.dsub_0 : ARMGenRegisterInfo.qsub_0; for (int vec = 0; vec < numVecs; ++vec) replaceUses(new SDValue(n, vec), curDAG.getTargetExtractSubreg(sub0 + vec, dl, vt, superReg)); replaceUses(new SDValue(n, numVecs), new SDValue(vld, 1)); if (isUpdating) replaceUses(new SDValue(n, numVecs + 1), new SDValue(vld, 2)); return null; } private SDNode selectVLDSTLane(SDNode n, boolean isLoad, boolean isUpdating, int numVecs, int[] dOpcodes, int[] qOpcodes) { Util.assertion(numVecs >= 2 && numVecs <= 4, "VST numVecs out of range!"); DebugLoc dl = n.getDebugLoc(); int addrOpIdx = isUpdating ? 1: 2; int vec0Idx = 3; // addrOpIdx + (isUpdating ? 2 : 1) SDValue[] tmp = new SDValue[2]; if (!selectAddrMode6(n, n.getOperand(addrOpIdx), tmp)) return null; SDValue memAddr = tmp[0], align = tmp[1]; MachineMemOperand mmo = ((SDNode.MemIntrinsicSDNode)n).getMemOperand(); SDValue chain = n.getOperand(0); long lane = ((SDNode.ConstantSDNode)n.getOperand(vec0Idx + numVecs).getNode()).getZExtValue(); EVT vt = n.getOperand(vec0Idx).getValueType(); boolean is64BitVector = vt.is64BitVector(); long alignment = 0; if (numVecs != 3) { alignment = ((SDNode.ConstantSDNode)align.getNode()).getZExtValue(); int numBytes = numVecs * vt.getVectorElementType().getSizeInBits()/8; if (alignment > numBytes) alignment = numBytes; if (alignment < 8 && alignment < numBytes) alignment = 0; alignment = (alignment & ~alignment); if (alignment == 1) alignment = 0; } align = curDAG.getTargetConstant(alignment, new EVT(MVT.i32)); int opcodeIndex = 0; switch (vt.getSimpleVT().simpleVT) { // 64 bit registers case MVT.v8i8: opcodeIndex = 0; break; case MVT.v4i16: opcodeIndex = 1; break; case MVT.v2f32: case MVT.v2i32: opcodeIndex = 2; break; case MVT.v8i16: opcodeIndex = 0; break; case MVT.v4f32: case MVT.v4i32: opcodeIndex = 1; break; default: Util.shouldNotReachHere("unhandled vst type!"); } ArrayList<EVT> resTys = new ArrayList<>(); if (isLoad) { int resTyElts = numVecs == 3 ? 4 : numVecs; if (!is64BitVector) resTyElts *= 2; resTys.add(EVT.getVectorVT(curDAG.getContext(), new EVT(MVT.i64), resTyElts)); } // updating means we have to update the base register after the VLD or VST. if (isUpdating) resTys.add(new EVT(MVT.i32)); resTys.add(new EVT(MVT.Other)); SDValue pred = getAL(curDAG); SDValue reg0 = curDAG.getRegister(0, new EVT(MVT.i32)); ArrayList<SDValue> ops = new ArrayList<>(); ops.add(memAddr); ops.add(align); if (isUpdating) { SDValue inc = n.getOperand(addrOpIdx + 1); ops.add(inc.getNode() instanceof SDNode.ConstantSDNode ? reg0 : inc); } SDValue superReg; SDValue v0 = n.getOperand(vec0Idx + 0); SDValue v1 = n.getOperand(vec0Idx + 1); if (numVecs == 2) { if (is64BitVector) superReg = new SDValue(pairDRegs(new EVT(MVT.v2i64), v0, v1, dl), 0); else superReg = new SDValue(pairQRegs(new EVT(MVT.v4i64), v0, v1, dl), 0); } else { SDValue v2 = n.getOperand(vec0Idx + 2); SDValue v3 = numVecs == 3 ? new SDValue(curDAG.getMachineNode(TargetOpcode.IMPLICIT_DEF, dl, vt), 0) : n.getOperand(vec0Idx + 3); if (is64BitVector) superReg = new SDValue(quadDRegs(new EVT(MVT.v4i64), v0, v1, v2, v3, dl), 0); else superReg = new SDValue(quadQRegs(new EVT(MVT.v8i64), v0, v1, v2, v3, dl), 0); } ops.add(superReg); ops.add(getI32Imm(lane)); ops.add(pred); ops.add(reg0); ops.add(chain); int opc = is64BitVector ? dOpcodes[opcodeIndex] : qOpcodes[opcodeIndex]; SDValue[] res = new SDValue[ops.size()]; ops.toArray(res); EVT[] vts = new EVT[resTys.size()]; resTys.toArray(vts); SDNode.MachineSDNode vldLn = curDAG.getMachineNode(opc, dl, curDAG.makeVTList(vts), res); // transfer memory operand. vldLn.setMemRefs(new MachineMemOperand[] {mmo}); if (isLoad) return vldLn; // extract subregisters. superReg = new SDValue(vldLn, 0); int sub0 = is64BitVector ? ARMGenRegisterInfo.dsub_0 : ARMGenRegisterInfo.qsub_0; for (int vec = 0; vec < numVecs; ++vec) replaceUses(new SDValue(n, vec), curDAG.getTargetExtractSubreg(sub0 + vec, dl, vt, superReg)); replaceUses(new SDValue(n, numVecs), new SDValue(vldLn, 1)); if (isUpdating) replaceUses(new SDValue(n, numVecs + 1), new SDValue(vldLn, 2)); return null; } private SDNode selectVLDDup(SDNode n, boolean isUpdating, int numVecs, int[] opcodes) { Util.assertion(numVecs >=2 && numVecs <= 4, "VLDDup NumVecs out-of-range"); DebugLoc dl = n.getDebugLoc(); SDValue[] tmp = new SDValue[2]; if (!selectAddrMode6(n, n.getOperand(1), tmp)) return null; SDValue memAddr = tmp[0], align = tmp[1]; MachineMemOperand[] mmo = {((SDNode.MemIntrinsicSDNode)n).getMemOperand()}; SDValue chain = n.getOperand(0); EVT vt = n.getValueType(0); long alignment = 0; if (numVecs != 3) { alignment = ((SDNode.ConstantSDNode)align.getNode()).getZExtValue(); int numBytes = numVecs * vt.getVectorElementType().getSizeInBits()/8; if (alignment > numBytes) alignment = numBytes; if (alignment < 8 && alignment < numBytes) alignment = 0; // Alignment must be a power of two; make sure of that. alignment = (alignment & -alignment); if (alignment == 1) alignment = 0; } align = curDAG.getTargetConstant(alignment, new EVT(MVT.i32)); int opcodeIndex; switch (vt.getSimpleVT().simpleVT) { default: Util.shouldNotReachHere("unhandled vld-dup type"); case MVT.v8i8: opcodeIndex = 0; break; case MVT.v4i16: opcodeIndex = 1; break; case MVT.v2f32: case MVT.v2i32: opcodeIndex = 2; break; } SDValue pred = getAL(curDAG); SDValue reg0 = curDAG.getRegister(0, MVT.i32); SDValue superReg; int opc = opcodes[opcodeIndex]; ArrayList<SDValue> ops = new ArrayList<>(); ops.add(memAddr); ops.add(align); if (isUpdating) { SDValue inc = n.getOperand(2); ops.add(inc.getNode() instanceof SDNode.ConstantSDNode ? reg0 : inc); } ops.add(pred); ops.add(reg0); ops.add(chain); int resTyElts = (numVecs == 3) ? 4 : numVecs; ArrayList<EVT> resTys = new ArrayList<>(); resTys.add(EVT.getVectorVT(curDAG.getContext(), new EVT(MVT.i64), resTyElts)); if (isUpdating) resTys.add(new EVT(MVT.i32)); resTys.add(new EVT(MVT.Other)); SDValue[] res = new SDValue[ops.size()]; ops.toArray(res); SDNode.MachineSDNode vldDup = curDAG.getMachineNode(opc, dl, curDAG.getVTList(resTys), res); vldDup.setMemRefs(mmo); superReg = new SDValue(vldDup, 0); // Extract the subregisters. int subIdx = ARMGenRegisterInfo.dsub_0; for (int vec = 0; vec < numVecs; ++vec) replaceUses(new SDValue(n, vec), curDAG.getTargetExtractSubreg(subIdx+vec, dl, vt, superReg)); replaceUses(new SDValue(n, numVecs), new SDValue(vldDup, 1)); if (isUpdating) replaceUses(new SDValue(n, numVecs + 1), new SDValue(vldDup, 2)); return null; } static FunctionPass createARMISelDAG(ARMTargetMachine tm, TargetMachine.CodeGenOpt level) { return new ARMGenDAGISel(tm, level); } }
smackem/jobotwar
jobotwar-web/src/main/java/net/smackem/jobotwar/web/persist/BeanRepository.java
<filename>jobotwar-web/src/main/java/net/smackem/jobotwar/web/persist/BeanRepository.java package net.smackem.jobotwar.web.persist; import net.smackem.jobotwar.web.beans.EntityBean; import net.smackem.jobotwar.web.query.Query; import org.jetbrains.annotations.NotNull; import java.text.ParseException; import java.util.Collection; import java.util.List; import java.util.stream.Stream; public interface BeanRepository<T extends EntityBean> { /** * Selects the beans matching the specified query from the repository. * * @param query The query that is used to describe the result set. * @return A {@link Stream} of beans. * @throws ParseException If there was problem translating the {@code query} to the representation * required by the repository implementation. */ @NotNull Collection<T> select(@NotNull Query query) throws ParseException; /** * Gets the beans with the specified ids from the repo. * * @param ids The ids to look up. * @return A list containing the beans with the specified ids. Only the beans found in the repository * are returned, so an empty list means that none was found. */ @NotNull List<T> get(@NotNull String... ids); /** * Puts the specified bean into the repository. * * @param bean The bean to accept. * @throws ConstraintViolationException if the new bean violates a constraint of the repository implementation. */ void put(@NotNull T bean) throws ConstraintViolationException; /** * Updates the bean with the given id. * * @param bean The bean to update. * @throws NoSuchBeanException if no bean with id of the specified bean was found. */ void update(@NotNull T bean) throws NoSuchBeanException; /** * Deletes the bean with the given id from the repository. * * @param id The id of the bean to delete. * @return {@code true} if the bean with the given id was deleted. */ boolean delete(@NotNull String id); /** * @return The total number of beans in the repository. */ long count(); }
Yurzs/boto
tests/unit/s3/test_cors_configuration.py
<filename>tests/unit/s3/test_cors_configuration.py<gh_stars>1000+ #!/usr/bin/env python import unittest from boto.s3.cors import CORSConfiguration CORS_BODY_1 = ( '<CORSConfiguration>' '<CORSRule>' '<AllowedMethod>PUT</AllowedMethod>' '<AllowedMethod>POST</AllowedMethod>' '<AllowedMethod>DELETE</AllowedMethod>' '<AllowedOrigin>http://www.example.com</AllowedOrigin>' '<AllowedHeader>*</AllowedHeader>' '<ExposeHeader>x-amz-server-side-encryption</ExposeHeader>' '<MaxAgeSeconds>3000</MaxAgeSeconds>' '<ID>foobar_rule</ID>' '</CORSRule>' '</CORSConfiguration>') CORS_BODY_2 = ( '<CORSConfiguration>' '<CORSRule>' '<AllowedMethod>PUT</AllowedMethod>' '<AllowedMethod>POST</AllowedMethod>' '<AllowedMethod>DELETE</AllowedMethod>' '<AllowedOrigin>http://www.example.com</AllowedOrigin>' '<AllowedHeader>*</AllowedHeader>' '<ExposeHeader>x-amz-server-side-encryption</ExposeHeader>' '<MaxAgeSeconds>3000</MaxAgeSeconds>' '</CORSRule>' '<CORSRule>' '<AllowedMethod>GET</AllowedMethod>' '<AllowedOrigin>*</AllowedOrigin>' '<AllowedHeader>*</AllowedHeader>' '<MaxAgeSeconds>3000</MaxAgeSeconds>' '</CORSRule>' '</CORSConfiguration>') CORS_BODY_3 = ( '<CORSConfiguration>' '<CORSRule>' '<AllowedMethod>GET</AllowedMethod>' '<AllowedOrigin>*</AllowedOrigin>' '</CORSRule>' '</CORSConfiguration>') class TestCORSConfiguration(unittest.TestCase): def test_one_rule_with_id(self): cfg = CORSConfiguration() cfg.add_rule(['PUT', 'POST', 'DELETE'], 'http://www.example.com', allowed_header='*', max_age_seconds=3000, expose_header='x-amz-server-side-encryption', id='foobar_rule') self.assertEqual(cfg.to_xml(), CORS_BODY_1) def test_two_rules(self): cfg = CORSConfiguration() cfg.add_rule(['PUT', 'POST', 'DELETE'], 'http://www.example.com', allowed_header='*', max_age_seconds=3000, expose_header='x-amz-server-side-encryption') cfg.add_rule('GET', '*', allowed_header='*', max_age_seconds=3000) self.assertEqual(cfg.to_xml(), CORS_BODY_2) def test_minimal(self): cfg = CORSConfiguration() cfg.add_rule('GET', '*') self.assertEqual(cfg.to_xml(), CORS_BODY_3) if __name__ == "__main__": unittest.main()
elzasw/elza
elza/elza-core/src/main/java/cz/tacr/elza/repository/FundFileRepository.java
<gh_stars>0 package cz.tacr.elza.repository; import cz.tacr.elza.domain.ArrFile; import cz.tacr.elza.domain.ArrFund; import org.springframework.stereotype.Repository; import java.util.List; /** * ArrFile repository * * @author <NAME> <<EMAIL>> * @since 20.6.2016 */ @Repository public interface FundFileRepository extends ElzaJpaRepository<ArrFile,Integer>, FundFileRepositoryCustom { List<ArrFile> findByFund(ArrFund fund); }
danielogen/msc_research
selected projects/desktop/ganttproject-v2.8.11/ganttproject/src/net/sourceforge/ganttproject/chart/mouse/ChangeTaskProgressRuler.java
<filename>selected projects/desktop/ganttproject-v2.8.11/ganttproject/src/net/sourceforge/ganttproject/chart/mouse/ChangeTaskProgressRuler.java /* GanttProject is an opensource project management tool. License: GPL3 Copyright (C) 2011 GanttProject Team 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, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package net.sourceforge.ganttproject.chart.mouse; import java.util.List; import java.util.SortedMap; import java.util.TreeMap; import biz.ganttproject.core.chart.canvas.Canvas.Rectangle; import net.sourceforge.ganttproject.chart.TaskChartModelFacade; import net.sourceforge.ganttproject.task.Task; import net.sourceforge.ganttproject.task.TaskActivity; /** * Helper class for converting screen pixels into task completion percentage * value when changing the latter with a mouse. It operates with pixel offsets * from the chart viewport origin. * * @author <NAME> */ class ChangeTaskProgressRuler { private final Task myTask; private final TaskChartModelFacade myTaskChartFacade; private final SortedMap<Integer, Integer> myPixel2progress = new TreeMap<Integer, Integer>(); private int myMinPx; /** * Creates and initializes the ruler */ ChangeTaskProgressRuler(Task task, TaskChartModelFacade taskChartFacade) { myTask = task; myTaskChartFacade = taskChartFacade; float totalDuration = task.getDuration().getValue(); int visiblePixels = -1; float accumulatedDuration = 0f; List<Rectangle> taskRectangles = myTaskChartFacade.getTaskRectangles(myTask); myMinPx = taskRectangles.get(0).getLeftX(); myPixel2progress.put(myMinPx, 0); for (Rectangle r : taskRectangles) { TaskActivity activity = (TaskActivity) r.getModelObject(); if (r.isVisible()) { visiblePixels = r.getRightX(); } if (activity.getIntensity() > 0f) { accumulatedDuration += activity.getDuration().getValue(); } myPixel2progress.put(visiblePixels, (int) (accumulatedDuration * 100 / totalDuration)); } } /** * @return progress value corresponding to the given {@code pixels} value. */ int getProgress(int pixels) { if (pixels < myMinPx) { return 0; } SortedMap<Integer, Integer> tailMap = myPixel2progress.tailMap(pixels); if (tailMap.isEmpty()) { return 100; } if (tailMap.firstKey().intValue() == pixels) { return tailMap.get(pixels); } SortedMap<Integer, Integer> headMap = myPixel2progress.headMap(pixels); int lowerPx = headMap.isEmpty() ? 0 : headMap.lastKey(); int lowerProgress = headMap.isEmpty() ? 0 : headMap.get(lowerPx); int upperPx = tailMap.firstKey(); int upperProgress = tailMap.get(upperPx); float diffProgress = (upperProgress - lowerProgress) * ((float) (pixels - lowerPx) / (float) (upperPx - lowerPx)); return (int) (lowerProgress + diffProgress); } }
isabella232/devhub
src/utils/setup/fetch-build-time-media.js
<filename>src/utils/setup/fetch-build-time-media.js<gh_stars>0 import { initStitch } from './init-stitch'; import { STITCH_AUTH_APP_ID } from '../../constants'; import { parsePodcasts } from '../parse-podcasts'; import { simplifyTwitchResponse } from '../simplify-twitch-response'; import { simplifyYoutubeResponse } from '../simplify-youtube-response'; const MAX_RESULTS = 5; export const fetchBuildTimeMedia = async () => { const client = await initStitch(STITCH_AUTH_APP_ID); const [youtubeVideos, twitchVideos, lybsinPodcasts] = await Promise.all([ client.callFunction('fetchYoutubeData', [MAX_RESULTS]), client.callFunction('fetchMDBTwitchVideos', [MAX_RESULTS]), client.callFunction('fetchLybsinPodcasts', []), ]); return { allVideos: [ youtubeVideos.items.map(simplifyYoutubeResponse), twitchVideos.data.map(simplifyTwitchResponse), ].flat(), allPodcasts: parsePodcasts(lybsinPodcasts), }; };
williampansky/react-ccg
packages/server/src/on-plays/init-set002-on-play.js
<reponame>williampansky/react-ccg /* eslint-disable no-case-declarations */ import { add } from 'mathjs'; import actionPoints from '../state/action-points'; import drawCard from '../moves/draw-card'; import getCardByID from '../utils/get-card-by-id'; import createBoardSlotObject from '../creators/create-board-slot-object'; import playerHealth from '../state/player-health'; import boards from '../state/boards'; import createOnPlayObject from '../creators/create-onplay-object'; const initSet002OnPlay = (G, ctx, slotObject, cardId, index) => { const { turnOrder } = G; const { currentPlayer, random } = ctx; const otherPlayer = turnOrder.find(p => p !== currentPlayer); const { minionData: { entourage, numberPrimary, numberSecondary } } = slotObject; /** * Bool to determine if an ON_PLAY slot needs to be generated or not */ let createSpellObj = false; switch (cardId) { case 'CORE_001': // Deal 1 dmg case 'CORE_016': // Deal 1 damage if (G.boards[otherPlayer].length === 1) return; G.boards[otherPlayer].forEach((slot, i) => { if (!slot.isHidden) slot.canBeAttackedByOnPlay = true; if (!slot.isHidden) slot.showTooltip = true; createSpellObj = true; }); break; case 'CORE_006': if (G.boards[currentPlayer].length === 1) return; G.boards[currentPlayer].forEach((slot, i) => { if (index !== i) { slot.canBeHealed = true; createSpellObj = true; } }); break; case 'CORE_019': case 'CORE_041': // enhance all minions except itself G.boards[currentPlayer].forEach((_, i) => { if (index !== i) { // ............................ attack ....... health buffTarget(G, currentPlayer, i, numberPrimary, numberSecondary); } }); break; case 'CORE_021': // buff with +1/+1 case 'CORE_054': // buff with +1 hp if (G.boards[currentPlayer].length === 1) return; G.boards[currentPlayer].forEach((slot, i) => { if (index !== i) { slot.canBeBuffed = true; createSpellObj = true; } }); break; // eject default: break; } if (createSpellObj === true) G.spellObject[currentPlayer] = createOnPlayObject(cardId); }; // transformation method function buffTarget(G, player, index, n1 = 0, n2 = 0) { const AP = parseInt(G.boards[player][index].currentAttack); const HP = parseInt(G.boards[player][index].currentHealth); const newAP = Math.abs(AP + n1); const newHP = Math.abs(HP + n2); G.boards[player][index] = { ...G.boards[player][index], currentAttack: newAP, currentHealth: newHP, totalAttack: newAP, totalHealth: newHP }; } export default initSet002OnPlay;
dong706/CorbaDemo
src/main/java/org/omg/hw/emsMgr/QueryRedefineAlarmData_THelper.java
<filename>src/main/java/org/omg/hw/emsMgr/QueryRedefineAlarmData_THelper.java package org.omg.hw.emsMgr; /** * Generated from IDL definition of struct "QueryRedefineAlarmData_T" * @author JacORB IDL compiler */ public final class QueryRedefineAlarmData_THelper { private static org.omg.CORBA.TypeCode _type = null; public static org.omg.CORBA.TypeCode type () { if (_type == null) { _type = org.omg.CORBA.ORB.init().create_struct_tc(org.omg.hw.emsMgr.QueryRedefineAlarmData_THelper.id(),"QueryRedefineAlarmData_T",new org.omg.CORBA.StructMember[]{new org.omg.CORBA.StructMember("ruleID", org.omg.CORBA.ORB.init().get_primitive_tc(org.omg.CORBA.TCKind.from_int(3)), null),new org.omg.CORBA.StructMember("groupID", org.omg.CORBA.ORB.init().get_primitive_tc(org.omg.CORBA.TCKind.from_int(3)), null),new org.omg.CORBA.StructMember("alarmID", org.omg.CORBA.ORB.init().get_primitive_tc(org.omg.CORBA.TCKind.from_int(3)), null)}); } return _type; } public static void insert (final org.omg.CORBA.Any any, final org.omg.hw.emsMgr.QueryRedefineAlarmData_T s) { any.type(type()); write( any.create_output_stream(),s); } public static org.omg.hw.emsMgr.QueryRedefineAlarmData_T extract (final org.omg.CORBA.Any any) { return read(any.create_input_stream()); } public static String id() { return "IDL:mtnm.tmforum.org/emsMgr/QueryRedefineAlarmData_T:1.0"; } public static org.omg.hw.emsMgr.QueryRedefineAlarmData_T read (final org.omg.CORBA.portable.InputStream in) { org.omg.hw.emsMgr.QueryRedefineAlarmData_T result = new org.omg.hw.emsMgr.QueryRedefineAlarmData_T(); result.ruleID=in.read_long(); result.groupID=in.read_long(); result.alarmID=in.read_long(); return result; } public static void write (final org.omg.CORBA.portable.OutputStream out, final org.omg.hw.emsMgr.QueryRedefineAlarmData_T s) { out.write_long(s.ruleID); out.write_long(s.groupID); out.write_long(s.alarmID); } }
thejihuijin/realsense_sdk
tests/projection_tests.cpp
<filename>tests/projection_tests.cpp // License: Apache 2.0. See LICENSE file in root directory. // Copyright(c) 2016 Intel Corporation. All Rights Reserved. #include "projection_fixture.h" #include <stdio.h> #include <stdlib.h> #include <locale> #include <algorithm> #include "rs/utils/librealsense_conversion_utils.h" #include "rs/utils/smart_ptr_helpers.h" #ifdef WIN32 #define NOMINMAX #else #include <dirent.h> #endif using namespace rs::core; using namespace rs::utils; static point3dF32 world3dSrc[CUBE_VERTICES]; static const point3dF32 cube100mm[CUBE_VERTICES] = { { 0.f, 0.f, 0.f}, {100.f, 0.f, 0.f}, { 0.f, 100.f, 0.f}, {100.f, 100.f, 0.f}, { 0.f, 0.f, 100.f}, {100.f, 0.f, 100.f}, { 0.f, 100.f, 100.f}, {100.f, 100.f, 100.f}, }; __inline point3dF32 *cube100mmWorldTr(float trX, float trY, float trZ) { for( int n=0; n<CUBE_VERTICES; n++ ) { world3dSrc[n].x = cube100mm[n].x + trX; world3dSrc[n].y = cube100mm[n].y + trY; world3dSrc[n].z = cube100mm[n].z + trZ; } return &world3dSrc[0]; } __inline float distance3d(point3dF32 v1, point3dF32 v2) { return sqrtf( (v1.x - v2.x)*(v1.x - v2.x) + (v1.y - v2.y)*(v1.y - v2.y) + (v1.z - v2.z)*(v1.z - v2.z) ); } __inline float distancePixels(pointF32 v1, pointF32 v2) { #if WIN32 return std::max(fabs(v1.x - v2.x), fabs(v1.y - v2.y)); #else return static_cast<float>(std::max(fabs(static_cast<double>(v1.x - v2.x)), fabs(static_cast<double>(v1.y - v2.y)))); #endif } static const wchar_t* rsformatToWString(rs::format format) { switch(format) { case rs::format::any: return L"UNKNOWN"; case rs::format::bgra8: return L"bgra8"; case rs::format::rgba8: return L"rgba8"; case rs::format::bgr8: return L"bgr8"; case rs::format::rgb8: return L"rgb8"; case projection_tests_util::depth_format: return L"z16"; case rs::format::disparity16: return L"disparity16"; case rs::format::y8: return L"y8"; case rs::format::y16: return L"y16"; case rs::format::yuyv: return L"yuyv"; default: return L"Incorrect Pixel Format"; }; } __inline sizeI32 imSize(int32_t w, int32_t h) {sizeI32 sz = {w, h}; return sz;} /* Test: camera_to_color_to_camera Target: Checks compatibility of ProjectCameraToColor and ProjectColorToCamera Scope: 1. All available '.rssdk' files from PROJECTION folder with different aspect ratios and serialized projection data 2. Normal and far m_distances from object to Camera Description: A Cube with a size 100mm in Camera (World) coordinates projects to Color image and after that projects back to Camera. An expectation is to have projected back Cube coordinates near the source Cube in the World. An error gets as distance in mm of source Camera (World) coordinates and projected back to Camera through a Color Image. Pass Criteria: Test passes if average error and maximal error less than threshold. */ TEST_F(projection_fixture, camera_to_color_to_camera) { m_avg_err = 2.f; m_max_err = 2.f; point3dF32 pos3dDst[CUBE_VERTICES], pos_ijSrc[CUBE_VERTICES]; pointF32 pos_ijDst[CUBE_VERTICES]; for(int32_t dd = 0; dd < (int32_t)m_distances.size(); dd++) { point3dF32 *pos3dSrc = cube100mmWorldTr( 0.f, 0.f, m_distances[dd] ); m_sts = m_projection->project_camera_to_color(CUBE_VERTICES, pos3dSrc, pos_ijDst); if( m_sts == status_param_unsupported ) continue; else ASSERT_EQ(m_sts, status_no_error); for(int32_t n=0; n<CUBE_VERTICES; n++ ) { pos_ijSrc[n].x = pos_ijDst[n].x, pos_ijSrc[n].y = pos_ijDst[n].y; pos_ijSrc[n].z = pos3dSrc[n].z; } m_sts = m_projection->project_color_to_camera(CUBE_VERTICES, pos_ijSrc, pos3dDst); if( m_sts == status_param_unsupported ) continue; else ASSERT_EQ(m_sts, status_no_error); /* Check distance between source Camera coordinates and projected back to Camera coordinates */ float avg = 0.f, max = 0.f; for(int32_t n = 0; n < CUBE_VERTICES; n++ ) { float v = distance3d( pos3dSrc[n], pos3dDst[n]); if( max < v ) max = v; avg += v; } avg /= CUBE_VERTICES; EXPECT_LE(avg, m_avg_err); EXPECT_LE(max, m_max_err); if(avg > m_avg_err || max > m_max_err) { std::basic_ostringstream<wchar_t> stream; stream << L"FAIL: " << rsformatToWString(m_formats.at(rs::stream::color)) << " " << m_color_intrin.width << "x" << m_color_intrin.height << "; " << "File: " << projection_tests_util::file_name.c_str() << " distance[mm]=" << m_distances[dd] << "; m_avg_error[mm]=" << avg << "; m_max_error[mm]=" << max; m_log_util.m_logger->logw(logging_service::level_error, stream.str().c_str(), __FILE__, __LINE__, "camera_to_color_to_camera"); m_is_failed = true; } } } /* Test: camera_to_depth_to_camera Target: Checks compatibility of ProjectCameraToDepth and ProjectDepthToCamera Scope: 1. All available '.rssdk' files from PROJECTION folder with different aspect ratios and serialized projection data 2. Normal and far m_distances from object to Camera Description: A Cube with a size 100mm in Camera (World) corrdinates projects to Depth image and after that projects back to Camera. An expectation is to have projected back Cube coordinates near the source Cube in the World. An error gets as distance in mm of source Camera (World) coordinates and projected back to Camera through a Depth Image. Pass Criteria: Test passes if average error and maximal error less than threshold. */ TEST_F(projection_fixture, camera_to_depth_to_camera) { m_avg_err = 2.f; m_max_err = 2.2f; point3dF32 pos3dDst[CUBE_VERTICES], pos_ijSrc[CUBE_VERTICES]; pointF32 pos_ijDst[CUBE_VERTICES]; for(int32_t dd = 0; dd < (int32_t)m_distances.size(); dd++) { point3dF32 *pos3dSrc = cube100mmWorldTr( 0.f, 0.f, m_distances[dd] ); m_sts = m_projection->project_camera_to_depth(CUBE_VERTICES, pos3dSrc, pos_ijDst); if( m_sts == status_param_unsupported ) continue; else ASSERT_EQ(m_sts, status_no_error); for(int32_t n=0; n<CUBE_VERTICES; n++ ) { pos_ijSrc[n].x = pos_ijDst[n].x, pos_ijSrc[n].y = pos_ijDst[n].y; pos_ijSrc[n].z = pos3dSrc[n].z; } m_sts = m_projection->project_depth_to_camera(CUBE_VERTICES, pos_ijSrc, pos3dDst); if( m_sts == status_param_unsupported ) continue; else ASSERT_EQ(m_sts, status_no_error); /* Check distance between source Camera coordinates and projected back to Camera coordinates */ float avg = 0.f, max = 0.f; for(int32_t n = 0; n < CUBE_VERTICES; n++ ) { float v = distance3d( pos3dSrc[n], pos3dDst[n]); if( max < v ) max = v; avg += v; } avg /= CUBE_VERTICES; EXPECT_LE(avg, m_avg_err); EXPECT_LE(max, m_max_err); if( avg > m_avg_err || max > m_max_err) { std::basic_ostringstream<wchar_t> stream; stream << L"FAIL: " << rsformatToWString(m_formats.at(rs::stream::depth)) << " " << m_depth_intrin.width << "x" << m_depth_intrin.height << "; " << "File: " << projection_tests_util::file_name.c_str() << " distance[mm]=" << m_distances[dd] << "; m_avg_error[mm]=" << avg << "; m_max_error[mm]=" << max; m_log_util.m_logger->logw(logging_service::level_error, stream.str().c_str(), __FILE__, __LINE__, "camera_to_depth_to_camera"); m_is_failed = true; } } } /* Test: color_to_camera_to_color Target: Checks compatibility of ProjectColorToCamera and ProjectCameraToColor Scope: All available '.rssdk' files from PROJECTION folder with different aspect ratios and serialized projection data Description: A set of points from a different places of Color image in pixel coordinates project to Camera and after that projects back to Color image. An expectation is to have projected back Color image pixel coordinates near the source Color pixel coordinates. An error gets as distance in pixels of source Color coordinates and projected back to Color through a Camera Coordinate System. Pass Criteria: Test passes if average error and maximal error less than threshold. */ TEST_F(projection_fixture, color_to_camera_to_color) { m_avg_err = 0.0002f; m_max_err = 0.0005f; for(int32_t dd = 0; dd < (int32_t)m_distances.size(); dd++) { point3dF32 pos_uvzSrc[9] = { {static_cast<float>(m_color_intrin.width)/2.f, static_cast<float>(m_color_intrin.height)/2.f, m_distances[dd]}, {5.f, 5.f, m_distances[dd]}, {(static_cast<float>(m_color_intrin.width)-5.f), 5.f, m_distances[dd]}, {5.f, (static_cast<float>(m_color_intrin.height)-5.f), m_distances[dd]}, {(static_cast<float>(m_color_intrin.width)-5.f), (static_cast<float>(m_color_intrin.height)-5.f), m_distances[dd]}, {100.f, 100.f, m_distances[dd]}, {(static_cast<float>(m_color_intrin.width)-100.f), 100.f, m_distances[dd]}, {100.f, (static_cast<float>(m_color_intrin.height)-100.f), m_distances[dd]}, {(static_cast<float>(m_color_intrin.width)-100.f), (static_cast<float>(m_color_intrin.height)-100.f), m_distances[dd]}, }; const int npoints = sizeof(pos_uvzSrc)/sizeof(pos_uvzSrc[0]); point3dF32 pos3dDst[npoints]; pointF32 pos_uvzDst[npoints]; m_sts = m_projection->project_color_to_camera(npoints, pos_uvzSrc, pos3dDst); if( m_sts == status_param_unsupported ) continue; else ASSERT_EQ(m_sts, status_no_error); m_sts = m_projection->project_camera_to_color(npoints, pos3dDst, pos_uvzDst); if( m_sts == status_param_unsupported ) continue; else ASSERT_EQ(m_sts, status_no_error); /* Check coordinates */ float avg = 0.f, max = 0.f; for(int32_t n = 0; n < npoints; n++ ) { float v = sqrtf( (pos_uvzSrc[n].x - pos_uvzDst[n].x)*(pos_uvzSrc[n].x - pos_uvzDst[n].x) + (pos_uvzSrc[n].y - pos_uvzDst[n].y)*(pos_uvzSrc[n].y - pos_uvzDst[n].y) ); if( max < v ) max = v; avg += v; } avg /= npoints; EXPECT_LE(avg, m_avg_err); EXPECT_LE(max, m_max_err); if(avg > m_avg_err || max > m_max_err) { std::basic_ostringstream<wchar_t> stream; stream << L"FAIL: " << rsformatToWString(m_formats.at(rs::stream::color)) << " " << m_color_intrin.width << "x" << m_color_intrin.height << "; " << "File: " << projection_tests_util::file_name.c_str() << " distance[mm]=" << m_distances[dd] << "; m_avg_error[pxls]=" << avg << "; m_max_error[pxls]=" << max; m_log_util.m_logger->logw(logging_service::level_error, stream.str().c_str(), __FILE__, __LINE__, "color_to_camera_to_color"); m_is_failed = true; } } } /* Test: depth_to_camera_to_depth Target: Checks compatibility of ProjectDepthToCamera and ProjectCameraToDepth Scope: All available '.rssdk' files from PROJECTION folder with different aspect ratios and serialized projection data Description: A set of points from a different places of Depth image in pixel coordinates project to Camera and after that projects back to Depth image. An expectation is to have projected back Depth image pixel coordinates near the source Depth pixel coordinates. An error gets as distance in pixels of source Depth coordinates and projected back to Depth through a Camera Coordinate System. Pass Criteria: Test passes if average error and maximal error less than threshold */ TEST_F(projection_fixture, depth_to_camera_to_depth) { m_avg_err = 3.f; m_max_err = 7.f; for(int32_t dd = 0; dd < (int32_t)m_distances.size(); dd++) { point3dF32 pos_uvzSrc[9] = { {static_cast<float>(m_color_intrin.width)/2.f, static_cast<float>(m_color_intrin.height)/2.f, m_distances[dd]}, {5.f, 5.f, m_distances[dd]}, {(static_cast<float>(m_color_intrin.width)-5.f), 5.f, m_distances[dd]}, {5.f, (static_cast<float>(m_color_intrin.height)-5.f), m_distances[dd]}, {(static_cast<float>(m_color_intrin.width)-5.f), (static_cast<float>(m_color_intrin.height)-5.f), m_distances[dd]}, {100.f, 100.f, m_distances[dd]}, {(static_cast<float>(m_color_intrin.width)-100.f), 100.f, m_distances[dd]}, {100.f, (static_cast<float>(m_color_intrin.height)-100.f), m_distances[dd]}, {(static_cast<float>(m_color_intrin.width)-100.f), (static_cast<float>(m_color_intrin.height)-100.f), m_distances[dd]}, }; const int npoints = sizeof(pos_uvzSrc)/sizeof(pos_uvzSrc[0]); point3dF32 pos3dDst[npoints]; pointF32 pos_uvzDst[npoints]; m_sts = m_projection->project_depth_to_camera(npoints, pos_uvzSrc, pos3dDst); if( m_sts == status_param_unsupported ) continue; else ASSERT_EQ(m_sts, status_no_error); m_sts = m_projection->project_camera_to_depth(npoints, pos3dDst, pos_uvzDst); if( m_sts == status_param_unsupported ) continue; else ASSERT_EQ(m_sts, status_no_error); /* Check coordinates */ float avg = 0.f, max = 0.f; for(int32_t n = 0; n < npoints; n++ ) { float v = sqrtf( (pos_uvzSrc[n].x - pos_uvzDst[n].x)*(pos_uvzSrc[n].x - pos_uvzDst[n].x) + (pos_uvzSrc[n].y - pos_uvzDst[n].y)*(pos_uvzSrc[n].y - pos_uvzDst[n].y) ); if( max < v ) max = v; avg += v; } avg /= npoints; EXPECT_LE(avg, m_avg_err); EXPECT_LE(max, m_max_err); if( avg > m_avg_err || max > m_max_err) { std::basic_ostringstream<wchar_t> stream; stream << L"FAIL: " << rsformatToWString(m_formats.at(rs::stream::depth)) << " " << m_depth_intrin.width << "x" << m_depth_intrin.height << "; " << "File: " << projection_tests_util::file_name.c_str() << " distance[mm]=" << m_distances[dd] << "; m_avg_error[pxls]=" << avg << "; m_max_error[pxls]=" << max; m_log_util.m_logger->logw(logging_service::level_error, stream.str().c_str(), __FILE__, __LINE__, "depth_to_camera_to_depth"); m_is_failed = true; } } } /* Test: map_depth_to_color_to_depth Target: Checks compatibility of MapDepthToColor and MapColorToDepth Scope: All available '.rssdk' files from PROJECTION folder with different aspect ratios and serialized projection data Description: A set of valid point from a Depth image in pixel coordinates maps to Color and after that maps back to Depth image. An expectation is to have mapped back Depth image pixel coordinates near the source Depth pixel coordinates. An error gets as distance in pixels of source Depth coordinates and mapped back to Depth. Pass Criteria: Test passes if average error and maximal error less than threshold for all frames. */ TEST_F(projection_fixture, map_depth_to_color_to_depth) { m_avg_err = 0.7f; m_max_err = 2.f; m_points_max = 100; const int32_t skipped_frames_at_begin = 5; uint16_t invalid_value = 0; float avg = 0.f, max = 0.f; int32_t mnpoints = 0; bool skipped = false; int depthWidth = m_depth_intrin.width; int depthHeight = m_depth_intrin.height; for (int i = skipped_frames_at_begin; i < projection_tests_util::total_frames; i++) { m_device->set_frame_by_index(i, rs::stream::depth); int depthPitch = depthWidth * get_pixel_size(rs::utils::convert_pixel_format(m_device->get_stream_format(rs::stream::depth))); image_info DepthInfo = {depthWidth, depthHeight, convert_pixel_format(projection_tests_util::depth_format), depthPitch}; auto depth = get_unique_ptr_with_releaser(image_interface::create_instance_from_raw_data(&DepthInfo, {m_device->get_frame_data(rs::stream::depth), nullptr}, stream_type::depth, image_interface::flag::any, m_device->get_frame_timestamp(rs::stream::depth), m_device->get_frame_number(rs::stream::depth))); /* Retrieve the depth pixels */ const uint8_t * ddata = (uint8_t*)depth->query_data(); ASSERT_FALSE(!ddata); std::vector<point3dF32> pos_ijSrc; int32_t npoints = 0; for (int32_t y = 0; y < m_color_intrin.height; y++) { uint16_t *d = (uint16_t*)(ddata + y * depth->query_info().pitch); for (int32_t x = 0; x < m_color_intrin.width; x++) { if (d[x] == invalid_value || d[x] > MAX_DISTANCE) continue; // no mapping based on unreliable depth values point3dF32 pos_ijSrcTmp = {(float)x, (float)y, (float)d[x]}; pos_ijSrc.push_back(pos_ijSrcTmp); npoints ++; break; } if(npoints >= m_points_max) break; } std::vector<pointF32> pos_ijDst1(npoints); std::vector<pointF32> pos_ijDst2(npoints); m_sts = m_projection->map_depth_to_color(npoints, &pos_ijSrc[0], &pos_ijDst1[0]); if(m_sts == status_param_unsupported) { skipped = true; continue; } else if(m_sts < status_no_error) { m_log_util.m_logger->logw(logging_service::level_error, L"Unable to MapDepthToColor", __FILE__, __LINE__, "map_depth_to_color_to_depth"); ASSERT_EQ(m_sts, status_no_error); } m_sts = m_projection->map_color_to_depth(depth.get(), npoints, &pos_ijDst1[0], &pos_ijDst2[0]); if( m_sts == status_param_unsupported ) { skipped = true; } else if(m_sts < status_no_error) { m_log_util.m_logger->logw(logging_service::level_error, L"Unable to MapColorToDepth", __FILE__, __LINE__, "map_depth_to_color_to_depth"); ASSERT_EQ(m_sts, status_no_error); } /* Check coordinates */ for(int32_t n = 0; n < npoints; n++ ) { if( pos_ijDst2[n].x != -1.f ) { float v = static_cast<float>(std::max(fabs(pos_ijSrc[n].x - pos_ijDst2[n].x), fabs(pos_ijSrc[n].y - pos_ijDst2[n].y))); if( max < v ) max = v; avg += v; } } mnpoints += npoints; } if(!skipped) { ASSERT_NE(mnpoints, 0); avg = avg / static_cast<float>(mnpoints); EXPECT_LE(avg, m_avg_err); EXPECT_LE(max, m_max_err); if( avg > m_avg_err || max > m_max_err) { std::basic_ostringstream<wchar_t> stream; stream << L"FAIL: " << rsformatToWString(m_formats.at(rs::stream::color)) << " " << m_color_intrin.width << "x" << m_color_intrin.height << "; "; stream << rsformatToWString(m_formats.at(rs::stream::depth)) << " " << m_depth_intrin.width << "x" << m_depth_intrin.height << "; "; stream << "File: " << projection_tests_util::file_name.c_str() << "; m_avg_error[pxls]=" << avg << "; m_max_error[pxls]=" << max; m_log_util.m_logger->logw(logging_service::level_error, stream.str().c_str(), __FILE__, __LINE__, "map_depth_to_color_to_depth"); m_is_failed = true; } } } /* Test: map_depth_camera_color Target: Checks compatibility of ProjectDepthToCamera, ProjectCameraToColor and MapDepthToColor Scope: All available '.rssdk' files from PROJECTION folder with different aspect ratios and serialized projection data Description: A set of valid point from a Depth image in pixel coordinates maps to Color with MapDepthToColor. The same valid point from a Depth image in pixel coordinates projects to World with ProjectDepthToCamera and after that projects to Color with ProjectCameraToColor. An expectation is to have projected ProjectDepthToCamera->ProjectCameraToColor Color image pixel coordinates near the results of mapped Depth pixel coordinates with MapDepthToColor. An error gets as distance in pixels of mapped and projected Depth coordinates. Pass Criteria: Test passes if average error and maximal error less than threshold for all frames. */ TEST_F(projection_fixture, map_depth_camera_color) { m_avg_err = 0.0001f; m_max_err = 0.001f; m_points_max = 100; const int32_t skipped_frames_at_begin = 5; uint16_t invalid_value = 0; float avg = 0.f, max = 0.f; int32_t mnpoints = 0; bool skipped = false; for (int i = skipped_frames_at_begin; i < projection_tests_util::total_frames; i++) { m_device->set_frame_by_index(i, rs::stream::depth); int depthPitch = m_depth_intrin.width * get_pixel_size(rs::utils::convert_pixel_format(projection_tests_util::depth_format)); image_info DepthInfo = {m_depth_intrin.width, m_depth_intrin.height, convert_pixel_format(projection_tests_util::depth_format), depthPitch}; auto depth = get_unique_ptr_with_releaser(image_interface::create_instance_from_raw_data(&DepthInfo, {m_device->get_frame_data(rs::stream::depth), nullptr}, stream_type::depth, image_interface::flag::any, m_device->get_frame_timestamp(rs::stream::depth), m_device->get_frame_number(rs::stream::depth))); /* Retrieve the depth pixels */ const uint8_t * ddata = (uint8_t*)depth->query_data(); ASSERT_FALSE(!ddata); std::vector<point3dF32> pos_ijSrc; for (int32_t y = 0; y < m_color_intrin.height; y++) { uint16_t *d = (uint16_t*)(ddata + y * depth->query_info().pitch); for (int32_t x = 0; x < m_color_intrin.width; x++) { if (d[x] == invalid_value || d[x] > MAX_DISTANCE) continue; // no mapping based on unreliable depth values point3dF32 pos_ijSrcTmp = {(float)x, (float)y, (float)d[x]}; pos_ijSrc.push_back(pos_ijSrcTmp); } } int32_t npoints = static_cast<int32_t>(pos_ijSrc.size()); std::vector<pointF32> pos_ijDst1(npoints); std::vector<point3dF32> pos_ijMid(npoints); std::vector<pointF32> pos_ijDst2(npoints); m_sts = m_projection->map_depth_to_color(npoints, &pos_ijSrc[0], &pos_ijDst1[0]); if( m_sts == status_param_unsupported ) { skipped = true; } else if(m_sts < status_no_error) { ASSERT_EQ(m_sts, status_no_error); } m_sts = m_projection->project_depth_to_camera(npoints, &pos_ijSrc[0], &pos_ijMid[0]); if( m_sts == status_param_unsupported ) { skipped = true; } else if(m_sts < status_no_error) { m_log_util.m_logger->logw(logging_service::level_error, L"Unable to ProjectDepthToCamera", __FILE__, __LINE__, "map_depth_camera_color"); ASSERT_EQ(m_sts, status_no_error); } m_sts = m_projection->project_camera_to_color(npoints, &pos_ijMid[0], &pos_ijDst2[0]); if( m_sts == status_param_unsupported ) { skipped = true; } else if(m_sts < status_no_error) { m_log_util.m_logger->logw(logging_service::level_error, L"Unable to ProjectCameraToColor", __FILE__, __LINE__, "map_depth_camera_color"); ASSERT_EQ(m_sts, status_no_error); } /* Check coordinates */ for(int32_t n = 0; n < npoints; n++ ) { if( pos_ijDst1[n].x != -1.f && pos_ijDst2[n].x != -1.f ) { float v = distancePixels( pos_ijDst1[n], pos_ijDst2[n] ); if( max < v ) max = v; avg += v; } } mnpoints += npoints; } if(!skipped) { ASSERT_NE(mnpoints, 0); avg = avg / static_cast<float>(mnpoints); EXPECT_LE(avg, m_avg_err); EXPECT_LE(max, m_max_err); if( avg > m_avg_err || max > m_max_err) { std::basic_ostringstream<wchar_t> stream; stream << L"FAIL: " << rsformatToWString(m_formats.at(rs::stream::color)) << " " << m_color_intrin.width << "x" << m_color_intrin.height << "; "; stream << rsformatToWString(m_formats.at(rs::stream::depth)) << " " << m_depth_intrin.width << "x" << m_depth_intrin.height << "; "; stream << "File: " << projection_tests_util::file_name.c_str() << "; m_avg_error[pxls]=" << avg << "; m_max_error[pxls]=" << max; m_log_util.m_logger->logw(logging_service::level_error, stream.str().c_str(), __FILE__, __LINE__, "map_depth_camera_color"); m_is_failed = true; } } } /* Test: map_color_camera_depth Target: Checks compatibility of ProjectColorToCamera, ProjectCameraToDepth and MapColorToDepth Scope: All available '.rssdk' files from PROJECTION folder with different aspect ratios and serialized projection data Description: A set of valid point from a Color image in pixel coordinates maps to Depth with MapColorToDepth. The same valid point from a Color image in pixel coordinates projects to World with ProjectColorToCamera and after that projects to Depth with ProjectCameraToDepth. An expectation is to have projected ProjectColorToCamera->ProjectCameraToDepth Depth image pixel coordinates near the results of mapped Color pixel coordinates with MapColorToDepth. An error gets as distance in pixels of mapped and projected Color coordinates. Pass Criteria: Test passes if average error and maximal error less than threshold for all frames. */ TEST_F(projection_fixture, map_color_camera_depth) { const int32_t skipped_frames_at_begin = 5; m_avg_err = .6f; m_max_err = 4.f; m_points_max = 100; uint16_t invalid_value = 0; float avg = 0.f, max = 0.f; int32_t mnpoints = 0; bool skipped = false; for (int i = skipped_frames_at_begin; i < projection_tests_util::total_frames; i++) { m_device->set_frame_by_index(i, rs::stream::depth); int depthPitch = m_depth_intrin.width * get_pixel_size(rs::utils::convert_pixel_format(projection_tests_util::depth_format)); image_info DepthInfo = {m_depth_intrin.width, m_depth_intrin.height, convert_pixel_format(projection_tests_util::depth_format), depthPitch}; auto depth = get_unique_ptr_with_releaser(image_interface::create_instance_from_raw_data(&DepthInfo, {m_device->get_frame_data(rs::stream::depth), nullptr}, stream_type::depth, image_interface::flag::any, m_device->get_frame_timestamp(rs::stream::depth), m_device->get_frame_number(rs::stream::depth))); /* Retrieve the depth pixels */ const uint8_t * ddata = (uint8_t*)depth->query_data(); ASSERT_FALSE(!ddata); // Choose all points from a Depth std::vector<point3dF32> pos_ijSrc; for (int32_t y = 0; y < m_color_intrin.height; y++) { uint16_t *d = (uint16_t*)(ddata + y * depth->query_info().pitch); for (int32_t x = 0; x < m_color_intrin.width; x++) { if (d[x] == invalid_value || d[x] > MAX_DISTANCE) continue; // no mapping based on unreliable depth values point3dF32 pos_ijSrcTmp = {(float)x, (float)y, (float)d[x]}; pos_ijSrc.push_back(pos_ijSrcTmp); } } // Find a Color map of the choosen points std::vector<pointF32> pos_ijSrc1(pos_ijSrc.size()); m_sts = m_projection->map_depth_to_color(static_cast<int32_t>(pos_ijSrc.size()), &pos_ijSrc[0], &pos_ijSrc1[0]); if( m_sts == status_param_unsupported ) { skipped = true; } else if(m_sts < status_no_error) { m_log_util.m_logger->logw(logging_service::level_error, L"Unable to MapDepthToColor", __FILE__, __LINE__, "map_color_camera_depth"); ASSERT_EQ(m_sts, status_no_error); } int32_t npoints = 0; std::vector<pointF32> pos_ijSrc2; std::vector<point3dF32> pos_ijSrc3; for (size_t n = 0; n < pos_ijSrc1.size(); n++) { if( pos_ijSrc1[n].x != -1.f && pos_ijSrc1[n].y != -1.f ) { pos_ijSrc2.push_back(pos_ijSrc1[n]); point3dF32 pos_ijSrcTmp = {pos_ijSrc1[n].x, pos_ijSrc1[n].y, pos_ijSrc[n].z}; pos_ijSrc3.push_back(pos_ijSrcTmp); npoints ++; if( npoints >= m_points_max ) break; } } pos_ijSrc.clear(); pos_ijSrc1.clear(); // Maps and projects back Color points to Depth std::vector<pointF32> pos_ijDst1(npoints); m_sts = m_projection->map_color_to_depth(depth.get(), npoints, &pos_ijSrc2[0], &pos_ijDst1[0]); if( m_sts == status_param_unsupported ) { skipped = true; } else if(m_sts < status_no_error) { m_log_util.m_logger->logw(logging_service::level_error, L"Unable to MapColorToDepth", __FILE__, __LINE__, "map_color_camera_depth"); ASSERT_EQ(m_sts, status_no_error); } std::vector<point3dF32> pos_ijMid(npoints); std::vector<pointF32> pos_ijDst2(npoints); m_sts = m_projection->project_color_to_camera(npoints, &pos_ijSrc3[0], &pos_ijMid[0]); if( m_sts == status_param_unsupported ) { skipped = true; } else if(m_sts < status_no_error) { m_log_util.m_logger->logw(logging_service::level_error, L"Unable to ProjectColorToCamera", __FILE__, __LINE__, "map_color_camera_depth"); ASSERT_EQ(m_sts, status_no_error); } m_sts = m_projection->project_camera_to_depth(npoints, &pos_ijMid[0], &pos_ijDst2[0]); if( m_sts == status_param_unsupported ) { skipped = true; } else if(m_sts < status_no_error) { m_log_util.m_logger->logw(logging_service::level_error, L"Unable to ProjectCameraToDepth", __FILE__, __LINE__, "map_color_camera_depth"); ASSERT_EQ(m_sts, status_no_error); } for(int32_t n = 0; n < npoints; n++ ) { if( pos_ijDst1[n].x != -1.f && pos_ijDst2[n].x != -1.f ) { float v = distancePixels(pos_ijDst1[n], pos_ijDst2[n]); if(max < v) max = v; avg += v; } } mnpoints += npoints; } if(!skipped) { ASSERT_NE(mnpoints, 0); avg = avg / static_cast<float>(mnpoints); EXPECT_LE(avg, m_avg_err); EXPECT_LE(max, m_max_err); if( avg > m_avg_err || max > m_max_err) { std::basic_ostringstream<wchar_t> stream; stream << L"FAIL: " << rsformatToWString(m_formats.at(rs::stream::color)) << " " << m_color_intrin.width << "x" << m_color_intrin.height << "; "; stream << rsformatToWString(m_formats.at(rs::stream::depth)) << " " << m_depth_intrin.width << "x" << m_depth_intrin.height << "; "; stream << "File: " << projection_tests_util::file_name.c_str() << "; m_avg_error[pxls]=" << avg << "; m_max_error[pxls]=" << max; m_log_util.m_logger->logw(logging_service::level_error, stream.str().c_str(), __FILE__, __LINE__, "map_color_camera_depth"); m_is_failed = true; } } } /* Test: query_uvmap_map_depth_to_color Target: Checks compatibility of QueryUVMap and MapDepthToColor Scope: 1. All available '.rssdk' files from PROJECTION folder with different aspect ratios and serialized projection data 2. All valid Depth values Description: From a Depth image picks all valid pixels and calls MapDepthToColor. Also gets UV Map with QueryUVMap. An expectation is to have UV Map coordinates near the results of mapped Depth pixel coordinates with MapDepthToColor. An error gets as distance in pixels of mapped Depth coordinates. Pass Criteria: Test passes if average error and maximal error less than threshold for all frames. */ TEST_F(projection_fixture, query_uvmap_map_depth_to_color) { m_avg_err = 2.f; m_max_err = 3.f; const int32_t skipped_frames_at_begin = 5; uint16_t invalid_value = 0; float avg = 0.f, max = 0.f; int32_t mnpoints = 0; bool skipped = false; std::vector<pointF32> uvMap(m_depth_intrin.width * m_depth_intrin.height); for (int i = skipped_frames_at_begin; i < projection_tests_util::total_frames; i++) { m_device->set_frame_by_index(i, rs::stream::depth); int depthPitch = m_depth_intrin.width * get_pixel_size(rs::utils::convert_pixel_format(projection_tests_util::depth_format)); image_info DepthInfo = {m_depth_intrin.width, m_depth_intrin.height, convert_pixel_format(projection_tests_util::depth_format), depthPitch}; auto depth = get_unique_ptr_with_releaser(image_interface::create_instance_from_raw_data(&DepthInfo, {m_device->get_frame_data(rs::stream::depth), nullptr}, stream_type::depth, image_interface::flag::any, m_device->get_frame_timestamp(rs::stream::depth), m_device->get_frame_number(rs::stream::depth))); const uint8_t * ddata = (uint8_t*)depth->query_data(); /* Get uvMap */ m_sts = m_projection->query_uvmap(depth.get(), uvMap.data()); if(m_sts == status_feature_unsupported) { skipped = true; } else if(m_sts < status_no_error) { ASSERT_EQ(m_sts, status_no_error); } /* Retrieve the depth pixels */ // Choose valid points from a Depth std::vector<point3dF32> pos_ijSrc; int32_t npoints = 0; for (int32_t y = 0; y < m_depth_intrin.height; y++) { uint16_t *d = (uint16_t*)(ddata + y*depth->query_info().pitch); for (int32_t x = 0; x < m_depth_intrin.width; x++) { if (d[x] == invalid_value || d[x] > MAX_DISTANCE) continue; // no mapping based on unreliable depth values point3dF32 pos_ijSrcTmp = {(float)x, (float)y, (float)d[x]}; pos_ijSrc.push_back(pos_ijSrcTmp); npoints ++; } } // Find a Color map of the choosen points std::vector<pointF32> pos_ijDst(npoints); m_sts = m_projection->map_depth_to_color(npoints, pos_ijSrc.data(), pos_ijDst.data()); if( m_sts == status_param_unsupported ) { skipped = true; } else if(m_sts < status_no_error) { m_log_util.m_logger->logw(logging_service::level_error, L"Unable to MapDepthToColor", __FILE__, __LINE__, "query_uvmap_map_depth_to_color"); ASSERT_EQ(m_sts, status_no_error); } for(int32_t n = 0; n < npoints; n++ ) { pointF32 uv = uvMap[static_cast<int>(pos_ijSrc[n].y*static_cast<float>(m_depth_intrin.width) + pos_ijSrc[n].x)]; if( pos_ijDst[n].x != -1.f && pos_ijDst[n].y != -1.f && uv.x >= 0.f && uv.y >= 0.f && uv.x < 1.f && uv.y < 1.f) { uv.x *= static_cast<float>(m_depth_intrin.width); uv.y *= static_cast<float>(m_depth_intrin.height); float v = distancePixels( pos_ijDst[n], uv ); if( max < v ) max = v; avg += v; } } pos_ijDst.clear(); pos_ijSrc.clear(); mnpoints += npoints; } uvMap.clear(); if(!skipped) { ASSERT_NE(mnpoints, 0); avg = avg / static_cast<float>(mnpoints); EXPECT_LE(avg, m_avg_err); EXPECT_LE(max, m_max_err); if( avg > m_avg_err || max > m_max_err) { std::basic_ostringstream<wchar_t> stream; stream << L"FAIL: " << rsformatToWString(m_formats.at(rs::stream::color)) << " " << m_color_intrin.width << "x" << m_color_intrin.height << "; "; stream << rsformatToWString(m_formats.at(rs::stream::depth)) << " " << m_depth_intrin.width << "x" << m_depth_intrin.height << "; "; stream << "File: " << projection_tests_util::file_name.c_str() << "; m_avg_error[pxls]=" << avg << "; m_max_error[pxls]=" << max; m_log_util.m_logger->logw(logging_service::level_error, stream.str().c_str(), __FILE__, __LINE__, "query_uvmap_map_depth_to_color"); m_is_failed = true; } } } /* Test: query_invuvmap_map_color_to_depth Target: Checks compatibility of QueryInvUVMap and MapColorToDepth Scope: All available '.rssdk' files from PROJECTION folder with different aspect ratios and serialized projection data Description: From a Color image picks some amount of pixels and calls MapColorToDepth. Also gets Inverse UV Map with QueryInvUVMap. An expectation is to have Inverse UV Map coordinates near the results of mapped Color pixel coordinates with MapColorToDepth. An error gets as distance in pixels of mapped Color coordinates. Pass Criteria: Test passes if average error and maximal error less than threshold for all frames. */ TEST_F(projection_fixture, query_invuvmap_map_color_to_depth) { m_avg_err = 1.f; m_max_err = 1.f; m_points_max = 1000; const int32_t skipped_frames_at_begin = 5; float avg = 0.f, max = 0.f; int32_t mnpoints = 0; bool skipped = false; std::vector<pointF32> invUvMap(m_color_intrin.width * m_color_intrin.height); for (int i = skipped_frames_at_begin; i < projection_tests_util::total_frames; i++) { m_device->set_frame_by_index(i, rs::stream::depth); int depthPitch = m_depth_intrin.width * get_pixel_size(rs::utils::convert_pixel_format(m_device->get_stream_format(rs::stream::depth))); image_info DepthInfo = {m_depth_intrin.width, m_depth_intrin.height, convert_pixel_format(projection_tests_util::depth_format), depthPitch}; auto depth = get_unique_ptr_with_releaser(image_interface::create_instance_from_raw_data(&DepthInfo, {m_device->get_frame_data(rs::stream::depth), nullptr}, stream_type::depth, image_interface::flag::any, m_device->get_frame_timestamp(rs::stream::depth), m_device->get_frame_number(rs::stream::depth))); /* Get Inversed UV Map */ m_sts = m_projection->query_invuvmap(depth.get(), &invUvMap[0]); if( m_sts == status_feature_unsupported ) { skipped = true; } else if(m_sts < status_no_error) { m_log_util.m_logger->logw(logging_service::level_error, L"Unable to QueryInvUVMap", __FILE__, __LINE__, "query_invuvmap_map_color_to_depth"); ASSERT_EQ(m_sts, status_no_error); } // Choose valid points from a Depth std::vector<pointF32> pos_ijSrc; int32_t npoints = 0; for (int32_t y = m_color_intrin.height/2-20; y < m_color_intrin.height/2+20; y++) { for (int32_t x = m_color_intrin.width/2-20; x < m_color_intrin.width/2+20; x++) { pointF32 pos_ijSrcTmp = {(float)x, (float)y}; pos_ijSrc.push_back(pos_ijSrcTmp); npoints ++; break; } if( npoints >= m_points_max ) break; } // Find a Color map of the choosen points std::vector<pointF32> pos_ijDst(npoints); m_sts = m_projection->map_color_to_depth(depth.get(), npoints, pos_ijSrc.data(), pos_ijDst.data()); if( m_sts == status_param_unsupported ) { skipped = true; } else if(m_sts < status_no_error) { m_log_util.m_logger->logw(logging_service::level_error, L"Unable to MapColorToDepth", __FILE__, __LINE__, "query_invuvmap_map_color_to_depth"); ASSERT_EQ(m_sts, status_no_error); } for(int32_t n = 0; n < npoints; n++ ) { pointF32 invuv = invUvMap[static_cast<int>(pos_ijSrc[n].y*static_cast<float>(m_color_intrin.width)+pos_ijSrc[n].x)]; if( pos_ijDst[n].x >= 0.f && pos_ijDst[n].y >= 0.f && invuv.x >= 0.f ) { invuv.x *= static_cast<float>(m_color_intrin.width); invuv.y *= static_cast<float>(m_color_intrin.height); float v = distancePixels( pos_ijDst[n], invuv ); if( max < v ) max = v; avg += v; } } mnpoints += npoints; pos_ijDst.clear(); pos_ijSrc.clear(); } invUvMap.clear(); if(!skipped) { ASSERT_NE(mnpoints, 0); avg = avg / static_cast<float>(mnpoints); EXPECT_LE(avg, m_avg_err); EXPECT_LE(max, m_max_err); if( avg > m_avg_err || max > m_max_err) { std::basic_ostringstream<wchar_t> stream; stream << L"FAIL: " << rsformatToWString(m_formats.at(rs::stream::color)) << " " << m_color_intrin.width << "x" << m_color_intrin.height << "; "; stream << rsformatToWString(m_formats.at(rs::stream::depth)) << " " << m_depth_intrin.width << "x" << m_depth_intrin.height << "; "; stream << "File: " << projection_tests_util::file_name.c_str() << "; m_avg_error[pxls]=" << avg << "; m_max_error[pxls]=" << max; m_log_util.m_logger->logw(logging_service::level_error, stream.str().c_str(), __FILE__, __LINE__, "query_invuvmap_map_color_to_depth"); m_is_failed = true; } } } /* Test: query_vertices_project_depth_to_camera Target: Checks compatibility of QueryVertices and ProjectDepthToCamera Scope: 1. All available '.rssdk' files from PROJECTION folder with different aspect ratios and serialized projection data 2. All valid Depth values Description: From a Depth image picks all valid pixels and calls ProjectDepthToCamera. Also gets vertices from a Depth image with QueryInvUVMap. An expectation is to have vertices coordinates near the results of projected Depth pixel coordinates with ProjectDepthToCamera. An error gets as distance in mm. Pass Criteria: Test passes if average error and maximal error less than threshold for all frames. */ TEST_F(projection_fixture, query_vertices_project_depth_to_camera) { m_avg_err = 2.f; m_max_err = 3.f; const int32_t skipped_frames_at_begin = 5; uint16_t invalid_value = 0; float avg = 0.f, max = 0.f; int32_t mnpoints = 0; bool skipped = false; std::vector<point3dF32> pos_ijDst1(m_depth_intrin.width*m_depth_intrin.height); for (int i = skipped_frames_at_begin; i < projection_tests_util::total_frames; i++) { m_device->set_frame_by_index(i, rs::stream::depth); int depthPitch = m_depth_intrin.width * get_pixel_size(rs::utils::convert_pixel_format(projection_tests_util::depth_format)); image_info DepthInfo = {m_depth_intrin.width, m_depth_intrin.height, convert_pixel_format(projection_tests_util::depth_format), depthPitch}; auto depth = get_unique_ptr_with_releaser(image_interface::create_instance_from_raw_data(&DepthInfo, {m_device->get_frame_data(rs::stream::depth), nullptr}, stream_type::depth, image_interface::flag::any, m_device->get_frame_timestamp(rs::stream::depth), m_device->get_frame_number(rs::stream::depth))); const uint8_t* ddata = (uint8_t*)depth->query_data(); // Get QueryVertices m_sts = m_projection->query_vertices(depth.get(), pos_ijDst1.data()); if( m_sts == status_feature_unsupported ) { skipped = true; } else if(m_sts < status_no_error) { m_log_util.m_logger->logw(logging_service::level_error, L"Unable to QueryVertices", __FILE__, __LINE__, "query_vertices_project_depth_to_camera"); ASSERT_EQ(m_sts, status_no_error); } int32_t npoints = 0; std::vector<point3dF32> pos_ijSrc; for (int32_t y = 0; y < m_depth_intrin.height; y++) { uint16_t *d = (uint16_t*)(ddata + y*depth->query_info().pitch); for (int32_t x = 0; x < m_depth_intrin.width; x++) { if (d[x] == invalid_value || d[x] > MAX_DISTANCE) continue; // no mapping based on unreliable depth values point3dF32 pos_ijSrcTmp = {(float)x, (float)y, (float)d[x]}; pos_ijSrc.push_back(pos_ijSrcTmp); npoints++; } } /* Get ProjectDepthToCamera */ std::vector<point3dF32> pos_ijDst2(npoints); m_sts = m_projection->project_depth_to_camera(npoints, pos_ijSrc.data(), pos_ijDst2.data()); if( m_sts == status_param_unsupported ) { skipped = true; } else if(m_sts < status_no_error) { m_log_util.m_logger->logw(logging_service::level_error, L"Unable to ProjectDepthToCamera", __FILE__, __LINE__, "query_vertices_project_depth_to_camera"); ASSERT_EQ(m_sts, status_no_error); } for(int32_t n = 0; n < npoints; n++ ) { point3dF32 vertex = pos_ijDst1[static_cast<int>(pos_ijSrc[n].y*static_cast<float>(m_depth_intrin.width)+pos_ijSrc[n].x)]; if( !(vertex.x >= 0.f && vertex.y >= 0.f && pos_ijDst2[n].x >= 0.f && pos_ijDst2[n].y >= 0.f) ) continue; float v = distance3d(vertex, pos_ijDst2[n]); if( max < v ) max = v; avg += v; } mnpoints += npoints; pos_ijDst2.clear(); pos_ijSrc.clear(); } pos_ijDst1.clear(); if(!skipped) { ASSERT_NE(mnpoints, 0); avg = avg / static_cast<float>(mnpoints); EXPECT_LE(avg, m_avg_err); EXPECT_LE(max, m_max_err); if( avg > m_avg_err ) { std::basic_ostringstream<wchar_t> stream; stream << L"FAIL: " << rsformatToWString(m_formats.at(rs::stream::color)) << " " << m_color_intrin.width << "x" << m_color_intrin.height << "; "; stream << rsformatToWString(m_formats.at(rs::stream::depth)) << " " << m_depth_intrin.width << "x" << m_depth_intrin.height << "; "; stream << "File: " << projection_tests_util::file_name.c_str() << "; m_avg_error[mm]=" << avg << "; m_max_error[mm]=" << max; m_log_util.m_logger->logw(logging_service::level_error, stream.str().c_str(), __FILE__, __LINE__, "query_vertices_project_depth_to_camera"); m_is_failed = true; } } } /* Test: query_uvmap_query_invuvmap Target: Checks compatibility of QueryInvUVMap and MapColorToDepth Scope: All available '.rssdk' files from PROJECTION folder with different aspect ratios and serialized projection data Description: Gets UV Map with QueryUVMap, and Inverse UV Map with QueryInvUVMap. An expectation is to have source Depth image pixel coordinates near the results of mapped back pixel coordinates with QueryInvUVMap. An error gets as distance in pixels of mapped Depth coordinates. Pass Criteria: Test passes if average error and maximal error less than threshold for all frames. */ TEST_F(projection_fixture, DISABLED_query_uvmap_query_invuvmap) { m_avg_err = 3.f; m_max_err = 6.f; const int32_t skipped_frames_at_begin = 5; float avg = 0.f, max = 0.f; int32_t npoints = 0; bool skipped = false; for (int i = skipped_frames_at_begin; i < projection_tests_util::total_frames; i++) { m_device->set_frame_by_index(i, rs::stream::depth); int depthPitch = m_depth_intrin.width * get_pixel_size(rs::utils::convert_pixel_format(projection_tests_util::depth_format)); image_info DepthInfo = { m_depth_intrin.width, m_depth_intrin.height, convert_pixel_format(projection_tests_util::depth_format), depthPitch }; auto depth = get_unique_ptr_with_releaser(image_interface::create_instance_from_raw_data(&DepthInfo, {m_device->get_frame_data(rs::stream::depth), nullptr}, stream_type::depth, image_interface::flag::any, m_device->get_frame_timestamp(rs::stream::depth), m_device->get_frame_number(rs::stream::depth))); /* Get UV Map */ std::vector<pointF32> uvMap(m_depth_intrin.width * m_depth_intrin.height); m_sts = m_projection->query_uvmap(depth.get(), uvMap.data()); if(m_sts == status_feature_unsupported) { skipped = true; } else if(m_sts < status_no_error) { m_log_util.m_logger->logw(logging_service::level_error, L"Unable to QueryUVMap", __FILE__, __LINE__, "query_uvmap_query_invuvmap"); ASSERT_EQ(m_sts, status_no_error); } /* Get Inverse UV Map */ std::vector<pointF32> invUvMap(m_color_intrin.width * m_color_intrin.height); m_sts = m_projection->query_invuvmap(depth.get(), invUvMap.data()); if(m_sts == status_feature_unsupported) { skipped = true; } else if(m_sts < status_no_error) { m_log_util.m_logger->logw(logging_service::level_error, L"Unable to QueryInvUVMap", __FILE__, __LINE__, "query_uvmap_query_invuvmap"); ASSERT_EQ(m_sts, status_no_error); } for (int32_t y = 0; y < m_depth_intrin.height; y++) { for (int32_t x = 0; x < m_depth_intrin.width; x++) { pointF32 uv = uvMap[y*m_depth_intrin.width+x]; if (uv.x < 0.f || uv.x >= 1.f || uv.y < 0.f || uv.y >= 1.f) continue; uv.x *= static_cast<float>(m_depth_intrin.width); uv.x += 0.5f; uv.y *= static_cast<float>(m_depth_intrin.height); uv.y += 0.5f; pointF32 invuv = invUvMap[m_color_intrin.width*(int)uv.y+(int)uv.x]; if(invuv.x < 0.f || invuv.x >= 1.f || invuv.y < 0.f || invuv.y >= 1.f) continue; invuv.x *= static_cast<float>(m_color_intrin.width); invuv.y *= static_cast<float>(m_color_intrin.height); pointF32 src = {(float)x, (float)y}; float v = distancePixels( src, invuv ); if(max < v) max = v; avg += v; npoints++; } } } if(!skipped) { ASSERT_NE(npoints, 0); avg = avg / static_cast<float>(npoints); EXPECT_LE(avg, m_avg_err); EXPECT_LE(max, m_max_err); if( avg > m_avg_err || max > m_max_err) { std::basic_ostringstream<wchar_t> stream; stream << L"FAIL: " << rsformatToWString(m_formats.at(rs::stream::color)) << " " << m_color_intrin.width << "x" << m_color_intrin.height << "; "; stream << rsformatToWString(m_formats.at(rs::stream::depth)) << " " << m_depth_intrin.width << "x" << m_depth_intrin.height << "; "; stream << "File: " << projection_tests_util::file_name.c_str() << "; m_avg_error[pxls]=" << avg; m_log_util.m_logger->logw(logging_service::level_error, stream.str().c_str(), __FILE__, __LINE__, "query_uvmap_query_invuvmap"); m_is_failed = true; } } } /* Test: create_depth_image_mapped_to_color_query_invuvmap Target: Checks compatibility of QueryInvUVMap and MapColorToDepth Scope: All available '.rssdk' files from PROJECTION folder with different aspect ratios and serialized projection data Description: Gets Inverse UV Map with QueryInvUVMap, and also creates Depth mapped to Color image with CreateDepthImageMappedToColor An expectation is to have exactely the same Depth values on the image and [picked from a Depth Image with QueryInvUVMap. An error gets as percent of inequal Depth values. Pass Criteria: Test passes if average error and maximal error less than threshold for all frames. */ TEST_F(projection_fixture, create_depth_image_mapped_to_color_query_invuvmap) { m_avg_err = 1.f; m_max_err = 1.f; const int32_t skipped_frames_at_begin = 5; uint16_t invalid_value = 0; float avg = 0.f; int32_t npoints = 0; bool skipped = false; int depthPitch = m_depth_intrin.width * get_pixel_size(rs::utils::convert_pixel_format(projection_tests_util::depth_format)); int colorPitch = m_color_intrin.width * get_pixel_size(rs::utils::convert_pixel_format(projection_tests_util::color_format)); image_info depthInfo = { m_depth_intrin.width, m_depth_intrin.height, convert_pixel_format(projection_tests_util::depth_format), depthPitch }; image_info colorInfo = { m_color_intrin.width, m_color_intrin.height, convert_pixel_format(projection_tests_util::color_format), colorPitch }; m_device->start(); for(int i = skipped_frames_at_begin; i < projection_tests_util::total_frames; i++) { m_device->set_frame_by_index(i, rs::stream::depth); const void* depthData = (void*)m_device->get_frame_data(rs::stream::depth); const void* colorData = (void*)m_device->get_frame_data(rs::stream::color); auto depth = get_unique_ptr_with_releaser(image_interface::create_instance_from_raw_data(&depthInfo, {depthData, nullptr}, stream_type::depth, image_interface::flag::any, m_device->get_frame_timestamp(rs::stream::depth), m_device->get_frame_number(rs::stream::depth))); auto color = get_unique_ptr_with_releaser(image_interface::create_instance_from_raw_data(&colorInfo, {colorData, nullptr}, stream_type::color, image_interface::flag::any, m_device->get_frame_timestamp(rs::stream::color), m_device->get_frame_number(rs::stream::color))); /* Get Inverse UV Map */ std::vector<pointF32> invUvMap(colorInfo.width * colorInfo.height); m_sts = m_projection->query_invuvmap(depth.get(), invUvMap.data()); if(m_sts == status_feature_unsupported) { skipped = true; } else if(m_sts < status_no_error) { ASSERT_EQ(m_sts, status_no_error); } auto depth2color = get_unique_ptr_with_releaser(m_projection->create_depth_image_mapped_to_color(depth.get(), color.get())); ASSERT_NE(depth2color.get(), nullptr); ASSERT_NE(depth2color->query_data(), nullptr); const uint8_t* depth2color_data = (const uint8_t*)depth2color->query_data(); image_info depth2colorInfo = depth2color->query_info(); const uint8_t* depth_data = (const uint8_t*)depth->query_data(); for (int32_t y = 0; y < m_depth_intrin.height; y++) { for (int32_t x = 0; x < m_depth_intrin.width; x++) { pointF32 invuv = invUvMap[y*m_color_intrin.width+x]; if(invuv.x < 0.f || invuv.y < 0.f || invuv.x >= 1.f || invuv.y >= 1.f) continue; invuv.x *= static_cast<float>(m_color_intrin.width); invuv.x += 0.5f; invuv.y *= static_cast<float>(m_color_intrin.height); invuv.y += 0.5f; uint16_t d1 = (uint16_t)(depth_data + (int)invuv.y*depthInfo.pitch)[(int)invuv.x]; uint16_t d2 = (uint16_t)(depth2color_data + y*depth2colorInfo.pitch)[x]; if (d1 == invalid_value || d2 == invalid_value) continue; if(0 != abs(d1 - d2)) { avg++; } npoints++; } } } if(!skipped) { ASSERT_NE(npoints, 0); avg = avg / static_cast<float>(npoints); EXPECT_LE(avg, m_avg_err); if( avg > m_avg_err ) { std::basic_ostringstream<wchar_t> stream; stream << L"FAIL: " << rsformatToWString(m_formats.at(rs::stream::color)) << " " << m_color_intrin.width << "x" << m_color_intrin.height << "; "; stream << rsformatToWString(m_formats.at(rs::stream::depth)) << " " << m_depth_intrin.width << "x" << m_depth_intrin.height << "; "; stream << "File: " << projection_tests_util::file_name.c_str() << "; avg_err= " << avg; m_log_util.m_logger->logw(logging_service::level_error, stream.str().c_str(), __FILE__, __LINE__, "create_depth_image_mapped_to_color_query_invuvmap"); m_is_failed = true; } } } /* Test: create_color_image_mapped_to_depth_query_uvmap Target: Checks compatibility of CreateColorImageMappedToDepth and QueryUVMap Scope: All available '.rssdk' files from PROJECTION folder with different aspect ratios and serialized projection data Description: Gets UV Map with QueryUVMap, and also creates Color mapped to Depth image with CreateColorImageMappedToDepth An expectation is to have exactely the same Color values on the image and picked from a Color Image with QueryUVMap. An error gets as percent of inequal Color values. Pass Criteria: Test passes if average error and maximal error less than threshold for all frames. */ TEST_F(projection_fixture, create_color_image_mapped_to_depth_query_uvmap) { m_avg_err = 1.f; m_max_err = 1.f; const int32_t skipped_frames_at_begin = 5; uint32_t invalid_value = 0; float avg = 0.f; int32_t npoints = 0; int32_t colorComponents = 1; bool skipped = false; int depthPitch = m_depth_intrin.width * get_pixel_size(rs::utils::convert_pixel_format(projection_tests_util::depth_format)); int colorPitch = m_color_intrin.width * get_pixel_size(rs::utils::convert_pixel_format(projection_tests_util::color_format)); image_info depthInfo = { m_depth_intrin.width, m_depth_intrin.height, convert_pixel_format(projection_tests_util::depth_format), depthPitch }; image_info colorInfo = { m_color_intrin.width, m_color_intrin.height, convert_pixel_format(projection_tests_util::color_format), colorPitch }; m_device->start(); for(int i = skipped_frames_at_begin; i < projection_tests_util::total_frames; i++) { m_device->set_frame_by_index(i, rs::stream::depth); const void* depthData = m_device->get_frame_data(rs::stream::depth); const void* colorData = m_device->get_frame_data(rs::stream::color); auto depth = get_unique_ptr_with_releaser(image_interface::create_instance_from_raw_data(&depthInfo, {depthData, nullptr}, stream_type::depth, image_interface::flag::any, m_device->get_frame_timestamp(rs::stream::depth), m_device->get_frame_number(rs::stream::depth))); auto color = get_unique_ptr_with_releaser(image_interface::create_instance_from_raw_data(&colorInfo, {colorData, nullptr}, stream_type::color, image_interface::flag::any, m_device->get_frame_timestamp(rs::stream::color), m_device->get_frame_number(rs::stream::color))); /* Get uvmap */ std::vector<pointF32> uvMap(depthInfo.width * depthInfo.height); m_sts = m_projection->query_uvmap(depth.get(), uvMap.data()); if(m_sts == status_feature_unsupported) { skipped = true; } else if(m_sts < status_no_error) { ASSERT_EQ(m_sts, status_no_error); } auto color2depth = get_unique_ptr_with_releaser(m_projection->create_color_image_mapped_to_depth(depth.get(), color.get())); ASSERT_NE(color2depth.get(), nullptr); ASSERT_NE(color2depth->query_data(), nullptr); const uint8_t* color2depth_data = (const uint8_t*)color2depth->query_data(); const uint8_t* color_data = (const uint8_t*)color->query_data(); image_info color2depth_info = color2depth->query_info(); colorComponents = get_pixel_size(color2depth_info.format); ASSERT_NE(colorComponents, 0); for (int32_t y = 0; y < m_color_intrin.height; y++) { for (int32_t x = 0; x < m_color_intrin.width; x++) { pointF32 uv = uvMap[y*m_depth_intrin.width+x]; if(uv.x < 0.f || uv.x >= 1.f || uv.y < 0.f || uv.y >= 1.f) continue; uv.x *= static_cast<float>(m_depth_intrin.width); uv.x += 0.5f; uv.y *= static_cast<float>(m_depth_intrin.height); uv.y += 0.5f; for (int32_t cc = 0; cc < colorComponents; cc++) { uint32_t c1 = (uint32_t)(color_data + (int)uv.y*colorInfo.pitch)[(int)uv.x + cc]; uint32_t c2 = (uint32_t)(color2depth_data + y*colorInfo.pitch)[x + cc]; if (c1 == invalid_value || c2 == invalid_value) continue; if(0 != abs((long)(c1 - c2))) { avg++; } } npoints++; } } } if(!skipped) { ASSERT_NE(npoints, 0); avg = avg / static_cast<float>(colorComponents) / static_cast<float>(npoints); EXPECT_LE(avg, m_avg_err); if( avg > m_avg_err ) { std::basic_ostringstream<wchar_t> stream; stream << L"FAIL: " << rsformatToWString(m_formats.at(rs::stream::color)) << " " << m_color_intrin.width << "x" << m_color_intrin.height << "; "; stream << rsformatToWString(m_formats.at(rs::stream::depth)) << " " << m_depth_intrin.width << "x" << m_depth_intrin.height << "; "; stream << "File: " << projection_tests_util::file_name.c_str() << "; avg_err= " << avg; m_log_util.m_logger->logw(logging_service::level_error, stream.str().c_str(), __FILE__, __LINE__, "create_depth_image_mapped_to_color_query_invuvmap"); m_is_failed = true; } } }
NeoflexConsulting/nussknacker
engine/lite/kafka/integration-test/src/it/scala/pl/touk/nussknacker/engine/lite/kafka/NuKafkaRuntimeTestMixin.scala
package pl.touk.nussknacker.engine.lite.kafka import org.apache.commons.io.FileUtils import org.apache.kafka.clients.admin.NewTopic import org.scalatest.TestSuite import pl.touk.nussknacker.engine.build.EspProcessBuilder import pl.touk.nussknacker.engine.canonize.ProcessCanonizer import pl.touk.nussknacker.engine.graph.EspProcess import pl.touk.nussknacker.engine.kafka.{KafkaClient, KafkaUtils} import pl.touk.nussknacker.engine.marshall.ProcessMarshaller import pl.touk.nussknacker.engine.spel.Implicits._ import scala.collection.JavaConverters._ import java.io.File import java.nio.charset.StandardCharsets import scala.compat.java8.OptionConverters.RichOptionForJava8 trait NuKafkaRuntimeTestMixin { self: TestSuite => protected def kafkaBoostrapServer: String protected def prepareTestCaseFixture(testCaseName: String, prepareScenario: (String, String) => EspProcess): NuKafkaRuntimeTestTestCaseFixture = { val rootName = self.suiteName + "-" + testCaseName val inputTopic = rootName + "-input" val outputTopic = rootName + "-output" // TODO: replace with KafkaClient when it stop to use zkAddress for its admin client KafkaUtils.usingAdminClient(kafkaBoostrapServer) { client => client.createTopics(List( new NewTopic(inputTopic, Option.empty[Integer].asJava, Option.empty[java.lang.Short].asJava), new NewTopic(outputTopic, Option(1: Integer).asJava, Option.empty[java.lang.Short].asJava) ).asJava) } val scenarioFile = saveScenarioToTmp(prepareScenario(inputTopic, outputTopic), rootName) NuKafkaRuntimeTestTestCaseFixture(inputTopic, outputTopic, scenarioFile) } private def saveScenarioToTmp(scenario: EspProcess, scenarioFilePrefix: String): File = { val canonicalScenario = ProcessCanonizer.canonize(scenario) val json = ProcessMarshaller.toJson(canonicalScenario) val jsonFile = File.createTempFile(getClass.getSimpleName, ".json") jsonFile.deleteOnExit() FileUtils.write(jsonFile, json.toString(), StandardCharsets.UTF_8) jsonFile } } case class NuKafkaRuntimeTestTestCaseFixture(inputTopic: String, outputTopic: String, scenarioFile: File) object NuKafkaRuntimeTestSamples { def jsonPingPongScenario(inputTopic: String, outputTopic: String): EspProcess = EspProcessBuilder .id("json-ping-pong") .source("source", "kafka-json", "topic" -> s"'$inputTopic'") .emptySink("sink", "kafka-json", "topic" -> s"'$outputTopic'", "value" -> "#input") val jsonPingMessage: String = """{"foo":"ping"}""".stripMargin }
fangjiaxiaobai/learn
13-design-pattern/chapter01-factoryDesignPattern/src/demo2_factory/LowCarFactory.java
<gh_stars>0 package demo2_factory; /** * @author fangjiaxiaobai * @date 2017/12/29 */ public class LowCarFactory implements IFactory { @Override public ICar create() { return new LowCar(); } }
GabrielSturtevant/mage
Mage.Sets/src/mage/cards/a/AbsorbVis.java
package mage.cards.a; import java.util.UUID; import mage.abilities.costs.mana.ManaCostsImpl; import mage.abilities.effects.common.GainLifeEffect; import mage.abilities.effects.common.LoseLifeTargetEffect; import mage.abilities.keyword.BasicLandcyclingAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.target.TargetPlayer; /** * * @author Loki */ public final class AbsorbVis extends CardImpl { public AbsorbVis(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.SORCERY}, "{6}{B}"); this.getSpellAbility().addEffect(new LoseLifeTargetEffect(4)); this.getSpellAbility().addEffect(new GainLifeEffect(4).setText("and you gain 4 life")); this.getSpellAbility().addTarget(new TargetPlayer()); this.addAbility(new BasicLandcyclingAbility(new ManaCostsImpl("{1}{B}"))); } private AbsorbVis(final AbsorbVis card) { super(card); } @Override public AbsorbVis copy() { return new AbsorbVis(this); } }
prytoegrian/auto-reply
search/github.go
<gh_stars>10-100 package search import ( "github.com/google/go-github/github" "github.com/parkr/auto-reply/ctx" "github.com/parkr/githubapi/githubsearch" ) func GitHubIssues(context *ctx.Context, query githubsearch.IssueSearchParameters) ([]github.Issue, error) { issues := []github.Issue{} opts := &github.SearchOptions{Sort: "created", Order: "desc", ListOptions: github.ListOptions{Page: 0, PerPage: 100}} queryStr := query.String() for { result, resp, err := context.GitHub.Search.Issues(context.Context(), queryStr, opts) if err != nil { return nil, context.NewError("search: error running GitHub issues search query: '%s': %v", queryStr, err) } for _, issue := range result.Issues { issues = append(issues, issue) } if resp.NextPage == 0 { break } opts.ListOptions.Page = resp.NextPage } return issues, nil }
sheppas/the-completionist
client/components/SearchResults.js
<filename>client/components/SearchResults.js /*What I want to happen: The search term is listed in the headline for search results. How do I ensure that it makes it from the search bar, to the request, and then here in the headline?*/ import React from "react" import {connect} from "react-redux" import { Link } from "react-router-dom" class SearchResults extends React.Component { constructor(props) { super(props) } render(){ const movies = this.props.movies ? this.props.movies : [] if (movies.length === 0) { return ( <div> <h2>It appears these are not the droids you're looking for. Please search again.</h2> </div> ); } return ( <div> <h2>Your Search Results</h2> <div className="listed-movies"> {movies.map((movie) => ( <div key={movie.id} className='individual-movie'> <Link to={`/movies/${movie.id}`}> <img src={`https://image.tmdb.org/t/p/w500/${movie.poster_path}`} width='150' height='225'/> <p>{movie.title}</p> </Link> </div> ))} </div> </div> ); } } const mapState = (state) => { return { movies: state.searchResults } } export default connect(mapState)(SearchResults)
ch98road/leetcode
src/cmcandy/C_Language_Answers/algo/11_findMaxLength.cpp
#include <iostream> #include <vector> #include <map> using namespace ::std; class Solution { public: int findMaxLength(vector<int> &nums) { // 用map记录差值,然后每次找到sum的时候从map中找对应的,如果没有,则当前sum的位置是最早的,有则出现了一组符合条件的子数组,计算长度 map<int, int> m; m[0] = -1; int len = nums.size(); int sum = 0; int res = 0; for (int i = 0; i < len; i++) { sum += nums[i] == 0 ? -1 : 1; if (m.find(sum) == m.end()) { m[sum] = i; } else { res = max(res, i - m[sum]); } } return res; } };
jessicaleete/numerical_computing
Labs/BSplines/plots.py
import numpy as np from scipy.interpolate import splev import matplotlib matplotlib.rcParams = matplotlib.rc_params_from_file('../../matplotlibrc') from matplotlib import pyplot as plt def basis_plot(n, k, res=401): """ Plots some b-spline basis functions. Uses same knot vector as the circle interpolation problem.""" # Make the knot vector. t = np.array([0]*(k) + range(n) + [n]*(k+1)) # Preallocate array to store the control points. c = np.zeros(t.size - k) # Parameter values to use for plot: T = np.linspace(0, n, res) # Plot each basis function. for i in xrange(t.size - k - 1): # Set the corresponding coefficient to 1. c[i] = 1 # plot it. plt.plot(T, splev(T, (t, c, k))) # Set the corresponding coefficient back to 0. c[i] = 0. # Save and clear the figure. plt.savefig("bspline_basis.pdf") plt.clf() if __name__ == "__main__": basis_plot(8, 3)
mozammel/mNet
src/main/java/org/jugbd/mnet/service/PatientService.java
<gh_stars>1-10 package org.jugbd.mnet.service; import org.jugbd.mnet.domain.Patient; import org.jugbd.mnet.web.controller.PatientSearchCmd; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import java.util.List; /** * @author ronygomes */ public interface PatientService { Patient create(Patient patient); Patient findOne(Long id); List<Patient> findAll(); Page findPatientBySearchCmd(final PatientSearchCmd searchCmd, Pageable pageable); Page<Patient> findAll(Pageable pageable); long count(); void update(Patient patient); }
franc90/age-akka-starter
src/main/java/org/age/akka/core/helper/AkkaConfigurationLoader.java
package org.age.akka.core.helper; import com.google.common.base.Charsets; import com.google.common.io.Resources; import org.age.akka.core.exceptions.AkkaTemplateLoadingException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Named; import java.io.IOException; import java.net.URL; @Named public class AkkaConfigurationLoader { private static final Logger log = LoggerFactory.getLogger(AkkaConfigurationLoader.class); private static final String templateLocation = "akka/config/template/configTemplate.txt"; public String loadConfigurationTemplate() { try { URL url = Resources.getResource(templateLocation); return Resources.toString(url, Charsets.UTF_8); } catch (IOException e) { log.error("Could not load template"); throw new AkkaTemplateLoadingException("Could not load template"); } } }
patternfly-java/showcase
src/main/java/org/patternfly/showcase/client/documentation/components/TabsComponent.java
package org.patternfly.showcase.client.documentation.components; import org.patternfly.components.Tabs; import org.patternfly.showcase.client.Resources; import static java.util.Collections.singletonList; import static org.jboss.elemento.Elements.div; import static org.jboss.elemento.Elements.p; import static org.patternfly.components.Icon.icon; import static org.patternfly.resources.CSS.fas; import static org.patternfly.resources.CSS.util; public class TabsComponent extends BaseComponent { public TabsComponent() { super("Tabs", p().textContent("Tabs are used to present a set on tabs for organizing content on a page. " + "It must always be used together with a tab content component.").element(), singletonList( new Snippet("Basic", Resources.get().tabs().getText(), () -> { return Tabs.tabs() .add("Tab Item 1", div().textContent("Tab 1")) .add("Tab Item 2", div().textContent("Tab 2")) .add("Tab Item 3", div().textContent("Tab 3")) .add("tab-item-4", tab -> tab .add("Tab 4") .add(icon(fas("address-book")).css(util("pl-sm"))), panel -> panel.textContent(("Tab 4"))) .element(); }))); } }
jambolo/jambolo.github.io
docs/equity/html/search/files_11.js
var searchData= [ ['validator_2ecpp',['Validator.cpp',['../_validator_8cpp.html',1,'']]], ['validator_2eh',['Validator.h',['../_validator_8h.html',1,'']]], ['verackmessage_2ecpp',['VerackMessage.cpp',['../_verack_message_8cpp.html',1,'']]], ['verackmessage_2eh',['VerackMessage.h',['../_verack_message_8h.html',1,'']]], ['versionmessage_2ecpp',['VersionMessage.cpp',['../_version_message_8cpp.html',1,'']]], ['versionmessage_2eh',['VersionMessage.h',['../_version_message_8h.html',1,'']]] ];
StrikS/jdi-light
jdi-bdd/src/main/java/com/epam/jdi/bdd/stepdefs/DropdownSteps.java
<reponame>StrikS/jdi-light package com.epam.jdi.bdd.stepdefs; import com.epam.jdi.light.elements.interfaces.complex.IsDropdown; import cucumber.api.java.en.Then; import static com.epam.jdi.light.elements.init.entities.collection.EntitiesCollection.getUI; /** * Created by <NAME> on 26.09.2019 * Email: <EMAIL>; Skype: roman.iovlev */ public class DropdownSteps { public static IsDropdown dropdown(String name) { return getUI(name, IsDropdown.class); } @Then("^the \"([^\"]*)\" in \"([^\"]*)\" is selected$") public void theInIsSelected(String textValue, String name) { dropdown(name).is().selected(textValue); } }
ceekay1991/AliPayForDebug
AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/CCardVoiceOverItem.h
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by <NAME>. // #import <objc/NSObject.h> @class NSString; @interface CCardVoiceOverItem : NSObject { NSString *_title; unsigned long long _index; NSString *_action; } @property(copy, nonatomic) NSString *action; // @synthesize action=_action; @property(nonatomic) unsigned long long index; // @synthesize index=_index; @property(copy, nonatomic) NSString *title; // @synthesize title=_title; - (void).cxx_destruct; @end
Angel-Asensio/levelup-java-examples
src/test/java/com/levelup/java/array/ShiftValuesInArray.java
package com.levelup.java.array; import static org.junit.Assert.assertTrue; import java.util.Arrays; import org.apache.log4j.Logger; import org.junit.Test; /** * This java example will demonstrate shifting the values in array * * @author <NAME> * @see <a href='http://www.leveluplunch.com/java/examples/shift-elements-in-array/'>Shift elements in array</a> * */ public class ShiftValuesInArray { private static final Logger logger = Logger.getLogger(ShiftValuesInArray.class); @Test public void shift_values_in_array_with_java () { String[] shoeTypes = { "Nike", "Puma", "Converse", "Reebok", "Asics"}; String[] shoeTypesMinusNike = new String[shoeTypes.length - 1]; System.arraycopy(shoeTypes, 1, shoeTypesMinusNike, 0, shoeTypes.length - 1); logger.info(Arrays.toString(shoeTypesMinusNike)); assertTrue(Arrays.binarySearch(shoeTypesMinusNike, "Nike") < 0); } }
youngMen1/seal-common
seal-features/src/main/java/com/seal/features/entity/City.java
<reponame>youngMen1/seal-common package com.seal.features.entity; /** * @author fengzhiqiang * @date 2021/5/25 14:18 **/ public class City { /** * 城市名 */ private String name; /** * 构造器 * @param name 城市名 */ public City(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
ardikars/pcap
jdk7/src/test/java/pcap/jdk7/internal/DefaultTimestampTest.java
<filename>jdk7/src/test/java/pcap/jdk7/internal/DefaultTimestampTest.java<gh_stars>10-100 /* * Copyright (c) 2020-2021 Pcap Project * SPDX-License-Identifier: MIT OR Apache-2.0 */ package pcap.jdk7.internal; import com.sun.jna.Native; import com.sun.jna.NativeLong; import com.sun.jna.Pointer; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; @RunWith(JUnitPlatform.class) class DefaultTimestampTest { @Test void newInstance() { DefaultTimestamp timestamp = new DefaultTimestamp(); Assertions.assertEquals(0, timestamp.second()); Assertions.assertEquals(0, timestamp.microSecond()); Pointer pointer = new Pointer(Native.malloc(DefaultTimestamp.SIZEOF)); pointer.setNativeLong(DefaultTimestamp.TV_SEC_OFFSET, new NativeLong(1)); pointer.setNativeLong(DefaultTimestamp.TV_USEC_OFFSET, new NativeLong(2)); DefaultTimestamp fromPointer = new DefaultTimestamp(pointer); Assertions.assertEquals(1, fromPointer.second()); Assertions.assertEquals(2, fromPointer.microSecond()); Native.free(Pointer.nativeValue(pointer)); } }
ckamtsikis/cmssw
GeometryReaders/XMLIdealGeometryESSource/test/complines.cc
#include <fstream> #include <iostream> #include <sstream> #include <string> #include <vector> #include <cmath> #include <iomanip> int main (int argc, char *argv[]) { std::string fname1, fname2; // assume two arguments NO MATTER WHAT! crash otherwise... who cares? if ( argc == 3 ) { // std::cout << "got two" << std::endl; fname1 = argv[1]; fname2 = argv[2]; // std::cout << fname1 << " and " << fname2 << std::endl; } else { std::cout << "need two arguments (filenames) to compare dumpGeoHistory" << std::endl; return 1; } std::ifstream f1(fname1.c_str()); std::ifstream f2(fname2.c_str()); std::string l1, l2, ts; std::vector<double> t1(3), t2(3), r1(9), r2(9); while ( !f1.eof() && !f2.eof() ) { getline(f1, l1, ','); getline(f2, l2, ','); if ( l1 != l2 ) { std::cout << "Lines don't match or are out of synchronization." << " The difference is much bigger than just the numbers," << " actual parts are missing or added. This program " << " does not handle this at this time... use diff first." << std::endl << "["<<l1 <<"]"<< std::endl << "["<<l2 <<"]"<< std::endl << std::endl; return 1; } // std::cout << "1================================" << std::endl; // std::cout << "["<<l1 <<"]"<< std::endl // << "["<<l2 <<"]"<< std::endl; // std::cout << "================================" << std::endl; size_t i = 0; while ( i < 3 ) { ts.clear(); getline(f1,ts,','); // std::cout << ts << std::endl; std::istringstream s1 (ts); s1>>t1[i++]; } i=0; while ( i < 8 ) { ts.clear(); getline(f1,ts,','); // std::cout << ts << std::endl; std::istringstream s1 (ts); s1>>r1[i++]; } ts.clear(); getline(f1, ts); std::istringstream s2(ts); s2>>r1[8]; i=0; while ( i < 3 ) { ts.clear(); getline(f2,ts,','); // std::cout << ts << std::endl; std::istringstream s1 (ts); s1>>t2[i++]; } i=0; while ( i < 8 ) { ts.clear(); getline(f2,ts,','); // std::cout << ts << std::endl; std::istringstream s1 (ts); s1>>r2[i++]; } ts.clear(); getline(f2, ts); std::istringstream s3(ts); s3>>r2[8]; // std::cout << "2================================" << std::endl; // std::cout << "["<<l1 <<"]"<< std::endl // << "["<<l2 <<"]"<< std::endl; // std::cout << "ts = " << ts << std::endl; // std::cout << "================================" << std::endl; // std::cout << "l1=" << l1 << std::endl; std::vector<bool> cerrorind; cerrorind.reserve(3); for (i=0; i < 3; i++) { // std::cout << std::setw(13) // << std::setprecision(7) << std::fixed // << "t1[" << i << "] = " << t1[i] // << " t2[" << i << "] = " << t2[i] << std::endl; if ( std::fabs(t1[i] - t2[i]) > 0.0000001 ) cerrorind[i] = true; else cerrorind[i] = false; } if ( cerrorind[0] || cerrorind[1] || cerrorind[2] ) std::cout << l1; for ( i=0; i<3; ++i ) { if ( cerrorind[i] ) { std::cout << " coordinate "; if ( i == 0 ) std::cout << "x "; else if ( i == 1 ) std::cout << "y "; else if ( i == 2 ) std::cout << "z "; std::cout << " is different by: " << std::setw(13) << std::setprecision(7) << std::fixed << t1[i] - t2[i] << " mm "; } } bool rerror(false); for (i=0; i < 9; i++) { // std::cout << "r1[" << i << "] = " << r1[i] // << " r2[" << i << "] = " << r2[i] << std::endl; if ( std::fabs(r1[i] - r2[i]) > 0.0000001 ) rerror = true; } if ( rerror && !cerrorind[0] && !cerrorind[1] && !cerrorind[2] ) { std::cout << l1 << " "; } if ( rerror ) { for (i=0; i < 9; i++) { // std::cout << "r1[" << i << "] = " << r1[i] // << " r2[" << i << "] = " << r2[i] << std::endl; if ( std::fabs(r1[i] - r2[i]) > 0.0000001 ) { // std::cout << std::endl; std::cout << " index " << i << " of rotation matrix differs by " << std::setw(13) << std::setprecision(7) << std::fixed << r1[i] - r2[i]; } } std::cout << std::endl; } else if ( cerrorind[0] || cerrorind[1] || cerrorind[2]) { std::cout << std::endl; } // std::cout << "3================================" << std::endl; // std::cout << "["<<l1 <<"]"<< std::endl // << "["<<l2 <<"]"<< std::endl; // std::cout << "================================" << std::endl; // getline(f1, l1, ','); // getline(f2, l2, ','); // if ( f1.peek() != 10 ) { // std::cout << "not eol on f1 doing an extra getline()" << std::endl; // getline(f1,ts); // std::cout << "why this is left?" << ts << std::endl; // } // if ( f2.peek() != 10 ) { // std::cout << "not eol on f2 doing an extra getline()" << std::endl; // getline(f2,ts); // std::cout << "why this is left?" << ts << std::endl; // } } return 0; }
antonmedv/year
packages/2018/07/06/index.js
<reponame>antonmedv/year module.exports = new Date(2018, 6, 6)
chessbot108/solved-problems
codes/algorithms/dijkstra's.cpp
<gh_stars>1-10 #include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #include <ctime> #include <cmath> #include <cassert> #include <algorithm> #include <vector> #include <string> #include <map> #include <set> #include <sstream> #include <list> #include <queue> #include <stack> //#include <unordered_map> //#include <unordered_set> #include <functional> #define max_v 1100 #define LOGN 50 #define int_max 0x3f3f3f3f #define cont continue #define byte_max 0x3f #define pow_2(n) (1 << (n)) //tree #define lsb(n) ((n)&(-(n))) #define LC(n) (((n) << 1) + 1) #define RC(n) (((n) << 1) + 2) #define LOG2(n) ((int)(ceil(log2((n))))) using namespace std; void setIO(const string& file_name){ freopen((file_name+".in").c_str(), "r", stdin); freopen((file_name+".out").c_str(), "w+", stdout); } struct node{ int key, dist; node(){} node(int a, int b){ key = a, dist = b; } bool operator < (const node& b) const{ return dist > b.dist; } }; list<pair<int, int> > arr[max_v]; priority_queue<node> pq; int dist[max_v], n, m; int main(){ scanf("%d%d" &n, &m); for(int i = 0; i<m; i++){ int a, b, c; //u, v, weight scanf("%d%d%d", &a, &b, &c); arr[a].push_back(make_pair(b, c)); arr[b].push_back(make_pair(a, c)); } return 0; }
Colorado-School-of-Mines-Robotics-Club/SpaceGrantMachineVision
Code/source/logger/Logger.py
<reponame>Colorado-School-of-Mines-Robotics-Club/SpaceGrantMachineVision import signal from datetime import datetime from multiprocessing import Queue, Process from time import sleep class Logger: logThread = None shouldThreadJoin = False buffer = Queue() logToConsole = True logToFile = False filepath = "" @classmethod def setLogToConsole(cls, enable: bool): """ Tells the Logger whether to print to the console Args: enable (boolean): Whether to print to the console """ cls.buffer.put(("logToConsole", enable)) @classmethod def openFile(cls, filepath: str): """ Confirms that the file can be opened and prints an opening message Args: filepath (str): The file that the log should be written to """ if filepath == "": cls.buffer.put(("logToFile", False)) return try: file = open(filepath, "a") file.write("\n\nStarting log at [" + datetime.now().strftime("%H:%M:%S") + "]\n") file.close() cls.buffer.put(("filepath", filepath)) cls.buffer.put(("logToFile", True)) except IOError: print("ERROR: unable to log to file at: " + filepath) cls.buffer.put(("logToFile", False)) @classmethod def close(cls): """ DO NOT DIRECTLY CALL - If logger is open, output a closing message to the file """ if cls.logToFile: try: file = open(cls.filepath, "a") file.write("Closing log at [" + datetime.now().strftime("%H:%M:%S") + "]\n\n\n") file.close() except IOError: return @classmethod def log(cls, message): """ Adds the message to the buffer, then the logger thread logs the provided string to the console and/or file as configured Args: message (str/Exception): The message to be output to the console and/or file """ # enables .log to handle Exception types directly if isinstance(message, Exception): cls.buffer.put(repr(message)) elif isinstance(message, str): cls.buffer.put(message) else: cls.buffer.put("ERROR: Cannot log message of type " + str(type(message))) @classmethod def init(cls, filepath=""): """ Start the logger thread, will log to file if specified """ cls.buffer = Queue() cls.buffer.put(("shouldThreadJoin", False)) cls.filepath = filepath Logger.openFile(filepath) cls.logThread = Process(target=Logger.runLogThread, args=(cls.buffer,), daemon=True) cls.logThread.start() return @classmethod def shutdown(cls): """Stops the logger thread """ cls.buffer.put(("shouldThreadJoin", True)) if cls.logThread.is_alive(): cls.logThread.join() @classmethod def handle_sigint_signal(cls, sig, frame): cls.shouldThreadJoin = True cls.buffer.put("Logger received SIGINT signal!") return @classmethod def handle_sigterm_signal(cls, sig, frame): cls.shouldThreadJoin = True cls.buffer.put("Logger received SIGTERM signal!") return @classmethod def runLogThread(cls, buffer: Queue): """Function used by the logger thread Args: buffer (Queue): queue for putting the messages when using .log method """ cls.buffer = buffer signal.signal(signal.SIGINT, Logger.handle_sigint_signal) signal.signal(signal.SIGTERM, Logger.handle_sigterm_signal) while True: while not cls.buffer.empty(): val = cls.buffer.get() if isinstance(val, str): finalMessage = f'[{datetime.now().strftime("%H:%M:%S")}] {val}\n' if cls.logToConsole: print(finalMessage, end="") if cls.logToFile: # and toFile: try: file = open(cls.filepath, "a") file.write(finalMessage) file.close() except IOError: return elif isinstance(val, tuple): try: logSetting = True if val[0] == "logToConsole": assert isinstance(val[1], bool) cls.logToConsole = val[1] elif val[0] == "logToFile": assert isinstance(val[1], bool) cls.logToFile = val[1] elif val[0] == "filepath": assert isinstance(val[1], str) cls.filepath = val[1] elif val[0] == "shouldThreadJoin": assert isinstance(val[1], bool) cls.shouldThreadJoin = val[1] logSetting = False else: cls.buffer.put(f'Unknown setting <{val[0]}> with value <{str(val[1])}') logSetting = False if logSetting: cls.buffer.put(f'Logger setting <{val[0]}> is now <{str(val[1])}>') except AssertionError: cls.buffer.put(f'Unknown setting <{str(val[0])}> with value <{str(val[1])}') else: cls.buffer.put(f'Invalid logger command of type <{type(val)}>') if cls.shouldThreadJoin: #and cls.buffer.empty(): break sleep(0.1) Logger.close()
Ludaxord/ConceptEngine
ConceptEngine/ConceptEngine/Concept-Engine/Graphics/Main/Managers/CEPlaygroundManager.h
<reponame>Ludaxord/ConceptEngine<filename>ConceptEngine/ConceptEngine/Concept-Engine/Graphics/Main/Managers/CEPlaygroundManager.h #pragma once #include "../../../Core/Common/CEManager.h" namespace ConceptEngine::Graphics::Main::Managers { class CEPlaygroundManager : public Core::Common::CEManager { public: CEPlaygroundManager(); ~CEPlaygroundManager() override; protected: private: }; }
atul-vyshnav/2021_IBM_Code_Challenge_StockIT
src/StockIT-v2-release_source_from_JADX/sources/com/google/android/gms/internal/ads/zzcwz.java
<filename>src/StockIT-v2-release_source_from_JADX/sources/com/google/android/gms/internal/ads/zzcwz.java package com.google.android.gms.internal.ads; /* compiled from: com.google.android.gms:play-services-ads@@19.4.0 */ public final class zzcwz implements zzeoy<zzcxa> { private final zzeph<zzbyf> zzfbh; private final zzeph<zzbvh> zzfch; private final zzeph<zzbuc> zzfcn; private final zzeph<zzbuu> zzfcx; private final zzeph<zzbvr> zzfdf; private final zzeph<zzbwa> zzfdj; private final zzeph<zzcau> zzfdo; private final zzeph<zzbxy> zzfdr; private final zzeph<zzbuk> zzfdy; private final zzeph<zzcal> zzgqj; public zzcwz(zzeph<zzbuc> zzeph, zzeph<zzbuu> zzeph2, zzeph<zzbvh> zzeph3, zzeph<zzbvr> zzeph4, zzeph<zzbuk> zzeph5, zzeph<zzbyf> zzeph6, zzeph<zzcau> zzeph7, zzeph<zzbwa> zzeph8, zzeph<zzcal> zzeph9, zzeph<zzbxy> zzeph10) { this.zzfcn = zzeph; this.zzfcx = zzeph2; this.zzfch = zzeph3; this.zzfdf = zzeph4; this.zzfdy = zzeph5; this.zzfbh = zzeph6; this.zzfdo = zzeph7; this.zzfdj = zzeph8; this.zzgqj = zzeph9; this.zzfdr = zzeph10; } public final /* synthetic */ Object get() { return new zzcxa(this.zzfcn.get(), this.zzfcx.get(), this.zzfch.get(), this.zzfdf.get(), this.zzfdy.get(), this.zzfbh.get(), this.zzfdo.get(), this.zzfdj.get(), this.zzgqj.get(), this.zzfdr.get()); } }
efurze/dicefire
public/js/app/ai/human.js
<gh_stars>0 if (typeof module !== 'undefined' && module.exports) { var Globals = require('../globals.js'); var window = {}; } var AI = AI || {}; AI.Human = function (id){ }; // Factory method. Called when the AI is first started. Tells the AI its player number // and the list of other players, so it can know who is human and where // in the turn order this AI shows up. AI.Human.create = function(playerId, isHumanList) { return new AI.Human(playerId); }; AI.Human.getName = function() {return "human";}; // Called each time the AI has a turn. AI.Human.prototype.startTurn = function(interface) { }; if (typeof module !== 'undefined' && module.exports) { module.exports = AI.Human; }
alphagov-mirror/paas-cf
tools/metrics/gauges_uaa_test.go
<reponame>alphagov-mirror/paas-cf<filename>tools/metrics/gauges_uaa_test.go package main import ( "time" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" . "github.com/onsi/gomega/gstruct" uaaclient "github.com/cloudfoundry-community/go-uaa" m "github.com/alphagov/paas-cf/tools/metrics/pkg/metrics" ) var _ = Describe("UAA", func() { MinusOneDay := -1 * 24 * time.Hour OneDayAgo := time.Now().Add(MinusOneDay) ThirtyOneDaysAgo := time.Now().Add(MinusOneDay * 31) Context("Users Aggregation", func() { It("Should aggregate users correctly for no users", func() { gauges := UAAUsersByOriginGauges([]uaaclient.User{}) Expect(gauges).To(HaveLen(0)) }) It("Should aggregate users correctly for a UAA user", func() { gauges := UAAUsersByOriginGauges([]uaaclient.User{ {Origin: "uaa"}, }) Expect(gauges).To(HaveLen(1)) Expect(gauges).To(ContainElement( MatchFields(IgnoreExtras, Fields{ "Name": Equal("uaa.users"), "Unit": Equal("count"), "Kind": Equal(m.Gauge), "Value": BeNumerically("==", 1), "Tags": ContainElement(MatchFields(IgnoreExtras, Fields{ "Label": Equal("origin"), "Value": Equal("uaa"), })), }), )) }) It("Should aggregate users correctly for some UAA users", func() { gauges := UAAUsersByOriginGauges([]uaaclient.User{ {Origin: "uaa"}, {Origin: "uaa"}, {Origin: "google"}, {Origin: "microsoft"}, {Origin: "uaa"}, {Origin: "uaa"}, {Origin: "google"}, }) Expect(gauges).To(HaveLen(3)) Expect(gauges).To(ContainElement( MatchFields(IgnoreExtras, Fields{ "Name": Equal("uaa.users"), "Unit": Equal("count"), "Kind": Equal(m.Gauge), "Value": BeNumerically("==", 4), "Tags": ContainElement(MatchFields(IgnoreExtras, Fields{ "Label": Equal("origin"), "Value": Equal("uaa"), })), }), )) Expect(gauges).To(ContainElement( MatchFields(IgnoreExtras, Fields{ "Name": Equal("uaa.users"), "Unit": Equal("count"), "Kind": Equal(m.Gauge), "Value": BeNumerically("==", 2), "Tags": ContainElement(MatchFields(IgnoreExtras, Fields{ "Label": Equal("origin"), "Value": Equal("google"), })), }), )) Expect(gauges).To(ContainElement( MatchFields(IgnoreExtras, Fields{ "Name": Equal("uaa.users"), "Unit": Equal("count"), "Kind": Equal(m.Gauge), "Value": BeNumerically("==", 1), "Tags": ContainElement(MatchFields(IgnoreExtras, Fields{ "Label": Equal("origin"), "Value": Equal("microsoft"), })), }), )) }) }) Context("Active Users (logged in within 30 days)", func() { It("Should select active users", func() { activeUsers := []uaaclient.User{{ Origin: "uaa", LastLogonTime: int(OneDayAgo.Unix() * 1000), }} Expect(UAAActiveUsers(activeUsers)).To(HaveLen(1)) }) It("Should reject inactive users", func() { inactiveUsers := []uaaclient.User{{ Origin: "uaa", LastLogonTime: int(ThirtyOneDaysAgo.Unix() * 1000), }} Expect(UAAActiveUsers(inactiveUsers)).To(HaveLen(0)) }) It("Should select active and reject inactive users", func() { users := []uaaclient.User{{ Origin: "google", LastLogonTime: int(OneDayAgo.Unix() * 1000), }, { Origin: "uaa", LastLogonTime: int(ThirtyOneDaysAgo.Unix() * 1000), }} activeUsers := UAAActiveUsers(users) Expect(activeUsers).To(HaveLen(1)) Expect(activeUsers[0].Origin).To(Equal("google")) }) }) Context("Active Users Aggregation (logged in within 30 days)", func() { It("Should select active users as gauges", func() { users := []uaaclient.User{{ Origin: "uaa", LastLogonTime: int(OneDayAgo.Unix() * 1000), }} gauges := UAAActiveUsersByOriginGauges(users) Expect(gauges).To(HaveLen(1)) Expect(gauges).To(ContainElement( MatchFields(IgnoreExtras, Fields{ "Name": Equal("uaa.active.users"), "Unit": Equal("count"), "Kind": Equal(m.Gauge), "Value": BeNumerically("==", 1), "Tags": ContainElement(MatchFields(IgnoreExtras, Fields{ "Label": Equal("origin"), "Value": Equal("uaa"), })), }), )) }) It("Should reject inactive users as gauges", func() { users := []uaaclient.User{{ Origin: "uaa", LastLogonTime: int(ThirtyOneDaysAgo.Unix() * 1000), }} gauges := UAAActiveUsersByOriginGauges(users) Expect(gauges).To(HaveLen(0)) }) It("Should select active and reject inactive users as gauges", func() { users := []uaaclient.User{{ Origin: "google", LastLogonTime: int(OneDayAgo.Unix() * 1000), }, { Origin: "uaa", LastLogonTime: int(ThirtyOneDaysAgo.Unix() * 1000), }} gauges := UAAActiveUsersByOriginGauges(users) Expect(gauges).To(HaveLen(1)) Expect(gauges).To(ContainElement( MatchFields(IgnoreExtras, Fields{ "Name": Equal("uaa.active.users"), "Unit": Equal("count"), "Kind": Equal(m.Gauge), "Value": BeNumerically("==", 1), "Tags": ContainElement(MatchFields(IgnoreExtras, Fields{ "Label": Equal("origin"), "Value": Equal("google"), })), }), )) }) It("Should select active and reject inactive users as gauges for many users", func() { users := []uaaclient.User{{ Origin: "google", LastLogonTime: int(OneDayAgo.Unix() * 1000), }, { Origin: "google", LastLogonTime: int(time.Now().Add(MinusOneDay*60).Unix() * 1000), }, { Origin: "microsoft", LastLogonTime: int(time.Now().Add(MinusOneDay*2).Unix() * 1000), }, { Origin: "microsoft", LastLogonTime: int(time.Now().Add(MinusOneDay*91).Unix() * 1000), }, { Origin: "uaa", LastLogonTime: int(time.Now().Add(MinusOneDay*2).Unix() * 1000), }, { Origin: "uaa", LastLogonTime: int(time.Now().Add(MinusOneDay*31).Unix() * 1000), }} gauges := UAAActiveUsersByOriginGauges(users) Expect(gauges).To(HaveLen(3)) Expect(gauges).To(ContainElement( MatchFields(IgnoreExtras, Fields{ "Name": Equal("uaa.active.users"), "Unit": Equal("count"), "Kind": Equal(m.Gauge), "Value": BeNumerically("==", 1), "Tags": ContainElement(MatchFields(IgnoreExtras, Fields{ "Label": Equal("origin"), "Value": Equal("google"), })), }), )) Expect(gauges).To(ContainElement( MatchFields(IgnoreExtras, Fields{ "Name": Equal("uaa.active.users"), "Unit": Equal("count"), "Kind": Equal(m.Gauge), "Value": BeNumerically("==", 1), "Tags": ContainElement(MatchFields(IgnoreExtras, Fields{ "Label": Equal("origin"), "Value": Equal("microsoft"), })), }), )) Expect(gauges).To(ContainElement( MatchFields(IgnoreExtras, Fields{ "Name": Equal("uaa.active.users"), "Unit": Equal("count"), "Kind": Equal(m.Gauge), "Value": BeNumerically("==", 1), "Tags": ContainElement(MatchFields(IgnoreExtras, Fields{ "Label": Equal("origin"), "Value": Equal("uaa"), })), }), )) }) }) })
JosuaKrause/JKanvas
src/main/java/jkanvas/nodelink/layout/LayoutedView.java
<reponame>JosuaKrause/JKanvas<gh_stars>1-10 package jkanvas.nodelink.layout; import java.awt.geom.RectangularShape; import jkanvas.animation.AnimatedPosition; import jkanvas.nodelink.NodeLinkView; /** * A layouted view. * * @author Joschi <<EMAIL>> * @param <T> The node position type. */ public interface LayoutedView<T extends AnimatedPosition> extends NodeLinkView<T> { /** * Setter. * * @param layouter The layouter. */ void setLayouter(AbstractLayouter<T> layouter); /** * Getter. * * @return The current layouter. */ AbstractLayouter<T> getLayouter(); /** * Getter. * * @param bbox The rectangle in which the bounding box will be stored. */ void getBoundingBox(RectangularShape bbox); }
mihaid-b/CyberSakura
Gathered CTF writeups/ptr-yudai-writeups/2019/picoCTF_2019/pwn/l1im1tl355/solve.py
from pwn import * print(0x80485c6) sock = process("./vuln") sock.recvline() sock.recvline() sock.sendline(str(0x80485c6)) sock.recvline() sock.recvline() sock.sendline(str(-5)) sock.interactive()
Kuanhao-Chao/multiStringTie
SuperReads_RNA/global-1/jellyfish/include/jellyfish/compare_and_swap.hpp
<filename>SuperReads_RNA/global-1/jellyfish/include/jellyfish/compare_and_swap.hpp /* This file is part of Jflib. Jflib 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. Jflib 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 Jflib. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _JFLIB_COMPARE_AND_SWAP_H_ #define _JFLIB_COMPARE_AND_SWAP_H_ #include <sys/types.h> #include <stdint.h> namespace jflib { // // Atomic load (get) and store (set). For now assume that the // // architecture does this based on the virtual key word (true for // // x86_64). TODO: improve on other architectures. // template<typename T> // T a_get(const T &x) { return *(volatile T*)&x; } // template<typename T, typename U> // T &a_set(T &lhs, const U &rhs) { // *(volatile T*)&lhs = rhs; // return lhs; // } // Numeric type of length rounded up to the size of a // word. Undefined, and raise a compilation error, if the length is // not a machine word size template<typename T, size_t n> union word_t; template<typename T> union word_t<T, 1> { typedef uint8_t w_t; T v; w_t w; }; template<typename T> union word_t<T, 2> { typedef uint16_t w_t; T v; w_t w; }; template<typename T> union word_t<T, 4> { typedef uint32_t w_t; T v; w_t w; }; template<typename T> union word_t<T, 8> { typedef uint64_t w_t; T v; w_t w; }; /** Type safe version of CAS. * @param [in] ptr Memory location. * @param [in] ov Presumed value at location. * @param [in] nv Value to write. * @param [out] cv Value at location at time of call. * @return true if CAS is successful. * * The CAS operation is successful if, at the time of call, ov is * equal to *ptr, the value at the memory location. In that case, nv * is written to *ptr, and when the call returns, cv == ov. * * If it fails, cv contains *ptr at the time of call. */ template<typename T> bool cas(T *ptr, const T &ov, const T &nv, T *cv) { typedef word_t<T, sizeof(T)> val_t; val_t _cv, _ov, _nv; _ov.v = ov; _nv.v = nv; _cv.w = __sync_val_compare_and_swap((typename val_t::w_t *)ptr, _ov.w, _nv.w); *cv = _cv.v; return _cv.w == _ov.w; } /** Type safe version of CAS. Identical to 4 argument version, * except does not return the previous value. */ template<typename T> bool cas(T *ptr, const T &ov, const T &nv) { T cv; return cas(ptr, ov, nv, &cv); } } #endif /* _JFLIB_COMPARE_AND_SWAP_H_ */
kgudel/hmda-platform
hmda/src/test/scala/hmda/model/filing/submissions/PaginatedResourceSpec.scala
<gh_stars>10-100 package hmda.model.filing.submissions import org.scalatest.{MustMatchers, WordSpec} class PaginatedResourceSpec extends WordSpec with MustMatchers { val resource = PaginatedResource(totalRecords = 44, offset = 3)(_) val resource2 = PaginatedResource(totalRecords = 44, offset = 0)(_) "Paginated Resource paginates offset collections" must { "first page contains index 0 thru (20 - offset)" in { val pageOne = resource(1) pageOne.fromIndex mustBe 0 pageOne.toIndex mustBe 17 } "second page contains next 20 results" in { val pageTwo = resource(2) pageTwo.fromIndex mustBe 17 pageTwo.toIndex mustBe 37 } "third page contains all remaining" in { val pageThree = resource(3) pageThree.fromIndex mustBe 37 pageThree.toIndex mustBe 44 } } "Paginated Resource paginates collections with no offset" must { "first page contains index 0 thru 20" in { val pageOne = resource2(1) pageOne.fromIndex mustBe 0 pageOne.toIndex mustBe 20 } "second page contains next 20 results" in { val pageTwo = resource2(2) pageTwo.fromIndex mustBe 20 pageTwo.toIndex mustBe 40 } "third page contains all remaining" in { val pageThree = resource2(3) pageThree.fromIndex mustBe 40 pageThree.toIndex mustBe 44 } } }
mevroy/reminders
yourwebproject/src/main/java/com/yourpackagename/yourwebproject/webapp/controller/GroupEventInviteRSVPsController.java
<gh_stars>0 /** * */ package com.yourpackagename.yourwebproject.webapp.controller; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import com.yourpackagename.commons.util.CommonUtils; import com.yourpackagename.framework.exception.auth.UserPermissionException; import com.yourpackagename.yourwebproject.actor.MailSenderUntypedActor; import com.yourpackagename.yourwebproject.common.CheckPermission; import com.yourpackagename.yourwebproject.common.EnableLogging; import com.yourpackagename.yourwebproject.model.entity.GroupContent; import com.yourpackagename.yourwebproject.model.entity.GroupDependents; import com.yourpackagename.yourwebproject.model.entity.GroupEmail; import com.yourpackagename.yourwebproject.model.entity.GroupEmailActivity; import com.yourpackagename.yourwebproject.model.entity.GroupEmailTemplate; import com.yourpackagename.yourwebproject.model.entity.GroupEventInvite; import com.yourpackagename.yourwebproject.model.entity.GroupEventInviteRSVP; import com.yourpackagename.yourwebproject.model.entity.GroupEventPass; import com.yourpackagename.yourwebproject.model.entity.GroupEventPassCategory; import com.yourpackagename.yourwebproject.model.entity.GroupEventPaymentTransaction; import com.yourpackagename.yourwebproject.model.entity.GroupEventPaymentType; import com.yourpackagename.yourwebproject.model.entity.GroupEvents; import com.yourpackagename.yourwebproject.model.entity.GroupMember; import com.yourpackagename.yourwebproject.model.entity.GroupSMS; import com.yourpackagename.yourwebproject.model.entity.Groups; import com.yourpackagename.yourwebproject.model.entity.enums.EmailActivity; import com.yourpackagename.yourwebproject.model.entity.enums.PaymentStatus; import com.yourpackagename.yourwebproject.model.entity.enums.Role; import com.yourpackagename.yourwebproject.service.GroupEmailActivityService; import com.yourpackagename.yourwebproject.service.GroupEmailTemplateService; import com.yourpackagename.yourwebproject.service.GroupEmailsService; import com.yourpackagename.yourwebproject.service.GroupEventInviteRSVPService; import com.yourpackagename.yourwebproject.service.GroupEventInviteService; import com.yourpackagename.yourwebproject.service.GroupEventPassCategoryService; import com.yourpackagename.yourwebproject.service.GroupEventPassesService; import com.yourpackagename.yourwebproject.service.GroupEventPaymentTransactionService; import com.yourpackagename.yourwebproject.service.GroupEventPaymentTypeService; import com.yourpackagename.yourwebproject.service.GroupEventsService; import com.yourpackagename.yourwebproject.service.GroupMembersService; import com.yourpackagename.yourwebproject.service.GroupSMSService; import com.yourpackagename.yourwebproject.service.GroupsService; /** * @author mdsouza * */ @Controller @EnableLogging(loggerClass = "GroupEventInviteRSVPsController") @CheckPermission(allowedRoles = { Role.SUPER_ADMIN, Role.ADMIN, Role.SUPER_USER, Role.USER, Role.ANONYMOUS }) public class GroupEventInviteRSVPsController extends BaseWebAppController { @Autowired private GroupEventInviteRSVPService groupEventInviteRSVPService; @Autowired private GroupEventInviteService groupEventInviteService; @Autowired private GroupEventsService groupEventsService; @Autowired private GroupEventPaymentTransactionService groupEventPaymentTransactionService; @Autowired private GroupEmailsService groupEmailsService; @Autowired private MailSenderUntypedActor mailSenderUntypedActor; @Autowired private GroupEmailTemplateService groupEmailTemplateService; @Autowired private GroupsService groupsService; @Autowired private GroupEmailActivityService groupEmailActivityService; @Autowired private GroupEventPassesService groupEventPassesService; @Autowired private GroupEventPassCategoryService groupEventPassCategoryService; @Autowired private GroupEventPaymentTypeService groupEventPaymentTypeService; @Autowired private GroupSMSService groupSMSService; @Autowired private GroupMembersService groupMembersService; private Logger log = LoggerFactory .getLogger(GroupEventInviteRSVPsController.class); @RequestMapping(value = "/completePayment", method = RequestMethod.POST) public String completePayment( Model model, @RequestParam(required = true) String eId, @RequestParam(required = false) Long pmtId, @ModelAttribute("groupEventPaymentTransaction") GroupEventPaymentTransaction groupEventPaymentTransaction, @PathVariable String groupCode) throws Exception { String referenceNumber = StringUtils.trim(groupEventPaymentTransaction .getUserReferenceNumber()); Groups group = groupsService.findByGroupCode(groupCode); GroupEventPaymentTransaction gepT = groupEventPaymentTransactionService .findById(groupEventPaymentTransaction.getTransactionId()); if((PaymentStatus.AWAITINGPMT.equals(gepT.getPaymentStatus()) && gepT.getTransactionExpiryDateTime().before( Calendar.getInstance().getTime())) || PaymentStatus.EXPIRED.equals(gepT.getPaymentStatus())) { model.addAttribute("popupModal", true); model.addAttribute("popupTitle", "Transaction Expired!"); model.addAttribute( "popupMessage", "Oops! Your update did not complete as this transaction has expired. Nothing to worry. Just do the same ticket selection as you did earlier and update the payment reference number!"); return this.buy(model, gepT.getGroupEventInvite() .getGroupEventInviteId(), "", "false", groupCode); } GroupEvents groupEventDB = groupEventsService.findByGroupEventCode(gepT .getGroupEventCode()); gepT.setUserReferenceNumber(referenceNumber); gepT.setUpdatedAt(Calendar.getInstance().getTime()); gepT.setTransactionDateTime(Calendar.getInstance().getTime()); gepT.setTransactionExpiryDateTime(new DateTime().plusHours(96).toDate()); gepT.setPaymentStatus(PaymentStatus.PROCESSINGPMT); if (pmtId > 0) { GroupEventPaymentType gep = groupEventPaymentTypeService .findById(pmtId); gepT.setGroupEventPaymentType(gep); } if (StringUtils.isNotBlank(referenceNumber)) { String body = "Payment Rcvd for :" + groupEventDB.getEventName() + "\n"; String user = (("Name:" + gepT.getGroupEventInvite().getGroupMember() .getFirstName() + " " + gepT.getGroupEventInvite() .getGroupMember().getLastName()).length() > 25) ? ("Name:" + gepT.getGroupEventInvite().getGroupMember() .getFirstName() + " " + gepT.getGroupEventInvite() .getGroupMember().getLastName()).substring(0, 25) : ("Name:" + gepT.getGroupEventInvite().getGroupMember() .getFirstName() + " " + gepT .getGroupEventInvite().getGroupMember() .getLastName()); user += "\nRef No:" + referenceNumber + "\n"; user += "Pmt Amount:" + gepT.getTransactionAmount() + "\n"; if (group != null && StringUtils.isNotBlank(group.getContactNumber())) { for (String phoneumber : CommonUtils.convertStringToList( group.getContactNumber(), ",")) { GroupSMS groupSMS = new GroupSMS(); groupSMS.setMobileNumber(phoneumber); groupSMS.setBody(body + user); groupSMS.setGroupCode(group.getGroupCode()); try { groupSMSService.insert(groupSMS); } catch (Exception e) { log.error("Error creating SMS to admin"); } } } if (groupEventDB.isAutoResponseForRSVPAllowed() && StringUtils.isNotBlank(groupEventDB .getAutoResponseRSVPTemplate())) { List<GroupEventPass> groupPasses = groupEventPassesService .findByTransaction(gepT); Map<String, Object> modelMap = new HashMap<String, Object>(); modelMap.put("groupMember", gepT.getGroupEventInvite() .getGroupMember()); modelMap.put("groupEventInvite", groupEventInviteService .findById(gepT.getGroupEventInvite() .getGroupEventInviteId())); modelMap.put("groupEvent", groupEventDB); modelMap.put("groupEmailTemplate", groupEmailTemplateService .findbyTemplateName(groupEventDB .getAutoResponseRSVPTemplate())); List<GroupEventInviteRSVP> tempList = groupEventInviteRSVPService .findByGroupEventInvite(groupEventPaymentTransaction .getGroupEventInvite()); if (tempList != null && tempList.size() > 0) { modelMap.put("groupEventInviteRSVP", tempList.get(0)); } modelMap.put("groupEventPaymentTransaction", gepT); modelMap.put("groupEventPasses", groupPasses); GroupEmail groupEmail = new GroupEmail(); try { groupEmail = groupEmailsService.createEmail(groupEmail, modelMap); gepT.setCorrespondenceDateTime(Calendar.getInstance() .getTime()); } catch (Exception e) { log.error("Unable to create Completion email"); } } gepT = groupEventPaymentTransactionService.update(gepT); } model.addAttribute("info", true); model.addAttribute( "infoMessage", "Your reference number <b>" + gepT.getUserReferenceNumber() + "</b> is now updated against your purchase transaction. Please allow 2 -3 business days for the funds to clear. You will receive an email update once the payment is cleared."); return this.buy(model, gepT.getGroupEventInvite() .getGroupEventInviteId(), "", "true", groupCode); // return "redirect:buy?eId=" // + gepT.getGroupEventInvite().getGroupEventInviteId(); } @RequestMapping(value = "/buy", method = RequestMethod.POST) public String doBuy(Model model, @RequestParam(required = true) String eId, @RequestParam(required = false) String transactionId, @ModelAttribute("groupEvent") GroupEvents groupEvent, @PathVariable String groupCode) throws Exception { if (StringUtils.isBlank(eId)) { return "Invitation ID is required to assign tickets"; } GroupEventInvite gei = groupEventInviteService.findById(eId); GroupEvents grpEventDB = groupEventsService.findByGroupEventCode(gei .getGroupEventCode()); if (groupEvent != null && CollectionUtils.isNotEmpty(groupEvent .getGroupEventPassCategories())) { double total = 0; int totalPasses = 0; for (GroupEventPassCategory gepc : groupEvent .getGroupEventPassCategories()) { total += (gepc.getNumberOfPasses() * gepc.getPassPrice()); totalPasses += gepc.getNumberOfPasses(); } GroupEventPaymentTransaction groupEventPaymentTransaction = new GroupEventPaymentTransaction(); groupEventPaymentTransaction.setTotalNumberOfProducts(totalPasses); groupEventPaymentTransaction.setTransactionAmount(total); groupEventPaymentTransaction.setTransactionDateTime(Calendar .getInstance().getTime()); if(grpEventDB.getTransactionExpiryInMinutes()>0) { groupEventPaymentTransaction .setTransactionExpiryDateTime(new DateTime().plusMinutes(grpEventDB.getTransactionExpiryInMinutes()) .toDate().after(grpEventDB.getEventDate()) ? grpEventDB .getEventDate() : new DateTime().plusMinutes(grpEventDB.getTransactionExpiryInMinutes()) .toDate()); } else { groupEventPaymentTransaction .setTransactionExpiryDateTime(grpEventDB .getEventDate()); } String userCode = StringUtils.isNotBlank(gei .getGroupEventInviteCode()) ? gei.getGroupEventInviteCode() : CommonUtils.generateRandomString(8, 8); groupEventPaymentTransaction.setUserCode(userCode); groupEventPaymentTransaction.setGroupEventCode(gei .getGroupEventCode()); groupEventPaymentTransaction.setGroupEventInvite(gei); groupEventPaymentTransaction.setUpdatedAt(Calendar.getInstance() .getTime()); groupEventPaymentTransaction .setPaymentStatus(PaymentStatus.AWAITINGPMT); if (StringUtils.isNotBlank(transactionId)) { GroupEventPaymentTransaction dbTransaction = groupEventPaymentTransactionService .findById(transactionId); groupEventPaymentTransaction.setTransactionId(transactionId); groupEventPaymentTransaction .setTransactionDateTime(dbTransaction .getTransactionDateTime()); groupEventPaymentTransaction .setTransactionExpiryDateTime(dbTransaction .getTransactionExpiryDateTime()); groupEventPaymentTransaction .setCorrespondenceDateTime(dbTransaction .getCorrespondenceDateTime()); groupEventPaymentTransaction.setUserCode(dbTransaction .getUserCode()); groupEventPaymentTransaction .setPaymentStatus(dbTransaction.getPaymentStatus()); } try { if (StringUtils.isBlank(transactionId)) { groupEventPaymentTransaction = groupEventPaymentTransactionService .insertOrUpdate(groupEventPaymentTransaction); List<GroupEventPass> assignedPasses = groupEventPassesService .assignPassesToTransaction( groupEventPaymentTransaction, groupEvent.getGroupEventPassCategories()); if (CollectionUtils.isEmpty(assignedPasses)) { groupEventPaymentTransaction .setPaymentStatus(PaymentStatus.CANCELLED); groupEventPaymentTransaction .setErrorMessage("Not enough tickets available"); groupEventPaymentTransaction = groupEventPaymentTransactionService .insertOrUpdate(groupEventPaymentTransaction); log.error("No Tickets assigned as tickets info is not available for :" + groupEventPaymentTransaction .getGroupEventInvite().getGroupMember() .getFirstName() + " - MemID:" + groupEventPaymentTransaction .getGroupEventInvite().getGroupMember() .getMembershipIdentifier()); Groups grp = groupsService.findByGroupCode(gei .getGroupCode()); model.addAttribute("popupModal", true); model.addAttribute("popupTitle", "Not Enough Tickets"); model.addAttribute( "popupMessage", "Unfortunately someone just booked tickets online just before you did and we do not have enough passes to be assigned to you at this stage. Please reduce the number or contact us via email @ " + grp.getContactEmail()); return this.buy(model, gei.getGroupEventInviteId(), "Online Booking", "", gei.getGroupCode()); } else if (groupEventPaymentTransaction .getTransactionAmount() <= 0) { groupEventPaymentTransaction .setPaymentStatus(PaymentStatus.PROCESSINGPMT); groupEventPaymentTransaction = groupEventPaymentTransactionService .insertOrUpdate(groupEventPaymentTransaction); model.addAttribute("popupModal", true); model.addAttribute("popupTitle", "Hurray!"); model.addAttribute( "popupMessage", "Congratulations <b>" + gei.getGroupMember().getFirstName() + "</b>! You have successfully reserved your products. If these are passes for any MKC events, you will receive your passes via Email/SMS shortly. <div id='clock'></div>"); return this.buy(model, gei.getGroupEventInviteId(), "Online Booking", "", gei.getGroupCode()); } model.addAttribute("info", true); model.addAttribute( "infoMessage", "Excellent News <b>" + gei.getGroupMember().getFirstName() + "</b>! We have now reserved the products, for you, until <b>" + CommonUtils .printDateInHomeTimeZone(groupEventPaymentTransaction .getTransactionExpiryDateTime()) + "</b> after which this transaction expires. If you are purchasing passes for an event, please make sure to complete the payment before the expiry period to avoid disappointment. The total amount for this transaction is : <b>$ " + groupEventPaymentTransaction .getTransactionAmount() + "</b>. <div id='clock'></div>"); } else { groupEventPaymentTransaction = groupEventPaymentTransactionService .insertOrUpdate(groupEventPaymentTransaction); model.addAttribute("info", true); model.addAttribute( "infoMessage", "Welcome back <b>" + gei.getGroupMember().getFirstName() + "</b>! This transaction will expire at <b>" + CommonUtils .printDateInHomeTimeZone(groupEventPaymentTransaction .getTransactionExpiryDateTime()) + "</b>. If you are purchasing passes for an event, please make sure to complete the payment before the expiry period to avoid disappointment. The total amount for this transaction is : <b>$ " + groupEventPaymentTransaction .getTransactionAmount() + "</b>. <div id='clock'></div>"); } } catch (Exception e) { log.error("Error while creating a transaction record for user: " + gei.getGroupMember().getFirstName()); } model.addAttribute("groupEvent", grpEventDB); model.addAttribute("groupEventPaymentTransaction", groupEventPaymentTransaction); } return "paymentPage"; } @RequestMapping(value = { "/verifyPurchase", "/completePayment","/cancelTransaction" }, method = RequestMethod.GET) public String verifyReload(Locale locale, Model model, @RequestParam(required = true) String eId, @PathVariable String groupCode) throws Exception { return "redirect:buy?eId=" + eId; } @RequestMapping(value = { "/buyRegister" }, method = RequestMethod.GET) public String buyFromEvent(Locale locale, Model model, @RequestParam(required = true) String eventCode, @RequestParam(required = true) String serialNumber, @PathVariable String groupCode) throws Exception { try { if (StringUtils.isNotBlank(serialNumber) && StringUtils.isNotBlank(eventCode)) { GroupMember groupMember = groupMembersService .findById(serialNumber); GroupEvents ge = groupEventsService .findByGroupEventCode(eventCode); if (ge != null) { GroupEventInvite gei = groupEventInviteService .findByGroupMemberAndGroupEvent(groupMember, ge); if (gei != null) { return "redirect:buy?eId=" + gei.getGroupEventInviteId(); } } } } catch (Exception e) { log.error("Exception occured while finding member and event. Returning to register interest Page"); } return "redirect:registerInterest?serialumber=" + serialNumber; } @RequestMapping(value = "/verifyPurchase", method = RequestMethod.POST) public String proceedPayment(Locale locale, Model model, @ModelAttribute("groupEvent") GroupEvents groupEvent, @RequestParam(required = true) String eId, BindingResult results, @PathVariable String groupCode) throws Exception { model.addAttribute("groupEvent", groupEvent); if (StringUtils.isBlank(eId)) { return "Invitation ID is required to assign tickets"; } GroupEventInvite gei = groupEventInviteService.findById(eId); model.addAttribute("groupMember", gei.getGroupMember()); GroupEvents groupEventDB = groupEventsService.findByGroupEventCode(gei .getGroupEventCode()); String noPassMsg = "<br/>"; if (groupEvent != null) { double total = 0; int totalPasses = 0; boolean notEnoughPasses = false; int subtractFromTotalPasses = 0; for (GroupEventPassCategory gepc : groupEvent .getGroupEventPassCategories()) { if (gepc.getNumberOfPasses() > 0) { GroupEventPassCategory gepcDB = groupEventPassCategoryService .findById(gepc.getGroupEventPassCategoryId()); int maxPassesForEvent = gepcDB.getGroupEvent() .getMaxNumberOfPasses(); if (maxPassesForEvent > 0) { if (maxPassesForEvent - subtractFromTotalPasses <= 0) { gepcDB.getGroupEvent().setMaxNumberOfPasses(1); } else { gepcDB.getGroupEvent() .setMaxNumberOfPasses( maxPassesForEvent - subtractFromTotalPasses); } } int availablePasses = groupEventPassesService .checkAndReturnPassAvailability(gepcDB, (int) gepc.getNumberOfPasses()); /* * List<GroupEventPass> geps = groupEventPassesService . * findUnSoldTicketsByGroupCodeAndGroupEventCodeAndGroupEventPassCategory * ( gei.getGroupCode(), gei.getGroupEventCode(), gepc); */ if (availablePasses < gepc.getNumberOfPasses()) { notEnoughPasses = true; noPassMsg += "<b>" + gepcDB.getPassCategoryNameShort() + "</b> - Requested : " + gepc.getNumberOfPasses() + " ~ Available : " + (availablePasses<0?"0":availablePasses) + "<br/>"; } else { subtractFromTotalPasses += gepc.getNumberOfPasses(); } total += (gepc.getNumberOfPasses() * gepc.getPassPrice()); totalPasses += gepc.getNumberOfPasses(); // code to check if this is working or not } } if (notEnoughPasses) { model.addAttribute("popupModal", true); model.addAttribute("popupTitle", "Not Enough Tickets"); model.addAttribute( "popupMessage", "Unfortunately we do not have enough tickets to be assigned to you at this stage. " + noPassMsg); return this.buy(model, gei.getGroupEventInviteId(), "", "true", gei.getGroupCode()); } if (totalPasses <= 0) { model.addAttribute("error", true); model.addAttribute( "errorMessage", "Looks like you have not made a selection from the dropdowns below. If the dropdowns are disabled, then you may not be able to make the purchase online. Please contact us via email"); return this.buy(model, gei.getGroupEventInviteId(), "", "true", gei.getGroupCode()); } GroupEventPaymentTransaction gepT = new GroupEventPaymentTransaction(); gepT.setTotalNumberOfProducts(totalPasses); gepT.setTransactionAmount(total); gepT.setTransactionDateTime(Calendar.getInstance().getTime()); if(groupEventDB.getTransactionExpiryInMinutes()>0) { gepT.setTransactionExpiryDateTime(new DateTime().plusMinutes(groupEventDB.getTransactionExpiryInMinutes()) .toDate().after(groupEventDB.getEventDate()) ? groupEventDB .getEventDate() : new DateTime().plusMinutes(groupEventDB.getTransactionExpiryInMinutes()).toDate()); } else { gepT .setTransactionExpiryDateTime(groupEventDB .getEventDate()); } gepT.setGroupEventInvite(gei); gepT.setGroupEventCode(gei.getGroupEventCode()); String userCode = StringUtils.isNotBlank(gei .getGroupEventInviteCode()) ? gei.getGroupEventInviteCode() : CommonUtils.generateRandomString(8, 8); gepT.setUserCode(userCode); model.addAttribute("groupEventPaymentTransaction", gepT); } return "verifyPage"; /* * HashMap<String, Long> counter = new HashMap<String, Long>(); boolean * notEnoughTickets = false; String notEnoughTicketsMessage = * "Error! Not Enough Tickets to be assigned."; try { GroupEventInvite * gei = groupEventInviteService .findById(groupEventInviteId); * List<GroupEventPass> finalPassList = new ArrayList<GroupEventPass>(); * List<GroupEventPassCategory> gpcsRaw = groupEvent * .getGroupEventPassCategories(); HashMap<String, * GroupEventPassCategory> rawCategoriesMap = new HashMap<String, * GroupEventPassCategory>(); for (GroupEventPassCategory gcpR : * gpcsRaw) { if (!StringUtils * .equals(gcpR.getGroupEventPassCategoryId(), "0")) { long count = * gcpR.getNumberOfPasses(); if (rawCategoriesMap.containsKey(gcpR * .getGroupEventPassCategoryId())) { gcpR = rawCategoriesMap.get(gcpR * .getGroupEventPassCategoryId()); * gcpR.setNumberOfPasses(gcpR.getNumberOfPasses() + count); } * rawCategoriesMap.put(gcpR.getGroupEventPassCategoryId(), gcpR); } } * List<GroupEventPassCategory> gpcs = new * ArrayList<GroupEventPassCategory>(); * * for (Map.Entry<String, GroupEventPassCategory> entry : * rawCategoriesMap .entrySet()) { GroupEventPassCategory value = * entry.getValue(); gpcs.add(value); * * } * * if (CollectionUtils.isNotEmpty(gpcs)) { for (GroupEventPassCategory * gpcUser : gpcs) { if (gpcUser != null && !StringUtils.equals( * gpcUser.getGroupEventPassCategoryId(), "0")) * * { GroupEventPassCategory gpc = groupEventPassCategoryService * .findById(gpcUser.getGroupEventPassCategoryId()); * List<GroupEventPass> geps = groupEventPassesService * .findUnSoldTicketsByGroupCodeAndGroupEventCodeAndGroupEventPassCategory * ( groupCode, gei.getGroupEventCode(), gpc); if (geps != null && * geps.size() >= gpcUser.getNumberOfPasses()) { for (int a = 0; a < * gpcUser.getNumberOfPasses(); a++) { finalPassList.add(geps.get(a)); * * } Long currentCurrent = gpcUser.getNumberOfPasses(); if * (counter.containsKey(gpc .getPassCategoryNameShort())) { * currentCurrent = counter.get(gpc .getPassCategoryNameShort()) + * currentCurrent; * * } counter.put(gpc.getPassCategoryNameShort(), currentCurrent); * * } else { notEnoughTickets = true; notEnoughTicketsMessage = * notEnoughTicketsMessage + "<li>" + gpc.getPassCategoryNameShort() + * " - Requested:" + gpcUser.getNumberOfPasses() + ", Available:" + * geps.size() + "</li>"; * * } * * } } if (notEnoughTickets) { return notEnoughTicketsMessage; } } * * if (CollectionUtils.isEmpty(finalPassList)) { return * "Error! Looks like you haven't selected any tickets. Please try again!" * ; } for (GroupEventPass gep : finalPassList) { gep.setSold(true); * gep.setUpdatedAt(Calendar.getInstance().getTime()); * gep.setPassInvalidated(false); * gep.setSoldBy(this.getloggedInUser().getUserName()); * gep.setGroupEventInvite(gei); groupEventPassesService.update(gep); } * } catch (Exception e) { // TODO Auto-generated catch block * e.printStackTrace(); } * * String ticketingStatus = "success"; * * * return ticketingStatus; */ } @RequestMapping(value = "/buy", method = RequestMethod.GET) public String buy(Model model, @RequestParam(required = true) String eId, @RequestParam(required = false) String rsvpMessage, @RequestParam(required = false) String suppressPopUps, @PathVariable String groupCode) throws Exception { if (StringUtils.isBlank(rsvpMessage)) { rsvpMessage = "Online Booking"; } model.addAttribute("rsvpMessage", rsvpMessage); GroupEventInvite gei; try { gei = groupEventInviteService.findById(eId); if (gei == null) { // model.addAttribute("error", true); // model.addAttribute("errorMessage", // "Sorry! You do not have a valid invite to RSVP for this event."); // return "createRSVP"; throw new UserPermissionException( "Sorry! You do not have a valid invite to RSVP for this event."); } model.addAttribute("groupMember", gei.getGroupMember()); } catch (Exception ex) { model.addAttribute("error", true); model.addAttribute("errorMessage", "Sorry! You do not have a valid invite to RSVP for this event."); return "buy"; /* * throw new UserPermissionException( * "Sorry! You do not have a valid invite to RSVP for this event."); */ } Groups grp = groupsService.findByGroupCode(gei.getGroupCode()); if (!gei.isInviteDelivered()) { gei.setInviteDelivered(true); gei.setUpdatedAt(Calendar.getInstance().getTime()); groupEventInviteService.update(gei); } GroupEvents grpEvent = groupEventsService.findByGroupEventCode(gei .getGroupEventCode()); /* code to get the non expire transactions */ List<GroupEventPaymentTransaction> paymentTransactions = groupEventPaymentTransactionService .findByGroupEventInvite(gei, true); List<GroupEventPaymentTransaction> viewOnlyTransactions = new ArrayList<GroupEventPaymentTransaction>(); GroupEventPaymentTransaction activeTransaction = new GroupEventPaymentTransaction(); if (CollectionUtils.isNotEmpty(paymentTransactions)) { for (GroupEventPaymentTransaction transaction : paymentTransactions) { transaction = this.expireTransaction(transaction, false); if (!PaymentStatus.AWAITINGPMT.equals(transaction .getPaymentStatus())) { viewOnlyTransactions.add(transaction); } else { activeTransaction = transaction; } } } if (activeTransaction != null && StringUtils.isNotBlank(activeTransaction.getTransactionId())) { List<GroupEventPass> passesForTransaction = groupEventPassesService .findByTransaction(activeTransaction); if (CollectionUtils.isNotEmpty(passesForTransaction)) { HashMap<String, GroupEventPassCategory> purchasedPassCategories = new HashMap<String, GroupEventPassCategory>(); for (GroupEventPass groupEventPass : passesForTransaction) { if (purchasedPassCategories.containsKey(groupEventPass .getGroupEventPassCategory() .getGroupEventPassCategoryId())) { GroupEventPassCategory gep = purchasedPassCategories .get(groupEventPass.getGroupEventPassCategory() .getGroupEventPassCategoryId()); long count = gep.getNumberOfPasses(); gep.setNumberOfPasses(count + 1); purchasedPassCategories.put(groupEventPass .getGroupEventPassCategory() .getGroupEventPassCategoryId(), gep); } else { long count = 1; GroupEventPassCategory gepc = groupEventPass .getGroupEventPassCategory(); gepc.setNumberOfPasses(count); purchasedPassCategories.put(groupEventPass .getGroupEventPassCategory() .getGroupEventPassCategoryId(), gepc); } } if (purchasedPassCategories != null && !purchasedPassCategories.isEmpty()) { List<GroupEventPassCategory> list = new ArrayList<GroupEventPassCategory>(); for (Map.Entry<String, GroupEventPassCategory> entry : purchasedPassCategories .entrySet()) { list.add(entry.getValue()); } double total = 0; int totalPasses = 0; for (GroupEventPassCategory gepcl : list) { total += (gepcl.getNumberOfPasses() * gepcl .getPassPrice()); totalPasses += gepcl.getNumberOfPasses(); } activeTransaction.setTotalNumberOfProducts(totalPasses); activeTransaction.setTransactionAmount(total); grpEvent.setGroupEventPassCategories(list); model.addAttribute("cancelButton", true); model.addAttribute("groupEventPaymentTransaction", activeTransaction); model.addAttribute("groupEvent", grpEvent); model.addAttribute("popupModal", true); model.addAttribute("popupTitle", "Payment Required"); model.addAttribute( "popupMessage", "Our records indicate that you have a pending transaction of <b>$" + total + "</b> to be completed for your purchase. Please make a payment before <b>" + CommonUtils .printDateInHomeTimeZone(activeTransaction .getTransactionExpiryDateTime()) + "</b>. Thanks!"); return "verifyPage"; } } else { log.info("There is active transaction but no tickets assigned. So OK to proceed below i reckon."); } } model.addAttribute("paymentTransactions", paymentTransactions); List<GroupEventPass> passes = groupEventPassesService .findByGroupEventInvite(gei); GroupMember gm = gei.getGroupMember(); String[] memberTypes = new String[2]; memberTypes[0] = gm.getMemberCategoryCode(); String memberType = gm.isActiveMember() ? "ACTIVE" : "INACTIVE"; memberTypes[1] = memberType; HashMap<String, Integer> passCategorisation = new HashMap<String, Integer>(); if (CollectionUtils.isNotEmpty(passes)) { for (GroupEventPass pass : passes) { if (passCategorisation .containsKey(pass.getGroupEventPassCategory() .getPassCategoryNameShort())) { int count = passCategorisation.get(pass .getGroupEventPassCategory() .getPassCategoryNameShort()) + 1; passCategorisation.put(pass.getGroupEventPassCategory() .getPassCategoryNameShort(), count); } else { passCategorisation.put(pass.getGroupEventPassCategory() .getPassCategoryNameShort(), 1); } } } List<GroupEventPassCategory> passListForPurchase = groupEventPassCategoryService .findByGroupCodeAndGroupEventCodeForMemberType(groupCode, gei.getGroupEventCode(), false, true, memberTypes); if (passCategorisation != null) { for (GroupEventPassCategory gepc : passListForPurchase) { if (passCategorisation.containsKey(gepc .getPassCategoryNameShort())) { int count = passCategorisation.get(gepc .getPassCategoryNameShort()); int maxPurchasePerInvite = gepc.getMaxPurchasePerInvite(); if(maxPurchasePerInvite >=0){ int remainingBuyingPower = maxPurchasePerInvite - count; gepc.setMaxPurchasePerInvite(remainingBuyingPower > 0 ? remainingBuyingPower : 0);} } if (gepc.getNumberOfPasses() > 0) { long soldPassesForGEC = groupEventPassesService .findSoldTicketsByGroupCodeAndGroupEventCodeAndGroupEventPassCategory( groupCode, gei.getGroupEventCode(), gepc) .size(); int remainingEventCapacity = (int) gepc.getNumberOfPasses() - (int) soldPassesForGEC; if (remainingEventCapacity <= 0) { // Here disable purchase is true because event is maxed // out. gepc.setDisablePurchase(true); } } } } grpEvent.setGroupEventPassCategories(passListForPurchase); model.addAttribute("passListForPurchase", passListForPurchase); /* * List<GroupEventInviteRSVP> rsvpList = groupEventInviteRSVPService * .findByGroupEventInvite(gei); * * GroupEventInviteRSVP ger = new GroupEventInviteRSVP(); * * if (rsvpList != null && rsvpList.size() > 0) { ger = rsvpList.get(0); * model.addAttribute("info", true); model.addAttribute( "infoMessage", * "Our records indicate that you have already RSVP'd. " + * (!grpEvent.isPaidEvent() ? "No further action needed. " : "") + * (grpEvent.getRsvpDeadlineDate() != null && * grpEvent.getRsvpDeadlineDate().before( * Calendar.getInstance().getTime()) ? * "No further changes are allowed as the RSVP deadline date has crossed. " * : "")); } else { if (grpEvent.isPaidEvent()) { * model.addAttribute("info", true); model.addAttribute( "infoMessage", * "<b>How does it work?</b><br/><br/>Just provide us the count for the number of people attending in the below form and click SUBMIT. You will receive an email within a minute, detailing the total amount that needs to be paid along with payment instructions. Just follow the instructions in that email and you will receive your E-Tickets soon!" * ); } } * * ger.setGroupEventInvite(gei); */ if (grpEvent.getMaxNumberOfPasses() > 0) { // This has to be before RSVP deadline because otherwise, even after // the deadline it will show some tickets being available List<GroupEventPass> gep = groupEventPassesService .findSoldTicketsByGroupCodeAndGroupEventCode(groupCode, gei.getGroupEventCode()); int percentageTicketsSold = ((gep.size() * 100) / grpEvent .getMaxNumberOfPasses()); if (percentageTicketsSold > 50 && percentageTicketsSold < 100) { if (StringUtils.isBlank(suppressPopUps)) { model.addAttribute("error", true); model.addAttribute( "errorMessage", "Tickets are selling soon. Just " + (100 - percentageTicketsSold) + "% of the tickets are remaining. Act fast to avoid dissapointment."); } } if (gep != null && (grpEvent.getMaxNumberOfPasses() - gep.size() <= 0)) { model.addAttribute("disableButton", true); if (StringUtils.isBlank(suppressPopUps)) { model.addAttribute("popupModal", true); model.addAttribute("popupTitle", "Oops!"); model.addAttribute( "popupMessage", "Sorry! The tickets for this event are sold out at the moment. Contact us with further questions @ " + grp.getContactEmail()); } } } if (grpEvent.getRsvpDeadlineDate() != null && grpEvent.getRsvpDeadlineDate().before( Calendar.getInstance().getTime())) { model.addAttribute("disableButton", true); if (StringUtils.isBlank(suppressPopUps)) { model.addAttribute("popupModal", true); model.addAttribute("popupTitle", "Oops!"); model.addAttribute( "popupMessage", "Sorry! The booking deadline for this event has passed. If you still need tickets, please follow the instructions in your invite email or contact your event organiser. Contact us with further questions @ " + grp.getContactEmail()); } } /* * if (grpEvent.isPaidEvent() && * StringUtils.isNotBlank(gei.getTransactionReference()) && * "true".equalsIgnoreCase(ger.getRsvpOutcome())) { * model.addAttribute("disableButton", true); * model.addAttribute("popupModal", true); * model.addAttribute("popupTitle", "Status"); model.addAttribute( * "popupMessage", * "We have received your Transaction Reference Number - " + * gei.getTransactionReference().toUpperCase() + * " and are processing it. No further actions can be processed on this page at this time. Once your transaction is approved, this page will show the status of your payment (usually within 2 - 3 business days). If you need to purchase additional tickets, contact us with further details @ " * + grp.getContactEmail()); * * } */ /* * if (grpEvent.isPaidEvent() && gei.isTransactionApproved()) { * model.addAttribute("disableButton", true); * model.addAttribute("popupModal", true); * model.addAttribute("popupTitle", "Status"); model.addAttribute( * "popupMessage", * "Please note that we have received and approved your payment" + * (gei.getPaidAmount() > 0.0 ? " of $" + gei.getPaidAmount() : "") + * (StringUtils.isNotBlank(gei .getTransactionReference()) ? * " for transaction reference number - " + * gei.getTransactionReference() : "") + * ". You should be receiving your tickets soon. No further actions can be processed on this page at this time. If you need to purchase additional tickets, contact us with further details @ " * + grp.getContactEmail()); * * } * * model.addAttribute("groupEventInviteRSVP", ger); */ model.addAttribute("groupEvent", grpEvent); model.addAttribute("groupEventInvite", gei); model.addAttribute("groupEventPaymentTransaction", activeTransaction); return "buy"; } @RequestMapping(value = "/createRSVP", method = RequestMethod.GET) public String createRSVPRequest(Model model, @RequestParam(required = true) String groupEventInviteId, @RequestParam(required = false) String rsvpMessage, @PathVariable String groupCode) throws Exception { if (StringUtils.isBlank(rsvpMessage)) { rsvpMessage = "RSVP"; } model.addAttribute("rsvpMessage", rsvpMessage); GroupEventInvite gei; try { gei = groupEventInviteService.findById(groupEventInviteId); if (gei == null) { // model.addAttribute("error", true); // model.addAttribute("errorMessage", // "Sorry! You do not have a valid invite to RSVP for this event."); // return "createRSVP"; throw new UserPermissionException( "Sorry! You do not have a valid invite to RSVP for this event."); } } catch (Exception ex) { model.addAttribute("error", true); model.addAttribute("errorMessage", "Sorry! You do not have a valid invite to RSVP for this event."); return "createRSVP"; /* * throw new UserPermissionException( * "Sorry! You do not have a valid invite to RSVP for this event."); */ } Groups grp = groupsService.findByGroupCode(gei.getGroupCode()); if (!gei.isInviteDelivered()) { gei.setInviteDelivered(true); gei.setUpdatedAt(Calendar.getInstance().getTime()); groupEventInviteService.update(gei); } GroupEvents grpEvent = groupEventsService.findByGroupEventCode(gei .getGroupEventCode()); List<GroupEventInviteRSVP> rsvpList = groupEventInviteRSVPService .findByGroupEventInvite(gei); GroupEventInviteRSVP ger = new GroupEventInviteRSVP(); if (rsvpList != null && rsvpList.size() > 0) { ger = rsvpList.get(0); model.addAttribute("info", true); model.addAttribute( "infoMessage", "Our records indicate that you have already RSVP'd. " + (!grpEvent.isPaidEvent() ? "No further action needed. " : "") + (grpEvent.getRsvpDeadlineDate() != null && grpEvent.getRsvpDeadlineDate().before( Calendar.getInstance().getTime()) ? "No further changes are allowed as the RSVP deadline date has crossed. " : "")); } else { if (grpEvent.isPaidEvent()) { model.addAttribute("info", true); model.addAttribute( "infoMessage", "<b>How does it work?</b><br/><br/>Just provide us the count for the number of people attending in the below form and click SUBMIT. You will receive an email within a minute, detailing the total amount that needs to be paid along with payment instructions. Just follow the instructions in that email and you will receive your E-Tickets soon!"); } } ger.setGroupEventInvite(gei); if (grpEvent.getMaxNumberOfPasses() > 0) { // This has to be before RSVP deadline because otherwise, even after // the deadline it will show some tickets being available List<GroupEventPass> gep = groupEventPassesService .findSoldTicketsByGroupCodeAndGroupEventCode(groupCode, gei.getGroupEventCode()); int percentageTicketsSold = ((gep.size() * 100) / grpEvent .getMaxNumberOfPasses()); if (percentageTicketsSold > 50) { model.addAttribute("popupModal", true); model.addAttribute("popupTitle", "Hurry Up!"); model.addAttribute( "popupMessage", "Tickets are selling soon. Just " + (100 - percentageTicketsSold) + "% of the tickets are remaining. Act fast to avoid dissapointment."); } if (gep != null && (grpEvent.getMaxNumberOfPasses() - gep.size() <= 0)) { model.addAttribute("disableButton", true); model.addAttribute("popupModal", true); model.addAttribute("popupTitle", "Oops!"); model.addAttribute( "popupMessage", "Sorry! The tickets for this event are sold out at the moment. Contact us with further questions @ " + grp.getContactEmail()); } } if (grpEvent.getRsvpDeadlineDate() != null && grpEvent.getRsvpDeadlineDate().before( Calendar.getInstance().getTime())) { model.addAttribute("disableButton", true); if (rsvpList == null || (rsvpList != null && rsvpList.size() <= 0)) { model.addAttribute("popupModal", true); model.addAttribute("popupTitle", "Oops!"); model.addAttribute( "popupMessage", "Sorry! The RSVP deadline for this event has passed. If you still wish you RSVP, please follow the instructions in your invite email or contact your event organiser. Contact us with further questions @ " + grp.getContactEmail()); } } if (grpEvent.isPaidEvent() && StringUtils.isNotBlank(gei.getTransactionReference()) && "true".equalsIgnoreCase(ger.getRsvpOutcome())) { model.addAttribute("disableButton", true); model.addAttribute("popupModal", true); model.addAttribute("popupTitle", "Status"); model.addAttribute( "popupMessage", "We have received your Transaction Reference Number - " + gei.getTransactionReference().toUpperCase() + " and are processing it. No further actions can be processed on this page at this time. Once your transaction is approved, this page will show the status of your payment (usually within 2 - 3 business days). If you need to purchase additional tickets, contact us with further details @ " + grp.getContactEmail()); } if (grpEvent.isPaidEvent() && gei.isTransactionApproved()) { model.addAttribute("disableButton", true); model.addAttribute("popupModal", true); model.addAttribute("popupTitle", "Status"); model.addAttribute( "popupMessage", "Please note that we have received and approved your payment" + (gei.getPaidAmount() > 0.0 ? " of $" + gei.getPaidAmount() : "") + (StringUtils.isNotBlank(gei .getTransactionReference()) ? " for transaction reference number - " + gei.getTransactionReference() : "") + ". You should be receiving your tickets soon. No further actions can be processed on this page at this time. If you need to purchase additional tickets, contact us with further details @ " + grp.getContactEmail()); } model.addAttribute("groupEventInviteRSVP", ger); model.addAttribute("groupEvent", grpEvent); return "createRSVP"; } @RequestMapping(value = "/saveGroupEventInviteRSVP", method = RequestMethod.POST) public String saveGroupEventInviteRSVP( Model model, @ModelAttribute("groupEventInviteRSVP") GroupEventInviteRSVP groupEventInviteRSVP, @RequestParam(required = false) String rsvpMessage) throws Exception { GroupEventInvite groupEventInvite = groupEventInviteService .findById(groupEventInviteRSVP.getGroupEventInvite() .getGroupEventInviteId()); groupEventInvite.setRsvpd(true); groupEventInvite.setUpdatedAt(Calendar.getInstance().getTime()); /* * Setting the code that members can carry with them - Will have to be * moved from here to create Invite location as some people may not RSVP * but still turn up for the event * groupEventInvite.setGroupEventInviteCode(groupEventInvite * .getGroupEventInviteId().substring(0, 5).toUpperCase()); */ if (StringUtils.isNotBlank(groupEventInviteRSVP .getTransactionReference())) { groupEventInvite.setTransactionReference(groupEventInviteRSVP .getTransactionReference().toUpperCase()); } groupEventInviteRSVP.setMemberCategoryCode(groupEventInvite .getGroupMember().getMemberCategoryCode()); groupEventInviteRSVP.setGroupEventCode(groupEventInvite .getGroupEventCode()); groupEventInviteRSVP.setGroupCode(groupEventInvite.getGroupCode()); groupEventInviteRSVP.setRsvpDateTime(Calendar.getInstance().getTime()); groupEventInviteRSVP.setGroupMember(groupEventInvite.getGroupMember()); groupEventInviteRSVP.setRsvpd(true); groupEventInviteRSVP.setGroupEventInvite(groupEventInvite); GroupEventInviteRSVP geiR = groupEventInviteRSVPService .insert(groupEventInviteRSVP); groupEventInviteService.update(groupEventInvite); GroupEvents grpEvent = groupEventsService .findByGroupEventCode(groupEventInvite.getGroupEventCode()); Map<String, Object> modelMap = new HashMap<String, Object>(); if (grpEvent != null && grpEvent.isAutoResponseForRSVPAllowed() && !StringUtils.isBlank(grpEvent.getAutoResponseRSVPTemplate())) { GroupEmailTemplate gEmailTemplate = groupEmailTemplateService .findbyTemplateName(grpEvent.getAutoResponseRSVPTemplate()); if (gEmailTemplate != null) { GroupMember groupMember = groupEventInvite.getGroupMember(); modelMap.put("groupMember", groupMember); modelMap.put("groupEventInvite", groupEventInvite); modelMap.put("groupEvent", grpEvent); modelMap.put("groupEventInviteRSVP", geiR); GroupEmail groupEmail = new GroupEmail(); groupEmail.setEmailAddress(groupMember.getPrimaryEmail()); groupEmail.setBccEmailAddress(groupMember.getOtherEmail()); String ccEmail = ""; for (GroupDependents groupDependents : groupMember .getGroupDependents()) { if (StringUtils.isNotBlank(groupDependents.getEmail())) ccEmail += groupDependents.getEmail() + ","; } if (StringUtils.isNotBlank(ccEmail)) { ccEmail = ccEmail.substring(0, ccEmail.length() - 1); groupEmail.setCcEmailAddress(ccEmail); } groupEmail.setSubject(gEmailTemplate.getSubject()); groupEmail.setFromAlias(gEmailTemplate.getFromAlias()); groupEmail.setFromAliasPersonalString(gEmailTemplate .getFromAliasPersonalString()); groupEmail.setHtml(gEmailTemplate.isHtml()); groupEmail.setReplyToEmail(gEmailTemplate.getReplyToEmail()); groupEmail.setEmailAccountCode(gEmailTemplate .getEmailAccountCode()); /* * If there are any attachments, just add it to the email Object * now */ groupEmail.setAttachments(gEmailTemplate.getAttachments()); // groupEmail.setCreatedBy(jobCode); groupEmail.setCreatedAt(new Date()); /* set the body to Template name intermittently */ groupEmail.setBody(gEmailTemplate.getTemplateName()); groupEmail.setGroupMember(groupMember); groupEmail.setGroupEventInviteId(groupEventInvite .getGroupEventInviteId()); Date emailExpdate = grpEvent.getEventDate(); if (groupEventInvite.getInviteExpiryDate() != null && emailExpdate != null && emailExpdate.after(groupEventInvite .getInviteExpiryDate())) { emailExpdate = groupEventInvite.getInviteExpiryDate(); } groupEmail.setEmailExpirydate(emailExpdate); groupEmail.setEmailingDate(groupEventInvite .getInviteStartDate()); /* * Intermittently set the hold email to true so that Other * batches dont pick the email when the body is actually set as * the template name */ groupEmail.setEmailHeld(true); groupEmail .setExpressEmail(gEmailTemplate.isExpressEmail() && StringUtils.isBlank(gEmailTemplate .getAttachments())); GroupEmail newEmail = groupEmailsService.insert(groupEmail); GroupEmailActivity groupEmailActivity = new GroupEmailActivity(); groupEmailActivity.setEmailActivity(EmailActivity.CREATE); groupEmailActivity.setActivityTime(groupEmail.getCreatedAt()); groupEmailActivity.setActivityBy(groupMember.getFirstName() + " " + groupMember.getLastName()); groupEmailActivity.setGroupEmail(newEmail); groupEmailActivityService.insert(groupEmailActivity); modelMap.put("groupEmail", newEmail); newEmail.setBody(mailSenderUntypedActor.prepareEmailBody( gEmailTemplate.getTemplateName(), modelMap)); newEmail.setEmailHeld(groupEventInvite.isInviteHeld() || !groupMember.isPrimaryEmailVerified()); groupEmailsService.insertOrUpdate(newEmail); GroupEmailActivity groupEmailActivity2 = new GroupEmailActivity(); groupEmailActivity2.setEmailActivity(EmailActivity.UPDATE); groupEmailActivity2.setActivityTime(Calendar.getInstance() .getTime()); groupEmailActivity2.setActivityBy(groupMember.getFirstName() + " " + groupMember.getLastName()); groupEmailActivity2.setGroupEmail(newEmail); groupEmailActivityService.insert(groupEmailActivity2); } } model.addAttribute("groupEventInviteRSVP", geiR); model.addAttribute("groupEvent", grpEvent); model.addAttribute("success", true); model.addAttribute("rsvpMessage", rsvpMessage); if (grpEvent.isPaidEvent() && StringUtils.isNotBlank(geiR.getTransactionReference()) && "true".equalsIgnoreCase(geiR.getRsvpOutcome())) { model.addAttribute("disableButton", true); model.addAttribute( "successMessage", "You have successfully updated your Transaction Reference Number and no further updates will be allowed to this page. Once your transaction is approved, this page will show the status of your payment (usually within 2 - 3 business days)."); } else { model.addAttribute("successMessage", "You have successfully RSVP'd for this event. Thank you!"); } return "createRSVP"; } @RequestMapping(value = "/loadCustomInvitation", method = RequestMethod.GET) public String loadCustomInvitationContent(Model model, @RequestParam(required = false) String groupEventInviteId, @PathVariable String groupCode) throws Exception { if (StringUtils.isNotBlank(groupEventInviteId)) { try { GroupEventInvite gei = groupEventInviteService .findById(groupEventInviteId); model.addAttribute("groupEventInvite", gei); List<GroupEventInvite> geis = new ArrayList<GroupEventInvite>(); List<GroupEventInviteRSVP> grsvps = new ArrayList<GroupEventInviteRSVP>(); geis = groupEventInviteService.findByGroupCodeAndEventCode( gei.getGroupCode(), gei.getGroupEventCode()); for (GroupEventInvite geI : geis) { List<GroupEventInviteRSVP> tempList = groupEventInviteRSVPService .findByGroupEventInvite(geI); if (tempList != null && tempList.size() > 0) { if (StringUtils.isNotBlank(tempList.get(0) .getRsvpComments())) grsvps.add(tempList.get(0)); } } model.addAttribute("groupEventInviteRSVPs", grsvps); } catch (Exception nf) { log.error("Unable to Invite for Invite ID:" + groupEventInviteId); model.addAttribute("exception", "In-valid Invite"); return "error"; } } return "loadCustomInvite"; } public GroupEventPaymentTransaction expireTransaction( GroupEventPaymentTransaction groupEventPaymentTransaction, boolean ignoreReferenceNumber) { if (groupEventPaymentTransaction == null || PaymentStatus.EXPIRED.equals(groupEventPaymentTransaction .getPaymentStatus())) { log.error("Transaction is null or Already Marked Expired."); } else { if (!groupEventPaymentTransaction.isTransactionApproved() && ((groupEventPaymentTransaction .getTransactionExpiryDateTime() != null && groupEventPaymentTransaction .getTransactionExpiryDateTime().before( Calendar.getInstance().getTime()) && (PaymentStatus.AWAITINGPMT .equals(groupEventPaymentTransaction .getPaymentStatus()))))) { if (ignoreReferenceNumber || StringUtils.isBlank(groupEventPaymentTransaction .getUserReferenceNumber())) { groupEventPaymentTransaction .setPaymentStatus(PaymentStatus.EXPIRED); groupEventPaymentTransaction.setUpdatedAt(Calendar .getInstance().getTime()); List<GroupEventPass> groupPasses = groupEventPassesService .findByTransaction(groupEventPaymentTransaction); if (CollectionUtils.isNotEmpty(groupPasses)) { for (GroupEventPass pass : groupPasses) { groupEventPassesService.releaseGroupEventPass(pass); } } try { groupEventPaymentTransaction = groupEventPaymentTransactionService .update(groupEventPaymentTransaction); } catch (Exception e) { log.error("Error - Expiring the transaction failed"); } } } } return groupEventPaymentTransaction; } @RequestMapping(value = "/cancelTransaction", method = RequestMethod.POST) public String cancelTransaction(Model model, @RequestParam(required = false) String transactionId, @RequestParam(required = true) String eId, @PathVariable String groupCode, boolean ignoreReferenceNumber) throws Exception { if (StringUtils.isBlank(transactionId)) { String returnPage = this.buy(model, eId, "", "", groupCode); return returnPage; } GroupEventPaymentTransaction groupEventPaymentTransaction; try { groupEventPaymentTransaction = groupEventPaymentTransactionService .findById(transactionId); if (groupEventPaymentTransaction == null || PaymentStatus.CANCELLED .equals(groupEventPaymentTransaction .getPaymentStatus())) { log.error("Transaction is null or Already Marked Expired."); String nextP = this.buy(model, eId, "", "", groupCode); addError( "Your transaction is already marked as cancelled. Refresh this page view the status of your most recent transactions", model); return nextP; } else { if (PaymentStatus.APPROVED.equals(groupEventPaymentTransaction .getPaymentStatus()) || PaymentStatus.PROCESSED .equals(groupEventPaymentTransaction .getPaymentStatus())) { String nextP = this.buy(model, eId, "", "", groupCode); addError( "Your transaction is already Approved/Processed. You cannot cancel a Approved/Processed transaction! Refresh this page view the status of your most recent transactions", model); return nextP; } else if (ignoreReferenceNumber || StringUtils.isBlank(groupEventPaymentTransaction .getUserReferenceNumber())) { groupEventPaymentTransaction .setPaymentStatus(PaymentStatus.CANCELLED); groupEventPaymentTransaction.setUpdatedAt(Calendar .getInstance().getTime()); List<GroupEventPass> groupPasses = groupEventPassesService .findByTransaction(groupEventPaymentTransaction); if (CollectionUtils.isNotEmpty(groupPasses)) { for (GroupEventPass pass : groupPasses) { groupEventPassesService.releaseGroupEventPass(pass); } } try { groupEventPaymentTransaction = groupEventPaymentTransactionService .update(groupEventPaymentTransaction); } catch (Exception e) { log.error("Error - Expiring the transaction failed"); } } String nextPage = this.buy(model, eId, "", "", groupCode); addSuccess("Your transaction was successfully cancelled!", model); return nextPage; } } catch (Exception e1) { String page = this.buy(model, eId, "", "", groupCode); addError( "Error occured while updating your trasaction. If this problem persists, please contact your administrator!", model); return page; } } }
pysmell/git-practice
nettystudy/src/main/java/com/meiya/nettypackage3/NettyExample1.java
<filename>nettystudy/src/main/java/com/meiya/nettypackage3/NettyExample1.java package com.meiya.nettypackage3; /* * netty如何拦截和处理异常 * * client和server步骤 * 1、客户端连接到服务器 * 2、建立连接后,发送或接收数据 * 3、服务器处理所有的客户端连接 * * 客户端和服务端连接的例子 * 服务器会写数据到客户端并且处理多个客户端的并发连接。从理论上来说,限制程序性能的因素只有系统资源和JVM。为了 方便理解,这里举了个生活例子,在山谷或高山上大声喊,你会听见回声,回声是山返回的;在这个例子中,你是客户端,山是服务器。喊的行为就 类似于一个Netty客户端将数据发送到服务器,听到回声就类似于服务器将相同的数据返回给你,你离开山谷就断开了连接,但是你可以返回进行重连 服务器并且可以发送更多的数据。 * * */ public class NettyExample1 { }
semyont/datacollector
container/src/test/java/com/streamsets/datacollector/util/TestSystemProcess.java
<gh_stars>1-10 /** * Copyright 2015 StreamSets Inc. * * Licensed under the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.streamsets.datacollector.util; import com.google.common.base.Joiner; import com.google.common.collect.Iterables; import com.google.common.io.Files; import com.streamsets.pipeline.api.impl.Utils; import org.apache.commons.io.FileUtils; import org.junit.After; import org.junit.Assert; import org.junit.Assume; import org.junit.Before; import org.junit.Test; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.TimeUnit; public class TestSystemProcess { private File tempDir; private SystemProcessImpl process; @Before public void setup() throws Exception { tempDir = Files.createTempDir(); } @After public void tearDown() { if (process != null) { process.cleanup(); } if (tempDir != null) { FileUtils.deleteQuietly(tempDir); } } @Test public void testStart() throws Exception { process = new SystemProcessImpl("sleep", tempDir, Arrays. asList("/bin/sleep", "1.1")); process.start(); Assert.assertTrue(process.isAlive()); } @Test public void testKill() throws Exception { process = new SystemProcessImpl("sleep", tempDir, Arrays. asList("/bin/sleep", "3.1")); process.start(); long start = System.currentTimeMillis(); process.kill(5000); long elapsed = System.currentTimeMillis() - start; Assert.assertTrue("Expected elapsed time to be less than 3000: " + elapsed, elapsed < 3000); } @Test public void testForceKill() throws Exception { Assume.assumeFalse("Test only works on java 1.8 and newer, not: " + System.getProperty("java.version"), System.getProperty("java.version", "").contains("1.7")); Assume.assumeTrue("Test only works on linux, not: " + System.getProperty("os.name"), System.getProperty("os.name", "").trim().toLowerCase().contains("linux")); process = new SystemProcessImpl("sleep", tempDir, Arrays. asList("/bin/bash", "-c", "trap true 15; sleep 3.1")); process.start(); long start = System.currentTimeMillis(); process.kill(5000); long elapsed = System.currentTimeMillis() - start; Assert.assertTrue("Expected elapsed time to be less than 3000: " + elapsed, elapsed < 3000); } @Test public void testOutput() throws Exception { process = new SystemProcessImpl("output", tempDir, Arrays. asList("/bin/bash", "-c", "for i in {0..2}; do echo $i; done")); process.start(); while(process.isAlive()) { TimeUnit.MILLISECONDS.sleep(10); } String error = Joiner.on("\n").join(process.getAllError()); Assert.assertTrue(error, error.isEmpty()); List<String> lines = new ArrayList<>(); Iterables.addAll(lines, process.getOutput()); Assert.assertEquals(Arrays.asList("0", "1", "2"), lines); } @Test public void testError() throws Exception { process = new SystemProcessImpl("output", tempDir, Arrays. asList("/bin/bash", "-c", "for i in {0..2}; do echo $i 1>&2; done")); process.start(); while(process.isAlive()) { TimeUnit.MILLISECONDS.sleep(10); } String error = Joiner.on("\n").join(process.getAllOutput()); Assert.assertTrue(error, error.isEmpty()); List<String> lines = new ArrayList<>(); Iterables.addAll(lines, process.getError()); Assert.assertEquals(Arrays.asList("0", "1", "2"), lines); } @Test public void testCleanup() throws Exception { for (int i = 0; i < 10; i++) { File f = new File(tempDir, Utils.format("file-{}{}", i, SystemProcessImpl.OUT_EXT)); Assert.assertTrue(f.createNewFile()); } SystemProcessImpl.clean(tempDir, 5); String[] expected = tempDir.list(); Arrays.sort(expected); Assert.assertArrayEquals(new String[]{"file-5.out", "file-6.out", "file-7.out", "file-8.out", "file-9.out"}, expected); } }
jbb-project/jbb
tech-services/jbb-lib-properties/src/main/java/org/jbb/lib/properties/JbbPropertyFilesResolver.java
<gh_stars>1-10 /* * Copyright (C) 2018 the original author or authors. * * This file is part of jBB Application Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 */ package org.jbb.lib.properties; import com.google.common.collect.Sets; import java.util.Set; import lombok.RequiredArgsConstructor; import org.aeonbits.owner.Config; import org.apache.commons.lang3.Validate; import org.jbb.lib.commons.JbbMetaData; import org.springframework.stereotype.Component; @Component @RequiredArgsConstructor public class JbbPropertyFilesResolver { private static final String JBB_HOME_PREFIX = "file:${jbb.home}"; private final JbbMetaData metaData; private static boolean fileIsInJbbHome(String sourceRawString) { return sourceRawString.startsWith(JBB_HOME_PREFIX); } public Set<String> resolvePropertyFileNames(Class<? extends ModuleStaticProperties> clazz) { Validate.notNull(clazz, "Class cannot be null"); Set<String> result = Sets.newHashSet(); Config.Sources annotation = clazz.getAnnotation(Config.Sources.class); for (String sourceRawString : annotation.value()) { if (fileIsInJbbHome(sourceRawString)) { String resolvedFilePath = resolveFullPath(sourceRawString); result.add(resolvedFilePath); } } return result; } private String resolveFullPath(String sourceRawString) { return sourceRawString.replace(JBB_HOME_PREFIX, metaData.jbbHomePath()); } }
bhuwanupadhyay/old-is-gold
inventory/inventory-spring-boot/src/main/java/k8s/orderg/inventory/utils/MonoUtils.java
package k8s.orderg.inventory.utils; import lombok.experimental.UtilityClass; import reactor.core.publisher.Mono; import java.util.Optional; import java.util.function.Supplier; @SuppressWarnings("OptionalUsedAsFieldOrParameterType") @UtilityClass public class MonoUtils { public static <T> Mono<T> fromOptional(Optional<T> option) { return option.map(Mono::just).orElseGet(Mono::empty); } public static <T> Mono<T> fromOptional(Optional<T> option, Supplier<? extends Exception> errorSupplier) { return option.map(Mono::just).orElseGet(() -> Mono.error(errorSupplier.get())); } // public static <T> Mono<T> fromOptionalWithNotFoundException(Optional<T> option, String resourceName) { // return option. // map(Mono::just). // orElseGet(() -> Mono.error(new NotFoundResourceException(resourceName))); // } }
EnderNightLord-ChromeBook/fuchsia-pine64-pinephone
src/ui/input/drivers/hidctl/hidctl.cc
<reponame>EnderNightLord-ChromeBook/fuchsia-pine64-pinephone // Copyright 2017 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. #include "hidctl.h" #include <fuchsia/hardware/hidctl/c/fidl.h> #include <stdio.h> #include <string.h> #include <zircon/compiler.h> #include <memory> #include <utility> #include <ddk/binding.h> #include <ddk/debug.h> #include <ddk/driver.h> #include <ddk/platform-defs.h> #include <fbl/array.h> #include <fbl/auto_lock.h> #include <pretty/hexdump.h> namespace hidctl { zx_status_t HidCtl::Create(void* ctx, zx_device_t* parent) { auto dev = std::unique_ptr<HidCtl>(new HidCtl(parent)); zx_status_t status = dev->DdkAdd("hidctl"); if (status != ZX_OK) { zxlogf(ERROR, "%s: could not add device: %d", __func__, status); } else { // devmgr owns the memory now __UNUSED auto* ptr = dev.release(); } return status; } zx_status_t HidCtl::FidlMakeHidDevice(void* ctx, const fuchsia_hardware_hidctl_HidCtlConfig* config, const uint8_t* rpt_desc_data, size_t rpt_desc_count, fidl_txn_t* txn) { HidCtl* hidctl = static_cast<HidCtl*>(ctx); // Create the sockets for Sending/Recieving fake HID reports. zx::socket local, remote; zx_status_t status = zx::socket::create(ZX_SOCKET_DATAGRAM, &local, &remote); if (status != ZX_OK) { return status; } // Create the fake HID device. uint8_t* report_desc_data = new uint8_t[rpt_desc_count]; memcpy(report_desc_data, rpt_desc_data, rpt_desc_count); fbl::Array<const uint8_t> report_desc(report_desc_data, rpt_desc_count); auto hiddev = std::unique_ptr<hidctl::HidDevice>( new hidctl::HidDevice(hidctl->zxdev(), config, std::move(report_desc), std::move(local))); status = hiddev->DdkAdd("hidctl-dev"); if (status != ZX_OK) { zxlogf(ERROR, "hidctl: could not add hid device: %d", status); return status; } // The device thread will be created in DdkInit. zxlogf(INFO, "hidctl: created hid device"); // devmgr owns the memory until release is called __UNUSED auto ptr = hiddev.release(); zx_handle_t report_socket = remote.release(); return fuchsia_hardware_hidctl_DeviceMakeHidDevice_reply(txn, report_socket); } zx_status_t HidCtl::DdkMessage(fidl_incoming_msg_t* msg, fidl_txn_t* txn) { static const fuchsia_hardware_hidctl_Device_ops_t kOps = { .MakeHidDevice = HidCtl::FidlMakeHidDevice, }; return fuchsia_hardware_hidctl_Device_dispatch(this, txn, msg, &kOps); } HidCtl::HidCtl(zx_device_t* device) : ddk::Device<HidCtl, ddk::Messageable>(device) {} void HidCtl::DdkRelease() { delete this; } int hid_device_thread(void* arg) { HidDevice* device = reinterpret_cast<HidDevice*>(arg); return device->Thread(); } #define HID_SHUTDOWN ZX_USER_SIGNAL_7 HidDevice::HidDevice(zx_device_t* device, const fuchsia_hardware_hidctl_HidCtlConfig* config, fbl::Array<const uint8_t> report_desc, zx::socket data) : ddk::Device<HidDevice, ddk::Initializable, ddk::Unbindable>(device), boot_device_(config->boot_device), dev_class_(config->dev_class), report_desc_(std::move(report_desc)), data_(std::move(data)) { ZX_DEBUG_ASSERT(data_.is_valid()); } void HidDevice::DdkInit(ddk::InitTxn txn) { int ret = thrd_create_with_name(&thread_, hid_device_thread, reinterpret_cast<void*>(this), "hidctl-thread"); ZX_DEBUG_ASSERT(ret == thrd_success); txn.Reply(ZX_OK); } void HidDevice::DdkRelease() { zxlogf(DEBUG, "hidctl: DdkRelease"); int ret = thrd_join(thread_, nullptr); ZX_DEBUG_ASSERT(ret == thrd_success); delete this; } void HidDevice::DdkUnbind(ddk::UnbindTxn txn) { zxlogf(DEBUG, "hidctl: DdkUnbind"); fbl::AutoLock lock(&lock_); if (data_.is_valid()) { // Prevent further writes to the socket zx_status_t status = data_.shutdown(ZX_SOCKET_SHUTDOWN_READ); ZX_DEBUG_ASSERT(status == ZX_OK); // Signal the thread to shutdown status = data_.signal(0, HID_SHUTDOWN); ZX_DEBUG_ASSERT(status == ZX_OK); // The thread will reply to the unbind txn when it exits the loop. unbind_txn_ = std::move(txn); } else { // The thread has already shut down, can reply immediately. txn.Reply(); } } zx_status_t HidDevice::HidbusQuery(uint32_t options, hid_info_t* info) { zxlogf(DEBUG, "hidctl: query"); info->dev_num = 0; info->device_class = dev_class_; info->boot_device = boot_device_; return ZX_OK; } zx_status_t HidDevice::HidbusStart(const hidbus_ifc_protocol_t* ifc) { zxlogf(DEBUG, "hidctl: start"); fbl::AutoLock lock(&lock_); if (client_.is_valid()) { return ZX_ERR_ALREADY_BOUND; } client_ = ddk::HidbusIfcProtocolClient(ifc); return ZX_OK; } void HidDevice::HidbusStop() { zxlogf(DEBUG, "hidctl: stop"); fbl::AutoLock lock(&lock_); client_.clear(); } zx_status_t HidDevice::HidbusGetDescriptor(hid_description_type_t desc_type, void* out_data_buffer, size_t data_size, size_t* out_data_actual) { zxlogf(DEBUG, "hidctl: get descriptor %u", desc_type); if (out_data_buffer == nullptr || out_data_actual == nullptr) { return ZX_ERR_INVALID_ARGS; } if (desc_type != HID_DESCRIPTION_TYPE_REPORT) { return ZX_ERR_NOT_FOUND; } if (data_size < report_desc_.size()) { return ZX_ERR_BUFFER_TOO_SMALL; } memcpy(out_data_buffer, report_desc_.data(), report_desc_.size()); *out_data_actual = report_desc_.size(); return ZX_OK; } zx_status_t HidDevice::HidbusGetReport(uint8_t rpt_type, uint8_t rpt_id, void* data, size_t len, size_t* out_len) { zxlogf(DEBUG, "hidctl: get report type=%u id=%u", rpt_type, rpt_id); if (out_len == nullptr) { return ZX_ERR_INVALID_ARGS; } // TODO: send get report message over socket return ZX_ERR_NOT_SUPPORTED; } zx_status_t HidDevice::HidbusSetReport(uint8_t rpt_type, uint8_t rpt_id, const void* data, size_t len) { zxlogf(DEBUG, "hidctl: set report type=%u id=%u", rpt_type, rpt_id); // TODO: send set report message over socket return ZX_ERR_NOT_SUPPORTED; } zx_status_t HidDevice::HidbusGetIdle(uint8_t rpt_id, uint8_t* duration) { zxlogf(DEBUG, "hidctl: get idle"); // TODO: send get idle message over socket return ZX_ERR_NOT_SUPPORTED; } zx_status_t HidDevice::HidbusSetIdle(uint8_t rpt_id, uint8_t duration) { zxlogf(DEBUG, "hidctl: set idle"); // TODO: send set idle message over socket return ZX_OK; } zx_status_t HidDevice::HidbusGetProtocol(uint8_t* protocol) { zxlogf(DEBUG, "hidctl: get protocol"); // TODO: send get protocol message over socket return ZX_ERR_NOT_SUPPORTED; } zx_status_t HidDevice::HidbusSetProtocol(uint8_t protocol) { zxlogf(DEBUG, "hidctl: set protocol"); // TODO: send set protocol message over socket return ZX_OK; } int HidDevice::Thread() { zxlogf(DEBUG, "hidctl: starting main thread"); zx_signals_t pending; std::unique_ptr<uint8_t[]> buf(new uint8_t[mtu_]); zx_status_t status = ZX_OK; const zx_signals_t wait = ZX_SOCKET_READABLE | ZX_SOCKET_PEER_CLOSED | HID_SHUTDOWN; while (true) { status = data_.wait_one(wait, zx::time::infinite(), &pending); if (status != ZX_OK) { zxlogf(ERROR, "hidctl: error waiting on data: %d", status); break; } if (pending & ZX_SOCKET_READABLE) { status = Recv(buf.get(), mtu_); if (status != ZX_OK) { break; } } if (pending & ZX_SOCKET_PEER_CLOSED) { zxlogf(DEBUG, "hidctl: socket closed (peer)"); break; } if (pending & HID_SHUTDOWN) { zxlogf(DEBUG, "hidctl: socket closed (self)"); break; } } zxlogf(INFO, "hidctl: device destroyed"); { fbl::AutoLock lock(&lock_); data_.reset(); // Check if the device has a pending unbind txn to reply to. if (unbind_txn_) { unbind_txn_->Reply(); } else { // Request the device unbinding process to begin. DdkAsyncRemove(); } } return static_cast<int>(status); } zx_status_t HidDevice::Recv(uint8_t* buffer, uint32_t capacity) { size_t actual = 0; zx_status_t status = ZX_OK; // Read all the datagrams out of the socket. while (status == ZX_OK) { status = data_.read(0u, buffer, capacity, &actual); if (status == ZX_ERR_SHOULD_WAIT || status == ZX_ERR_PEER_CLOSED) { break; } if (status != ZX_OK) { zxlogf(ERROR, "hidctl: error reading data: %d", status); return status; } fbl::AutoLock lock(&lock_); if (unlikely(zxlog_level_enabled(DEBUG))) { zxlogf(DEBUG, "hidctl: received %zu bytes", actual); hexdump8_ex(buffer, actual, 0); } if (client_.is_valid()) { client_.IoQueue(buffer, actual, zx_clock_get_monotonic()); } } return ZX_OK; } static constexpr zx_driver_ops_t driver_ops = []() { zx_driver_ops_t ops = {}; ops.version = DRIVER_OPS_VERSION; ops.bind = HidCtl::Create; return ops; }(); } // namespace hidctl // clang-format off ZIRCON_DRIVER_BEGIN(hidctl, hidctl::driver_ops, "zircon", "0.1", 3) BI_ABORT_IF(NE, BIND_PLATFORM_DEV_VID, PDEV_VID_TEST), BI_ABORT_IF(NE, BIND_PLATFORM_DEV_PID, PDEV_PID_HIDCTL_TEST), BI_MATCH() ZIRCON_DRIVER_END(hidctl) // clang-format on
jippo015/Sub-Zero.bundle
Contents/Libraries/Shared/pysubs2/txt_generic.py
<filename>Contents/Libraries/Shared/pysubs2/txt_generic.py # coding=utf-8 from __future__ import print_function, division, unicode_literals import re from numbers import Number from pysubs2.time import times_to_ms from .formatbase import FormatBase from .ssaevent import SSAEvent from .ssastyle import SSAStyle # thanks to http://otsaloma.io/gaupol/doc/api/aeidon.files.mpl2_source.html MPL2_FORMAT = re.compile(r"^(?um)\[(-?\d+)\]\[(-?\d+)\](.*?)$") class TXTGenericFormat(FormatBase): @classmethod def guess_format(cls, text): if MPL2_FORMAT.match(text): return "mpl2" class MPL2Format(FormatBase): @classmethod def guess_format(cls, text): return TXTGenericFormat.guess_format(text) @classmethod def from_file(cls, subs, fp, format_, **kwargs): def prepare_text(lines): out = [] for s in lines.split("|"): if s.startswith("/"): out.append(r"{\i1}%s{\i0}" % s[1:]) continue out.append(s) return "\n".join(out) subs.events = [SSAEvent(start=times_to_ms(s=float(start) / 10), end=times_to_ms(s=float(end) / 10), text=prepare_text(text)) for start, end, text in MPL2_FORMAT.findall(fp.getvalue())] @classmethod def to_file(cls, subs, fp, format_, **kwargs): raise NotImplemented
juanfelipe82193/opensap
sapui5-sdk-1.74.0/resources/sap/gantt/eventHandler/MouseWheelHandler-dbg.js
/*! * SAP UI development toolkit for HTML5 (SAPUI5) (c) Copyright 2009-2015 SAP SE. All rights reserved */ sap.ui.define([ "jquery.sap.global", "sap/ui/Device", "sap/ui/base/Object" ], function (jQuery, Device, BaseObject) { "use strict"; /** * Constructor for a new MouseWheelHandler * * Initialize the handler and reserve the caller of this handler as the '_oSourceChart' * currently, '_oSourceChart' may be an instance of GanttChart or GanttChartWithTable * @param {object} oChart an instance of the caller * * @class * Defines the properties required for the initialization of mouse wheel zooming * @extends sap.ui.base.Object * * @author SAP SE * @version 1.74.0 * * @constructor * @private * @alias sap.gantt.eventHandler.MouseWheelHandler */ var MouseWheelHandler = BaseObject.extend("sap.gantt.eventHandler.MouseWheelHandler", { constructor : function (oChart) { BaseObject.call(this); this._oSourceChart = oChart; this._lastCalledMouseWheelZoom = 0; this._iMouseWheelZoomTimer = undefined; } }); /** * All pre-process work for mouse wheel event are handled here * @param {object} oEvent JQuery event object * @return {boolean} true if mouse wheel zoom is triggered */ MouseWheelHandler.prototype.handleEvent = function (oEvent, bSuppressSyncEvent) { var oOriginalEvent = oEvent.originalEvent; var bIsShitKey = oOriginalEvent.shiftKey; var bIsCtrlKey = oOriginalEvent.ctrlKey; var iScrollDelta = this._getScrollDelta(oOriginalEvent); //this flag is used for outer caller to know whether a zoom is actually triggered, if so, a sync between //multiple views may be needed var bIsZoomTriggerred = false; if (bIsShitKey) { //SHIFT + CTRL + WHEEL for zoom if (bIsCtrlKey) { bIsZoomTriggerred = this._handleZoom(oEvent, iScrollDelta, bSuppressSyncEvent); } else { //SHIFT+WHEEL for horizontal scrolling this._handleHScroll(oEvent, iScrollDelta); } } else { //Pure wheel scroll trigger a vertical scroll this._handleVScroll(oEvent, iScrollDelta); } return bIsZoomTriggerred; }; /** * calculate the scroll delta * @param {object} oEvent JQuery event object * @return {number} the scroll range of the wheel event */ MouseWheelHandler.prototype._getScrollDelta = function (oEvent) { var iScrollDelta = 0; if (Device.browser.firefox) { iScrollDelta = oEvent.detail; } else { //For IE, FF, CHROME, the scroll delta is all on 'deltaY', even with key 'shift', 'ctrl', 'alt', or 'shift+ctrl' iScrollDelta = oEvent.deltaY || oEvent.deltaX; } return iScrollDelta; }; /** * when the mouse SCROLL + SHIFT + CTRL key, trigger a zoom * @param {object} oEvent JQuery event object * @param {number} iScrollDelta scroll range of wheel event * @return {boolean} true if mouse wheel zoom is triggered */ MouseWheelHandler.prototype._handleZoom = function (oEvent, iScrollDelta, bSuppressSyncEvent) { var oZoomStrategy = this._oSourceChart.getAxisTimeStrategy(); var bIsZoomTriggerred = false; if (oZoomStrategy.getMouseWheelZoomType() !== sap.gantt.MouseWheelZoomType.None) { var bZoomIn = iScrollDelta < 0; if ((!bZoomIn && oZoomStrategy.getZoomLevel() > 0 ) || (bZoomIn && oZoomStrategy.getZoomLevel() < oZoomStrategy.getZoomLevels() - 1)) { if (this._oSourceChart._destroyCursorLine) { this._oSourceChart._destroyCursorLine(); } // update the visible horizon by using a delayed mechanism to avoid to many update // it will trigger an update each 100ms, so the update requests fired with 100ms will be done once // Except: if it is firstly triggered, or the last delayed call is finished and the time elapsed since last call is long enough for the // whole re-draw to be finished, we do an immediate update instead of a delayed one var iTimerDelay = (!this._iMouseWheelZoomTimer && (Date.now() - this._lastCalledMouseWheelZoom > 100)) ? 0 : 100; if (iTimerDelay === 0) { this._updateVisibleHorizon(oEvent, iScrollDelta, bSuppressSyncEvent); } else { this._iMouseWheelZoomTimer = this._iMouseWheelZoomTimer || jQuery.sap.delayedCall(iTimerDelay, this, this._updateVisibleHorizon, [oEvent, iScrollDelta, bSuppressSyncEvent]); } bIsZoomTriggerred = true; } this._preventBubbleAndDefault(oEvent); } return bIsZoomTriggerred; }; /** * calculate new visible horizon time range * @param {object} oEvent JQuery event object * @param {number} iScrollDelta scroll range of wheel event */ MouseWheelHandler.prototype._updateVisibleHorizon = function (oEvent, iScrollDelta, bSuppressSyncEvent) { this._lastCalledMouseWheelZoom = Date.now(); var oZoomStrategy = this._oSourceChart.getAxisTimeStrategy(); var oOriginalEvent = oEvent.originalEvent; //calculate the time where mouse pointer located var $chartSvg = jQuery(this._oSourceChart.getDomSelectorById("svg")); if ($chartSvg) { //for MS Edge, the pageX is not usable when browser zoom rate <> 100% and RTL = true, //instead, clientX is always right for all zoom rate and RTL scenario var iMousePosition = (Device.browser.edge ? oOriginalEvent.clientX : oOriginalEvent.pageX) - $chartSvg.offset().left || oOriginalEvent.offsetX; var oTimeAtMousePosition = oZoomStrategy.getAxisTime().viewToTime(iMousePosition); // update visible horizon according to different zoom granularity configured in zoom strategy oZoomStrategy.updateVisibleHorizonOnMouseWheelZoom(oTimeAtMousePosition, iScrollDelta, oEvent, bSuppressSyncEvent); } this._iMouseWheelZoomTimer = undefined; }; /** * SHIFT+WHEEL for horizontal scrolling * @param {object} oEvent JQuery event object * @param {number} iScrollDelta scroll range of wheel event */ MouseWheelHandler.prototype._handleHScroll = function (oEvent, iScrollDelta) { var oHSb = this._oSourceChart.getTTHsbDom(); var bScrolledToEnd = false; var bScrollingForward = iScrollDelta > 0; if (oHSb) { if (bScrollingForward) { bScrolledToEnd = Math.round(oHSb.scrollLeft) === oHSb.scrollWidth - oHSb.clientWidth; } else { bScrolledToEnd = oHSb.scrollLeft === 0; } //bubble-up only when scrolling reaches ganttchart boundary if (!bScrolledToEnd) { this._preventBubbleAndDefault(oEvent); oHSb.scrollLeft += iScrollDelta; } } }; /** * Pure WHEEL for vertical scrolling * @param {object} oEvent JQuery event object * @param {number} iScrollDelta scroll range of wheel event */ MouseWheelHandler.prototype._handleVScroll = function (oEvent, iScrollDelta) { var oVSb = this._oSourceChart.getTTVsbDom(); var bScrolledToEnd = false; var bScrollingForward = iScrollDelta > 0; if (oVSb) { if (bScrollingForward) { bScrolledToEnd = Math.round(oVSb.scrollTop) === oVSb.scrollHeight - oVSb.clientHeight; } else { bScrolledToEnd = oVSb.scrollTop === 0; } //bubble-up only when scrolling reaches ganttchart boundary if (!bScrolledToEnd) { this._preventBubbleAndDefault(oEvent); var iRowsPerStep = iScrollDelta / this._oSourceChart.getBaseRowHeight(); // If at least one row is scrolled, floor to full rows. // Below one row, just scroll pixels. if (iRowsPerStep > 1) { iRowsPerStep = Math.floor(iRowsPerStep); } oVSb.scrollTop += iRowsPerStep * this._getScrollingPixelsForRow(); } } }; //calculate pixels of a row in scrollable area MouseWheelHandler.prototype._getScrollingPixelsForRow = function () { var oTable = this._oSourceChart._oTT; if (oTable) { var iVisibleRowCount = oTable.getVisibleRowCount(); var iScrollableRowCount = Math.max(1, iVisibleRowCount - oTable.getFixedRowCount() - oTable.getFixedBottomRowCount()); var iRowHeight = this._oSourceChart.getBaseRowHeight(); var iVSbHeight = iScrollableRowCount * iRowHeight; var iBindingRowCount = oTable.getBinding("rows").getLength(); var iTotalScrollRowCount = Math.max(iBindingRowCount, iVisibleRowCount + 1); var iTotalScrollRange = iTotalScrollRowCount * iRowHeight; var iVirtualScrollRange = Math.max(1, iTotalScrollRange - iVSbHeight - this._getRowHeightsDelta()); var iMaxRowCountForScroll; if (iVisibleRowCount > iBindingRowCount) { iMaxRowCountForScroll = iBindingRowCount; } else { iMaxRowCountForScroll = Math.max(0, iBindingRowCount - iVisibleRowCount - 1); } return Math.ceil(iVirtualScrollRange / Math.max(1, iMaxRowCountForScroll)); } return 0; }; //calculate the delta heights in case expand chart is opened MouseWheelHandler.prototype._getRowHeightsDelta = function() { var oTable = this._oSourceChart._oTT; if (oTable) { var iBindingRowCount = oTable.getBinding("rows").getLength(); var iVisibleRowCount = oTable.getVisibleRowCount(); var iEstimatedViewportHeight = this._oSourceChart.getBaseRowHeight() * iVisibleRowCount; var aRowHeights = this._oSourceChart._getRowHeights(); // Case: Not enough data to fill all available rows, only sum used rows. if (iVisibleRowCount > iBindingRowCount) { aRowHeights = aRowHeights.slice(0, iBindingRowCount); } var iRowHeightsDelta = aRowHeights.reduce(function(a, b) { return a + b; }, 0) - iEstimatedViewportHeight; if (iRowHeightsDelta > 0) { iRowHeightsDelta = Math.ceil(iRowHeightsDelta); } return Math.max(0, iRowHeightsDelta); } return 0; }; MouseWheelHandler.prototype._preventBubbleAndDefault = function (oEvent) { oEvent.preventDefault(); oEvent.stopPropagation(); }; return MouseWheelHandler; }, true);
GlobalFishingWatch/ais-tools
ais_tools/ais.py
<filename>ais_tools/ais.py from ais_tools.transcode import DecodeError from ais_tools.transcode import MessageTranscoder from ais_tools.transcode import bits_to_nmea from ais_tools.transcode import nmea_to_bits from ais_tools.transcode import byte_align from ais_tools import ais18 from ais_tools import ais24 from ais_tools import ais25 message_types = { 18: ais18.ais18_fields, 24: [ais24.AIS24Transcoder()], 25: ais25.ais25_fields, } class AISMessageTranscoder(MessageTranscoder): def message_type_fields(self, msg_type): if msg_type not in message_types: raise DecodeError('AIS: Unknown message type {}'.format(msg_type)) return message_types.get(msg_type, []) def encode_fields(self, message): return self.message_type_fields(message.get('id')) def decode_fields(self, bits, message): return self.message_type_fields(message.get('id', bits[0:6].uint)) def encode_nmea(self, message): return bits_to_nmea(byte_align(self.encode(message))) def decode_nmea(self, body, pad=0): return self.decode(nmea_to_bits(body, pad))
vpavlin/fabric8-wit
controller/render.go
package controller import ( "github.com/almighty/almighty-core/app" "github.com/almighty/almighty-core/errors" "github.com/almighty/almighty-core/jsonapi" "github.com/almighty/almighty-core/rendering" "github.com/goadesign/goa" uuid "github.com/satori/go.uuid" ) const ( RenderingType = "rendering" RenderedValue = "value" ) // RenderController implements the render resource. type RenderController struct { *goa.Controller } // NewRenderController creates a render controller. func NewRenderController(service *goa.Service) *RenderController { return &RenderController{Controller: service.NewController("RenderController")} } // Render runs the render action. func (c *RenderController) Render(ctx *app.RenderRenderContext) error { content := ctx.Payload.Data.Attributes.Content markup := ctx.Payload.Data.Attributes.Markup if !rendering.IsMarkupSupported(markup) { return jsonapi.JSONErrorResponse(ctx, errors.NewBadParameterError("Unsupported markup type", markup)) } htmlResult := rendering.RenderMarkupToHTML(content, markup) res := &app.MarkupRenderingSingle{Data: &app.MarkupRenderingData{ ID: uuid.NewV4().String(), Type: RenderingType, Attributes: &app.MarkupRenderingDataAttributes{ RenderedContent: htmlResult, }}} return ctx.OK(res) }
code-review-doctor/domonic
domonic/xml/aframe.py
""" domonic.aframe ==================================== Generate aframe tags with python 3 https://aframe.io/ """ from domonic.dom import Element class aframe_tag(Element): def __str__(self): return f"<a-{self.name}{self.__attributes__}>{self.content}</a-{self.name}>" entity = type('entity', (aframe_tag, Element,), {'name': 'entity'}) scene = type('scene', (aframe_tag, Element,), {'name': 'scene'}) material = type('material', (aframe_tag, Element,), {'name': 'material'}) appearance = type('appearance', (aframe_tag, Element,), {'name': 'appearance'}) shape = type('shape', (aframe_tag, Element,), {'name': 'shape'}) # transform = type('transform', (aframe_tag, Element,), {'name': 'transform'}) # inline = type('inline', (aframe_tag, Element,), {'name': 'inline'}) sphere = type('sphere', (aframe_tag, Element,), {'name': 'sphere'}) box = type('box', (aframe_tag, Element,), {'name': 'box'}) plane = type('plane', (aframe_tag, Element,), {'name': 'plane'}) sky = type('sky', (aframe_tag, Element,), {'name': 'sky'}) mixin = type('mixin', (aframe_tag, Element,), {'name': 'mixin'}) circle = type('circle', (aframe_tag, Element,), {'name': 'circle'}) camera = type('camera', (aframe_tag, Element,), {'name': 'camera'}) cone = type('cone', (aframe_tag, Element,), {'name': 'cone'}) cursor = type('cursor', (aframe_tag, Element,), {'name': 'cursor'}) curvedimage = type('curvedimage', (aframe_tag, Element,), {'name': 'curvedimage'}) cylinder = type('cylinder', (aframe_tag, Element,), {'name': 'cylinder'}) dodecahedron = type('dodecahedron', (aframe_tag, Element,), {'name': 'dodecahedron'}) icosahedron = type('icosahedron', (aframe_tag, Element,), {'name': 'icosahedron'}) image = type('image', (aframe_tag, Element,), {'name': 'image'}) light = type('light', (aframe_tag, Element,), {'name': 'light'}) alink = type('alink', (aframe_tag, Element,), {'name': 'alink'}) octahedron = type('octahedron', (aframe_tag, Element,), {'name': 'octahedron'}) plane = type('plane', (aframe_tag, Element,), {'name': 'plane'}) ring = type('ring', (aframe_tag, Element,), {'name': 'ring'}) sound = type('sound', (aframe_tag, Element,), {'name': 'sound'}) sphere = type('sphere', (aframe_tag, Element,), {'name': 'sphere'}) tetrahedron = type('tetrahedron', (aframe_tag, Element,), {'name': 'tetrahedron'}) text = type('text', (aframe_tag, Element,), {'name': 'text'}) torus = type('torus', (aframe_tag, Element,), {'name': 'torus'}) triangle = type('triangle', (aframe_tag, Element,), {'name': 'triangle'}) video = type('video', (aframe_tag, Element,), {'name': 'video'}) videosphere = type('videosphere', (aframe_tag, Element,), {'name': 'videosphere'}) gltf = type('gltf', (aframe_tag, Element,), {'name': 'gltf'}) gltf_model = type('gltf_model', (aframe_tag, Element,), {'name': 'gltf_model'}) torus_knot = type('torus_knot', (aframe_tag, Element,), {'name': 'torus_knot'}) obj_model = type('obj_model', (aframe_tag, Element,), {'name': 'obj_model'}) # <a-box> # <a-camera> # <a-circle> # <a-cone> # <a-cursor> # <a-curvedimage> # <a-cylinder> # <a-dodecahedron> # <a-gltf-model> # <a-icosahedron> # <a-image> # <a-light> # <a-link> # <a-obj-model> # <a-octahedron> # <a-plane> # <a-ring> # <a-sky> # <a-sound> # <a-sphere> # <a-tetrahedron> # <a-text> # <a-torus-knot> # <a-torus> # <a-triangle> # <a-video> # <a-videosphere>
javrasya/zemberek-nlp
core/src/main/java/zemberek/core/Range.java
package zemberek.core; import com.google.common.base.Preconditions; import com.google.common.primitives.Ints; /** * Defines an integer range. */ public class Range implements Comparable<Range> { public final int from; public final int to; public Range(int from, int to) { Preconditions.checkArgument(from < to, "Range start cannot be larger than end. But start=" + from + "end=" + to); this.to = to; this.from = from; } public int mid() { return from + (to - from) / 2; } public int length() { return to - from; } public Range copy(int offset) { return new Range(offset + from, offset + to); } @Override public String toString() { return from + "-" + to; } @Override public int compareTo(Range range) { return Ints.compare(length(), range.length()); } }
jmsgrogan/PyChaste
dynamic/wrappers/cell_based/ApoptoticCellKiller2.cppwg.hpp
<reponame>jmsgrogan/PyChaste<filename>dynamic/wrappers/cell_based/ApoptoticCellKiller2.cppwg.hpp #ifndef ApoptoticCellKiller2_hpp__pyplusplus_wrapper #define ApoptoticCellKiller2_hpp__pyplusplus_wrapper namespace py = pybind11; void register_ApoptoticCellKiller2_class(py::module &m); #endif // ApoptoticCellKiller2_hpp__pyplusplus_wrapper
magaum/metadata
src/test/java/net/sf/esfinge/metadata/locate/levelLocator/CTAux2/package-info.java
<gh_stars>1-10 package net.sf.esfinge.metadata.locate.levelLocator.CTAux2;
GMcD/ts-serverless
micros/vang/models/room_model.go
<filename>micros/vang/models/room_model.go<gh_stars>10-100 package models import ( uuid "github.com/gofrs/uuid" ) type RoomModel struct { ObjectId uuid.UUID `json:"objectId" bson:"objectId"` Members []string `json:"members" bson:"members"` Type int8 `json:"type" bson:"type"` // {0: peer, 1: multiple} ReadDate map[string]int64 `json:"readDate" bson:"readDate"` // {'userId1': last_seen_date_time, 'userId2': last_seen_date_time} ReadCount map[string]int64 `json:"readCount" bson:"readCount"` // {'userId1': read_count, 'userId2': read_count} ReadMessageId map[string]string `json:"readMessageId" bson:"readMessageId"` // {'userId1': 'message_id_234', 'userId2': 'message_id_2323'} DeactiveUsers []string `json:"deactiveUsers" bson:"deactiveUsers"` // ['userId1', 'userId2'] LastMessage map[string]interface{} `json:"lastMessage" bson:"lastMessage"` // {'text': 'message_text', 'ownerId': 'userId'} MemberCount int64 `json:"memberCount" bson:"memberCount"` MessageCount int64 `json:"messageCount" bson:"messageCount"` CreatedDate int64 `json:"createdDate" bson:"createdDate"` UpdatedDate int64 `json:"updatedDate" bson:"updatedDate"` }
ChangFeng2015/leetcode
src/main/java/leetCode/concurrent2/ThreadC.java
package leetCode.concurrent2; /** * @ClassName ThreadC * @Description TODO * @Author Dave * @Date 2018/10/29 21:24 * @Version 1.0 **/ public class ThreadC extends Thread { private RepastService service; public ThreadC(RepastService service) { super(); this.service = service; } @Override public void run() { service.get(); } }
terrasan111/eshegay
chapter_004/src/main/java/ru/job4j/collectionpro/list/Cycle.java
package ru.job4j.collectionpro.list; /** * Created by Evgeniy on 25.03.2018. */ public class Cycle<T> { private int size = 0; private Node<T> first; public Node<T> getFirst() { return first; } public void add(Object value) { if (first == null) { this.first = new Node(value); } else { Node temp = first; while (temp.getNext() != null) { temp = temp.getNext(); } temp.setValue(new Node(value)); size++; } } public T get(int index) { Node<T> temp = first.getNext(); for (int i = 0; i < index; i++) { temp = getNextElement(temp); } return temp.getValue(); } private Node<T> getNextElement(Node<T> value) { return value.getNext(); } private class Node<T> { T value; Node<T> next; public Node(T value) { this.value = value; } public T getValue() { return value; } public void setValue(T value) { this.value = value; } public Node<T> getNext() { return next; } } boolean hasCycle(Node first) { Node tort = first; Node hare = first.next; while (true) { if (tort.next == null) { break; } if (tort == hare) { return true; } tort = tort.next; hare = hare.next.next; } return false; } }
kgnzt/polyseerio-ruby
lib/sdk/factory.rb
<gh_stars>1-10 require 'sdk/static/index' require 'sdk/method/index' require 'sdk/helper' module Polyseerio module SDK # SDK static module. module Static # Generates static functions. def self.factory(request, resource, statics = [], options = {}) accumulator = Helper.accumulate_procs('static', MAP) statics = statics.each_with_object({}, &accumulator) # curry request, resource, and options statics.each_with_object(statics) do |(name, static), hash| if static.arity > 3 hash[name] = static.curry.call(request, resource, options) end end statics end end # SDK Method (instance) module. module Method # Generates method (instance) functions. def self.factory(_request, _resource, methods = [], _options = {}) accumulator = Helper.accumulate_procs('method', MAP) methods = methods.each_with_object({}, &accumulator) methods end end end end
edorig/histoscope_plot_widgets
util/misc.c
<reponame>edorig/histoscope_plot_widgets<gh_stars>1-10 /******************************************************************************* * * * misc.c -- Miscelaneous Motif convenience functions * * * * Copyright (c) 1991 Universities Research Association, Inc. * * All rights reserved. * * * * This material resulted from work developed under a Government Contract and * * is subject to the following license: The Government retains a paid-up, * * nonexclusive, irrevocable worldwide license to reproduce, prepare derivative * * works, perform publicly and display publicly by or for the Government, * * including the right to distribute to other Government contractors. Neither * * the United States nor the United States Department of Energy, nor any of * * their employees, makes any warrenty, express or implied, or assumes any * * legal liability or responsibility for the accuracy, completeness, or * * usefulness of any information, apparatus, product, or process disclosed, or * * represents that its use would not infringe privately owned rights. * * * * Fermilab Nirvana GUI Library * * July 28, 1992 * * * * Written by <NAME> * * * *******************************************************************************/ static char SCCSID[] = "@(#)misc.c 1.39 2/1/96"; #include <stdlib.h> #include <stdarg.h> #include <math.h> #include <stdio.h> #include <time.h> #ifdef VMS #include <types.h> #include <unixio.h> #include <file.h> #endif /*VMS*/ #include <X11/Intrinsic.h> #include <X11/Xatom.h> #include <X11/keysym.h> #include <Xm/Xm.h> #include <Xm/Label.h> #include <Xm/LabelG.h> #include <Xm/ToggleB.h> #include <Xm/PushB.h> #include <Xm/Separator.h> #include <Xm/RowColumn.h> #include <Xm/CascadeB.h> #include <Xm/AtomMgr.h> #include <Xm/Protocols.h> #include <Xm/Text.h> #include "DialogF.h" #include "misc.h" /* math.h on Sun mysteriously excludes strtod and other functions when POSIX compliance is turned on */ extern double strtod(); /* structure for passing history-recall data to callbacks */ typedef struct { char ***list; int *nItems; int index; } histInfo; /* Maximum size of a history-recall list. Typically never invoked, since user must first make this many entries in the text field, limited for safety, to the maximum reasonable number of times user can hit up-arrow before carpal tunnel syndrome sets in */ #define HISTORY_LIST_TRIM_TO 3 /* 1000 */ #define HISTORY_LIST_MAX 6 /* 2000 */ /* flags to enable/disable delete key remapping and pointer centered dialogs */ static int RemapDeleteEnabled = True; static int PointerCenteredDialogsEnabled = False; /* bitmap and mask for waiting (wrist-watch) cursor */ #define watch_x_hot 7 #define watch_y_hot 7 #define watch_width 16 #define watch_height 16 static unsigned char watch_bits[] = { 0xe0, 0x07, 0xe0, 0x07, 0xe0, 0x07, 0xe0, 0x07, 0x10, 0x08, 0x08, 0x11, 0x04, 0x21, 0x04, 0x21, 0xe4, 0x21, 0x04, 0x20, 0x08, 0x10, 0x10, 0x08, 0xe0, 0x07, 0xe0, 0x07, 0xe0, 0x07, 0xe0, 0x07 }; #define watch_mask_width 16 #define watch_mask_height 16 static unsigned char watch_mask_bits[] = { 0xf0, 0x0f, 0xf0, 0x0f, 0xf0, 0x0f, 0xf0, 0x0f, 0xf8, 0x1f, 0xfc, 0x3f, 0xfe, 0x7f, 0xfe, 0x7f, 0xfe, 0x7f, 0xfe, 0x7f, 0xfc, 0x3f, 0xf8, 0x1f, 0xf0, 0x0f, 0xf0, 0x0f, 0xf0, 0x0f, 0xf0, 0x0f }; static void addMnemonicGrabs(Widget addTo, Widget w); static void mnemonicCB(Widget w, XtPointer callData, XKeyEvent *event); static void findAndActivateMnemonic(Widget w, unsigned int keycode); static void removeWhiteSpace(char *string); static void warnHandlerCB(String message); static void passwdCB(Widget w, char * passTxt, XmTextVerifyCallbackStruct *txtVerStr); static void histDestroyCB(Widget w, XtPointer clientData, XtPointer callData); static void histArrowKeyEH(Widget w, XtPointer callData, XEvent *event, Boolean *continueDispatch); /* ** Set up closeCB to be called when the user selects close from the ** window menu. The close menu item usually activates f.kill which ** sends a WM_DELETE_WINDOW protocol request for the window. */ void AddMotifCloseCallback(Widget shell, XtCallbackProc closeCB, void *arg) { static Atom wmpAtom, dwAtom = 0; Display *display = XtDisplay(shell); /* deactivate the built in delete response of killing the application */ XtVaSetValues(shell, XmNdeleteResponse, XmDO_NOTHING, 0); /* add a delete window protocol callback instead */ if (dwAtom == 0) { wmpAtom = XmInternAtom(display, "WM_PROTOCOLS", TRUE); dwAtom = XmInternAtom(display, "WM_DELETE_WINDOW", TRUE); } XmAddProtocolCallback(shell, wmpAtom, dwAtom, closeCB, arg); } /* ** Motif still generates spurrious passive grab warnings on both IBM and SGI ** This routine suppresses them */ void SuppressPassiveGrabWarnings(void) { XtSetWarningHandler(warnHandlerCB); } /* ** This routine kludges around the problem of backspace not being mapped ** correctly when Motif is used between a server with a delete key in ** the traditional typewriter backspace position and a client that ** expects a backspace key in that position. Though there are three ** distinct levels of key re-mapping in effect when a user is running ** a Motif application, none of these is really appropriate or effective ** for eliminating the delete v.s. backspace problem. Our solution is, ** sadly, to eliminate the forward delete functionality of the delete key ** in favor of backwards delete for both keys. So as not to prevent the ** user or the application from applying other translation table re-mapping, ** we apply re-map the key as a post-processing step, applied after widget ** creation. As a result, the re-mapping necessarily becomes embedded ** throughout an application (wherever text widgets are created), and ** within library routines, including the Nirvana utility library. To ** make this remapping optional, the SetDeleteRemap function provides a ** way for an application to turn this functionality on and off. It is ** recommended that applications that use this routine provide an ** application resource called remapDeleteKey so savvy users can get ** their forward delete functionality back. */ void RemapDeleteKey(Widget w) { static XtTranslations table = NULL; static char *translations = "~Shift~Ctrl~Meta~Alt<Key>osfDelete: delete-previous-character()\n"; if (RemapDeleteEnabled) { if (table == NULL) table = XtParseTranslationTable(translations); XtOverrideTranslations(w, table); } } void SetDeleteRemap(int state) { RemapDeleteEnabled = state; } /* ** ManageDialogCenteredOnPointer is used in place of XtManageChild for ** popping up a dialog to enable the dialog to be centered under the ** mouse pointer. Whether it pops up the dialog centered under the pointer ** or in its default position centered over the parent widget, depends on ** the value set in the SetPointerCenteredDialogs call. */ void ManageDialogCenteredOnPointer(Widget dialogChild) { Widget shell = XtParent(dialogChild); Window root, child; unsigned int mask; unsigned int width, height, borderWidth, depth; int x, y, winX, winY, maxX, maxY; Boolean mappedWhenManaged; /* If this feature is not enabled, just manage the dialog */ if (!PointerCenteredDialogsEnabled) { XtManageChild(dialogChild); return; } /* Temporarily set value of XmNmappedWhenManaged to stop the dialog from popping up right away */ XtVaGetValues(shell, XmNmappedWhenManaged, &mappedWhenManaged, 0); XtVaSetValues(shell, XmNmappedWhenManaged, False, 0); /* Manage the dialog */ XtManageChild(dialogChild); /* Get the pointer position (x, y) */ XQueryPointer(XtDisplay(shell), XtWindow(shell), &root, &child, &x, &y, &winX, &winY, &mask); /* Translate the pointer position (x, y) into a position for the new window that will place the pointer at its center */ XGetGeometry(XtDisplay(shell), XtWindow(shell), &root, &winX, &winY, &width, &height, &borderWidth, &depth); width += 2 * borderWidth; height += 2 * borderWidth; x -= width/2; y -= height/2; /* Ensure that the dialog remains on screen */ maxX = XtScreen(shell)->width - width; maxY = XtScreen(shell)->height - height; if (x < 0) x = 0; if (x > maxX) x = maxX; if (y < 0) y = 0; if (y > maxY) y = maxY; /* Set desired window position in the DialogShell */ XtVaSetValues(shell, XmNx, x, XmNy, y, NULL); /* Map the widget */ XtMapWidget(shell); /* Restore the value of XmNmappedWhenManaged */ XtVaSetValues(shell, XmNmappedWhenManaged, mappedWhenManaged, 0); } /* ** Cause dialogs created by libNUtil.a routines (such as DialogF and ** GetNewFilename), and dialogs which use ManageDialogCenteredOnPointer ** to pop up over the pointer (state = True), or pop up in their default ** positions (state = False) */ void SetPointerCenteredDialogs(int state) { PointerCenteredDialogsEnabled = state; } /* ** Raise a window to the top and give it the input focus. Setting input focus ** is important on systems which use explict (rather than pointer) focus. ** ** The X alternatives XMapRaised, and XSetInputFocus both have problems. ** XMapRaised only gives the window the focus if it was initially not visible, ** and XSetInputFocus sets the input focus, but crashes if the window is not ** visible. ** ** This routine should also be used in the case where a dialog is popped up and ** subsequent calls to the dialog function use a flag, or the XtIsManaged, to ** decide whether to create a new instance of the dialog, because on slower ** systems, events can intervene while a dialog is still on its way up and its ** window is still invisible, causing a subtle crash potential if ** XSetInputFocus is used. */ void RaiseShellWindow(Widget shell) { RaiseWindow(XtDisplay(shell), XtWindow(shell)); } void RaiseWindow(Display *display, Window w) { XWindowAttributes winAttr; XGetWindowAttributes(display, w, &winAttr); if (winAttr.map_state == IsViewable) XSetInputFocus(display, w, RevertToParent, CurrentTime); XMapRaised(display, w); } /* ** Add a handler for mnemonics in a dialog (Motif currently only handles ** mnemonics in menus) following the example of M.S. Windows. To add ** mnemonics to a dialog, set the XmNmnemonic resource, as you would in ** a menu, on push buttons or toggle buttons, and call this function ** when the dialog is fully constructed. Mnemonics added or changed ** after this call will not be noticed. To add a mnemonic to a text field ** or list, set the XmNmnemonic resource on the appropriate label and set ** the XmNuserData resource of the label to the widget to get the focus ** when the mnemonic is typed. */ void AddDialogMnemonicHandler(Widget dialog) { XtAddEventHandler(dialog, KeyPressMask, False, (XtEventHandler)mnemonicCB, (XtPointer)0); addMnemonicGrabs(dialog, dialog); } /* ** Removes the event handler and key-grabs added by AddDialogMnemonicHandler */ void RemoveDialogMnemonicHandler(Widget dialog) { XtUngrabKey(dialog, AnyKey, Mod1Mask); XtRemoveEventHandler(dialog, KeyPressMask, False, (XtEventHandler)mnemonicCB, (XtPointer)0); } /* ** PopDownBugPatch ** ** Under some circumstances, popping down a dialog and its parent in ** rapid succession causes a crash. This routine delays and ** processs events until receiving a ReparentNotify event. ** (I have no idea why a ReparentNotify event occurs at all, but it does ** mark the point where it is safe to destroy or pop down the parent, and ** it might have something to do with the bug.) There is a failsafe in ** the form of a ~1.5 second timeout in case no ReparentNotify arrives. ** Use this sparingly, only when real crashes are observed, and periodically ** check to make sure that it is still necessary. */ void PopDownBugPatch(Widget w) { time_t stopTime; stopTime = time(NULL) + 1; while (time(NULL) <= stopTime) { XEvent event; XtAppContext context = XtWidgetToApplicationContext(w); XtAppPeekEvent(context, &event); if (event.xany.type == ReparentNotify) return; XtAppProcessEvent(context, XtIMAll); } } /* ** Convert a compound string to a C style null terminated string. ** Returned string must be freed by the caller. */ char *GetXmStringText(XmString fromString) { XmStringContext context; char *text, *toPtr, *toString, *fromPtr; XmStringCharSet charset; XmStringDirection direction; Boolean separator; /* Malloc a buffer large enough to hold the string. XmStringLength should always be slightly longer than necessary, but won't be shorter than the equivalent null-terminated string */ toString = XtMalloc(XmStringLength(fromString)); /* loop over all of the segments in the string, copying each segment into the output string and converting separators into newlines */ XmStringInitContext(&context, fromString); toPtr = toString; while (XmStringGetNextSegment(context, &text, &charset, &direction, &separator)) { for (fromPtr=text; *fromPtr!='\0'; fromPtr++) *toPtr++ = *fromPtr; if (separator) *toPtr++ = '\n'; } /* terminate the string, free the context, and return the string */ *toPtr++ = '\0'; XmStringFreeContext(context); return toString; } /* ** Get the XFontStruct that corresponds to the default (first) font in ** a Motif font list. Since Motif stores this, it saves us from storing ** it or querying it from the X server. */ XFontStruct *GetDefaultFontStruct(XmFontList font) { XFontStruct *fs; XmFontContext context; XmStringCharSet charset; XmFontListInitFontContext(&context, font); XmFontListGetNextFont(context, &charset, &fs); XmFontListFreeFontContext(context); XtFree(charset); return fs; } /* ** Create a string table suitable for passing to XmList widgets */ XmString* StringTable(int count, ... ) { va_list ap; XmString *array; int i; char *str; va_start(ap, count); array = (XmString*)XtMalloc((count+1) * sizeof(XmString)); for(i = 0; i < count; i++ ) { str = va_arg(ap, char *); array[i] = XmStringCreateSimple(str); } array[i] = (XmString)0; va_end(ap); return(array); } void FreeStringTable(XmString *table) { int i; for(i = 0; table[i] != 0; i++) XmStringFree(table[i]); XtFree((char *)table); } /* ** Simulate a button press. The purpose of this routine is show users what ** is happening when they take an action with a non-obvious side effect, ** such as when a user double clicks on a list item. The argument is an ** XmPushButton widget to "press" */ void SimulateButtonPress(Widget widget) { XKeyPressedEvent keyEvent; memset((char *)&keyEvent, 0, sizeof(XKeyPressedEvent)); keyEvent.type = KeyPress; keyEvent.serial = 1; keyEvent.send_event = True; keyEvent.display = XtDisplay(widget); keyEvent.window = XtWindow(widget); XtCallActionProc(widget, "ArmAndActivate", (XEvent *)&keyEvent, NULL, 0); } /* ** Add an item to an already established pull-down or pop-up menu, including ** mnemonics, accelerators and callbacks. */ Widget AddMenuItem(Widget parent, char *name, char *label, char mnemonic, char *acc, char *accText, XtCallbackProc callback, void *cbArg) { Widget button; XmString st1, st2; button = XtVaCreateManagedWidget(name, xmPushButtonWidgetClass, parent, XmNlabelString, st1=XmStringCreateSimple(label), XmNmnemonic, mnemonic, XmNacceleratorText, st2=XmStringCreateSimple(accText), XmNaccelerator, acc, NULL); XtAddCallback(button, XmNactivateCallback, callback, cbArg); XmStringFree(st1); XmStringFree(st2); return button; } /* ** Add a toggle button item to an already established pull-down or pop-up ** menu, including mnemonics, accelerators and callbacks. */ Widget AddMenuToggle(Widget parent, char *name, char *label, char mnemonic, char *acc, char *accText, XtCallbackProc callback, void *cbArg, int set) { Widget button; XmString st1, st2; button = XtVaCreateManagedWidget(name, xmToggleButtonWidgetClass, parent, XmNlabelString, st1=XmStringCreateSimple(label), XmNmnemonic, mnemonic, XmNacceleratorText, st2=XmStringCreateSimple(accText), XmNaccelerator, acc, XmNset, set, NULL); XtAddCallback(button, XmNvalueChangedCallback, callback, cbArg); XmStringFree(st1); XmStringFree(st2); return button; } /* ** Add a separator line to a menu */ Widget AddMenuSeparator(Widget parent, char *name) { Widget button; button = XmCreateSeparator(parent, name, NULL, 0); XtManageChild(button); return button; } /* ** Add a sub-menu to an established pull-down or pop-up menu, including ** mnemonics, accelerators and callbacks. Returns the menu pane of the ** new sub menu. */ Widget AddSubMenu(Widget parent, char *name, char *label, char mnemonic) { Widget menu; XmString st1; menu = XmCreatePulldownMenu(parent, name, NULL, 0); XtVaCreateManagedWidget(name, xmCascadeButtonWidgetClass, parent, XmNlabelString, st1=XmStringCreateSimple(label), XmNmnemonic, mnemonic, XmNsubMenuId, menu, 0); XmStringFree(st1); return menu; } /* ** SetIntLabel, SetFloatLabel, SetIntText, SetFloatText ** ** Set the text of a motif label or text widget to show an integer or ** floating number. */ void SetIntLabel(Widget label, int value) { char labelString[20]; XmString s1; sprintf(labelString, "%d", value); s1=XmStringCreateSimple(labelString); XtVaSetValues(label, XmNlabelString, s1, 0); XmStringFree(s1); } void SetFloatLabel(Widget label, double value) { char labelString[20]; XmString s1; sprintf(labelString, "%g", value); s1=XmStringCreateSimple(labelString); XtVaSetValues(label, XmNlabelString, s1, 0); XmStringFree(s1); } void SetIntText(Widget text, int value) { char labelString[20]; sprintf(labelString, "%d", value); XmTextSetString(text, labelString); } void SetFloatText(Widget text, double value) { char labelString[20]; sprintf(labelString, "%g", value); XmTextSetString(text, labelString); } /* ** GetIntText, GetFloatText, GetIntTextWarn, GetFloatTextWarn ** ** Get the text of a motif text widget as an integer or floating point number. ** The functions will return TEXT_READ_OK of the value was read correctly. ** If not, they will return either TEXT_IS_BLANK, or TEXT_NOT_NUMBER. The ** GetIntTextWarn and GetFloatTextWarn will display a dialog warning the ** user that the value could not be read. The argument fieldName is used ** in the dialog to help the user identify where the problem is. Set ** warnBlank to true if a blank field is also considered an error. */ int GetFloatText(Widget text, double *value) { char *strValue, *endPtr; int retVal; strValue = XmTextGetString(text); /* Get Value */ removeWhiteSpace(strValue); /* Remove blanks and tabs */ *value = strtod(strValue, &endPtr); /* Convert string to double */ if (strlen(strValue) == 0) /* String is empty */ retVal = TEXT_IS_BLANK; else if (*endPtr != '\0') /* Whole string not parsed */ retVal = TEXT_NOT_NUMBER; else retVal = TEXT_READ_OK; XtFree(strValue); return retVal; } int GetIntText(Widget text, int *value) { char *strValue, *endPtr; int retVal; strValue = XmTextGetString(text); /* Get Value */ removeWhiteSpace(strValue); /* Remove blanks and tabs */ *value = strtol(strValue, &endPtr, 10); /* Convert string to long */ if (strlen(strValue) == 0) /* String is empty */ retVal = TEXT_IS_BLANK; else if (*endPtr != '\0') /* Whole string not parsed */ retVal = TEXT_NOT_NUMBER; else retVal = TEXT_READ_OK; XtFree(strValue); return retVal; } int GetFloatTextWarn(Widget text, double *value, char *fieldName, int warnBlank) { int result; char *valueStr; result = GetFloatText(text, value); if (result == TEXT_READ_OK || (result == TEXT_IS_BLANK && !warnBlank)) return result; valueStr = XmTextGetString(text); if (result == TEXT_IS_BLANK) DialogF (DF_ERR, text, 1, "Please supply %s value", "Dismiss", fieldName); else /* TEXT_NOT_NUMBER */ DialogF (DF_ERR, text, 1, "Can't read %s value: \"%s\"", "Dismiss", fieldName, valueStr); XtFree(valueStr); return result; } int GetIntTextWarn(Widget text, int *value, char *fieldName, int warnBlank) { int result; char *valueStr; result = GetIntText(text, value); if (result == TEXT_READ_OK || (result == TEXT_IS_BLANK && !warnBlank)) return result; valueStr = XmTextGetString(text); if (result == TEXT_IS_BLANK) DialogF (DF_ERR, text, 1, "Please supply a value for %s", "Dismiss", fieldName); else /* TEXT_NOT_NUMBER */ DialogF (DF_ERR, text, 1, "Can't read integer value \"%s\" in %s", "Dismiss", valueStr, fieldName); XtFree(valueStr); return result; } int TextWidgetIsBlank(Widget textW) { char *str; int retVal; str = XmTextGetString(textW); removeWhiteSpace(str); retVal = *str == '\0'; XtFree(str); return retVal; } /* ** Turn a multi-line editing text widget into a fake single line text area ** by disabling the translation for Return. This is a way to give users ** extra space, by allowing wrapping, but still prohibiting newlines. ** (SINGLE_LINE_EDIT mode can't be used, in this case, because it forces ** the widget to be one line high). */ void MakeSingleLineTextW(Widget textW) { static XtTranslations noReturnTable = NULL; static char *noReturnTranslations = "<Key>Return: activate()\n"; if (noReturnTable == NULL) noReturnTable = XtParseTranslationTable(noReturnTranslations); XtOverrideTranslations(textW, noReturnTable); } /* ** Add up-arrow/down-arrow recall to a single line text field. When user ** presses up-arrow, string is cleared and recent entries are presented, ** moving to older ones as each successive up-arrow is pressed. Down-arrow ** moves to more recent ones, final down-arrow clears the field. Associated ** routine, AddToHistoryList, makes maintaining a history list easier. ** ** Arguments are the widget, and pointers to the history list and number of ** items, which are expected to change periodically. */ void AddHistoryToTextWidget(Widget textW, char ***historyList, int *nItems) { histInfo *histData; /* create a data structure for passing history info to the callbacks */ histData = (histInfo *)XtMalloc(sizeof(histInfo)); histData->list = historyList; histData->nItems = nItems; histData->index = -1; /* Add an event handler for handling up/down arrow events */ XtAddEventHandler(textW, KeyPressMask, False, (XtEventHandler)histArrowKeyEH, histData); /* Add a destroy callback for freeing history data structure */ XtAddCallback(textW, XmNdestroyCallback, histDestroyCB, histData); } static void histDestroyCB(Widget w, XtPointer clientData, XtPointer callData) { XtFree((char *)clientData); } static void histArrowKeyEH(Widget w, XtPointer callData, XEvent *event, Boolean *continueDispatch) { histInfo *histData = (histInfo *)callData; KeySym keysym = XLookupKeysym((XKeyEvent *)event, 0); /* only process up and down arrow keys */ if (keysym != XK_Up && keysym != XK_Down) return; /* increment or decrement the index depending on which arrow was pressed */ histData->index += (keysym == XK_Up) ? 1 : -1; /* if the index is out of range, beep, fix it up, and return */ if (histData->index < -1) { histData->index = -1; XBell(XtDisplay(w), 0); return; } if (histData->index >= *histData->nItems) { histData->index = *histData->nItems - 1; XBell(XtDisplay(w), 0); return; } /* Change the text field contents */ XmTextSetString(w, histData->index == -1 ? "" : (*histData->list)[histData->index]); } /* ** Copies a string on to the end of history list, which may be reallocated ** to make room. If historyList grows beyond its internally set boundary ** for size (HISTORY_LIST_MAX), it is trimmed back to a smaller size ** (HISTORY_LIST_TRIM_TO). Before adding to the list, checks if the item ** is a duplicate of the last item. If so, it is not added. */ void AddToHistoryList(char *newItem, char ***historyList, int *nItems) { char **newList; int i; if (*nItems != 0 && !strcmp(newItem, **historyList)) return; if (*nItems == HISTORY_LIST_MAX) { for (i=HISTORY_LIST_TRIM_TO; i<HISTORY_LIST_MAX; i++) XtFree((*historyList)[i]); *nItems = HISTORY_LIST_TRIM_TO; } newList = (char **)XtMalloc(sizeof(char *) * (*nItems + 1)); for (i=0; i < *nItems; i++) newList[i+1] = (*historyList)[i]; if (*nItems != 0 && *historyList != NULL) XtFree((char *)*historyList); (*nItems)++; newList[0] = XtNewString(newItem); *historyList = newList; } /* * PasswordText - routine to add a callback to any text widget so that all * text typed by the user is echoed with asterisks, allowing * a password to be typed in without being seen. * * parameters: w - text widget to add the callback to * passTxt - pointer to a string created by caller of this routine. * **NOTE** The length of this string should be one * greater than the maximum specified by XmNmaxLength. * This string is set to empty just before the callback * is added. */ void PasswordText(Widget w, char *passTxt) { passTxt[0] = '\0'; XtAddCallback(w, XmNmodifyVerifyCallback, (XtCallbackProc)passwdCB,passTxt); } /* ** BeginWait/EndWait ** ** Display/Remove a watch cursor over topCursorWidget and its descendents */ void BeginWait(Widget topCursorWidget) { Display *display = XtDisplay(topCursorWidget); Pixmap pixmap; Pixmap maskPixmap; XColor xcolors[2]; static Cursor waitCursor = 0; /* if the watch cursor hasn't been created yet, create it */ if (!waitCursor) { pixmap = XCreateBitmapFromData(display, DefaultRootWindow(display), (char *)watch_bits, watch_width, watch_height); maskPixmap = XCreateBitmapFromData(display, DefaultRootWindow(display), (char *)watch_mask_bits, watch_width, watch_height); xcolors[0].pixel = BlackPixelOfScreen(DefaultScreenOfDisplay(display)); xcolors[1].pixel = WhitePixelOfScreen(DefaultScreenOfDisplay(display)); XQueryColors(display, DefaultColormapOfScreen( DefaultScreenOfDisplay(display)), xcolors, 2); waitCursor = XCreatePixmapCursor(display, pixmap, maskPixmap, &xcolors[0], &xcolors[1], watch_x_hot, watch_y_hot); XFreePixmap(display, pixmap); XFreePixmap(display, maskPixmap); } /* display the cursor */ XDefineCursor(display, XtWindow(topCursorWidget), waitCursor); } void EndWait(Widget topCursorWidget) { XUndefineCursor(XtDisplay(topCursorWidget), XtWindow(topCursorWidget)); } /* */ /* passwdCB: callback routine added by PasswordText routine. This routine */ /* echoes each character typed as an asterisk (*) and a few other */ /* necessary things so that the password typed in is not visible */ /* */ static void passwdCB(Widget w, char * passTxt, XmTextVerifyCallbackStruct *txtVerStr) /* XmTextVerifyCallbackStruct: */ /* int reason; should be XmCR_MODIFYING_TEXT_VALUE */ /* XEvent *event; points to XEvent that triggered the callback */ /* Boolean doit; indicates whether action should be performed; setting */ /* this to false negates the action */ /* long currInsert, current position of insert cursor */ /* newInsert; position user attempts to position the insert cursor */ /* long startPos, starting position of the text to modify */ /* endPos; ending position of the text to modify */ /* XmTextBlock text; */ /* XmTextBlock (used to pass text around): */ /* char *ptr; points to text to be inserted */ /* int length; Number of bytes (length) */ /* XmTextFormat format; Representations format */ /* XmTextFormat: either FMT8BIT or FMT16BIT */ { int numCharsTyped, i, j, pos; /* ensure text format is 8-bit characters */ if (txtVerStr->text->format != FMT8BIT) return; /* verify assumptions */ /* if (txtVerStr->endPos < txtVerStr->startPos) fprintf(stderr, "User password callback error: endPos < startPos\n"); if (strlen(passTxt) == 0 && txtVerStr->endPos != 0) fprintf(stderr, "User password callback error: no txt, but end != 0\n"); printf("passTxt = %s, startPos = %d, endPos = %d, txtBlkAddr = %d\n", passTxt, txtVerStr->startPos, txtVerStr->endPos, txtVerStr->text); if (txtVerStr->text != NULL && txtVerStr->text->ptr != NULL) printf(" string typed = %s, length = %d\n", txtVerStr->text->ptr, txtVerStr->text->length); */ /* If necessary, expand/compress passTxt and insert any new text */ if (txtVerStr->text != NULL && txtVerStr->text->ptr != NULL) numCharsTyped = txtVerStr->text->length; else numCharsTyped = 0; /* numCharsTyped = # chars to insert (that user typed) */ /* j = # chars to expand (+) or compress (-) the password string */ j = numCharsTyped - (txtVerStr->endPos - txtVerStr->startPos); if (j > 0) /* expand case: start at ending null */ for (pos = strlen(passTxt) + 1; pos >= txtVerStr->endPos; --pos) passTxt[pos+j] = passTxt[pos]; if (j < 0) /* compress case */ for (pos = txtVerStr->startPos + numCharsTyped; pos <= strlen(passTxt)+1; ++pos) passTxt[pos] = passTxt[pos-j]; /* then copy text to be inserted into passTxt */ for (pos = txtVerStr->startPos, i = 0; i < numCharsTyped; ++i) { passTxt[pos+i] = *(txtVerStr->text->ptr + i); /* Replace text typed by user with asterisks (*) */ *(txtVerStr->text->ptr + i) = '*'; } /* printf(" Password string now = %s\n", passTxt); */ } /* ** Remove the white space (blanks and tabs) from a string */ static void removeWhiteSpace(char *string) { char *outPtr = string; while (TRUE) { if (*string == 0) { *outPtr = 0; return; } else if (*string != ' ' && *string != '\t') *(outPtr++) = *(string++); else string++; } } static void warnHandlerCB(String message) { if (strstr(message, "XtRemoveGrab")) return; if (strstr(message, "Attempt to remove non-existant passive grab")) return; fprintf(stderr, message); } /* ** Part of dialog mnemonic processing. Search the widget tree under w ** for widgets with mnemonics. When found, add a passive grab to the ** dialog widget for the mnemonic character, thus directing mnemonic ** events to the dialog widget. */ static void addMnemonicGrabs(Widget dialog, Widget w) { char mneString[2]; WidgetList children; int numChildren, i, isMenu; KeySym mnemonic = '\0'; unsigned char rowColType; if (XtIsComposite(w)) { if (XtClass(w) == xmRowColumnWidgetClass) { XtVaGetValues(w, XmNrowColumnType, &rowColType, 0); isMenu = rowColType != XmWORK_AREA; } else isMenu = False; if (!isMenu) { XtVaGetValues(w, XmNchildren, &children, XmNnumChildren, &numChildren, 0); for (i=0; i<numChildren; i++) addMnemonicGrabs(dialog, children[i]); } } else { XtVaGetValues(w, XmNmnemonic, &mnemonic, 0); if (mnemonic != '\0') { mneString[0] = mnemonic; mneString[1] = '\0'; XtGrabKey(dialog, XKeysymToKeycode(XtDisplay(dialog), XStringToKeysym(mneString)), Mod1Mask, True, GrabModeAsync, GrabModeAsync); } } } /* ** Callback routine for dialog mnemonic processing. */ static void mnemonicCB(Widget w, XtPointer callData, XKeyEvent *event) { findAndActivateMnemonic(w, event->keycode); } /* ** Look for a widget in the widget tree w, with a mnemonic matching ** keycode. When one is found, simulate a button press on that widget ** and give it the keyboard focus. If the mnemonic is on a label, ** look in the userData field of the label to see if it points to ** another widget, and give that the focus. This routine is just ** sufficient for NEdit, no doubt it will need to be extended for ** mnemonics on widgets other than just buttons and text fields. */ static void findAndActivateMnemonic(Widget w, unsigned int keycode) { WidgetList children; int numChildren, i, isMenu; KeySym mnemonic = '\0'; char mneString[2]; Widget userData; unsigned char rowColType; if (XtIsComposite(w)) { if (XtClass(w) == xmRowColumnWidgetClass) { XtVaGetValues(w, XmNrowColumnType, &rowColType, 0); isMenu = rowColType != XmWORK_AREA; } else isMenu = False; if (!isMenu) { XtVaGetValues(w, XmNchildren, &children, XmNnumChildren, &numChildren, 0); for (i=0; i<numChildren; i++) findAndActivateMnemonic(children[i], keycode); } } else { XtVaGetValues(w, XmNmnemonic, &mnemonic, 0); if (mnemonic != '\0') { mneString[0] = mnemonic; mneString[1] = '\0'; if (XKeysymToKeycode(XtDisplay(XtParent(w)), XStringToKeysym(mneString)) == keycode) { if (XtClass(w) == xmLabelWidgetClass || XtClass(w) == xmLabelGadgetClass) { XtVaGetValues(w, XmNuserData, &userData, 0); if (userData!=NULL && XtIsWidget(userData)) XmProcessTraversal(userData, XmTRAVERSE_CURRENT); } else { XmProcessTraversal(w, XmTRAVERSE_CURRENT); SimulateButtonPress(w); } } } } }
TigerBSD/FreeBSD-Custom-ThinkPad
FreeBSD/sys/fs/nandfs/nandfs_subr.c
/*- * Copyright (c) 2010-2012 Semihalf * Copyright (c) 2008, 2009 <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * From: NetBSD: nilfs_subr.c,v 1.4 2009/07/29 17:06:57 reinoud */ #include <sys/cdefs.h> __FBSDID("$FreeBSD$"); #include <sys/param.h> #include <sys/systm.h> #include <sys/namei.h> #include <sys/resourcevar.h> #include <sys/kernel.h> #include <sys/file.h> #include <sys/stat.h> #include <sys/buf.h> #include <sys/bio.h> #include <sys/proc.h> #include <sys/mount.h> #include <sys/vnode.h> #include <sys/signalvar.h> #include <sys/malloc.h> #include <sys/dirent.h> #include <sys/lockf.h> #include <sys/libkern.h> #include <geom/geom.h> #include <geom/geom_vfs.h> #include <vm/vm.h> #include <vm/vm_extern.h> #include <machine/_inttypes.h> #include "nandfs_mount.h" #include "nandfs.h" #include "nandfs_subr.h" MALLOC_DEFINE(M_NANDFSMNT, "nandfs_mount", "NANDFS mount"); MALLOC_DEFINE(M_NANDFSTEMP, "nandfs_tmt", "NANDFS tmp"); uma_zone_t nandfs_node_zone; void nandfs_bdflush(struct bufobj *bo, struct buf *bp); int nandfs_bufsync(struct bufobj *bo, int waitfor); struct buf_ops buf_ops_nandfs = { .bop_name = "buf_ops_nandfs", .bop_write = bufwrite, .bop_strategy = bufstrategy, .bop_sync = nandfs_bufsync, .bop_bdflush = nandfs_bdflush, }; int nandfs_bufsync(struct bufobj *bo, int waitfor) { struct vnode *vp; int error = 0; vp = bo->__bo_vnode; ASSERT_VOP_LOCKED(vp, __func__); error = nandfs_sync_file(vp); if (error) nandfs_warning("%s: cannot flush buffers err:%d\n", __func__, error); return (error); } void nandfs_bdflush(bo, bp) struct bufobj *bo; struct buf *bp; { struct vnode *vp; int error; if (bo->bo_dirty.bv_cnt <= ((dirtybufthresh * 8) / 10)) return; vp = bp->b_vp; if (NANDFS_SYS_NODE(VTON(vp)->nn_ino)) return; if (NANDFS_IS_INDIRECT(bp)) return; error = nandfs_sync_file(vp); if (error) nandfs_warning("%s: cannot flush buffers err:%d\n", __func__, error); } int nandfs_init(struct vfsconf *vfsp) { nandfs_node_zone = uma_zcreate("nandfs node zone", sizeof(struct nandfs_node), NULL, NULL, NULL, NULL, 0, 0); return (0); } int nandfs_uninit(struct vfsconf *vfsp) { uma_zdestroy(nandfs_node_zone); return (0); } /* Basic calculators */ uint64_t nandfs_get_segnum_of_block(struct nandfs_device *nandfsdev, nandfs_daddr_t blocknr) { uint64_t segnum, blks_per_seg; MPASS(blocknr >= nandfsdev->nd_fsdata.f_first_data_block); blks_per_seg = nandfsdev->nd_fsdata.f_blocks_per_segment; segnum = blocknr / blks_per_seg; segnum -= nandfsdev->nd_fsdata.f_first_data_block / blks_per_seg; DPRINTF(SYNC, ("%s: returning blocknr %jx -> segnum %jx\n", __func__, blocknr, segnum)); return (segnum); } void nandfs_get_segment_range(struct nandfs_device *nandfsdev, uint64_t segnum, uint64_t *seg_start, uint64_t *seg_end) { uint64_t blks_per_seg; blks_per_seg = nandfsdev->nd_fsdata.f_blocks_per_segment; *seg_start = nandfsdev->nd_fsdata.f_first_data_block + blks_per_seg * segnum; if (seg_end != NULL) *seg_end = *seg_start + blks_per_seg -1; } void nandfs_calc_mdt_consts(struct nandfs_device *nandfsdev, struct nandfs_mdt *mdt, int entry_size) { uint32_t blocksize = nandfsdev->nd_blocksize; mdt->entries_per_group = blocksize * 8; mdt->entries_per_block = blocksize / entry_size; mdt->blocks_per_group = (mdt->entries_per_group -1) / mdt->entries_per_block + 1 + 1; mdt->groups_per_desc_block = blocksize / sizeof(struct nandfs_block_group_desc); mdt->blocks_per_desc_block = mdt->groups_per_desc_block * mdt->blocks_per_group + 1; } int nandfs_dev_bread(struct nandfs_device *nandfsdev, nandfs_lbn_t blocknr, struct ucred *cred, int flags, struct buf **bpp) { int blk2dev = nandfsdev->nd_blocksize / DEV_BSIZE; int error; DPRINTF(BLOCK, ("%s: read from block %jx vp %p\n", __func__, blocknr * blk2dev, nandfsdev->nd_devvp)); error = bread(nandfsdev->nd_devvp, blocknr * blk2dev, nandfsdev->nd_blocksize, NOCRED, bpp); if (error) nandfs_error("%s: cannot read from device - blk:%jx\n", __func__, blocknr); return (error); } /* Read on a node */ int nandfs_bread(struct nandfs_node *node, nandfs_lbn_t blocknr, struct ucred *cred, int flags, struct buf **bpp) { nandfs_daddr_t vblk; int error; DPRINTF(BLOCK, ("%s: vp:%p lbn:%#jx\n", __func__, NTOV(node), blocknr)); error = bread(NTOV(node), blocknr, node->nn_nandfsdev->nd_blocksize, cred, bpp); KASSERT(error == 0, ("%s: vp:%p lbn:%#jx err:%d\n", __func__, NTOV(node), blocknr, error)); if (!nandfs_vblk_get(*bpp) && ((*bpp)->b_flags & B_CACHE) && node->nn_ino != NANDFS_DAT_INO) { nandfs_bmap_lookup(node, blocknr, &vblk); nandfs_vblk_set(*bpp, vblk); } return (error); } int nandfs_bread_meta(struct nandfs_node *node, nandfs_lbn_t blocknr, struct ucred *cred, int flags, struct buf **bpp) { nandfs_daddr_t vblk; int error; DPRINTF(BLOCK, ("%s: vp:%p lbn:%#jx\n", __func__, NTOV(node), blocknr)); error = bread(NTOV(node), blocknr, node->nn_nandfsdev->nd_blocksize, cred, bpp); KASSERT(error == 0, ("%s: vp:%p lbn:%#jx err:%d\n", __func__, NTOV(node), blocknr, error)); if (!nandfs_vblk_get(*bpp) && ((*bpp)->b_flags & B_CACHE) && node->nn_ino != NANDFS_DAT_INO) { nandfs_bmap_lookup(node, blocknr, &vblk); nandfs_vblk_set(*bpp, vblk); } return (error); } int nandfs_bdestroy(struct nandfs_node *node, nandfs_daddr_t vblk) { int error; if (!NANDFS_SYS_NODE(node->nn_ino)) NANDFS_WRITEASSERT(node->nn_nandfsdev); error = nandfs_vblock_end(node->nn_nandfsdev, vblk); if (error) { nandfs_error("%s: ending vblk: %jx failed\n", __func__, (uintmax_t)vblk); return (error); } node->nn_inode.i_blocks--; return (0); } int nandfs_bcreate(struct nandfs_node *node, nandfs_lbn_t blocknr, struct ucred *cred, int flags, struct buf **bpp) { int error; ASSERT_VOP_LOCKED(NTOV(node), __func__); if (!NANDFS_SYS_NODE(node->nn_ino)) NANDFS_WRITEASSERT(node->nn_nandfsdev); DPRINTF(BLOCK, ("%s: vp:%p lbn:%#jx\n", __func__, NTOV(node), blocknr)); *bpp = getblk(NTOV(node), blocknr, node->nn_nandfsdev->nd_blocksize, 0, 0, 0); KASSERT((*bpp), ("%s: vp:%p lbn:%#jx\n", __func__, NTOV(node), blocknr)); if (*bpp) { vfs_bio_clrbuf(*bpp); (*bpp)->b_blkno = ~(0); /* To avoid VOP_BMAP in bdwrite */ error = nandfs_bmap_insert_block(node, blocknr, *bpp); if (error) { nandfs_warning("%s: failed bmap insert node:%p" " blk:%jx\n", __func__, node, blocknr); brelse(*bpp); return (error); } node->nn_inode.i_blocks++; return (0); } return (-1); } int nandfs_bcreate_meta(struct nandfs_node *node, nandfs_lbn_t blocknr, struct ucred *cred, int flags, struct buf **bpp) { struct nandfs_device *fsdev; nandfs_daddr_t vblk; int error; ASSERT_VOP_LOCKED(NTOV(node), __func__); NANDFS_WRITEASSERT(node->nn_nandfsdev); DPRINTF(BLOCK, ("%s: vp:%p lbn:%#jx\n", __func__, NTOV(node), blocknr)); fsdev = node->nn_nandfsdev; *bpp = getblk(NTOV(node), blocknr, node->nn_nandfsdev->nd_blocksize, 0, 0, 0); KASSERT((*bpp), ("%s: vp:%p lbn:%#jx\n", __func__, NTOV(node), blocknr)); memset((*bpp)->b_data, 0, fsdev->nd_blocksize); vfs_bio_clrbuf(*bpp); (*bpp)->b_blkno = ~(0); /* To avoid VOP_BMAP in bdwrite */ nandfs_buf_set(*bpp, NANDFS_VBLK_ASSIGNED); if (node->nn_ino != NANDFS_DAT_INO) { error = nandfs_vblock_alloc(fsdev, &vblk); if (error) { nandfs_buf_clear(*bpp, NANDFS_VBLK_ASSIGNED); brelse(*bpp); return (error); } } else vblk = fsdev->nd_fakevblk++; nandfs_vblk_set(*bpp, vblk); nandfs_bmap_insert_block(node, blocknr, *bpp); return (0); } /* Translate index to a file block number and an entry */ void nandfs_mdt_trans(struct nandfs_mdt *mdt, uint64_t index, nandfs_lbn_t *blocknr, uint32_t *entry_in_block) { uint64_t blknr; uint64_t group, group_offset, blocknr_in_group; uint64_t desc_block, desc_offset; /* Calculate our offset in the file */ group = index / mdt->entries_per_group; group_offset = index % mdt->entries_per_group; desc_block = group / mdt->groups_per_desc_block; desc_offset = group % mdt->groups_per_desc_block; blocknr_in_group = group_offset / mdt->entries_per_block; /* To descgroup offset */ blknr = 1 + desc_block * mdt->blocks_per_desc_block; /* To group offset */ blknr += desc_offset * mdt->blocks_per_group; /* To actual file block */ blknr += 1 + blocknr_in_group; *blocknr = blknr; *entry_in_block = group_offset % mdt->entries_per_block; } void nandfs_mdt_trans_blk(struct nandfs_mdt *mdt, uint64_t index, uint64_t *desc, uint64_t *bitmap, nandfs_lbn_t *blocknr, uint32_t *entry_in_block) { uint64_t blknr; uint64_t group, group_offset, blocknr_in_group; uint64_t desc_block, desc_offset; /* Calculate our offset in the file */ group = index / mdt->entries_per_group; group_offset = index % mdt->entries_per_group; desc_block = group / mdt->groups_per_desc_block; desc_offset = group % mdt->groups_per_desc_block; blocknr_in_group = group_offset / mdt->entries_per_block; /* To descgroup offset */ *desc = desc_block * mdt->blocks_per_desc_block; blknr = 1 + desc_block * mdt->blocks_per_desc_block; /* To group offset */ blknr += desc_offset * mdt->blocks_per_group; *bitmap = blknr; /* To actual file block */ blknr += 1 + blocknr_in_group; *blocknr = blknr; *entry_in_block = group_offset % mdt->entries_per_block; DPRINTF(ALLOC, ("%s: desc_buf: %jx bitmap_buf: %jx entry_buf: %jx entry: %x\n", __func__, (uintmax_t)*desc, (uintmax_t)*bitmap, (uintmax_t)*blocknr, *entry_in_block)); } int nandfs_vtop(struct nandfs_node *node, nandfs_daddr_t vblocknr, nandfs_daddr_t *pblocknr) { struct nandfs_node *dat_node; struct nandfs_dat_entry *entry; struct buf *bp; nandfs_lbn_t ldatblknr; uint32_t entry_in_block; int locked, error; if (node->nn_ino == NANDFS_DAT_INO || node->nn_ino == NANDFS_GC_INO) { *pblocknr = vblocknr; return (0); } /* only translate valid vblocknrs */ if (vblocknr == 0) return (0); dat_node = node->nn_nandfsdev->nd_dat_node; nandfs_mdt_trans(&node->nn_nandfsdev->nd_dat_mdt, vblocknr, &ldatblknr, &entry_in_block); locked = NANDFS_VOP_ISLOCKED(NTOV(dat_node)); if (!locked) VOP_LOCK(NTOV(dat_node), LK_SHARED); error = nandfs_bread(dat_node, ldatblknr, NOCRED, 0, &bp); if (error) { DPRINTF(TRANSLATE, ("vtop: can't read in DAT block %#jx!\n", (uintmax_t)ldatblknr)); brelse(bp); VOP_UNLOCK(NTOV(dat_node), 0); return (error); } /* Get our translation */ entry = ((struct nandfs_dat_entry *) bp->b_data) + entry_in_block; DPRINTF(TRANSLATE, ("\tentry %p data %p entry_in_block %x\n", entry, bp->b_data, entry_in_block)) DPRINTF(TRANSLATE, ("\tvblk %#jx -> %#jx for cp [%#jx-%#jx]\n", (uintmax_t)vblocknr, (uintmax_t)entry->de_blocknr, (uintmax_t)entry->de_start, (uintmax_t)entry->de_end)); *pblocknr = entry->de_blocknr; brelse(bp); if (!locked) VOP_UNLOCK(NTOV(dat_node), 0); MPASS(*pblocknr >= node->nn_nandfsdev->nd_fsdata.f_first_data_block || *pblocknr == 0); return (0); } int nandfs_segsum_valid(struct nandfs_segment_summary *segsum) { return (segsum->ss_magic == NANDFS_SEGSUM_MAGIC); } int nandfs_load_segsum(struct nandfs_device *fsdev, nandfs_daddr_t blocknr, struct nandfs_segment_summary *segsum) { struct buf *bp; int error; DPRINTF(VOLUMES, ("nandfs: try segsum at block %jx\n", (uintmax_t)blocknr)); error = nandfs_dev_bread(fsdev, blocknr, NOCRED, 0, &bp); if (error) return (error); memcpy(segsum, bp->b_data, sizeof(struct nandfs_segment_summary)); brelse(bp); if (!nandfs_segsum_valid(segsum)) { DPRINTF(VOLUMES, ("%s: bad magic pseg:%jx\n", __func__, blocknr)); return (EINVAL); } return (error); } static int nandfs_load_super_root(struct nandfs_device *nandfsdev, struct nandfs_segment_summary *segsum, uint64_t pseg) { struct nandfs_super_root super_root; struct buf *bp; uint64_t blocknr; uint32_t super_root_crc, comp_crc; int off, error; /* Check if there is a superroot */ if ((segsum->ss_flags & NANDFS_SS_SR) == 0) { DPRINTF(VOLUMES, ("%s: no super root in pseg:%jx\n", __func__, pseg)); return (ENOENT); } /* Get our super root, located at the end of the pseg */ blocknr = pseg + segsum->ss_nblocks - 1; DPRINTF(VOLUMES, ("%s: try at %#jx\n", __func__, (uintmax_t)blocknr)); error = nandfs_dev_bread(nandfsdev, blocknr, NOCRED, 0, &bp); if (error) return (error); memcpy(&super_root, bp->b_data, sizeof(struct nandfs_super_root)); brelse(bp); /* Check super root CRC */ super_root_crc = super_root.sr_sum; off = sizeof(super_root.sr_sum); comp_crc = crc32((uint8_t *)&super_root + off, NANDFS_SR_BYTES - off); if (super_root_crc != comp_crc) { DPRINTF(VOLUMES, ("%s: invalid crc:%#x [expect:%#x]\n", __func__, super_root_crc, comp_crc)); return (EINVAL); } nandfsdev->nd_super_root = super_root; DPRINTF(VOLUMES, ("%s: got valid superroot\n", __func__)); return (0); } /* * Search for the last super root recorded. */ int nandfs_search_super_root(struct nandfs_device *nandfsdev) { struct nandfs_super_block *super; struct nandfs_segment_summary segsum; uint64_t seg_start, seg_end, cno, seq, create, pseg; uint64_t segnum; int error, found; error = found = 0; /* Search for last super root */ pseg = nandfsdev->nd_super.s_last_pseg; segnum = nandfs_get_segnum_of_block(nandfsdev, pseg); cno = nandfsdev->nd_super.s_last_cno; create = seq = 0; DPRINTF(VOLUMES, ("%s: start in pseg %#jx\n", __func__, (uintmax_t)pseg)); for (;;) { error = nandfs_load_segsum(nandfsdev, pseg, &segsum); if (error) break; if (segsum.ss_seq < seq || segsum.ss_create < create) break; /* Try to load super root */ if (segsum.ss_flags & NANDFS_SS_SR) { error = nandfs_load_super_root(nandfsdev, &segsum, pseg); if (error) break; /* confused */ found = 1; super = &nandfsdev->nd_super; nandfsdev->nd_last_segsum = segsum; super->s_last_pseg = pseg; super->s_last_cno = cno++; super->s_last_seq = segsum.ss_seq; super->s_state = NANDFS_VALID_FS; seq = segsum.ss_seq; create = segsum.ss_create; } else { seq = segsum.ss_seq; create = segsum.ss_create; } /* Calculate next partial segment location */ pseg += segsum.ss_nblocks; DPRINTF(VOLUMES, ("%s: next partial seg is %jx\n", __func__, (uintmax_t)pseg)); /* Did we reach the end of the segment? if so, go to the next */ nandfs_get_segment_range(nandfsdev, segnum, &seg_start, &seg_end); if (pseg >= seg_end) { pseg = segsum.ss_next; DPRINTF(VOLUMES, (" partial seg oor next is %jx[%jx - %jx]\n", (uintmax_t)pseg, (uintmax_t)seg_start, (uintmax_t)seg_end)); } segnum = nandfs_get_segnum_of_block(nandfsdev, pseg); } if (error && !found) return (error); return (0); } int nandfs_get_node_raw(struct nandfs_device *nandfsdev, struct nandfsmount *nmp, uint64_t ino, struct nandfs_inode *inode, struct nandfs_node **nodep) { struct nandfs_node *node; struct vnode *nvp; struct mount *mp; int error; *nodep = NULL; /* Associate with mountpoint if present */ if (nmp) { mp = nmp->nm_vfs_mountp; error = getnewvnode("nandfs", mp, &nandfs_vnodeops, &nvp); if (error) return (error); } else { mp = NULL; error = getnewvnode("snandfs", mp, &nandfs_system_vnodeops, &nvp); if (error) return (error); } if (mp) NANDFS_WRITELOCK(nandfsdev); DPRINTF(IFILE, ("%s: ino: %#jx -> vp: %p\n", __func__, (uintmax_t)ino, nvp)); /* Lock node */ lockmgr(nvp->v_vnlock, LK_EXCLUSIVE, NULL); if (mp) { error = insmntque(nvp, mp); if (error != 0) { *nodep = NULL; return (error); } } node = uma_zalloc(nandfs_node_zone, M_WAITOK | M_ZERO); /* Crosslink */ node->nn_vnode = nvp; nvp->v_bufobj.bo_ops = &buf_ops_nandfs; node->nn_nmp = nmp; node->nn_nandfsdev = nandfsdev; nvp->v_data = node; /* Initiase NANDFS node */ node->nn_ino = ino; if (inode != NULL) node->nn_inode = *inode; nandfs_vinit(nvp, ino); /* Return node */ *nodep = node; DPRINTF(IFILE, ("%s: ino:%#jx vp:%p node:%p\n", __func__, (uintmax_t)ino, nvp, *nodep)); return (0); } int nandfs_get_node(struct nandfsmount *nmp, uint64_t ino, struct nandfs_node **nodep) { struct nandfs_device *nandfsdev; struct nandfs_inode inode, *entry; struct vnode *nvp, *vpp; struct thread *td; struct buf *bp; uint64_t ivblocknr; uint32_t entry_in_block; int error; /* Look up node in hash table */ td = curthread; *nodep = NULL; if ((ino < NANDFS_ATIME_INO) && (ino != NANDFS_ROOT_INO)) { printf("nandfs_get_node: system ino %"PRIu64" not in mount " "point!\n", ino); return (ENOENT); } error = vfs_hash_get(nmp->nm_vfs_mountp, ino, LK_EXCLUSIVE, td, &nvp, NULL, NULL); if (error) return (error); if (nvp != NULL) { *nodep = (struct nandfs_node *)nvp->v_data; return (0); } /* Look up inode structure in mountpoints ifile */ nandfsdev = nmp->nm_nandfsdev; nandfs_mdt_trans(&nandfsdev->nd_ifile_mdt, ino, &ivblocknr, &entry_in_block); VOP_LOCK(NTOV(nmp->nm_ifile_node), LK_SHARED); error = nandfs_bread(nmp->nm_ifile_node, ivblocknr, NOCRED, 0, &bp); if (error) { brelse(bp); VOP_UNLOCK(NTOV(nmp->nm_ifile_node), 0); return (ENOENT); } /* Get inode entry */ entry = (struct nandfs_inode *) bp->b_data + entry_in_block; memcpy(&inode, entry, sizeof(struct nandfs_inode)); brelse(bp); VOP_UNLOCK(NTOV(nmp->nm_ifile_node), 0); /* Get node */ error = nandfs_get_node_raw(nmp->nm_nandfsdev, nmp, ino, &inode, nodep); if (error) { *nodep = NULL; return (error); } nvp = (*nodep)->nn_vnode; error = vfs_hash_insert(nvp, ino, 0, td, &vpp, NULL, NULL); if (error) { *nodep = NULL; return (error); } return (error); } void nandfs_dispose_node(struct nandfs_node **nodep) { struct nandfs_node *node; struct vnode *vp; /* Protect against rogue values */ node = *nodep; if (!node) { return; } DPRINTF(NODE, ("nandfs_dispose_node: %p\n", *nodep)); vp = NTOV(node); vp->v_data = NULL; /* Free our associated memory */ uma_zfree(nandfs_node_zone, node); *nodep = NULL; } int nandfs_lookup_name_in_dir(struct vnode *dvp, const char *name, int namelen, uint64_t *ino, int *found, uint64_t *off) { struct nandfs_node *dir_node = VTON(dvp); struct nandfs_dir_entry *ndirent; struct buf *bp; uint64_t file_size, diroffset, blkoff; uint64_t blocknr; uint32_t blocksize = dir_node->nn_nandfsdev->nd_blocksize; uint8_t *pos, name_len; int error; *found = 0; DPRINTF(VNCALL, ("%s: %s file\n", __func__, name)); if (dvp->v_type != VDIR) { return (ENOTDIR); } /* Get directory filesize */ file_size = dir_node->nn_inode.i_size; /* Walk the directory */ diroffset = 0; blocknr = 0; blkoff = 0; error = nandfs_bread(dir_node, blocknr, NOCRED, 0, &bp); if (error) { brelse(bp); return (EIO); } while (diroffset < file_size) { if (blkoff >= blocksize) { blkoff = 0; blocknr++; brelse(bp); error = nandfs_bread(dir_node, blocknr, NOCRED, 0, &bp); if (error) { brelse(bp); return (EIO); } } /* Read in one dirent */ pos = (uint8_t *) bp->b_data + blkoff; ndirent = (struct nandfs_dir_entry *) pos; name_len = ndirent->name_len; if ((name_len == namelen) && (strncmp(name, ndirent->name, name_len) == 0) && (ndirent->inode != 0)) { *ino = ndirent->inode; *off = diroffset; DPRINTF(LOOKUP, ("found `%.*s` with ino %"PRIx64"\n", name_len, ndirent->name, *ino)); *found = 1; break; } /* Advance */ diroffset += ndirent->rec_len; blkoff += ndirent->rec_len; } brelse(bp); return (error); } int nandfs_get_fsinfo(struct nandfsmount *nmp, struct nandfs_fsinfo *fsinfo) { struct nandfs_device *fsdev; fsdev = nmp->nm_nandfsdev; memcpy(&fsinfo->fs_fsdata, &fsdev->nd_fsdata, sizeof(fsdev->nd_fsdata)); memcpy(&fsinfo->fs_super, &fsdev->nd_super, sizeof(fsdev->nd_super)); snprintf(fsinfo->fs_dev, sizeof(fsinfo->fs_dev), "%s", nmp->nm_vfs_mountp->mnt_stat.f_mntfromname); return (0); } void nandfs_inode_init(struct nandfs_inode *inode, uint16_t mode) { struct timespec ts; vfs_timestamp(&ts); inode->i_blocks = 0; inode->i_size = 0; inode->i_ctime = ts.tv_sec; inode->i_ctime_nsec = ts.tv_nsec; inode->i_mtime = ts.tv_sec; inode->i_mtime_nsec = ts.tv_nsec; inode->i_mode = mode; inode->i_links_count = 1; if (S_ISDIR(mode)) inode->i_links_count = 2; inode->i_flags = 0; inode->i_special = 0; memset(inode->i_db, 0, sizeof(inode->i_db)); memset(inode->i_ib, 0, sizeof(inode->i_ib)); } void nandfs_inode_destroy(struct nandfs_inode *inode) { MPASS(inode->i_blocks == 0); bzero(inode, sizeof(*inode)); } int nandfs_fs_full(struct nandfs_device *nffsdev) { uint64_t space, bps; bps = nffsdev->nd_fsdata.f_blocks_per_segment; space = (nffsdev->nd_clean_segs - 1) * bps; DPRINTF(BUF, ("%s: bufs:%jx space:%jx\n", __func__, (uintmax_t)nffsdev->nd_dirty_bufs, (uintmax_t)space)); if (nffsdev->nd_dirty_bufs + (nffsdev->nd_segs_reserved * bps) >= space) return (1); return (0); } static int _nandfs_dirty_buf(struct buf *bp, int dirty_meta, int force) { struct nandfs_device *nffsdev; struct nandfs_node *node; uint64_t ino, bps; if (NANDFS_ISGATHERED(bp)) { bqrelse(bp); return (0); } if ((bp->b_flags & (B_MANAGED | B_DELWRI)) == (B_MANAGED | B_DELWRI)) { bqrelse(bp); return (0); } node = VTON(bp->b_vp); nffsdev = node->nn_nandfsdev; DPRINTF(BUF, ("%s: buf:%p\n", __func__, bp)); ino = node->nn_ino; if (nandfs_fs_full(nffsdev) && !NANDFS_SYS_NODE(ino) && !force) { brelse(bp); return (ENOSPC); } bp->b_flags |= B_MANAGED; bdwrite(bp); nandfs_dirty_bufs_increment(nffsdev); KASSERT((bp->b_vp), ("vp missing for bp")); KASSERT((nandfs_vblk_get(bp) || ino == NANDFS_DAT_INO), ("bp vblk is 0")); /* * To maintain consistency of FS we need to force making * meta buffers dirty, even if free space is low. */ if (dirty_meta && ino != NANDFS_GC_INO) nandfs_bmap_dirty_blocks(VTON(bp->b_vp), bp, 1); bps = nffsdev->nd_fsdata.f_blocks_per_segment; if (nffsdev->nd_dirty_bufs >= (bps * nandfs_max_dirty_segs)) { mtx_lock(&nffsdev->nd_sync_mtx); if (nffsdev->nd_syncing == 0) { DPRINTF(SYNC, ("%s: wakeup gc\n", __func__)); nffsdev->nd_syncing = 1; wakeup(&nffsdev->nd_syncing); } mtx_unlock(&nffsdev->nd_sync_mtx); } return (0); } int nandfs_dirty_buf(struct buf *bp, int force) { return (_nandfs_dirty_buf(bp, 1, force)); } int nandfs_dirty_buf_meta(struct buf *bp, int force) { return (_nandfs_dirty_buf(bp, 0, force)); } void nandfs_undirty_buf_fsdev(struct nandfs_device *nffsdev, struct buf *bp) { BUF_ASSERT_HELD(bp); if (bp->b_flags & B_DELWRI) { bp->b_flags &= ~(B_DELWRI|B_MANAGED); nandfs_dirty_bufs_decrement(nffsdev); } /* * Since it is now being written, we can clear its deferred write flag. */ bp->b_flags &= ~B_DEFERRED; brelse(bp); } void nandfs_undirty_buf(struct buf *bp) { struct nandfs_node *node; node = VTON(bp->b_vp); nandfs_undirty_buf_fsdev(node->nn_nandfsdev, bp); } void nandfs_vblk_set(struct buf *bp, nandfs_daddr_t blocknr) { nandfs_daddr_t *vblk = (nandfs_daddr_t *)(&bp->b_fsprivate1); *vblk = blocknr; } nandfs_daddr_t nandfs_vblk_get(struct buf *bp) { nandfs_daddr_t *vblk = (nandfs_daddr_t *)(&bp->b_fsprivate1); return (*vblk); } void nandfs_buf_set(struct buf *bp, uint32_t bits) { uintptr_t flags; flags = (uintptr_t)bp->b_fsprivate3; flags |= (uintptr_t)bits; bp->b_fsprivate3 = (void *)flags; } void nandfs_buf_clear(struct buf *bp, uint32_t bits) { uintptr_t flags; flags = (uintptr_t)bp->b_fsprivate3; flags &= ~(uintptr_t)bits; bp->b_fsprivate3 = (void *)flags; } int nandfs_buf_check(struct buf *bp, uint32_t bits) { uintptr_t flags; flags = (uintptr_t)bp->b_fsprivate3; if (flags & bits) return (1); return (0); } int nandfs_erase(struct nandfs_device *fsdev, off_t offset, size_t size) { DPRINTF(BLOCK, ("%s: performing erase at offset %jx size %zx\n", __func__, offset, size)); MPASS(size % fsdev->nd_erasesize == 0); return (g_delete_data(fsdev->nd_gconsumer, offset, size)); } int nandfs_vop_islocked(struct vnode *vp) { int islocked; islocked = VOP_ISLOCKED(vp); return (islocked == LK_EXCLUSIVE || islocked == LK_SHARED); } nandfs_daddr_t nandfs_block_to_dblock(struct nandfs_device *fsdev, nandfs_lbn_t block) { return (btodb(block * fsdev->nd_blocksize)); }
myxor/ceema
src/threepl/MessageHandler.h
<filename>src/threepl/MessageHandler.h // // Created by hbruintjes on 15/03/17. // #pragma once #include <protocol/packet/Message.h> #include <unordered_map> #include <api/BlobAPI.h> #include "GroupStore.h" class ThreeplConnection; class ContactStore; class message_exception : public std::runtime_error { ceema::client_id m_cid; public: message_exception(ceema::client_id id, const char* what) : std::runtime_error(what), m_cid(id) { } message_exception(ceema::client_id id, std::string const& what) : std::runtime_error(what), m_cid(id) { } ceema::client_id id() const { return m_cid; } }; class ThreeplMessageHandler { ThreeplConnection& m_connection; ContactStore& m_contacts; GroupStore& m_groups; ceema::BlobAPI& m_blobAPI; std::unordered_map<ceema::client_id, std::vector<std::pair<std::unique_ptr<ceema::Message>, ceema::promise<std::unique_ptr<ceema::Message>>>>> packetQueue; ceema::message_id m_lastAgreeable; public: ThreeplMessageHandler(ThreeplConnection& session, ContactStore& contacts, GroupStore& groups, ceema::BlobAPI& blobAPI) : m_connection(session), m_contacts(contacts), m_groups(groups), m_blobAPI(blobAPI), m_lastAgreeable{} {} void onRecvMessage(std::unique_ptr<ceema::Message> msg); template<typename Payload> ceema::future<std::unique_ptr<ceema::Message>> sendPayload(ceema::Account const& sender, ceema::client_id const& recipient, Payload&& payload) { std::unique_ptr<ceema::Message> msg = std::make_unique<ceema::Message>( sender.id(), recipient, std::forward<Payload>(payload)); // Threepl does not make use of ACK, so no need to request one // If the network is down, Purple can't do much anyway msg->flags().set(ceema::MessageFlag::NO_ACK); if (sender.nick().size()) { msg->nick() = sender.nick(); } return sendMessage(std::move(msg)); } template<typename Payload> std::vector<ceema::future<std::unique_ptr<ceema::Message>>> sendPayload(ceema::Account const& sender, ThreeplGroup* group, Payload&& payload) { std::vector<ceema::future<std::unique_ptr<ceema::Message>>> res; for(ceema::client_id const& member: group->members()) { if (member == sender.id()) { continue; } res.push_back(sendPayload(sender, member, payload)); } return res; } ThreeplGroup* find_or_create_group(ceema::group_uid uid, ceema::Message const &msg, bool add_chat = false); ceema::message_id const& lastAgreeable() const { return m_lastAgreeable; } private: ceema::future<std::unique_ptr<ceema::Message>> sendMessage(std::unique_ptr<ceema::Message> msg); ceema::future<std::unique_ptr<ceema::Message>> enqueue(std::unique_ptr<ceema::Message> msg); void recv(ceema::Message& msg); void send(ceema::Message& msg); bool onMsgText(ceema::Message const& msg, ceema::PayloadText const& payload); bool onMsgPicture(ceema::Message const& msg, ceema::PayloadPicture const& payload); bool onMsgLocation(ceema::Message const& msg, ceema::PayloadLocation const& payload); bool onMsgAudio(ceema::Message const& msg, ceema::PayloadAudio const& payload, bool del); bool onMsgVideo(ceema::Message const& msg, ceema::PayloadVideo const& payload, bool del); bool onMsgFile(ceema::Message const& msg, ceema::PayloadFile const& payload, bool del); bool onMsgIcon(ceema::Message const& msg, ceema::PayloadIcon const& payload); bool onMsgIconClear(ceema::Message const& msg, ceema::PayloadIconClear const& payload); bool onMsgGroupText(ceema::Message const& msg, ThreeplGroup* group, ceema::PayloadGroupText const& payload); bool onMsgGroupLocation(ceema::Message const& msg, ThreeplGroup* group, ceema::PayloadGroupLocation const& payload); bool onMsgGroupPicture(ceema::Message const& msg, ceema::PayloadGroupPicture const& payload); // Audio, Video, File all handled as with Contact messages bool onMsgGroupMembers(ceema::Message const& msg, ThreeplGroup* group, ceema::PayloadGroupMembers const& payload); bool onMsgGroupTitle(ceema::Message const& msg, ThreeplGroup* group, ceema::PayloadGroupTitle const& payload); bool onMsgGroupLeave(ceema::Message const& msg, ThreeplGroup* group, ceema::PayloadGroupLeave const& payload); bool onMsgGroupIcon(ceema::Message const& msg, ThreeplGroup* group, ceema::PayloadGroupIcon const& payload); bool onMsgGroupSync(ceema::Message const& msg, ThreeplGroup* group, ceema::PayloadGroupSync const& payload); bool onMsgStatus(ceema::Message const& msg, ceema::PayloadMessageStatus const& payload); bool onMsgTyping(ceema::Message const& msg, ceema::PayloadTyping const& payload); bool isOwner(ceema::group_uid const& id) const; void requestSync(ceema::Message const& msg, ceema::group_uid const& id); };
saushew/huobiRAW
pkg/model/wallet/getwithdrawquotaresponse.go
<filename>pkg/model/wallet/getwithdrawquotaresponse.go package wallet type GetWithdrawQuotaResponse struct { Code int `json:"code"` Message string `json:"message"` Data *WithdrawQuota `json:"data"` } type WithdrawQuota struct { Currency string `json:"currency"` Chains []struct { Chain string `json:"chain"` MaxWithdrawAmt string `json:"maxWithdrawAmt"` WithdrawQuotaPerDay string `json:"withdrawQuotaPerDay"` RemainWithdrawQuotaPerDay string `json:"remainWithdrawQuotaPerDay"` WithdrawQuotaPerYear string `json:"withdrawQuotaPerYear"` RemainWithdrawQuotaPerYear string `json:"remainWithdrawQuotaPerYear"` WithdrawQuotaTotal string `json:"withdrawQuotaTotal"` RemainWithdrawQuotaTotal string `json:"remainWithdrawQuotaTotal"` } `json:"chains"` }
daten-und-bass/fliXnet
api/controllers/context/context_html_web_graph_search.js
<filename>api/controllers/context/context_html_web_graph_search.js 'use strict'; var contextHtmlWebGraphSearch = require('../../../config/context').context_html_web_graph.search; module.exports = contextHtmlWebGraphSearch;
ryota-sego/token
resources/js/exportWrappers/RouterWrapper.js
import {BrowserRouter as Router, Route} from "react-router-dom"; import ReactDOM from "react-dom"; import App from '../components/App' const RouterWrap = (props) => { return( <Router> <Route render={(routeProps)=> <App {...routeProps} />} /> </Router> ); } if (document.getElementById('app')) { ReactDOM.render(<RouterWrap />, document.getElementById('app')); }
AlphaSunny/study
study_php/hb/h5/user/js/addBank.js
$(function () { //token var token = GetCookie('user_token'); GetUsAccount(); //Get the list of added banks GetBankList(token, function (response) { if(response.errcode == '0'){ var data = response.rows, li = ''; if(data ==false){ $('.showBankRow').remove(); $('.bankTitle').attr('name', 'noBankList'); execI18n(); return; } $.each(data, function (i, val){ li+='<li class="width-20">' + '<img src="img/'+ data[i].option_key.toLowerCase() +'.png">' + '<span><i class="iconfont icon-duihao"></i></span>'+ '</li>' }); $('.bankTypeBox').append(li); } }, function (response) { LayerFun(response.errcode); }); //Select bank card type $(document).on('click', '.bankTypeBox li', function(){ $(this).addClass('border').siblings().removeClass('border').siblings().find('.icon-duihao').hide(); $(this).find('.icon-duihao').show(); $('.next').show(); var imgHtml = $(this).find('img').attr('src'); //Select proxy mode next step $('.next').click(function(){ window.location.href = 'addBankInfo.html?img=' + encodeURIComponent(imgHtml); }) }) });
rreusser/rreusser.github.io
src/src/centripetal-b-splines/polyline.js
module.exports = function (mesh, points, options) { options = options || {}; mesh = mesh || {}; mesh.cells = mesh.cells || []; mesh.positions = points; var nCells = points.length - (options.closed ? 0 : 1); for (var i = 0; i < nCells; i++) { mesh.cells[i] = [i, (i + 1) % points.length]; } mesh.cells.length = nCells; return mesh; };
loopingz/t1c-lib-js
lib/scripts/util/CertParser.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var asn1js = require("asn1js"); var Base64 = require("Base64"); var Certificate_1 = require("pkijs/build/Certificate"); var CoreModel_1 = require("../core/service/CoreModel"); var ResponseHandler_1 = require("./ResponseHandler"); var CertParser = (function () { function CertParser() { } CertParser.process = function (response, parseCerts, callback) { if (response && response.data && typeof response.data === 'object' && !Array.isArray(response.data)) { var _loop_1 = function (key) { var value = response.data[key]; if (key.indexOf('certificate') > -1) { if (typeof value === 'string') { response.data[key] = { base64: value }; CertParser.setParsed(response.data[key], value, parseCerts); } else if (Array.isArray(value)) { var newData_1 = []; value.forEach(function (certificate) { var cert = new CoreModel_1.T1CCertificate(certificate); CertParser.setParsed(cert, certificate, parseCerts); newData_1.push(cert); }); response.data[key] = newData_1; } else if (typeof value === 'object') { response.data[key] = { base64: value.base64 }; if (value.id) { response.data[key].id = value.id; } if (parseCerts) { response.data[key].parsed = CertParser.processCert(value.base64); } } } }; for (var key in response.data) { _loop_1(key); } } else { if (Array.isArray(response.data)) { var newData_2 = []; response.data.forEach(function (certificate) { if (typeof certificate === 'string') { var cert = new CoreModel_1.T1CCertificate(certificate); CertParser.setParsed(cert, certificate, parseCerts); newData_2.push(cert); } else { var cert = new CoreModel_1.T1CCertificate(certificate.base64, certificate.id); CertParser.setParsed(cert, certificate.base64, parseCerts); newData_2.push(cert); } }); response.data = newData_2; } else { var cert = new CoreModel_1.T1CCertificate(response.data); CertParser.setParsed(cert, response.data, parseCerts); response.data = cert; } } return ResponseHandler_1.ResponseHandler.response(response, callback); }; CertParser.processCert = function (certificate) { var rawCert = Base64.atob(certificate); var buffer = CertParser.str2ab(rawCert); var asn1 = asn1js.fromBER(buffer); return new Certificate_1.default({ schema: asn1.result }); }; CertParser.str2ab = function (str) { var buf = new ArrayBuffer(str.length); var bufView = new Uint8Array(buf); for (var i = 0, strLen = str.length; i < strLen; i++) { bufView[i] = str.charCodeAt(i); } return buf; }; CertParser.setParsed = function (cert, base64, parseCerts) { if (parseCerts) { cert.parsed = CertParser.processCert(base64); } else { delete cert.parsed; } }; return CertParser; }()); exports.CertParser = CertParser; //# sourceMappingURL=CertParser.js.map
narendly/SLogo
src/commandnode/YCoordinateNode.java
package commandnode; import exception.SLogoException; import model.SLogoCharacterState; /** * Node representation of YCor command */ public class YCoordinateNode extends NullaryNode{ /** * @param state * @return turtle current Y coordinate from center (0,0) */ public double evaluate(SLogoCharacterState state) throws SLogoException{ return state.getYCoor(); } }
WraithEngine/AwgenShell
AwgenShell/src/main/java/net/whg/awgenshell/arg/ArgumentValue.java
package net.whg.awgenshell.arg; /** * A single argument that is provided to the command when it is executed. * * @author TheDudeFromCI */ public interface ArgumentValue { /** * Gets the current value of this argument as a string. This value is not * promised to be consistant and may be recalculated each time this method is * called. If this argument is a dynamic command, then that command is executed * each time that the this method is called. In most cases, it is ideal to call * this method only once and store the value in a local variable unless calling * the method multiple times is intended. * * @return The current value of this argument. */ String getValue(); }
ppartarr/azure-sdk-for-java
sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageTag.java
<reponame>ppartarr/azure-sdk-for-java /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.cognitiveservices.vision.customvision.training.models; import java.util.UUID; import org.joda.time.DateTime; import com.fasterxml.jackson.annotation.JsonProperty; /** * The ImageTag model. */ public class ImageTag { /** * The tagId property. */ @JsonProperty(value = "tagId", access = JsonProperty.Access.WRITE_ONLY) private UUID tagId; /** * The tagName property. */ @JsonProperty(value = "tagName", access = JsonProperty.Access.WRITE_ONLY) private String tagName; /** * The created property. */ @JsonProperty(value = "created", access = JsonProperty.Access.WRITE_ONLY) private DateTime created; /** * Get the tagId value. * * @return the tagId value */ public UUID tagId() { return this.tagId; } /** * Get the tagName value. * * @return the tagName value */ public String tagName() { return this.tagName; } /** * Get the created value. * * @return the created value */ public DateTime created() { return this.created; } }
mkeilman/sirepo
tests/exporter_test.py
<gh_stars>10-100 # -*- coding: utf-8 -*- u"""? :copyright: Copyright (c) 2017 RadiaSoft LLC. All Rights Reserved. :license: http://www.apache.org/licenses/LICENSE-2.0.html """ from __future__ import absolute_import, division, print_function import pytest def test_create_zip(fc): from pykern import pkio from pykern import pkunit from pykern import pkcompat from pykern.pkcollections import PKDict from pykern.pkdebug import pkdp, pkdpretty from pykern.pkunit import pkeq from sirepo import srunit import base64 import re import zipfile imported = _import(fc) for sim_type, sim_name, expect in imported + [ ('elegant', 'bunchComp - fourDipoleCSR', ['WAKE-inputfile.knsl45.liwake.sdds', 'run.py', 'sirepo-data.json']), ('srw', 'Tabulated Undulator Example', ['magnetic_measurements.zip', 'run.py', 'sirepo-data.json']), ('warppba', 'Laser Pulse', ['run.py', 'sirepo-data.json']), ]: sim_id = fc.sr_sim_data(sim_name, sim_type)['models']['simulation']['simulationId'] with pkio.save_chdir(pkunit.work_dir()) as d: for t in 'zip', 'html': r = fc.sr_get( 'exportArchive', PKDict( simulation_type=sim_type, simulation_id=sim_id, filename='anything.' + t, ) ) p = d.join(sim_name + '.' + t) x = r.data if t == 'html': x = pkcompat.from_bytes(x) m = re.search(r'name="zip" \S+ value="([^"]+)"', x, flags=re.DOTALL) x = base64.b64decode(pkcompat.to_bytes(m.group(1))) p.write_binary(x) e = expect if t == 'html': e.remove('run.py') pkeq( e, sorted(zipfile.ZipFile(str(p)).namelist()), ) def _import(fc): from pykern.pkcollections import PKDict from pykern.pkdebug import pkdp from pykern import pkio from pykern import pkunit import zipfile res = [] for f in pkio.sorted_glob(pkunit.data_dir().join('*.zip')): with zipfile.ZipFile(str(f)) as z: expect = sorted(z.namelist() + ['run.py']) d = fc.sr_post_form( 'importFile', PKDict(folder='/exporter_test'), PKDict(simulation_type=f.basename.split('_')[0]), file=f, ) res.append((d.simulationType, d.models.simulation.name, expect)) return res
mjhopkins/google-api-java-client-services
clients/google-api-services-run/v1alpha1/1.30.1/com/google/api/services/run/v1alpha1/model/TriggerStatus.java
<filename>clients/google-api-services-run/v1alpha1/1.30.1/com/google/api/services/run/v1alpha1/model/TriggerStatus.java<gh_stars>100-1000 /* * 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. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.run.v1alpha1.model; /** * TriggerStatus represents the current state of a Trigger. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Cloud Run API. For a detailed explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class TriggerStatus extends com.google.api.client.json.GenericJson { /** * Array of observed TriggerConditions, indicating the current state of the Trigger. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<TriggerCondition> conditions; static { // hack to force ProGuard to consider TriggerCondition used, since otherwise it would be stripped out // see https://github.com/google/google-api-java-client/issues/543 com.google.api.client.util.Data.nullOf(TriggerCondition.class); } /** * ObservedGeneration is the 'Generation' of the Trigger that was last processed by the * controller. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Integer observedGeneration; /** * SubscriberURI is the resolved URI of the receiver for this Trigger. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String subscriberUri; /** * Array of observed TriggerConditions, indicating the current state of the Trigger. * @return value or {@code null} for none */ public java.util.List<TriggerCondition> getConditions() { return conditions; } /** * Array of observed TriggerConditions, indicating the current state of the Trigger. * @param conditions conditions or {@code null} for none */ public TriggerStatus setConditions(java.util.List<TriggerCondition> conditions) { this.conditions = conditions; return this; } /** * ObservedGeneration is the 'Generation' of the Trigger that was last processed by the * controller. * @return value or {@code null} for none */ public java.lang.Integer getObservedGeneration() { return observedGeneration; } /** * ObservedGeneration is the 'Generation' of the Trigger that was last processed by the * controller. * @param observedGeneration observedGeneration or {@code null} for none */ public TriggerStatus setObservedGeneration(java.lang.Integer observedGeneration) { this.observedGeneration = observedGeneration; return this; } /** * SubscriberURI is the resolved URI of the receiver for this Trigger. * @return value or {@code null} for none */ public java.lang.String getSubscriberUri() { return subscriberUri; } /** * SubscriberURI is the resolved URI of the receiver for this Trigger. * @param subscriberUri subscriberUri or {@code null} for none */ public TriggerStatus setSubscriberUri(java.lang.String subscriberUri) { this.subscriberUri = subscriberUri; return this; } @Override public TriggerStatus set(String fieldName, Object value) { return (TriggerStatus) super.set(fieldName, value); } @Override public TriggerStatus clone() { return (TriggerStatus) super.clone(); } }
FRCTeam1506/Falconstructor-2021
src/main/java/frc/robot/commands/Auton/Nothing.java
<reponame>FRCTeam1506/Falconstructor-2021<gh_stars>0 package frc.robot.commands.Auton; import edu.wpi.first.wpilibj2.command.CommandBase; public class Nothing extends CommandBase { public Nothing() {} @Override public void execute() {} @Override public boolean isFinished() { return false; } }
screwjack/nemesis
Main/LanguageStrings.h
<reponame>screwjack/nemesis /* Copyright (c) 2008 nemesis Developers Association. All rights reserved. Governed by the nemesis License 3.0 the full text of which is contained in the file License.txt included in nemesis binary and source code distribution packages. */ #ifndef TC_HEADER_Main_LanguageStrings #define TC_HEADER_Main_LanguageStrings #include "System.h" #include "Main.h" namespace nemesis { class LanguageStrings { public: LanguageStrings (); virtual ~LanguageStrings (); wxString operator[] (const string &key) const; bool Exists (const string &key) const { return Map.find (key) != Map.end(); } wstring Get (const string &key) const; void Init (); protected: map <string, wstring> Map; private: LanguageStrings (const LanguageStrings &); LanguageStrings &operator= (const LanguageStrings &); }; extern LanguageStrings LangString; } #endif // TC_HEADER_Main_LanguageStrings
13022108937/homework
JiaLu/learn/circulation_training22.py
<filename>JiaLu/learn/circulation_training22.py #!/usr/bin/env python import datetime num = int(input("Enter a number: ")) count = 1 start = datetime.datetime.now() for i in range(3,num,2): if i > 10 and i % 10 == 5: # if i > 11 and i % 6 !=5 and i % 6 != 1: continue for j in range(3,int(i ** 0.5 + 1),2): if i % j == 0: break else: count += 1 # print(i) end = datetime.datetime.now() times = (end - start).total_seconds() print(count) print(times)
go-things/things
src/usersvr/user/user.pb.go
<filename>src/usersvr/user/user.pb.go<gh_stars>10-100 // Code generated by protoc-gen-go. DO NOT EDIT. // source: user.proto package user import ( context "context" fmt "fmt" proto "github.com/golang/protobuf/proto" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" math "math" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package type PageInfo struct { Page int64 `protobuf:"varint,1,opt,name=page,proto3" json:"page,omitempty"` PageSize int64 `protobuf:"varint,2,opt,name=pageSize,proto3" json:"pageSize,omitempty"` SearchKey string `protobuf:"bytes,3,opt,name=searchKey,proto3" json:"searchKey,omitempty"` SearchType string `protobuf:"bytes,4,opt,name=searchType,proto3" json:"searchType,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *PageInfo) Reset() { *m = PageInfo{} } func (m *PageInfo) String() string { return proto.CompactTextString(m) } func (*PageInfo) ProtoMessage() {} func (*PageInfo) Descriptor() ([]byte, []int) { return fileDescriptor_116e343673f7ffaf, []int{0} } func (m *PageInfo) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_PageInfo.Unmarshal(m, b) } func (m *PageInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_PageInfo.Marshal(b, m, deterministic) } func (m *PageInfo) XXX_Merge(src proto.Message) { xxx_messageInfo_PageInfo.Merge(m, src) } func (m *PageInfo) XXX_Size() int { return xxx_messageInfo_PageInfo.Size(m) } func (m *PageInfo) XXX_DiscardUnknown() { xxx_messageInfo_PageInfo.DiscardUnknown(m) } var xxx_messageInfo_PageInfo proto.InternalMessageInfo func (m *PageInfo) GetPage() int64 { if m != nil { return m.Page } return 0 } func (m *PageInfo) GetPageSize() int64 { if m != nil { return m.PageSize } return 0 } func (m *PageInfo) GetSearchKey() string { if m != nil { return m.SearchKey } return "" } func (m *PageInfo) GetSearchType() string { if m != nil { return m.SearchType } return "" } type JwtToken struct { AccessToken string `protobuf:"bytes,1,opt,name=accessToken,proto3" json:"accessToken,omitempty"` AccessExpire int64 `protobuf:"varint,2,opt,name=accessExpire,proto3" json:"accessExpire,omitempty"` RefreshAfter int64 `protobuf:"varint,3,opt,name=refreshAfter,proto3" json:"refreshAfter,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *JwtToken) Reset() { *m = JwtToken{} } func (m *JwtToken) String() string { return proto.CompactTextString(m) } func (*JwtToken) ProtoMessage() {} func (*JwtToken) Descriptor() ([]byte, []int) { return fileDescriptor_116e343673f7ffaf, []int{1} } func (m *JwtToken) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_JwtToken.Unmarshal(m, b) } func (m *JwtToken) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_JwtToken.Marshal(b, m, deterministic) } func (m *JwtToken) XXX_Merge(src proto.Message) { xxx_messageInfo_JwtToken.Merge(m, src) } func (m *JwtToken) XXX_Size() int { return xxx_messageInfo_JwtToken.Size(m) } func (m *JwtToken) XXX_DiscardUnknown() { xxx_messageInfo_JwtToken.DiscardUnknown(m) } var xxx_messageInfo_JwtToken proto.InternalMessageInfo func (m *JwtToken) GetAccessToken() string { if m != nil { return m.AccessToken } return "" } func (m *JwtToken) GetAccessExpire() int64 { if m != nil { return m.AccessExpire } return 0 } func (m *JwtToken) GetRefreshAfter() int64 { if m != nil { return m.RefreshAfter } return 0 } type NilResp struct { XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *NilResp) Reset() { *m = NilResp{} } func (m *NilResp) String() string { return proto.CompactTextString(m) } func (*NilResp) ProtoMessage() {} func (*NilResp) Descriptor() ([]byte, []int) { return fileDescriptor_116e343673f7ffaf, []int{2} } func (m *NilResp) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_NilResp.Unmarshal(m, b) } func (m *NilResp) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_NilResp.Marshal(b, m, deterministic) } func (m *NilResp) XXX_Merge(src proto.Message) { xxx_messageInfo_NilResp.Merge(m, src) } func (m *NilResp) XXX_Size() int { return xxx_messageInfo_NilResp.Size(m) } func (m *NilResp) XXX_DiscardUnknown() { xxx_messageInfo_NilResp.DiscardUnknown(m) } var xxx_messageInfo_NilResp proto.InternalMessageInfo //用户属性信息 type UserInfo struct { Uid int64 `protobuf:"varint,1,opt,name=uid,proto3" json:"uid,omitempty"` UserName string `protobuf:"bytes,2,opt,name=userName,proto3" json:"userName,omitempty"` NickName string `protobuf:"bytes,3,opt,name=nickName,proto3" json:"nickName,omitempty"` InviterUid int64 `protobuf:"varint,4,opt,name=inviterUid,proto3" json:"inviterUid,omitempty"` InviterId string `protobuf:"bytes,5,opt,name=inviterId,proto3" json:"inviterId,omitempty"` Sex int64 `protobuf:"varint,6,opt,name=sex,proto3" json:"sex,omitempty"` City string `protobuf:"bytes,7,opt,name=city,proto3" json:"city,omitempty"` Country string `protobuf:"bytes,8,opt,name=country,proto3" json:"country,omitempty"` Province string `protobuf:"bytes,9,opt,name=province,proto3" json:"province,omitempty"` Language string `protobuf:"bytes,10,opt,name=language,proto3" json:"language,omitempty"` HeadImgUrl string `protobuf:"bytes,11,opt,name=headImgUrl,proto3" json:"headImgUrl,omitempty"` CreateTime int64 `protobuf:"varint,12,opt,name=createTime,proto3" json:"createTime,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *UserInfo) Reset() { *m = UserInfo{} } func (m *UserInfo) String() string { return proto.CompactTextString(m) } func (*UserInfo) ProtoMessage() {} func (*UserInfo) Descriptor() ([]byte, []int) { return fileDescriptor_116e343673f7ffaf, []int{3} } func (m *UserInfo) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_UserInfo.Unmarshal(m, b) } func (m *UserInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_UserInfo.Marshal(b, m, deterministic) } func (m *UserInfo) XXX_Merge(src proto.Message) { xxx_messageInfo_UserInfo.Merge(m, src) } func (m *UserInfo) XXX_Size() int { return xxx_messageInfo_UserInfo.Size(m) } func (m *UserInfo) XXX_DiscardUnknown() { xxx_messageInfo_UserInfo.DiscardUnknown(m) } var xxx_messageInfo_UserInfo proto.InternalMessageInfo func (m *UserInfo) GetUid() int64 { if m != nil { return m.Uid } return 0 } func (m *UserInfo) GetUserName() string { if m != nil { return m.UserName } return "" } func (m *UserInfo) GetNickName() string { if m != nil { return m.NickName } return "" } func (m *UserInfo) GetInviterUid() int64 { if m != nil { return m.InviterUid } return 0 } func (m *UserInfo) GetInviterId() string { if m != nil { return m.InviterId } return "" } func (m *UserInfo) GetSex() int64 { if m != nil { return m.Sex } return 0 } func (m *UserInfo) GetCity() string { if m != nil { return m.City } return "" } func (m *UserInfo) GetCountry() string { if m != nil { return m.Country } return "" } func (m *UserInfo) GetProvince() string { if m != nil { return m.Province } return "" } func (m *UserInfo) GetLanguage() string { if m != nil { return m.Language } return "" } func (m *UserInfo) GetHeadImgUrl() string { if m != nil { return m.HeadImgUrl } return "" } func (m *UserInfo) GetCreateTime() int64 { if m != nil { return m.CreateTime } return 0 } //用户核心信息 type UserCore struct { Uid int64 `protobuf:"varint,1,opt,name=uid,proto3" json:"uid,omitempty"` UserName string `protobuf:"bytes,2,opt,name=userName,proto3" json:"userName,omitempty"` Password string `protobuf:"bytes,3,opt,name=password,proto3" json:"password,omitempty"` Email string `protobuf:"bytes,4,opt,name=email,proto3" json:"email,omitempty"` Phone string `protobuf:"bytes,5,opt,name=phone,proto3" json:"phone,omitempty"` Wechat string `protobuf:"bytes,6,opt,name=wechat,proto3" json:"wechat,omitempty"` LastIP string `protobuf:"bytes,7,opt,name=lastIP,proto3" json:"lastIP,omitempty"` RegIP string `protobuf:"bytes,8,opt,name=regIP,proto3" json:"regIP,omitempty"` CreatedTime int64 `protobuf:"varint,9,opt,name=createdTime,proto3" json:"createdTime,omitempty"` Status int64 `protobuf:"varint,10,opt,name=status,proto3" json:"status,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *UserCore) Reset() { *m = UserCore{} } func (m *UserCore) String() string { return proto.CompactTextString(m) } func (*UserCore) ProtoMessage() {} func (*UserCore) Descriptor() ([]byte, []int) { return fileDescriptor_116e343673f7ffaf, []int{4} } func (m *UserCore) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_UserCore.Unmarshal(m, b) } func (m *UserCore) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_UserCore.Marshal(b, m, deterministic) } func (m *UserCore) XXX_Merge(src proto.Message) { xxx_messageInfo_UserCore.Merge(m, src) } func (m *UserCore) XXX_Size() int { return xxx_messageInfo_UserCore.Size(m) } func (m *UserCore) XXX_DiscardUnknown() { xxx_messageInfo_UserCore.DiscardUnknown(m) } var xxx_messageInfo_UserCore proto.InternalMessageInfo func (m *UserCore) GetUid() int64 { if m != nil { return m.Uid } return 0 } func (m *UserCore) GetUserName() string { if m != nil { return m.UserName } return "" } func (m *UserCore) GetPassword() string { if m != nil { return m.Password } return "" } func (m *UserCore) GetEmail() string { if m != nil { return m.Email } return "" } func (m *UserCore) GetPhone() string { if m != nil { return m.Phone } return "" } func (m *UserCore) GetWechat() string { if m != nil { return m.Wechat } return "" } func (m *UserCore) GetLastIP() string { if m != nil { return m.LastIP } return "" } func (m *UserCore) GetRegIP() string { if m != nil { return m.RegIP } return "" } func (m *UserCore) GetCreatedTime() int64 { if m != nil { return m.CreatedTime } return 0 } func (m *UserCore) GetStatus() int64 { if m != nil { return m.Status } return 0 } type RegisterCoreReq struct { ReqType string `protobuf:"bytes,1,opt,name=reqType,proto3" json:"reqType,omitempty"` Note string `protobuf:"bytes,2,opt,name=note,proto3" json:"note,omitempty"` Code string `protobuf:"bytes,3,opt,name=code,proto3" json:"code,omitempty"` CodeID string `protobuf:"bytes,4,opt,name=codeID,proto3" json:"codeID,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *RegisterCoreReq) Reset() { *m = RegisterCoreReq{} } func (m *RegisterCoreReq) String() string { return proto.CompactTextString(m) } func (*RegisterCoreReq) ProtoMessage() {} func (*RegisterCoreReq) Descriptor() ([]byte, []int) { return fileDescriptor_116e343673f7ffaf, []int{5} } func (m *RegisterCoreReq) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_RegisterCoreReq.Unmarshal(m, b) } func (m *RegisterCoreReq) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_RegisterCoreReq.Marshal(b, m, deterministic) } func (m *RegisterCoreReq) XXX_Merge(src proto.Message) { xxx_messageInfo_RegisterCoreReq.Merge(m, src) } func (m *RegisterCoreReq) XXX_Size() int { return xxx_messageInfo_RegisterCoreReq.Size(m) } func (m *RegisterCoreReq) XXX_DiscardUnknown() { xxx_messageInfo_RegisterCoreReq.DiscardUnknown(m) } var xxx_messageInfo_RegisterCoreReq proto.InternalMessageInfo func (m *RegisterCoreReq) GetReqType() string { if m != nil { return m.ReqType } return "" } func (m *RegisterCoreReq) GetNote() string { if m != nil { return m.Note } return "" } func (m *RegisterCoreReq) GetCode() string { if m != nil { return m.Code } return "" } func (m *RegisterCoreReq) GetCodeID() string { if m != nil { return m.CodeID } return "" } type RegisterCoreResp struct { Uid int64 `protobuf:"varint,1,opt,name=uid,proto3" json:"uid,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *RegisterCoreResp) Reset() { *m = RegisterCoreResp{} } func (m *RegisterCoreResp) String() string { return proto.CompactTextString(m) } func (*RegisterCoreResp) ProtoMessage() {} func (*RegisterCoreResp) Descriptor() ([]byte, []int) { return fileDescriptor_116e343673f7ffaf, []int{6} } func (m *RegisterCoreResp) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_RegisterCoreResp.Unmarshal(m, b) } func (m *RegisterCoreResp) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_RegisterCoreResp.Marshal(b, m, deterministic) } func (m *RegisterCoreResp) XXX_Merge(src proto.Message) { xxx_messageInfo_RegisterCoreResp.Merge(m, src) } func (m *RegisterCoreResp) XXX_Size() int { return xxx_messageInfo_RegisterCoreResp.Size(m) } func (m *RegisterCoreResp) XXX_DiscardUnknown() { xxx_messageInfo_RegisterCoreResp.DiscardUnknown(m) } var xxx_messageInfo_RegisterCoreResp proto.InternalMessageInfo func (m *RegisterCoreResp) GetUid() int64 { if m != nil { return m.Uid } return 0 } type Register2Req struct { Info *UserInfo `protobuf:"bytes,1,opt,name=info,proto3" json:"info,omitempty"` Password string `protobuf:"bytes,2,opt,name=password,proto3" json:"password,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *Register2Req) Reset() { *m = Register2Req{} } func (m *Register2Req) String() string { return proto.CompactTextString(m) } func (*Register2Req) ProtoMessage() {} func (*Register2Req) Descriptor() ([]byte, []int) { return fileDescriptor_116e343673f7ffaf, []int{7} } func (m *Register2Req) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Register2Req.Unmarshal(m, b) } func (m *Register2Req) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_Register2Req.Marshal(b, m, deterministic) } func (m *Register2Req) XXX_Merge(src proto.Message) { xxx_messageInfo_Register2Req.Merge(m, src) } func (m *Register2Req) XXX_Size() int { return xxx_messageInfo_Register2Req.Size(m) } func (m *Register2Req) XXX_DiscardUnknown() { xxx_messageInfo_Register2Req.DiscardUnknown(m) } var xxx_messageInfo_Register2Req proto.InternalMessageInfo func (m *Register2Req) GetInfo() *UserInfo { if m != nil { return m.Info } return nil } func (m *Register2Req) GetPassword() string { if m != nil { return m.Password } return "" } type Register2Resp struct { XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *Register2Resp) Reset() { *m = Register2Resp{} } func (m *Register2Resp) String() string { return proto.CompactTextString(m) } func (*Register2Resp) ProtoMessage() {} func (*Register2Resp) Descriptor() ([]byte, []int) { return fileDescriptor_116e343673f7ffaf, []int{8} } func (m *Register2Resp) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Register2Resp.Unmarshal(m, b) } func (m *Register2Resp) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_Register2Resp.Marshal(b, m, deterministic) } func (m *Register2Resp) XXX_Merge(src proto.Message) { xxx_messageInfo_Register2Resp.Merge(m, src) } func (m *Register2Resp) XXX_Size() int { return xxx_messageInfo_Register2Resp.Size(m) } func (m *Register2Resp) XXX_DiscardUnknown() { xxx_messageInfo_Register2Resp.DiscardUnknown(m) } var xxx_messageInfo_Register2Resp proto.InternalMessageInfo type GetUserInfoReq struct { Uid []int64 `protobuf:"varint,1,rep,packed,name=uid,proto3" json:"uid,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *GetUserInfoReq) Reset() { *m = GetUserInfoReq{} } func (m *GetUserInfoReq) String() string { return proto.CompactTextString(m) } func (*GetUserInfoReq) ProtoMessage() {} func (*GetUserInfoReq) Descriptor() ([]byte, []int) { return fileDescriptor_116e343673f7ffaf, []int{9} } func (m *GetUserInfoReq) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_GetUserInfoReq.Unmarshal(m, b) } func (m *GetUserInfoReq) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_GetUserInfoReq.Marshal(b, m, deterministic) } func (m *GetUserInfoReq) XXX_Merge(src proto.Message) { xxx_messageInfo_GetUserInfoReq.Merge(m, src) } func (m *GetUserInfoReq) XXX_Size() int { return xxx_messageInfo_GetUserInfoReq.Size(m) } func (m *GetUserInfoReq) XXX_DiscardUnknown() { xxx_messageInfo_GetUserInfoReq.DiscardUnknown(m) } var xxx_messageInfo_GetUserInfoReq proto.InternalMessageInfo func (m *GetUserInfoReq) GetUid() []int64 { if m != nil { return m.Uid } return nil } type GetUserInfoResp struct { Info []*UserInfo `protobuf:"bytes,1,rep,name=info,proto3" json:"info,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *GetUserInfoResp) Reset() { *m = GetUserInfoResp{} } func (m *GetUserInfoResp) String() string { return proto.CompactTextString(m) } func (*GetUserInfoResp) ProtoMessage() {} func (*GetUserInfoResp) Descriptor() ([]byte, []int) { return fileDescriptor_116e343673f7ffaf, []int{10} } func (m *GetUserInfoResp) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_GetUserInfoResp.Unmarshal(m, b) } func (m *GetUserInfoResp) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_GetUserInfoResp.Marshal(b, m, deterministic) } func (m *GetUserInfoResp) XXX_Merge(src proto.Message) { xxx_messageInfo_GetUserInfoResp.Merge(m, src) } func (m *GetUserInfoResp) XXX_Size() int { return xxx_messageInfo_GetUserInfoResp.Size(m) } func (m *GetUserInfoResp) XXX_DiscardUnknown() { xxx_messageInfo_GetUserInfoResp.DiscardUnknown(m) } var xxx_messageInfo_GetUserInfoResp proto.InternalMessageInfo func (m *GetUserInfoResp) GetInfo() []*UserInfo { if m != nil { return m.Info } return nil } type GetUserCoreReq struct { Uid int64 `protobuf:"varint,1,opt,name=uid,proto3" json:"uid,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *GetUserCoreReq) Reset() { *m = GetUserCoreReq{} } func (m *GetUserCoreReq) String() string { return proto.CompactTextString(m) } func (*GetUserCoreReq) ProtoMessage() {} func (*GetUserCoreReq) Descriptor() ([]byte, []int) { return fileDescriptor_116e343673f7ffaf, []int{11} } func (m *GetUserCoreReq) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_GetUserCoreReq.Unmarshal(m, b) } func (m *GetUserCoreReq) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_GetUserCoreReq.Marshal(b, m, deterministic) } func (m *GetUserCoreReq) XXX_Merge(src proto.Message) { xxx_messageInfo_GetUserCoreReq.Merge(m, src) } func (m *GetUserCoreReq) XXX_Size() int { return xxx_messageInfo_GetUserCoreReq.Size(m) } func (m *GetUserCoreReq) XXX_DiscardUnknown() { xxx_messageInfo_GetUserCoreReq.DiscardUnknown(m) } var xxx_messageInfo_GetUserCoreReq proto.InternalMessageInfo func (m *GetUserCoreReq) GetUid() int64 { if m != nil { return m.Uid } return 0 } type GetUserCoreResp struct { Info *UserCore `protobuf:"bytes,1,opt,name=info,proto3" json:"info,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *GetUserCoreResp) Reset() { *m = GetUserCoreResp{} } func (m *GetUserCoreResp) String() string { return proto.CompactTextString(m) } func (*GetUserCoreResp) ProtoMessage() {} func (*GetUserCoreResp) Descriptor() ([]byte, []int) { return fileDescriptor_116e343673f7ffaf, []int{12} } func (m *GetUserCoreResp) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_GetUserCoreResp.Unmarshal(m, b) } func (m *GetUserCoreResp) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_GetUserCoreResp.Marshal(b, m, deterministic) } func (m *GetUserCoreResp) XXX_Merge(src proto.Message) { xxx_messageInfo_GetUserCoreResp.Merge(m, src) } func (m *GetUserCoreResp) XXX_Size() int { return xxx_messageInfo_GetUserCoreResp.Size(m) } func (m *GetUserCoreResp) XXX_DiscardUnknown() { xxx_messageInfo_GetUserCoreResp.DiscardUnknown(m) } var xxx_messageInfo_GetUserCoreResp proto.InternalMessageInfo func (m *GetUserCoreResp) GetInfo() *UserCore { if m != nil { return m.Info } return nil } type LoginReq struct { UserID string `protobuf:"bytes,1,opt,name=userID,proto3" json:"userID,omitempty"` PwdType int32 `protobuf:"varint,2,opt,name=pwdType,proto3" json:"pwdType,omitempty"` Password string `protobuf:"bytes,3,opt,name=password,proto3" json:"password,omitempty"` LoginType string `protobuf:"bytes,4,opt,name=loginType,proto3" json:"loginType,omitempty"` Code string `protobuf:"bytes,5,opt,name=code,proto3" json:"code,omitempty"` CodeID string `protobuf:"bytes,6,opt,name=codeID,proto3" json:"codeID,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *LoginReq) Reset() { *m = LoginReq{} } func (m *LoginReq) String() string { return proto.CompactTextString(m) } func (*LoginReq) ProtoMessage() {} func (*LoginReq) Descriptor() ([]byte, []int) { return fileDescriptor_116e343673f7ffaf, []int{13} } func (m *LoginReq) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_LoginReq.Unmarshal(m, b) } func (m *LoginReq) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_LoginReq.Marshal(b, m, deterministic) } func (m *LoginReq) XXX_Merge(src proto.Message) { xxx_messageInfo_LoginReq.Merge(m, src) } func (m *LoginReq) XXX_Size() int { return xxx_messageInfo_LoginReq.Size(m) } func (m *LoginReq) XXX_DiscardUnknown() { xxx_messageInfo_LoginReq.DiscardUnknown(m) } var xxx_messageInfo_LoginReq proto.InternalMessageInfo func (m *LoginReq) GetUserID() string { if m != nil { return m.UserID } return "" } func (m *LoginReq) GetPwdType() int32 { if m != nil { return m.PwdType } return 0 } func (m *LoginReq) GetPassword() string { if m != nil { return m.Password } return "" } func (m *LoginReq) GetLoginType() string { if m != nil { return m.LoginType } return "" } func (m *LoginReq) GetCode() string { if m != nil { return m.Code } return "" } func (m *LoginReq) GetCodeID() string { if m != nil { return m.CodeID } return "" } type LoginResp struct { Info *UserInfo `protobuf:"bytes,1,opt,name=info,proto3" json:"info,omitempty"` Token *JwtToken `protobuf:"bytes,2,opt,name=token,proto3" json:"token,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *LoginResp) Reset() { *m = LoginResp{} } func (m *LoginResp) String() string { return proto.CompactTextString(m) } func (*LoginResp) ProtoMessage() {} func (*LoginResp) Descriptor() ([]byte, []int) { return fileDescriptor_116e343673f7ffaf, []int{14} } func (m *LoginResp) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_LoginResp.Unmarshal(m, b) } func (m *LoginResp) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_LoginResp.Marshal(b, m, deterministic) } func (m *LoginResp) XXX_Merge(src proto.Message) { xxx_messageInfo_LoginResp.Merge(m, src) } func (m *LoginResp) XXX_Size() int { return xxx_messageInfo_LoginResp.Size(m) } func (m *LoginResp) XXX_DiscardUnknown() { xxx_messageInfo_LoginResp.DiscardUnknown(m) } var xxx_messageInfo_LoginResp proto.InternalMessageInfo func (m *LoginResp) GetInfo() *UserInfo { if m != nil { return m.Info } return nil } func (m *LoginResp) GetToken() *JwtToken { if m != nil { return m.Token } return nil } type CheckTokenReq struct { Token string `protobuf:"bytes,1,opt,name=token,proto3" json:"token,omitempty"` Ip string `protobuf:"bytes,2,opt,name=ip,proto3" json:"ip,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *CheckTokenReq) Reset() { *m = CheckTokenReq{} } func (m *CheckTokenReq) String() string { return proto.CompactTextString(m) } func (*CheckTokenReq) ProtoMessage() {} func (*CheckTokenReq) Descriptor() ([]byte, []int) { return fileDescriptor_116e343673f7ffaf, []int{15} } func (m *CheckTokenReq) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_CheckTokenReq.Unmarshal(m, b) } func (m *CheckTokenReq) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_CheckTokenReq.Marshal(b, m, deterministic) } func (m *CheckTokenReq) XXX_Merge(src proto.Message) { xxx_messageInfo_CheckTokenReq.Merge(m, src) } func (m *CheckTokenReq) XXX_Size() int { return xxx_messageInfo_CheckTokenReq.Size(m) } func (m *CheckTokenReq) XXX_DiscardUnknown() { xxx_messageInfo_CheckTokenReq.DiscardUnknown(m) } var xxx_messageInfo_CheckTokenReq proto.InternalMessageInfo func (m *CheckTokenReq) GetToken() string { if m != nil { return m.Token } return "" } func (m *CheckTokenReq) GetIp() string { if m != nil { return m.Ip } return "" } type CheckTokenResp struct { Token string `protobuf:"bytes,1,opt,name=token,proto3" json:"token,omitempty"` Uid int64 `protobuf:"varint,2,opt,name=uid,proto3" json:"uid,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *CheckTokenResp) Reset() { *m = CheckTokenResp{} } func (m *CheckTokenResp) String() string { return proto.CompactTextString(m) } func (*CheckTokenResp) ProtoMessage() {} func (*CheckTokenResp) Descriptor() ([]byte, []int) { return fileDescriptor_116e343673f7ffaf, []int{16} } func (m *CheckTokenResp) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_CheckTokenResp.Unmarshal(m, b) } func (m *CheckTokenResp) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_CheckTokenResp.Marshal(b, m, deterministic) } func (m *CheckTokenResp) XXX_Merge(src proto.Message) { xxx_messageInfo_CheckTokenResp.Merge(m, src) } func (m *CheckTokenResp) XXX_Size() int { return xxx_messageInfo_CheckTokenResp.Size(m) } func (m *CheckTokenResp) XXX_DiscardUnknown() { xxx_messageInfo_CheckTokenResp.DiscardUnknown(m) } var xxx_messageInfo_CheckTokenResp proto.InternalMessageInfo func (m *CheckTokenResp) GetToken() string { if m != nil { return m.Token } return "" } func (m *CheckTokenResp) GetUid() int64 { if m != nil { return m.Uid } return 0 } type ModifyUserInfoReq struct { Uid int64 `protobuf:"varint,1,opt,name=uid,proto3" json:"uid,omitempty"` Info map[string]string `protobuf:"bytes,2,rep,name=info,proto3" json:"info,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *ModifyUserInfoReq) Reset() { *m = ModifyUserInfoReq{} } func (m *ModifyUserInfoReq) String() string { return proto.CompactTextString(m) } func (*ModifyUserInfoReq) ProtoMessage() {} func (*ModifyUserInfoReq) Descriptor() ([]byte, []int) { return fileDescriptor_116e343673f7ffaf, []int{17} } func (m *ModifyUserInfoReq) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_ModifyUserInfoReq.Unmarshal(m, b) } func (m *ModifyUserInfoReq) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_ModifyUserInfoReq.Marshal(b, m, deterministic) } func (m *ModifyUserInfoReq) XXX_Merge(src proto.Message) { xxx_messageInfo_ModifyUserInfoReq.Merge(m, src) } func (m *ModifyUserInfoReq) XXX_Size() int { return xxx_messageInfo_ModifyUserInfoReq.Size(m) } func (m *ModifyUserInfoReq) XXX_DiscardUnknown() { xxx_messageInfo_ModifyUserInfoReq.DiscardUnknown(m) } var xxx_messageInfo_ModifyUserInfoReq proto.InternalMessageInfo func (m *ModifyUserInfoReq) GetUid() int64 { if m != nil { return m.Uid } return 0 } func (m *ModifyUserInfoReq) GetInfo() map[string]string { if m != nil { return m.Info } return nil } type GetUserCoreListReq struct { Page *PageInfo `protobuf:"bytes,1,opt,name=page,proto3" json:"page,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *GetUserCoreListReq) Reset() { *m = GetUserCoreListReq{} } func (m *GetUserCoreListReq) String() string { return proto.CompactTextString(m) } func (*GetUserCoreListReq) ProtoMessage() {} func (*GetUserCoreListReq) Descriptor() ([]byte, []int) { return fileDescriptor_116e343673f7ffaf, []int{18} } func (m *GetUserCoreListReq) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_GetUserCoreListReq.Unmarshal(m, b) } func (m *GetUserCoreListReq) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_GetUserCoreListReq.Marshal(b, m, deterministic) } func (m *GetUserCoreListReq) XXX_Merge(src proto.Message) { xxx_messageInfo_GetUserCoreListReq.Merge(m, src) } func (m *GetUserCoreListReq) XXX_Size() int { return xxx_messageInfo_GetUserCoreListReq.Size(m) } func (m *GetUserCoreListReq) XXX_DiscardUnknown() { xxx_messageInfo_GetUserCoreListReq.DiscardUnknown(m) } var xxx_messageInfo_GetUserCoreListReq proto.InternalMessageInfo func (m *GetUserCoreListReq) GetPage() *PageInfo { if m != nil { return m.Page } return nil } type GetUserCoreListResp struct { Info []*UserCore `protobuf:"bytes,1,rep,name=info,proto3" json:"info,omitempty"` Total int64 `protobuf:"varint,2,opt,name=total,proto3" json:"total,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *GetUserCoreListResp) Reset() { *m = GetUserCoreListResp{} } func (m *GetUserCoreListResp) String() string { return proto.CompactTextString(m) } func (*GetUserCoreListResp) ProtoMessage() {} func (*GetUserCoreListResp) Descriptor() ([]byte, []int) { return fileDescriptor_116e343673f7ffaf, []int{19} } func (m *GetUserCoreListResp) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_GetUserCoreListResp.Unmarshal(m, b) } func (m *GetUserCoreListResp) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_GetUserCoreListResp.Marshal(b, m, deterministic) } func (m *GetUserCoreListResp) XXX_Merge(src proto.Message) { xxx_messageInfo_GetUserCoreListResp.Merge(m, src) } func (m *GetUserCoreListResp) XXX_Size() int { return xxx_messageInfo_GetUserCoreListResp.Size(m) } func (m *GetUserCoreListResp) XXX_DiscardUnknown() { xxx_messageInfo_GetUserCoreListResp.DiscardUnknown(m) } var xxx_messageInfo_GetUserCoreListResp proto.InternalMessageInfo func (m *GetUserCoreListResp) GetInfo() []*UserCore { if m != nil { return m.Info } return nil } func (m *GetUserCoreListResp) GetTotal() int64 { if m != nil { return m.Total } return 0 } func init() { proto.RegisterType((*PageInfo)(nil), "user.PageInfo") proto.RegisterType((*JwtToken)(nil), "user.JwtToken") proto.RegisterType((*NilResp)(nil), "user.NilResp") proto.RegisterType((*UserInfo)(nil), "user.UserInfo") proto.RegisterType((*UserCore)(nil), "user.UserCore") proto.RegisterType((*RegisterCoreReq)(nil), "user.RegisterCoreReq") proto.RegisterType((*RegisterCoreResp)(nil), "user.RegisterCoreResp") proto.RegisterType((*Register2Req)(nil), "user.Register2Req") proto.RegisterType((*Register2Resp)(nil), "user.Register2Resp") proto.RegisterType((*GetUserInfoReq)(nil), "user.GetUserInfoReq") proto.RegisterType((*GetUserInfoResp)(nil), "user.GetUserInfoResp") proto.RegisterType((*GetUserCoreReq)(nil), "user.GetUserCoreReq") proto.RegisterType((*GetUserCoreResp)(nil), "user.GetUserCoreResp") proto.RegisterType((*LoginReq)(nil), "user.LoginReq") proto.RegisterType((*LoginResp)(nil), "user.LoginResp") proto.RegisterType((*CheckTokenReq)(nil), "user.CheckTokenReq") proto.RegisterType((*CheckTokenResp)(nil), "user.CheckTokenResp") proto.RegisterType((*ModifyUserInfoReq)(nil), "user.ModifyUserInfoReq") proto.RegisterMapType((map[string]string)(nil), "user.ModifyUserInfoReq.InfoEntry") proto.RegisterType((*GetUserCoreListReq)(nil), "user.GetUserCoreListReq") proto.RegisterType((*GetUserCoreListResp)(nil), "user.GetUserCoreListResp") } func init() { proto.RegisterFile("user.proto", fileDescriptor_116e343673f7ffaf) } var fileDescriptor_116e343673f7ffaf = []byte{ // 937 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x56, 0xdd, 0x6e, 0xe3, 0x44, 0x14, 0x56, 0x7e, 0x1b, 0x9f, 0xb6, 0xc9, 0x32, 0xdb, 0x16, 0x13, 0xad, 0x50, 0xb1, 0xf6, 0xa2, 0x57, 0xbd, 0x28, 0x54, 0x5b, 0xad, 0xc4, 0x05, 0xda, 0x5d, 0x50, 0xa0, 0x94, 0xca, 0xb4, 0x0f, 0x60, 0xec, 0x13, 0x67, 0x94, 0xc4, 0x9e, 0x7a, 0x26, 0x6d, 0xc3, 0x15, 0x2f, 0xc1, 0x0b, 0xf0, 0x38, 0x3c, 0x01, 0x8f, 0x83, 0xce, 0xfc, 0xf8, 0x87, 0x24, 0x95, 0xb8, 0xf2, 0x7c, 0xdf, 0x9c, 0x19, 0x9f, 0xf3, 0x7d, 0x67, 0xc6, 0x06, 0x58, 0x49, 0x2c, 0xce, 0x45, 0x91, 0xab, 0x9c, 0x75, 0x69, 0x1c, 0x3c, 0xc3, 0xe0, 0x36, 0x4a, 0x71, 0x92, 0x4d, 0x73, 0xc6, 0xa0, 0x2b, 0xa2, 0x14, 0xfd, 0xd6, 0x69, 0xeb, 0xac, 0x13, 0xea, 0x31, 0x1b, 0xc3, 0x80, 0x9e, 0xbf, 0xf2, 0xdf, 0xd1, 0x6f, 0x6b, 0xbe, 0xc4, 0xec, 0x0d, 0x78, 0x12, 0xa3, 0x22, 0x9e, 0xfd, 0x84, 0x6b, 0xbf, 0x73, 0xda, 0x3a, 0xf3, 0xc2, 0x8a, 0x60, 0x5f, 0x02, 0x18, 0x70, 0xb7, 0x16, 0xe8, 0x77, 0xf5, 0x74, 0x8d, 0x09, 0x14, 0x0c, 0x7e, 0x7c, 0x52, 0x77, 0xf9, 0x1c, 0x33, 0x76, 0x0a, 0xfb, 0x51, 0x1c, 0xa3, 0x94, 0x1a, 0xea, 0x04, 0xbc, 0xb0, 0x4e, 0xb1, 0x00, 0x0e, 0x0c, 0xfc, 0xf4, 0x2c, 0x78, 0xe1, 0x72, 0x69, 0x70, 0x14, 0x53, 0xe0, 0xb4, 0x40, 0x39, 0xfb, 0x6e, 0xaa, 0xb0, 0xd0, 0x29, 0x75, 0xc2, 0x06, 0x17, 0x78, 0xb0, 0x77, 0xc3, 0x17, 0x21, 0x4a, 0x11, 0xfc, 0xdd, 0x86, 0xc1, 0xbd, 0xc4, 0x42, 0xd7, 0xfe, 0x0a, 0x3a, 0x2b, 0x9e, 0xd8, 0xd2, 0x69, 0x48, 0x95, 0x93, 0x42, 0x37, 0xd1, 0xd2, 0xbc, 0xcd, 0x0b, 0x4b, 0x4c, 0x73, 0x19, 0x8f, 0xe7, 0x7a, 0xce, 0x14, 0x5e, 0x62, 0xaa, 0x9b, 0x67, 0x8f, 0x5c, 0x61, 0x71, 0xcf, 0x13, 0x5d, 0x77, 0x27, 0xac, 0x31, 0xa4, 0x9a, 0x45, 0x93, 0xc4, 0xef, 0x19, 0xd5, 0x4a, 0x82, 0xf2, 0x90, 0xf8, 0xec, 0xf7, 0x4d, 0x1e, 0x12, 0x9f, 0xc9, 0x95, 0x98, 0xab, 0xb5, 0xbf, 0xa7, 0x43, 0xf5, 0x98, 0xf9, 0xb0, 0x17, 0xe7, 0xab, 0x4c, 0x15, 0x6b, 0x7f, 0xa0, 0x69, 0x07, 0xb5, 0x5f, 0x45, 0xfe, 0xc8, 0xb3, 0x18, 0x7d, 0xcf, 0x64, 0xe6, 0x30, 0xcd, 0x2d, 0xa2, 0x2c, 0x5d, 0x91, 0xc7, 0x60, 0xe6, 0x1c, 0xa6, 0xac, 0x67, 0x18, 0x25, 0x93, 0x65, 0x7a, 0x5f, 0x2c, 0xfc, 0x7d, 0xe3, 0x56, 0xc5, 0xd0, 0x7c, 0x5c, 0x60, 0xa4, 0xf0, 0x8e, 0x2f, 0xd1, 0x3f, 0x30, 0x55, 0x55, 0x4c, 0xf0, 0x87, 0x15, 0xf3, 0x43, 0x5e, 0xe0, 0xff, 0x17, 0x53, 0x44, 0x52, 0x3e, 0xe5, 0x45, 0xe2, 0xc4, 0x74, 0x98, 0x1d, 0x41, 0x0f, 0x97, 0x11, 0x5f, 0xd8, 0xfe, 0x31, 0x80, 0x58, 0x31, 0xcb, 0x33, 0xb4, 0xf2, 0x19, 0xc0, 0x4e, 0xa0, 0xff, 0x84, 0xf1, 0x2c, 0x52, 0x5a, 0x3d, 0x2f, 0xb4, 0x88, 0xf8, 0x45, 0x24, 0xd5, 0xe4, 0xd6, 0x4a, 0x68, 0x11, 0xed, 0x52, 0x60, 0x3a, 0xb9, 0xb5, 0x12, 0x1a, 0x40, 0xad, 0x68, 0xca, 0x4a, 0x74, 0xa5, 0x9e, 0xae, 0xa1, 0x4e, 0xd1, 0x7e, 0x52, 0x45, 0x6a, 0x25, 0xb5, 0x88, 0x9d, 0xd0, 0xa2, 0x60, 0x0e, 0xa3, 0x10, 0x53, 0x2e, 0x95, 0x51, 0x21, 0xc4, 0x07, 0xf2, 0xa9, 0xc0, 0x07, 0x7d, 0x00, 0x4c, 0x4f, 0x3b, 0x48, 0xae, 0x66, 0xb9, 0x72, 0x62, 0xe8, 0xb1, 0x76, 0x3a, 0x4f, 0x5c, 0x47, 0xe9, 0x31, 0xbd, 0x8c, 0x9e, 0x93, 0x8f, 0x56, 0x01, 0x8b, 0x82, 0xb7, 0xf0, 0xaa, 0xf9, 0x32, 0x29, 0x36, 0x65, 0x0f, 0x6e, 0xe0, 0xc0, 0x45, 0x5d, 0x50, 0x3e, 0x01, 0x74, 0x79, 0x36, 0xcd, 0x75, 0xc8, 0xfe, 0xc5, 0xf0, 0x5c, 0x5f, 0x07, 0xee, 0x0c, 0x84, 0x7a, 0xae, 0x61, 0x47, 0xbb, 0x69, 0x47, 0x30, 0x82, 0xc3, 0xda, 0x7e, 0x52, 0x04, 0x01, 0x0c, 0x7f, 0x40, 0x55, 0xee, 0x80, 0x0f, 0x55, 0x12, 0x1d, 0x97, 0xc4, 0x25, 0x8c, 0x1a, 0x31, 0x52, 0xd4, 0xf2, 0xe8, 0xec, 0xca, 0xa3, 0xb6, 0xb5, 0x53, 0x73, 0xb3, 0xbe, 0x6a, 0xeb, 0x52, 0x84, 0x9d, 0x25, 0xea, 0x08, 0xb3, 0xf5, 0x5f, 0x2d, 0x18, 0x5c, 0xe7, 0x29, 0xcf, 0x68, 0xd7, 0x13, 0xe8, 0x53, 0xcc, 0xe4, 0xa3, 0xb5, 0xc8, 0x22, 0xf2, 0x4e, 0x3c, 0x25, 0xda, 0x3b, 0x92, 0xa1, 0x17, 0x3a, 0xf8, 0x62, 0xc3, 0xbe, 0x01, 0x6f, 0x41, 0x3b, 0xd7, 0x2e, 0xbd, 0x8a, 0x28, 0x1d, 0xee, 0x6d, 0x75, 0xb8, 0xdf, 0x70, 0xf8, 0x1e, 0x3c, 0x9b, 0xe3, 0x4b, 0x55, 0xd5, 0x8c, 0x7b, 0x0b, 0x3d, 0xa5, 0xaf, 0xcf, 0x76, 0x3d, 0xc8, 0xdd, 0xb1, 0xa1, 0x99, 0x0c, 0x2e, 0xe1, 0xf0, 0xc3, 0x0c, 0xe3, 0xb9, 0x21, 0xf1, 0x81, 0x8e, 0x81, 0xaa, 0xdd, 0xba, 0x06, 0xb0, 0x21, 0xb4, 0xb9, 0xb0, 0xfe, 0xb7, 0xb9, 0x08, 0xae, 0x60, 0x58, 0x5f, 0x26, 0xc5, 0x8e, 0x75, 0xd6, 0xa3, 0x76, 0xe5, 0xd1, 0x9f, 0x2d, 0xf8, 0xec, 0xe7, 0x3c, 0xe1, 0xd3, 0xf5, 0xd6, 0x36, 0x29, 0xaf, 0x88, 0x4b, 0x5b, 0x62, 0x5b, 0xf7, 0xc4, 0x57, 0x26, 0xfb, 0x8d, 0x85, 0xe7, 0xf4, 0xfc, 0x44, 0x57, 0x9d, 0xa9, 0x7a, 0xfc, 0x0e, 0xbc, 0x92, 0xa2, 0x5d, 0xe7, 0xb8, 0xb6, 0x19, 0xd1, 0x90, 0xb2, 0x7c, 0x8c, 0x16, 0x2b, 0x77, 0xd0, 0x0c, 0x78, 0xdf, 0xbe, 0x6a, 0x05, 0x57, 0xc0, 0x6a, 0xbd, 0x73, 0xcd, 0xa5, 0xb2, 0x27, 0xa4, 0xfc, 0x06, 0x96, 0x1a, 0xba, 0x2f, 0xa4, 0xf9, 0x26, 0x06, 0xbf, 0xc0, 0xeb, 0x8d, 0x95, 0x2f, 0x35, 0x75, 0xd5, 0x79, 0x46, 0x34, 0x15, 0x2d, 0xac, 0x40, 0x06, 0x5c, 0xfc, 0xd3, 0x81, 0x2e, 0x05, 0xb2, 0x33, 0xe8, 0xe9, 0x66, 0x61, 0x76, 0xb5, 0x6b, 0xd2, 0xf1, 0xa8, 0x81, 0xa5, 0x60, 0xdf, 0xd2, 0xb7, 0xae, 0x3a, 0xff, 0xec, 0xd8, 0x04, 0xfc, 0xe7, 0x02, 0x1a, 0x9f, 0x6c, 0xa3, 0xa5, 0x60, 0xdf, 0x80, 0xe7, 0x96, 0x5f, 0x30, 0xd6, 0x0c, 0xa2, 0x9b, 0x62, 0xfc, 0x7a, 0x83, 0x93, 0x82, 0xbd, 0x87, 0xfd, 0xb4, 0x3a, 0xc9, 0xec, 0xc8, 0xc4, 0x34, 0x2f, 0x80, 0xf1, 0xf1, 0x16, 0xb6, 0xb1, 0x56, 0xe7, 0xdb, 0x5c, 0xeb, 0xd2, 0x3d, 0xde, 0xc2, 0x4a, 0xc1, 0xde, 0x01, 0xc4, 0x65, 0xf3, 0x31, 0x9b, 0x5a, 0xa3, 0x8b, 0xc7, 0x47, 0x9b, 0xa4, 0x14, 0xec, 0x0a, 0x86, 0xcb, 0x46, 0x07, 0xb1, 0xcf, 0x77, 0xf4, 0xd5, 0xf8, 0xd0, 0x4c, 0xd8, 0x9f, 0x03, 0xf6, 0x3d, 0x8c, 0xd2, 0xa6, 0xc7, 0xcc, 0xdf, 0x48, 0xce, 0x36, 0xcd, 0xf8, 0x8b, 0x1d, 0x33, 0x52, 0xfc, 0xd6, 0xd7, 0x3f, 0x5b, 0x5f, 0xff, 0x1b, 0x00, 0x00, 0xff, 0xff, 0x2c, 0xb3, 0x7c, 0x00, 0x7a, 0x09, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. var _ context.Context var _ grpc.ClientConn // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. const _ = grpc.SupportPackageIsVersion4 // UserClient is the client API for User service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. type UserClient interface { Login(ctx context.Context, in *LoginReq, opts ...grpc.CallOption) (*LoginResp, error) RegisterCore(ctx context.Context, in *RegisterCoreReq, opts ...grpc.CallOption) (*RegisterCoreResp, error) Register2(ctx context.Context, in *Register2Req, opts ...grpc.CallOption) (*Register2Resp, error) GetUserInfo(ctx context.Context, in *GetUserInfoReq, opts ...grpc.CallOption) (*GetUserInfoResp, error) GetUserCore(ctx context.Context, in *GetUserCoreReq, opts ...grpc.CallOption) (*GetUserCoreResp, error) CheckToken(ctx context.Context, in *CheckTokenReq, opts ...grpc.CallOption) (*CheckTokenResp, error) ModifyUserInfo(ctx context.Context, in *ModifyUserInfoReq, opts ...grpc.CallOption) (*NilResp, error) GetUserCoreList(ctx context.Context, in *GetUserCoreListReq, opts ...grpc.CallOption) (*GetUserCoreListResp, error) } type userClient struct { cc *grpc.ClientConn } func NewUserClient(cc *grpc.ClientConn) UserClient { return &userClient{cc} } func (c *userClient) Login(ctx context.Context, in *LoginReq, opts ...grpc.CallOption) (*LoginResp, error) { out := new(LoginResp) err := c.cc.Invoke(ctx, "/user.User/login", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *userClient) RegisterCore(ctx context.Context, in *RegisterCoreReq, opts ...grpc.CallOption) (*RegisterCoreResp, error) { out := new(RegisterCoreResp) err := c.cc.Invoke(ctx, "/user.User/registerCore", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *userClient) Register2(ctx context.Context, in *Register2Req, opts ...grpc.CallOption) (*Register2Resp, error) { out := new(Register2Resp) err := c.cc.Invoke(ctx, "/user.User/register2", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *userClient) GetUserInfo(ctx context.Context, in *GetUserInfoReq, opts ...grpc.CallOption) (*GetUserInfoResp, error) { out := new(GetUserInfoResp) err := c.cc.Invoke(ctx, "/user.User/getUserInfo", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *userClient) GetUserCore(ctx context.Context, in *GetUserCoreReq, opts ...grpc.CallOption) (*GetUserCoreResp, error) { out := new(GetUserCoreResp) err := c.cc.Invoke(ctx, "/user.User/getUserCore", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *userClient) CheckToken(ctx context.Context, in *CheckTokenReq, opts ...grpc.CallOption) (*CheckTokenResp, error) { out := new(CheckTokenResp) err := c.cc.Invoke(ctx, "/user.User/checkToken", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *userClient) ModifyUserInfo(ctx context.Context, in *ModifyUserInfoReq, opts ...grpc.CallOption) (*NilResp, error) { out := new(NilResp) err := c.cc.Invoke(ctx, "/user.User/modifyUserInfo", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *userClient) GetUserCoreList(ctx context.Context, in *GetUserCoreListReq, opts ...grpc.CallOption) (*GetUserCoreListResp, error) { out := new(GetUserCoreListResp) err := c.cc.Invoke(ctx, "/user.User/getUserCoreList", in, out, opts...) if err != nil { return nil, err } return out, nil } // UserServer is the server API for User service. type UserServer interface { Login(context.Context, *LoginReq) (*LoginResp, error) RegisterCore(context.Context, *RegisterCoreReq) (*RegisterCoreResp, error) Register2(context.Context, *Register2Req) (*Register2Resp, error) GetUserInfo(context.Context, *GetUserInfoReq) (*GetUserInfoResp, error) GetUserCore(context.Context, *GetUserCoreReq) (*GetUserCoreResp, error) CheckToken(context.Context, *CheckTokenReq) (*CheckTokenResp, error) ModifyUserInfo(context.Context, *ModifyUserInfoReq) (*NilResp, error) GetUserCoreList(context.Context, *GetUserCoreListReq) (*GetUserCoreListResp, error) } // UnimplementedUserServer can be embedded to have forward compatible implementations. type UnimplementedUserServer struct { } func (*UnimplementedUserServer) Login(ctx context.Context, req *LoginReq) (*LoginResp, error) { return nil, status.Errorf(codes.Unimplemented, "method Login not implemented") } func (*UnimplementedUserServer) RegisterCore(ctx context.Context, req *RegisterCoreReq) (*RegisterCoreResp, error) { return nil, status.Errorf(codes.Unimplemented, "method RegisterCore not implemented") } func (*UnimplementedUserServer) Register2(ctx context.Context, req *Register2Req) (*Register2Resp, error) { return nil, status.Errorf(codes.Unimplemented, "method Register2 not implemented") } func (*UnimplementedUserServer) GetUserInfo(ctx context.Context, req *GetUserInfoReq) (*GetUserInfoResp, error) { return nil, status.Errorf(codes.Unimplemented, "method GetUserInfo not implemented") } func (*UnimplementedUserServer) GetUserCore(ctx context.Context, req *GetUserCoreReq) (*GetUserCoreResp, error) { return nil, status.Errorf(codes.Unimplemented, "method GetUserCore not implemented") } func (*UnimplementedUserServer) CheckToken(ctx context.Context, req *CheckTokenReq) (*CheckTokenResp, error) { return nil, status.Errorf(codes.Unimplemented, "method CheckToken not implemented") } func (*UnimplementedUserServer) ModifyUserInfo(ctx context.Context, req *ModifyUserInfoReq) (*NilResp, error) { return nil, status.Errorf(codes.Unimplemented, "method ModifyUserInfo not implemented") } func (*UnimplementedUserServer) GetUserCoreList(ctx context.Context, req *GetUserCoreListReq) (*GetUserCoreListResp, error) { return nil, status.Errorf(codes.Unimplemented, "method GetUserCoreList not implemented") } func RegisterUserServer(s *grpc.Server, srv UserServer) { s.RegisterService(&_User_serviceDesc, srv) } func _User_Login_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(LoginReq) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(UserServer).Login(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/user.User/Login", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(UserServer).Login(ctx, req.(*LoginReq)) } return interceptor(ctx, in, info, handler) } func _User_RegisterCore_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(RegisterCoreReq) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(UserServer).RegisterCore(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/user.User/RegisterCore", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(UserServer).RegisterCore(ctx, req.(*RegisterCoreReq)) } return interceptor(ctx, in, info, handler) } func _User_Register2_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(Register2Req) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(UserServer).Register2(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/user.User/Register2", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(UserServer).Register2(ctx, req.(*Register2Req)) } return interceptor(ctx, in, info, handler) } func _User_GetUserInfo_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetUserInfoReq) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(UserServer).GetUserInfo(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/user.User/GetUserInfo", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(UserServer).GetUserInfo(ctx, req.(*GetUserInfoReq)) } return interceptor(ctx, in, info, handler) } func _User_GetUserCore_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetUserCoreReq) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(UserServer).GetUserCore(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/user.User/GetUserCore", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(UserServer).GetUserCore(ctx, req.(*GetUserCoreReq)) } return interceptor(ctx, in, info, handler) } func _User_CheckToken_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(CheckTokenReq) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(UserServer).CheckToken(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/user.User/CheckToken", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(UserServer).CheckToken(ctx, req.(*CheckTokenReq)) } return interceptor(ctx, in, info, handler) } func _User_ModifyUserInfo_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(ModifyUserInfoReq) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(UserServer).ModifyUserInfo(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/user.User/ModifyUserInfo", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(UserServer).ModifyUserInfo(ctx, req.(*ModifyUserInfoReq)) } return interceptor(ctx, in, info, handler) } func _User_GetUserCoreList_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetUserCoreListReq) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(UserServer).GetUserCoreList(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/user.User/GetUserCoreList", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(UserServer).GetUserCoreList(ctx, req.(*GetUserCoreListReq)) } return interceptor(ctx, in, info, handler) } var _User_serviceDesc = grpc.ServiceDesc{ ServiceName: "user.User", HandlerType: (*UserServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "login", Handler: _User_Login_Handler, }, { MethodName: "registerCore", Handler: _User_RegisterCore_Handler, }, { MethodName: "register2", Handler: _User_Register2_Handler, }, { MethodName: "getUserInfo", Handler: _User_GetUserInfo_Handler, }, { MethodName: "getUserCore", Handler: _User_GetUserCore_Handler, }, { MethodName: "checkToken", Handler: _User_CheckToken_Handler, }, { MethodName: "modifyUserInfo", Handler: _User_ModifyUserInfo_Handler, }, { MethodName: "getUserCoreList", Handler: _User_GetUserCoreList_Handler, }, }, Streams: []grpc.StreamDesc{}, Metadata: "user.proto", }
Uniandes-isis2603/s1_201820_sierra
sierra-web/src/main/java/co/edu/uniandes/csw/sierra/dtos/FacturaDetailDTO.java
<reponame>Uniandes-isis2603/s1_201820_sierra /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package co.edu.uniandes.csw.sierra.dtos; import co.edu.uniandes.csw.sierra.entities.ComprobanteEntity; import co.edu.uniandes.csw.sierra.entities.FacturaEntity; import java.util.ArrayList; import java.util.List; /** * FacturaDetailDTO es el objeto de transferencia de datos detallada de la * entidad Factura. * <p> * Al serializarse como JSON, esta clase implementa el siguiente modelo:<br> * <pre> * { * "id": number, * "valorTotal": number, * "fecha": date, * "adquisicion": * { * "id": number, * "valorTotal": number, * "fecha": date * }, * "comprobantes": * [ * { * "id": number, * "valorTotal": number, * "fecha": date, * "clienteId": number * } * ] * </pre> Por ejemplo, una Factura se representa de la siguiente manera: <br> * <p> * < * pre> * { * "id": 20, * "valorTotal": 20000, * "fecha": "13/02/2018", * "adquisicion": * { * "id": 1001, * "valorTotal": 20000, * "fecha": "13/02/2018" * }, * "comprobantes": * [ * { * "id": 1003, * "valorTotal": 20000, * "fecha": "13/02/2018", * "clienteId": 200 * }, * { * "id": 1003, * "valorTotal": 0, * "fecha": "13/02/2018", * "clienteId": 200 * } * ] * } * </pre> * * @author ja.amortegui10 */ public class FacturaDetailDTO extends FacturaDTO { private AdquisicionDTO adquisicion; private List<ComprobanteDetailDTO> comprobantes; public FacturaDetailDTO() { super(); } public FacturaDetailDTO(FacturaEntity entity) { super(entity); if (entity != null) { this.adquisicion = new AdquisicionDetailDTO(entity.getAdquisicion()); this.comprobantes = new ArrayList<>(); List<ComprobanteEntity> comprobantesEntity = entity.getComprobantes(); for (ComprobanteEntity comprobanteActual : comprobantesEntity) { this.comprobantes.add(new ComprobanteDetailDTO(comprobanteActual)); } } } /** * Transforma la clase de un DetailDTO a un Entity y retora el * resultado. * * @return */ @Override public FacturaEntity toEntity() { FacturaEntity entity = super.toEntity(); if (adquisicion != null) { entity.setAdquisicion(adquisicion.toEntity()); } List<ComprobanteEntity> comprobantesEntity = new ArrayList<>(); if (!comprobantes.isEmpty()) { for (ComprobanteDTO comprobanteActual : comprobantes) { comprobantesEntity.add(comprobanteActual.toEntity()); } } return entity; } public AdquisicionDTO getAdquisicion() { return adquisicion; } public List<ComprobanteDetailDTO> getComprobantes() { return comprobantes; } public void setAdquisicion(AdquisicionDTO adquisicion) { this.adquisicion = adquisicion; } public void setComprobantes(List<ComprobanteDetailDTO> comprobantes) { this.comprobantes = comprobantes; } }
kachick/rr
spec/suites/rspec_2/support/shared_contexts/double_definition_creators/mocking.rb
<reponame>kachick/rr<filename>spec/suites/rspec_2/support/shared_contexts/double_definition_creators/mocking.rb shared_context 'tests for a double definition creator method that supports mocking' do include DoubleDefinitionCreatorHelpers specify "TimesCalledError is raised at the verify step if the method is never called" do build_object_with_possible_methods(some_method: -> {}) do |subject| double_creator = double_definition_creator_for(subject) double_creator.some_method end expect { RR.verify }.to raise_error(RR::Errors::TimesCalledError) end it_behaves_like 'defining a method double that sets the implementation of that method' context 'defining a mock with an argument expectation with a times-called qualifier' do context 'by passing arguments to the double definition directly' do include_context 'using 1 of 2 ways to define a mock with an argument expectation with a times-called qualifier' def define_double_with_argument_expectation(double_creator, method_name, *args) double_creator.__send__(method_name, *args) end end # https://github.com/rr/rr/issues/23 unless supports_strong? context 'by using #with and arguments' do include_context 'using 1 of 2 ways to define a mock with an argument expectation with a times-called qualifier' def define_double_with_argument_expectation(double_creator, method_name, *args) double_creator.__send__(method_name).with(*args) end end end end context 'defining a mock with an argument expectation with a never-called qualifier' do context 'by passing arguments to the double definition directly' do include_context 'using 1 of 2 ways to define a mock with an argument expectation with a never-called qualifier' def define_double_with_argument_expectation(double_creator, method_name, *args) double_creator.__send__(method_name, *args) end end # https://github.com/rr/rr/issues/23 unless supports_strong? context 'by using #with and arguments' do include_context 'using 1 of 2 ways to define a mock with an argument expectation with a never-called qualifier' def define_double_with_argument_expectation(double_creator, method_name, *args) double_creator.__send__(method_name).with(*args) end end end end context 'defining a mock with an argument expectation without any qualifiers' do context 'by passing arguments to the double definition directly' do include_context 'using 1 of 2 ways to define a method double with an argument expectation without any qualifiers' def define_double_with_argument_expectation(double_creator, method_name, *args) double_creator.__send__(method_name, *args) end end # https://github.com/rr/rr/issues/23 unless supports_strong? context 'by using #with and arguments' do include_context 'using 1 of 2 ways to define a method double with an argument expectation without any qualifiers' def define_double_with_argument_expectation(double_creator, method_name, *args) double_creator.__send__(method_name).with(*args) end end end end it_behaves_like 'defining a method double qualified with #yields' it_behaves_like 'defining method doubles using the block form of the double definition creator' it_behaves_like 'defining a method double for sequential invocations of that method using #ordered/#then' it_behaves_like 'an object which has a method double wrapped in an array and flattened' if supports_proxying? && !supports_instance_of? it_behaves_like 'defining a method double on an object which is a proxy for another object' end if methods_being_doubled_exist_already? it "lets you double operator methods as well as normal ones" do object = build_object do |subject| double_definition_creator_for(subject).==(anything) { 'value' } end expect(object == :whatever).to eq 'value' end end if type_of_methods_being_tested == :class && methods_being_doubled_exist_already? && !supports_instance_of? it "in a parent class doesn't affect child classes" do parent_class = Class.new do def self.some_method; 'existing value'; end end child_class = Class.new(parent_class) double_creator = double_definition_creator_for(parent_class) double_creator.some_method { 'value' } parent_class.some_method expect(child_class.some_method).to eq 'existing value' end end end
elchuzade/frontend-challenge
client/src/components/expenses/Languages.js
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import ReactCountryFlag from 'react-country-flag'; import { connect } from 'react-redux'; import { switchLanguage } from '../../actions/commonActions'; class Languages extends Component { constructor(props) { super(props); this.state = { language: 'ENG' }; } componentWillReceiveProps(nextProps) { if (nextProps.locale) { this.setState({ language: nextProps.locale.language }); } } switchLanguage = (e, language) => { e.preventDefault(); this.setState({ language: language }); this.props.switchLanguage(language); }; render() { return ( <div className="text-center"> <button className={classnames('btn-sm mx-1', { 'btn-info': this.state.language === 'ENG', 'btn-outline-info': this.state.language !== 'ENG' })} onClick={e => this.switchLanguage(e, 'ENG')} > <ReactCountryFlag code="GB" /> </button> <button className={classnames('btn-sm mx-1', { 'btn-info': this.state.language === 'GER', 'btn-outline-info': this.state.language !== 'GER' })} onClick={e => this.switchLanguage(e, 'GER')} > <ReactCountryFlag code="DE" /> </button> </div> ); } } Languages.propTypes = { locale: PropTypes.object.isRequired, switchLanguage: PropTypes.func.isRequired }; const mapStateToProps = state => ({ locale: state.locale }); export default connect( mapStateToProps, { switchLanguage } )(Languages);
AvroNelson/s4-clarity-lib
s4/clarity/steputils/copyudfs.py
<filename>s4/clarity/steputils/copyudfs.py # Copyright 2016 Semaphore Solutions, Inc. # --------------------------------------------------------------------------- import logging log = logging.getLogger(__name__) def copy_from_input_to_output(step, udf_names): """ Copies a set of UDFs from the inputs of a step to its outputs. - Supply a list of UDFs if the source and destination names are the same. - Supply a dictionary (source name to destination name) if they differ. If the UDF is not present on the source, it is skipped. Will throw an exception if there are more than one input per output. :type step: s4.clarity.Step :type udf_names: list[str]|dict[str:str] """ pairs = _keyed_io_maps_to_array(step.details.iomaps_input_keyed()) return _copy(pairs, udf_names) def copy_from_output_to_input(step, udf_names): """ Copies a set of UDFs from the outputs of a step to its inputs, one to one. - Supply a list of UDFs if the source and destination names are the same. - Supply a dictionary (source name to destination name) if they differ. If the UDF is not present on the source, it is skipped. Will throw an exception if there are more than one input per output or more than one output per input. :type step: s4.clarity.Step :type udf_names: list[str]|dict[str:str] """ pairs = _keyed_io_maps_to_array(step.details.iomaps_output_keyed()) return _copy(pairs, udf_names) def _keyed_io_maps_to_array(keyed_io_maps): """ Prepares an array of keyed artifact to value artifacts :param dict[Artifact:list(Artifact)]: Artifact to list of Artifact dictionary :return: list[(Artifact, Artifact)] """ pairs = [] for key_artifact in keyed_io_maps: for related_artifact in keyed_io_maps[key_artifact]: pairs.append((key_artifact, related_artifact)) return pairs def copy_from_input_to_sample(step, udf_names): """ Copies a set of UDFs from the inputs of a step to each input's sample. - Supply a list of UDFs if the source and destination names are the same. - Supply a dictionary (source name to destination name) if they differ. If the UDF is not present on the source, it is skipped. :type step: s4.clarity.Step :type udf_names: list[str]|dict[str:str] """ pairs = [ (artifact, artifact.sample) for artifact in step.details.inputs ] return _copy(pairs, udf_names) def copy_from_output_to_sample(step, udf_names): """ Copies a set of UDFs from the outputs of a step to each output's sample. - Supply a list of UDFs if the source and destination names are the same. - Supply a dictionary (source name to destination name) if they differ. If the UDF is not present on the source, it is skipped. :type step: s4.clarity.Step :type udf_names: list[str]|dict[str:str] """ pairs = [ (artifact, artifact.sample) for artifact in step.details.outputs ] return _copy(pairs, udf_names) def copy_from_sample_to_input(step, udf_names): """ Copies a set of UDFs to the inputs of a step from each input's sample. - Supply a list of UDFs if the source and destination names are the same. - Supply a dictionary (source name to destination name) if they differ. If the UDF is not present on the source, it is skipped. :type step: s4.clarity.Step :type udf_names: list[str]|dict[str:str] """ pairs = [ (artifact.sample, artifact) for artifact in step.details.inputs ] return _copy(pairs, udf_names) def copy_from_sample_to_output(step, udf_names): """ Copies a set of UDFs to the outputs of a step from each output's sample. - Supply a list of UDFs if the source and destination names are the same. - Supply a dictionary (source name to destination name) if they differ. If the UDF is not present on the source, it is skipped. :type step: s4.clarity.Step :type udf_names: list[str]|dict[str:str] """ pairs = [ (artifact.sample, artifact) for artifact in step.details.outputs ] return _copy(pairs, udf_names) def _copy(pairs, udf_names): """ Does the copy operation. :type pairs: list[(Artifact, Artifact)] :type udf_names: list[str]|dict[str:str] """ for source, destination in pairs: if type(udf_names) == dict: for (source_udf, destination_udf) in udf_names.items(): if source_udf in source: log.info("Copying UDF '%s' on %s to UDF '%s' on %s", source_udf, source, destination_udf, destination) destination[destination_udf] = source[source_udf] else: for udf_name in udf_names: if udf_name in source: log.info("Copying UDF '%s' from %s to %s", udf_name, source, destination) destination[udf_name] = source[udf_name]
issi8131/konashi-android-sdk-master
konashi-android-sdk/src/main/java/com/uxxu/konashi/lib/util/PwmUtils.java
package com.uxxu.konashi.lib.util; import com.uxxu.konashi.lib.Konashi; import java.util.Arrays; /** * Created by izumin on 9/18/15. */ public final class PwmUtils { private PwmUtils() { throw new AssertionError("constructor of the utility class should not be called"); } public static boolean isValidPin(int pin) { return (pin >= Konashi.PIO0) && (pin <= Konashi.PIO2); } public static boolean isValidMode(int mode) { return (mode == Konashi.PWM_ENABLE) || (mode == Konashi.PWM_DISABLE) || (mode == Konashi.PWM_ENABLE_LED_MODE); } public static boolean isValidPeriod(int period, int duty) { return (period >= 0) && (duty >= 0) && (duty <= period); } public static boolean isValidDuty(int duty, int period) { return isValidPeriod(period, duty); } public static boolean isValidDutyRatio(float dutyRatio) { return dutyRatio >= 0.0 && dutyRatio <= 100.0; } public static int getPwmDuty(byte[] value) { byte[] bytes = Arrays.copyOfRange(value, 1, value.length); return KonashiUtils.bytes2int(bytes); } public static int getPwmPeriod(byte[] value) { byte[] bytes = Arrays.copyOfRange(value, 1, value.length); return KonashiUtils.bytes2int(bytes); } }
aklinker1/miasma
internal/server/services/plugin_service/getAppPlugins.go
package plugin_service import ( "github.com/aklinker1/miasma/internal/server/utils/server_models" "github.com/aklinker1/miasma/internal/shared/log" "github.com/aklinker1/miasma/package/models" "gorm.io/gorm" ) func GetAppPlugins(tx *gorm.DB, appID string) (*server_models.AppPlugins, error) { log.V("plugin_server.GetAppPlugins(%v)", appID) traefik := &models.TraefikPluginConfig{} err := tx.First(traefik, "app_id = ?", appID).Error if err != nil { traefik = nil } return &server_models.AppPlugins{ Traefik: traefik, }, nil }
T-PWK/java-string-analyser
src/main/java/org/tpwk/analyser/Analysable.java
<filename>src/main/java/org/tpwk/analyser/Analysable.java package org.tpwk.analyser; /** * The {@code Analysable} interface is implemented by a class performing input sting analysis * * @author T-PWK */ public interface Analysable { void analyse(String input); }