I'm getting a strange segfault error. I've pasted the relevant parts of the code below.
When I run the code in gdb I get the following output:
DERPE
DERPH0 1
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_PROTECTION_FAILURE at address: 0x00007fff5f3ffff0
0x000000010000fcee in Interval::contains (this=0x100103c90, other={isValid = 93, s = 1, e = 7, n = 5}) at interval.cpp:33
33 if (!contains(other.s)) {
A.cpp
void A::foo(){
...
std::cout << "DERPE" << std::endl;
std::cout << "DERPH" << id << " " << curr << std::endl;
\\graph is a vector<B>
std::cout << "DERPI" << id << " " << curr << " " << graph[id].bar(graph[curr]) << std::endl;
...
}
B.cpp
bool B::bar(B &other) const {
// each B contains 2 Intervals, adj, opp
return (other.adj.contains(this->adj) and
(!this->opp.isValid or other.adj.contains(this->opp) or
(other.opp.isValid and other.opp.contains(this->opp))));
}
Interval.cpp
bool Interval::contains(Interval other) const {
if (!contains(other.s)) {
return false;
}
...
}
When I try to mess around with gdb I get the following:
(gdb) p other
$1 = {
isValid = 93,
s = 1,
e = 7,
n = 5
}
(gdb) p this
$2 = (const Interval *) 0x100103c90
(gdb) p *this
$3 = {
isValid = 93,
s = 1,
e = 0,
n = 5
}
(gdb) p other.s
$4 = 1
(gdb) p (*this).contains(other.s)
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_PROTECTION_FAILURE at address: 0x00007fff5f3fff50
Interval::contains (this=Cannot access memory at address 0x7fff5f3fff50
) at interval.cpp:28
28 bool Interval::contains(int x) const {
The program being debugged was signaled while in a function called from GDB.
GDB remains in the frame where the signal was received.
To change this behavior use "set unwindonsignal on"
Evaluation of the expression containing the function (Interval::contains(int) const) will be abandoned.
(gdb) p this
Cannot access memory at address 0x7fff5f3fff50
Any ideas on how to approach this? I'm lost.
EDIT:
The full header file for Interval is as follows:
Interval.h
#ifndef INTERVAL_H
#define INTERVAL_H
#include <vector>
struct Interval {
bool isValid;
int s, e, n;
Interval() {};
Interval(int n);
Interval(int start, int end, int n);
bool operator==(const Interval other) const;
int length() const;
bool contains(int x) const;
bool contains(Interval other) const;
};
#endif
I don't have a copy constructor, but I figured that everything is just primitives, so the default copy constructor would work.
I played around with it some more and this seems relevant:
(gdb) backtrace 10
#0 0x000000010000fcce in Interval::contains (this=0x100103c90, other={isValid = 34, s = 1, e = 6, n = 5}) at interval.cpp:33
#1 0x000000010000fd9b in Interval::contains (this=0x100103c90, other={isValid = 34, s = 1, e = 6, n = 5}) at interval.cpp:52
#2 0x000000010000fd9b in Interval::contains (this=0x100103c90, other={isValid = 34, s = 1, e = 6, n = 5}) at interval.cpp:52
#3 0x000000010000fd9b in Interval::contains (this=0x100103c90, other={isValid = 34, s = 1, e = 6, n = 5}) at interval.cpp:52
#4 0x000000010000fd9b in Interval::contains (this=0x100103c90, other={isValid = 34, s = 1, e = 6, n = 5}) at interval.cpp:52
#5 0x000000010000fd9b in Interval::contains (this=0x100103c90, other={isValid = 34, s = 1, e = 6, n = 5}) at interval.cpp:52
#6 0x000000010000fd9b in Interval::contains (this=0x100103c90, other={isValid = 34, s = 1, e = 6, n = 5}) at interval.cpp:52
#7 0x000000010000fd9b in Interval::contains (this=0x100103c90, other={isValid = 34, s = 1, e = 6, n = 5}) at interval.cpp:52
#8 0x000000010000fd9b in Interval::contains (this=0x100103c90, other={isValid = 34, s = 1, e = 6, n = 5}) at interval.cpp:52
#9 0x000000010000fd9b in Interval::contains (this=0x100103c90, other={isValid = 34, s = 1, e = 6, n = 5}) at interval.cpp:52
(gdb) backtrace
#0 0x000000010000fcce in Interval::contains (this=0x100103c90, other={isValid = 34, s = 1, e = 6, n = 5}) at interval.cpp:33
...
#67667 0x000000010000fd9b in Interval::contains (this=0x100103c90, other={isValid = 34, s = 1, e = 6, n = 5}) at interval.cpp:52
(gdb)
I figured it out. Infinite backtrace meant that the recursion in contains was not handled properly (I was missing a base case), so it infinitely recursed -> stack overflow -> seg fault.
Related
I have a button that submits information and that works. All the numbers will be positive when entered by clients. The question at hand is:
If A4 = "Sell", cells A16, A18, and A20, return those numbers as negative values instead of positive. If A4 = "Buy", then return as is (positive).
Here's what I currently have. I don't know where to input this IF statement, or even how.
function SubmitBuy() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var formS = ss.getSheetByName("Front Sheet"); //Data entry sheet
var dataS = ss.getSheetByName("Front Sheet"); //Data Sheet
var values = [[formS.getRange("A2").getValue(),
formS.getRange("A4").getValue(),
formS.getRange("A6").getValue(),
formS.getRange("A8").getValue(),
formS.getRange("A10").getValue(),
formS.getRange("A12").getValue(),
formS.getRange("A16").getValue(),
formS.getRange("A18").getValue(),
formS.getRange("A20").getValue(),
formS.getRange("A28").getValue(), ]];
dataS.getRange(dataS.getLastRow() +1, 3, 1, 10 ).setValues(values);
ClearCells();
}
Get all of Column A's values and manipulate them using Array.map and Set:
function SubmitBuy() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const frontSheet = ss.getSheetByName('Front Sheet'); //Data entry sheet
const valuesA1A28 = frontSheet.getRange('A1:A28').getValues();
const rowsNeeded = [2, 4, 5, 8, 10, 12, 16, 18, 20];
const criteriaRow = 4;
const rowsToModify = new Set([16, 18, 20]);
const valuesNeeded = [
rowsNeeded.map((thisRow) => {
const thisValue = valuesA1A28[thisRow - 1][0];
if (
rowsToModify.has(thisRow) &&
valuesA1A28[criteriaRow - 1][0] === 'Sell'
)
return -thisValue;
else return thisValue;
}),
];
frontSheet
.getRange(frontSheet.getLastRow() + 1, 3, 1, 10)
.setValues(valuesNeeded);
ClearCells();
}
I am working on a module of the ns-3 simulator. For people unfamiliar with it, they exhibit a custom-made shared pointer: Ptr<T>. These objects are usually created using the CreateObject<T>(…) function which basically calls new T(…) and wraps it in a Ptr<T>.
I’m having troubles using one of these that I created in a constructor:
SatUtHelper::SatUtHelper (SatTypedefs::CarrierBandwidthConverter_t carrierBandwidthConverter,
uint32_t fwdLinkCarrierCount,
Ptr<SatSuperframeSeq> seq,
SatMac::ReadCtrlMsgCallback readCb,
SatMac::ReserveCtrlMsgCallback reserveCb,
SatMac::SendCtrlMsgCallback sendCb,
RandomAccessSettings_s randomAccessSettings)
: m_superframeSeq (seq),
m_llsConf (),
[...snip...]
{
[...snip...]
m_llsConf = CreateObject<SatLowerLayerServiceConf> ();
}
and that I use like so:
Ptr<SatRandomAccessConf> randomAccessConf = CreateObject<SatRandomAccessConf> (m_llsConf, m_superframeSeq);
The SatRandomAccessConf constructor begins like so:
SatRandomAccessConf::SatRandomAccessConf (Ptr<SatLowerLayerServiceConf> llsConf, Ptr<SatSuperframeSeq> superframeSeq)
: m_configurationIdPerAllocationChannel (),
m_slottedAlohaControlRandomizationIntervalInMilliSeconds (),
m_allocationChannelCount (llsConf->GetRaServiceCount ()),
m_crdsaSignalingOverheadInBytes (5),
m_slottedAlohaSignalingOverheadInBytes (3)
{
NS_LOG_FUNCTION (this);
if (m_allocationChannelCount < 1)
{
NS_FATAL_ERROR ("SatRandomAccessConf::SatRandomAccessConf - No random access allocation channel");
}
m_slottedAlohaControlRandomizationIntervalInMilliSeconds = (llsConf->GetDefaultControlRandomizationInterval ()).GetMilliSeconds ();
DoSlottedAlohaVariableSanityCheck ();
and contains some checks past that point which blows up due to having llsConf in an incoherent state.
I have used GDB to inspect the state of the llsConf object:
I put a breakpoint on the DoSlottedAlohaVariableSanityCheck ();
I called methods on llsConf that indeed returned garbage values;
I checked values of m_allocationChannelCount and m_slottedAlohaControlRandomizationIntervalInMilliSeconds that were not the same as the return values from the methods of llsConf;
I checked in upper frames the values on m_llsConf which were as expected;
I checked the content of the objects in both frames that differed in the caller and the callee; the content of llsConf having a suspiciously large amount of attributes set to 0.
Relevant parts of the GDB session:
(gdb) bt
#0 ns3::SatRandomAccessConf::DoSlottedAlohaVariableSanityCheck (this=0x55555a160a00) at ../contrib/satellite/model/satellite-random-access-container-conf.cc:146
#1 0x00007ffff76fe0e1 in ns3::SatRandomAccessConf::SatRandomAccessConf (this=0x55555a160a00, llsConf=..., superframeSeq=...) at ../contrib/satellite/model/satellite-random-access-container-conf.cc:75
#2 0x00007ffff781fa26 in ns3::CreateObject<ns3::SatRandomAccessConf, ns3::Ptr<ns3::SatLowerLayerServiceConf>, ns3::Ptr<ns3::SatSuperframeSeq> > (a1=..., a2=...) at ./ns3/object.h:557
#3 0x00007ffff781d494 in ns3::SatUtHelper::Install (this=0x555555841990, n=..., beamId=10, fCh=..., rCh=..., gwNd=..., ncc=..., cbChannel=..., cbRouting=...) at ../contrib/satellite/helper/satellite-ut-helper.cc:425
#4 0x00007ffff781b307 in ns3::SatUtHelper::Install (this=0x555555841990, c=..., beamId=10, fCh=..., rCh=..., gwNd=..., ncc=..., cbChannel=..., cbRouting=...) at ../contrib/satellite/helper/satellite-ut-helper.cc:231
#5 0x00007ffff77b03bc in ns3::SatBeamHelper::Install (this=0x5555557ecb20, ut=..., gwNode=..., gwId=3, beamId=10, ulFreqId=3, flFreqId=1, routingCallback=...) at ../contrib/satellite/helper/satellite-beam-helper.cc:475
#6 0x00007ffff77f0262 in ns3::SatHelper::DoCreateScenario (this=0x5555557ec810, beamInfos=std::map with 0 elements, gwUsers=1) at ../contrib/satellite/helper/satellite-helper.cc:566
#7 0x00007ffff77ee873 in ns3::SatHelper::CreateUserDefinedScenario (this=0x5555557ec810, infos=std::map with 0 elements) at ../contrib/satellite/helper/satellite-helper.cc:389
#8 0x00007ffff7844e0b in ns3::SimulationHelper::CreateSatScenario (this=0x5555557ec5a0, scenario=ns3::SatHelper::NONE, mobileUtsFolder="contrib/satellite/data/utpositions/mobiles/")
at ../contrib/satellite/helper/simulation-helper.cc:1170
#9 0x00007ffff784a1dc in ns3::SimulationHelper::ConfigureAttributesFromFile (this=0x5555557ec5a0, filePath="/tmp/sns-3-qs4ebg47/parameters.xml", overrideManualConfiguration=true) at ../contrib/satellite/helper/simulation-helper.cc:1555
#10 0x0000555555557225 in main (argc=3, argv=0x7fffffffe798) at ../contrib/satellite/examples/sat-generic-launcher.cc:60
(gdb) p llsConf->GetRaServiceCount()
$1 = 0 '\000'
(gdb) p llsConf->GetDefaultControlRandomizationInterval()
$2 = {static g_markingTimes = 0x7ffff39447a0 <ns3::Time::StaticInit()::markingTimes>, m_data = 93824994540112}
(gdb) p llsConf->GetDefaultControlRandomizationInterval().GetMilliSeconds()
$3 = 93824994
(gdb) p m_allocationChannelCount
$4 = 1
(gdb) p m_slottedAlohaControlRandomizationIntervalInMilliSeconds
$5 = 100
(gdb) p llsConf
$6 = {m_ptr = 0x7fffffffd718}
(gdb) p *(llsConf.m_ptr)
$7 = {<ns3::Object> = {<ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>> = {<ns3::ObjectBase> = {_vptr.ObjectBase = 0x5555557af810}, m_count = 1434627024}, m_tid = {m_tid = 21845}, m_disposed = false,
m_initialized = false, m_aggregates = 0x91c8f8cb8ee26900, m_getObjectCount = 0}, static m_minDaServiceEntries = 2 '\002', static m_minRaServiceEntries = 1 '\001', static m_maxDaServiceEntries = 4 '\004',
static m_maxRaServiceEntries = 3 '\003', m_dynamicRatePersistence = 0 '\000', m_volumeBacklogPersistence = 0 '\000', m_defaultControlRandomizationInterval = {
static g_markingTimes = 0x7ffff39447a0 <ns3::Time::StaticInit()::markingTimes>, m_data = 93824994540112}, m_daServiceEntryCount = 102 'f', m_daServiceEntries = {{m_constantAssignmentProvided = false, m_rbdcAllowed = false,
m_volumeAllowed = false, m_constantServiceRateStream = {m_ptr = 0x7fffffffdb50}, m_maximumServiceRateKbps = 54420, m_minimumServiceRateKbps = 63361, m_maximumBacklogInKbytes = 32767}, {m_constantAssignmentProvided = 54,
m_rbdcAllowed = 62, m_volumeAllowed = 103, m_constantServiceRateStream = {m_ptr = 0x0}, m_maximumServiceRateKbps = 51468, m_minimumServiceRateKbps = 63349, m_maximumBacklogInKbytes = 32767}, {m_constantAssignmentProvided = false,
m_rbdcAllowed = false, m_volumeAllowed = false, m_constantServiceRateStream = {m_ptr = 0x7ffff7710ce6 <ns3::SatRequestManager::AssignedDaResources(unsigned char, unsigned int)>}, m_maximumServiceRateKbps = 0,
m_minimumServiceRateKbps = 0, m_maximumBacklogInKbytes = 0}, {m_constantAssignmentProvided = 192, m_rbdcAllowed = 189, m_volumeAllowed = 112, m_constantServiceRateStream = {m_ptr = 0x0}, m_maximumServiceRateKbps = 65,
m_minimumServiceRateKbps = 0, m_maximumBacklogInKbytes = 0}}, m_raServiceIndexDefault = 0 '\000', m_raServiceEntryCount = 0 '\000', m_raServiceEntries = {{m_maxUniquePayloadPerBlock = 118 'v',
m_maxConsecutiveBlockAccessed = 130 '\202', m_minimumIdleBlock = 112 'p', m_backOffTimeInMilliSeconds = 32767, m_highLoadBackOffTimeInMilliSeconds = 0, m_backOffProbability = 0, m_highLoadBackOffProbability = 0,
m_numberOfInstances = 0 '\000', m_averageNormalizedOfferedLoadThreshold = 6.9533487051292957e-310, m_isCrdsaAllowed = false, m_isSlottedAlohaAllowed = false}, {m_maxUniquePayloadPerBlock = 54 '6',
m_maxConsecutiveBlockAccessed = 62 '>', m_minimumIdleBlock = 103 'g', m_backOffTimeInMilliSeconds = 32767, m_highLoadBackOffTimeInMilliSeconds = 0, m_backOffProbability = 0, m_highLoadBackOffProbability = 0,
m_numberOfInstances = 0 '\000', m_averageNormalizedOfferedLoadThreshold = 7.5592043813710721e-322, m_isCrdsaAllowed = false, m_isSlottedAlohaAllowed = false}, {m_maxUniquePayloadPerBlock = 113 'q',
m_maxConsecutiveBlockAccessed = 0 '\000', m_minimumIdleBlock = 0 '\000', m_backOffTimeInMilliSeconds = 0, m_highLoadBackOffTimeInMilliSeconds = 0, m_backOffProbability = 0, m_highLoadBackOffProbability = 0,
m_numberOfInstances = 0 '\000', m_averageNormalizedOfferedLoadThreshold = 6.9533487349484301e-310, m_isCrdsaAllowed = false, m_isSlottedAlohaAllowed = false}}}
(gdb) up
#2 0x00007ffff781fa26 in ns3::CreateObject<ns3::SatRandomAccessConf, ns3::Ptr<ns3::SatLowerLayerServiceConf>, ns3::Ptr<ns3::SatSuperframeSeq> > (a1=..., a2=...) at ./ns3/object.h:557
557 return CompleteConstruct (new T (a1,a2));
(gdb) up
#3 0x00007ffff781d494 in ns3::SatUtHelper::Install (this=0x555555841990, n=..., beamId=10, fCh=..., rCh=..., gwNd=..., ncc=..., cbChannel=..., cbRouting=...) at ../contrib/satellite/helper/satellite-ut-helper.cc:425
425 Ptr<SatRandomAccessConf> randomAccessConf = CreateObject<SatRandomAccessConf> (m_llsConf, m_superframeSeq);
(gdb) p m_llsConf->GetRaServiceCount()
$8 = 1 '\001'
(gdb) p m_llsConf->GetDefaultControlRandomizationInterval().GetMilliSeconds()
$9 = 100
(gdb) p m_llsConf
$10 = {m_ptr = 0x5555557af810}
(gdb) p *(m_llsConf.m_ptr)
$11 = {<ns3::Object> = {<ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>> = {<ns3::ObjectBase> = {_vptr.ObjectBase = 0x7ffff7d93850 <vtable for ns3::SatLowerLayerServiceConf+16>}, m_count = 6}, m_tid = {
m_tid = 406}, m_disposed = false, m_initialized = false, m_aggregates = 0x5555564d2540, m_getObjectCount = 0}, static m_minDaServiceEntries = 2 '\002', static m_minRaServiceEntries = 1 '\001',
static m_maxDaServiceEntries = 4 '\004', static m_maxRaServiceEntries = 3 '\003', m_dynamicRatePersistence = 5 '\005', m_volumeBacklogPersistence = 7 '\a', m_defaultControlRandomizationInterval = {
static g_markingTimes = 0x7ffff39447a0 <ns3::Time::StaticInit()::markingTimes>, m_data = 100000000}, m_daServiceEntryCount = 4 '\004', m_daServiceEntries = {{m_constantAssignmentProvided = false, m_rbdcAllowed = false,
m_volumeAllowed = false, m_constantServiceRateStream = {m_ptr = 0x5555561d07d0}, m_maximumServiceRateKbps = 9216, m_minimumServiceRateKbps = 10, m_maximumBacklogInKbytes = 384}, {m_constantAssignmentProvided = false,
m_rbdcAllowed = false, m_volumeAllowed = false, m_constantServiceRateStream = {m_ptr = 0x555555e48b20}, m_maximumServiceRateKbps = 9216, m_minimumServiceRateKbps = 10, m_maximumBacklogInKbytes = 384}, {
m_constantAssignmentProvided = false, m_rbdcAllowed = false, m_volumeAllowed = false, m_constantServiceRateStream = {m_ptr = 0x55555581d600}, m_maximumServiceRateKbps = 9216, m_minimumServiceRateKbps = 10,
m_maximumBacklogInKbytes = 384}, {m_constantAssignmentProvided = false, m_rbdcAllowed = false, m_volumeAllowed = false, m_constantServiceRateStream = {m_ptr = 0x5555557a95f0}, m_maximumServiceRateKbps = 9216,
m_minimumServiceRateKbps = 16, m_maximumBacklogInKbytes = 384}}, m_raServiceIndexDefault = 0 '\000', m_raServiceEntryCount = 1 '\001', m_raServiceEntries = {{m_maxUniquePayloadPerBlock = 1 '\001',
m_maxConsecutiveBlockAccessed = 6 '\006', m_minimumIdleBlock = 0 '\000', m_backOffTimeInMilliSeconds = 150, m_highLoadBackOffTimeInMilliSeconds = 500, m_backOffProbability = 1, m_highLoadBackOffProbability = 1,
m_numberOfInstances = 3 '\003', m_averageNormalizedOfferedLoadThreshold = 0.98999999999999999, m_isCrdsaAllowed = true, m_isSlottedAlohaAllowed = true}, {m_maxUniquePayloadPerBlock = 3 '\003',
m_maxConsecutiveBlockAccessed = 4 '\004', m_minimumIdleBlock = 2 '\002', m_backOffTimeInMilliSeconds = 250, m_highLoadBackOffTimeInMilliSeconds = 500, m_backOffProbability = 10000, m_highLoadBackOffProbability = 30000,
m_numberOfInstances = 2 '\002', m_averageNormalizedOfferedLoadThreshold = 0.5, m_isCrdsaAllowed = true, m_isSlottedAlohaAllowed = true}, {m_maxUniquePayloadPerBlock = 3 '\003', m_maxConsecutiveBlockAccessed = 4 '\004',
m_minimumIdleBlock = 2 '\002', m_backOffTimeInMilliSeconds = 250, m_highLoadBackOffTimeInMilliSeconds = 500, m_backOffProbability = 10000, m_highLoadBackOffProbability = 30000, m_numberOfInstances = 5 '\005',
m_averageNormalizedOfferedLoadThreshold = 0.5, m_isCrdsaAllowed = true, m_isSlottedAlohaAllowed = true}}}
Now if I add the line Ptr<SatLowerLayerServiceConf> uglyHack = llsConf; before the breakpoint, I can in fact see that, somehow, they are equal:
(gdb) p uglyHack
$1 = {m_ptr = 0x5555557af810}
(gdb) p llsConf
$2 = {m_ptr = 0x7fffffffd718}
(gdb) up
#2 0x00007ffff781fa56 in ns3::CreateObject<ns3::SatRandomAccessConf, ns3::Ptr<ns3::SatLowerLayerServiceConf>, ns3::Ptr<ns3::SatSuperframeSeq> > (a1=..., a2=...) at ./ns3/object.h:557
557 return CompleteConstruct (new T (a1,a2));
(gdb)
#3 0x00007ffff781d4c4 in ns3::SatUtHelper::Install (this=0x555555841990, n=..., beamId=10, fCh=..., rCh=..., gwNd=..., ncc=..., cbChannel=..., cbRouting=...) at ../contrib/satellite/helper/satellite-ut-helper.cc:425
425 Ptr<SatRandomAccessConf> randomAccessConf = CreateObject<SatRandomAccessConf> (m_llsConf, m_superframeSeq);
(gdb) p m_llsConf
$3 = {m_ptr = 0x5555557af810}
Does someone have any idea how the parameter passing and the copy assignment can allow such behaviour?
How can I align this text? \t is not good.
What I see (image)
Expected result (image)
I had this problem once in the past. To solve the issue I used monospace font.
To get everything aligned (fixed font width) I used these lines:
// Use "monospaced" font:
// ->insure left column alignment, as for the terminal
//
QFont font("monospace");
font.setPointSize(10);
myQTextEdit->setCurrentFont(font);
from my parent widget containing a QTextEdit child widget.
this line:
QString str = QString("B%1").arg(_ui->lineEdit->text().toInt(), 3, 10, QChar('0'));
lineEdit->text() = 1 , str = B001
lineEdit->text() = 01 , str = B001
lineEdit->text() = 001 , str = B001
lineEdit->text() = 0001 , str = B001
lineEdit->text() = 12 , str = B012
lineEdit->text() = 123 , str = B123
you can adapt it for your use.
Edit based on Hyde Comment
int main(int argc, char **argv)
{
qint32 a,b,c,d,e;
a = -1;b = 1;c = -1;d = 3;
e = (a*b) + (c*d);
QString str = QString("(%1*%2) + (%3*%4) = %5").arg(a, 2, 10, QChar(' '))
.arg(b, 2, 10, QChar(' '))
.arg(c, 2, 10, QChar(' '))
.arg(d, 2, 10, QChar(' '))
.arg(e);
QTextStream(stdout) << str << endl;
a = -1;b = 2;c = -1;d = 4;
e = (a*b) + (c*d);
str = QString("(%1*%2) + (%3*%4) = %5").arg(a, 2, 10, QChar(' '))
.arg(b, 2, 10, QChar(' '))
.arg(c, 2, 10, QChar(' '))
.arg(d, 2, 10, QChar(' '))
.arg(e);
QTextStream(stdout) << str << endl;
return 0;
}
the output is:
(-1 * 1) + (-1 * 3) = -4
(-1 * 2) + (-1 * 4) = -6
This way actually worked. But are there any simplified answer.
dayname(Num,Name) :-
member([Num,Name],
[[1,'Monday'],[2,'Tuesday'],[3,'Wednesday'],[4,'Thursday'],
[5,'Friday'],[6,'Saturday'],[7,'Sunday'],[8,'Monday'],
[9,'Tuesday'],[10,'Wednesday'],[11,'Thursday'],[12,'Friday'],
[13,'Saturday'],[14,'Sunday'],[15,'Monday'],[16,'Tuesday'],
[17,'Wednesday'],[18,'Thursday'],[19,'Friday'],[20,'Saturday'],
[21,'Sunday'],[22,'Monday'],[23,'Tuesday'],[24,'Wednesday'],
[25,'Thursday'],[26,'Friday'],[27,'Saturday'],[28,'Sunday'],
[29,'Monday'],[30,'Tuesday'],[31,'Monday']]).
Yes. First of all you do not need to use member/2 for facts. You can list these as facts:
dayname(1,'Monday').
dayname(2,'Tuesday').
dayname(3,'Wednesday').
dayname(4,'Thursday').
dayname(5,'Friday').
dayname(6,'Saturday').
dayname(7,'Sunday').
But now we have of course no way to obtain 'Monday' for 8. Probably the most declarative way to do this is the following clause:
:- use_module(library(clpfd)).
dayname(I,D) :-
I in 8..31,
J #= I-7,
dayname(J,D).
Putting this all together, we get:
:- use_module(library(clpfd)).
dayname(1,'Monday').
dayname(2,'Tuesday').
dayname(3,'Wednesday').
dayname(4,'Thursday').
dayname(5,'Friday').
dayname(6,'Saturday').
dayname(7,'Sunday').
dayname(I,D) :-
I in 8..31,
J #= I-7,
dayname(J,D).
We then query it in all possible ways:
?- dayname(I,D).
I = 1,
D = 'Monday' ;
I = 2,
D = 'Tuesday' ;
I = 3,
D = 'Wednesday' ;
I = 4,
D = 'Thursday' ;
I = 5,
D = 'Friday' ;
I = 6,
D = 'Saturday' ;
I = 7,
D = 'Sunday' ;
I = 8,
D = 'Monday' ;
I = 9,
D = 'Tuesday' ;
I = 10,
D = 'Wednesday' ;
I = 11,
D = 'Thursday' ;
I = 12,
D = 'Friday' ;
I = 13,
D = 'Saturday' ;
I = 14,
D = 'Sunday' ;
I = 15,
D = 'Monday' ;
I = 16,
D = 'Tuesday' ;
I = 17,
D = 'Wednesday' ;
I = 18,
D = 'Thursday' ;
I = 19,
D = 'Friday' ;
I = 20,
D = 'Saturday' ;
I = 21,
D = 'Sunday' ;
I = 22,
D = 'Monday' ;
I = 23,
D = 'Tuesday' ;
I = 24,
D = 'Wednesday' ;
I = 25,
D = 'Thursday' ;
I = 26,
D = 'Friday' ;
I = 27,
D = 'Saturday' ;
I = 28,
D = 'Sunday' ;
I = 29,
D = 'Monday' ;
I = 30,
D = 'Tuesday' ;
I = 31,
D = 'Wednesday' ;
false.
?- dayname(15,D).
D = 'Monday' ;
false.
?- dayname(I,'Thursday').
I = 4 ;
I = 11 ;
I = 18 ;
I = 25 ;
false.
?- dayname(12,'Thursday').
false.
?- dayname(11,'Thursday').
true ;
false.
liste = [1,2,8,12,19,78,34,197,1,-7,-45,-97,-32,23]
liste2 = []
def repetisjon(liste,liste2):
for count in liste:
if count > 0:
liste2.append(1)
elif count < 0:
liste2.append(0)
return liste2
return (liste2)
print (repetisjon(liste,liste2))
The point is to change all the values of the list. If it's greater than or equal to 0, it is to be replaced by the value 1. And if it's lower than 0, it is to be replaced by 0. But I wasn't able to change the current list. The only solution I found was to make a new list. But is there anyway to CHANGE the current list without making a new one? I tried this as well, but didnt work at all:
liste = [4,8,43,4,78,24,8,45,-78,-6,-7,-3,8,-12,4,36]
def repe (liste):
for count in liste:
if count > 0:
count == 1
else:
count == 0
print (liste)
repe(liste)
Here, I replace the content of liste with the transformed data. since sameliste points to the same list, its value changes too.
>>> sameliste = liste = [1,2,8,12,19,78,34,197,1,-7,-45,-97,-32,23]
>>> sameliste
[1, 2, 8, 12, 19, 78, 34, 197, 1, -7, -45, -97, -32, 23]
>>> liste
[1, 2, 8, 12, 19, 78, 34, 197, 1, -7, -45, -97, -32, 23]
>>> liste[:] = [int(x >= 0) for x in liste]
>>> liste
[1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1]
>>> sameliste
[1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1]
>>>