How To Change Retarget Difficulty For An Altcoin - c++

I am helping a community of an altcoin that needs to change it's retarget difficulty. So far I have written some code for the new wallet.
This is what I have done to the main.cpp file
I want to change the retarget the difficulty from 960 blocks (1 day) to 40 blocks (1 hours) of a coin. The block that I want the change to happen is 28000.
from:
static const int64 nTargetTimespan = 1 * 24 * 60 * 60; // UFO: 1 days
static const int64 nTargetSpacing = 90; // UFO: 1.5 minute blocks
static const int64 nInterval = nTargetTimespan / nTargetSpacing;
static const int64 nReTargetHistoryFact = 4; // look at 4 times the retarget interval into block history
to:
static int64 nTargetTimespan = 1 * 24 * 60 * 60; // 1 day
static int64 nTargetSpacing = 90; // 1.5 minute blocks
static int64 nInterval = nTargetTimespan / nTargetSpacing;
static int64 nReTargetHistoryFact = 4; // look at 4 times the retarget interval into block history
Then in the GetNextWorkRequired function this:
from:
// Genesis block
if (pindexLast == NULL)
return nProofOfWorkLimit;
// Only change once per interval
if ((pindexLast->nHeight+1) % nInterval != 0)
to:
// Genesis block
if (pindexLast == NULL)
return nProofOfWorkLimit;
// From block 28000 reassess the difficulty every 40 blocks
// Reduce Retarget factor to 2
if(pindexLast->nHeight >= 28000)
{
nTargetTimespan = 60 * 60; // 1 hours
nTargetSpacing = 1.5 * 60; // 1.5 minutes
nInterval = nTargetTimespan / nTargetSpacing;
nReTargetHistoryFact = 2;
}
else
{
nTargetTimespan = 1 * 24 * 60 * 60; // 1 day
nTargetSpacing = 1.5 * 60; // 1.5 minutes
nInterval = nTargetTimespan / nTargetSpacing;
nReTargetHistoryFact = 4;
}
// Only change once per interval
if ((pindexLast->nHeight+1) % nInterval != 0)
Is this code correct or is something else to be done?
Thanks I appreciate any help.

your code looks good. I was wondering the same, so i changed it as you did , but i got this error
GetNextWorkRequired RETARGET
nTargetTimespan = 60 nActualTimespan = 79
Before: 1d0d7333 0000000d73330000000000000000000000000000000000000000000000000000
After: 1d11b58b 00000011b58baeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
ERROR: AcceptBlock() : incorrect proof of work
ERROR: ProcessBlock() : AcceptBlock FAILED
I don't know if it could work if i release the new wallet

Related

c++ - The Value Changing Before I Save It

I'm reading a data from a game (SharedMemoryMapped) everything works good,
i got a time of a lap (in milliseconds), getting the seconds = Milliseconds / 1000f,
after that i'm tracking the position of the car until 1.000f which means the end and i need to save some data to the file,
but the lapTimeInSeconds is keep changing in the end of the loop before i get the values i need (Minutes: Seconds: MilliSeconds)
while (true) {
//........code........
// laptime
float lapTimeInSeconds = (float) ((float)graphic.iCurrentTime / 1000.0f);
printf("\rLAP: %.3f", lapTimeInSeconds);
// save
memcpy(&save_struct.lapTime_seconds, &lapTimeInSeconds, 4);
memcpy(&save_struct.normalizedCarPosition, &graphic.normalizedCarPosition, 4);
memcpy(&save_struct.gaz, &physics.gaz, 4);
memcpy(&save_struct.brake, &physics.brake, 4);
memcpy(&save_struct.speedKmh, &physics.speedKmh, 4);
memcpy(&save_struct.steerAngle, &physics.steerAngle, 4);
memcpy(&save_struct.gear, &physics.gear, 4);
memcpy(&save_struct.carCoordiantes, &graphic.carCoordiantes, sizeof(save_struct.carCoordiantes));
// write bytes into the file
fwrite(&save_struct, sizeof(SaveStruct), 1, saveFile);
if (graphic.normalizedCarPosition == 1) {
fclose(saveFile);
printf("\nFINAL LAP TIME: %.3f\n", lapTimeInSeconds); // HERE IS THE PROBLEM IT RESET TO 0.000 seconds, the VALUE GOT CHANGED AND SOMETIMES 0.654s
uint8_t seconds = (int) lapTimeInSeconds % 60;
uint8_t minutes = lapTimeInSeconds / 60;
uint16_t millisecond = (lapTimeInSeconds - ((minutes * 60) + seconds)) * 1000;
std::string final_file_name = "laps/lap-" + std::to_string(lapCount) + "-" + std::to_string(minutes) + "-" + std::to_string(seconds) + "-" + std::to_string(millisecond) + ".lap";
rename("laps/lap-not-completed.lap", final_file_name.c_str());
lapCount++;
saveFile = fopen("laps/lap-not-completed.lap", "wb");
}
}
The File name becomes 0 minutes, 0 seconds, 659 milliseconds
How to make lapTimeInSeconds not changing until i save the file ?!
Thank you.
The problem was :
the car position ( 1.000 ) means end of the lap, but the time got reset in (0.996)
so i had to change the condition..
#tadman thanks to you i changed:
// save
memcpy(&save_struct.lapTime_seconds, &lapTimeInSeconds, 4);
memcpy(&save_struct.normalizedCarPosition, &graphic.normalizedCarPosition, 4);
memcpy(&save_struct.gaz, &physics.gaz, 4);
memcpy(&save_struct.brake, &physics.brake, 4);
memcpy(&save_struct.speedKmh, &physics.speedKmh, 4);
memcpy(&save_struct.steerAngle, &physics.steerAngle, 4);
memcpy(&save_struct.gear, &physics.gear, 4);
memcpy(&save_struct.carCoordiantes, &graphic.carCoordiantes, sizeof(save_struct.carCoordiantes));
To:
save_struct.lapTime_seconds = (float) ((float)graphic.iCurrentTime / 1000.0f);
save_struct.normalizedCarPosition = graphic.normalizedCarPosition;
save_struct.gaz = physics.gaz;
save_struct.brake = physics.brake;
save_struct.speedKmh = physics.speedKmh;
save_struct.steerAngle = physics.steerAngle;
save_struct.gear = physics.gear;
save_struct.carCoordiantes[0][0] = graphic.carCoordiantes[0][0]; // x
save_struct.carCoordiantes[0][1] = graphic.carCoordiantes[0][1]; // y
save_struct.carCoordiantes[0][2] = graphic.carCoordiantes[0][2]; // z

can we set a bigger block size to the motion vector in ffmpeg

In the FFmpeg v5.0 function add_mb at line 1562 in mpegvideo.c file
static int add_mb(AVMotionVector *mb, uint32_t mb_type,
int dst_x, int dst_y,
int motion_x, int motion_y, int motion_scale,
int direction)
{
mb->w = IS_8X8(mb_type) || IS_8X16(mb_type) ? 8 : 16;
mb->h = IS_8X8(mb_type) || IS_16X8(mb_type) ? 8 : 16;
mb->motion_x = motion_x;
mb->motion_y = motion_y;
mb->motion_scale = motion_scale;
mb->dst_x = dst_x;
mb->dst_y = dst_y;
mb->src_x = dst_x + motion_x / motion_scale;
mb->src_y = dst_y + motion_y / motion_scale;
mb->source = direction ? 1 : -1;
mb->flags = 0; // XXX: does mb_type contain extra information that could be exported here?
return 1;
}
Depending on the MB_TYPE the block could take 8 or 16 pixels at one time so can we set the width and the height of the motion block to a bigger range in order to reduce the motion vector total length?
that could hurt the quality of the image but I'm ok with that.

Values of c++ array keep getting switched

I have an arduino program that runs a servo when it's at an odd angle, but after five seconds if still at that odd angle set it as the new center. the problem is that for some reason when I'm setting the angles of the current rotation to be the new center, the values get mixed up. Furthermore, the values of the center seem to be updating before the five seconds has even passed. I think this is something to do with the compiler. My code is here:
/*
Arduino and MPU6050 Accelerometer and Gyroscope Sensor Tutorial
by Dejan, https://howtomechatronics.com
*/
#include <Wire.h>
#include <Servo.h>
#define SERVO_PIN 9 //PWM pin that is connected to the servo
Servo demoServo; //create a servo object
int servoAngle = 0; //servo angle which can vary from 0 - 180
const int MPU = 0x68; // MPU6050 I2C address
float AccX, AccY, AccZ;
float GyroX, GyroY, GyroZ;
float accAngleX, accAngleY, gyroAngleX, gyroAngleY, gyroAngleZ;
float roll, pitch, yaw;
float rot[1];
float AccErrorX, AccErrorY, GyroErrorX, GyroErrorY, GyroErrorZ;
float elapsedTime, currentTime, previousTime;
int c = 0;
bool shake;
int shakeTime = 0;
float stablePos[1];
void setup() {
Serial.begin(19200);
Wire.begin(); // Initialize comunication
Wire.beginTransmission(MPU); // Start communication with MPU6050 // MPU=0x68
Wire.write(0x6B); // Talk to the register 6B
Wire.write(0x00); // Make reset - place a 0 into the 6B register
Wire.endTransmission(true); //end the transmission
demoServo.attach(SERVO_PIN);
delay(20);
stablePos[0] = 0;
stablePos[1] = 0;
rot[0] = 0;
rot[1] = 1;
}
void setIMU(float rot[])
{
// === Read acceleromter data === //
Wire.beginTransmission(MPU);
Wire.write(0x3B); // Start with register 0x3B (ACCEL_XOUT_H)
Wire.endTransmission(false);
Wire.requestFrom(MPU, 6, true); // Read 6 registers total, each axis value is stored in 2 registers
//For a range of +-2g, we need to divide the raw values by 16384, according to the datasheet
AccX = (Wire.read() << 8 | Wire.read()) / 16384.0; // X-axis value
AccY = (Wire.read() << 8 | Wire.read()) / 16384.0; // Y-axis value
AccZ = (Wire.read() << 8 | Wire.read()) / 16384.0; // Z-axis value
// Calculating Roll and Pitch from the accelerometer data
accAngleX = (atan(AccY / sqrt(pow(AccX, 2) + pow(AccZ, 2))) * 180 / PI) - 0.93; // AccErrorX ~(0.58) See the calculate_IMU_error()custom function for more details
accAngleY = (atan(-1 * AccX / sqrt(pow(AccY, 2) + pow(AccZ, 2))) * 180 / PI) - 4.23; // AccErrorY ~(-1.58)
// === Read gyroscope data === //
previousTime = currentTime; // Previous time is stored before the actual time read
currentTime = millis(); // Current time actual time read
elapsedTime = (currentTime - previousTime) / 1000; // Divide by 1000 to get seconds
Wire.beginTransmission(MPU);
Wire.write(0x43); // Gyro data first register address 0x43
Wire.endTransmission(false);
Wire.requestFrom(MPU, 6, true); // Read 4 registers total, each axis value is stored in 2 registers
GyroX = (Wire.read() << 8 | Wire.read()) / 131.0; // For a 250deg/s range we have to divide first the raw value by 131.0, according to the datasheet
GyroY = (Wire.read() << 8 | Wire.read()) / 131.0;
GyroZ = (Wire.read() << 8 | Wire.read()) / 131.0;
// Correct the outputs with the calculated error values
GyroX = GyroX + 0.43; // GyroErrorX ~(-0.56)
GyroY = GyroY + 0.63; // GyroErrorY ~(2)
GyroZ = GyroZ + 1.67; // GyroErrorZ ~ (-0.8)
// Currently the raw values are in degrees per seconds, deg/s, so we need to multiply by sendonds (s) to get the angle in degrees
gyroAngleX = gyroAngleX + GyroX * elapsedTime; // deg/s * s = deg
gyroAngleY = gyroAngleY + GyroY * elapsedTime;
yaw = yaw + GyroZ * elapsedTime;
// Complementary filter - combine acceleromter and gyro angle values
roll = 0.96 * gyroAngleX + 0.04 * accAngleX;
pitch = 0.96 * gyroAngleY + 0.04 * accAngleY;
rot[0] = pitch-10 > rot[0] || pitch+10 < rot[0] ? pitch : rot[0];
rot[1] = roll-10 > rot[1] || roll+10 < rot[1] ? roll : rot[1];
}
void loop() {
setIMU(rot);
Serial.print("STABLE AT:");
Serial.print(stablePos[0]);
Serial.print("/");
Serial.print(stablePos[1]);
Serial.print("\t CURRENTLY AT:");
Serial.print(rot[0]);
Serial.print("/");
Serial.println(rot[1]);
shake = (rot[0]>stablePos[0]+20 || rot[0]<stablePos[0]-20) ? true : (rot[1]>stablePos[1]+20 || rot[1]<stablePos[1]-20);
shakeTime = shake && shakeTime == 0 ? millis() + 5000 : shakeTime;
if (shakeTime < millis() && shakeTime != 0){
shakeTime = 0;
shake = false;
stablePos[0] = rot[0];
stablePos[1] = rot[1];
}
Serial.println(shake);
//Serial.println(shakeTime/1000);
demoServo.write(shake ? 180 : 0);
}
and the output of a test can be seen here:
STABLE AT:0.00/0.00 CURRENTLY AT:0.00/0.00
0
STABLE AT:0.00/0.00 CURRENTLY AT:0.00/0.00
0
STABLE AT:0.00/0.00 CURRENTLY AT:0.00/-0.00
0
STABLE AT:0.00/0.00 CURRENTLY AT:0.00/-0.14
0
STABLE AT:0.00/0.00 CURRENTLY AT:0.00/-0.26
0
STABLE AT:0.00/0.00 CURRENTLY AT:0.00/0.05
0
STABLE AT:0.00/10.98 CURRENTLY AT:10.98/0.41
0
STABLE AT:0.00/10.98 CURRENTLY AT:10.98/-0.00
0
STABLE AT:0.00/10.98 CURRENTLY AT:10.98/0.16
0
STABLE AT:0.00/10.98 CURRENTLY AT:10.98/0.00
0
STABLE AT:0.00/10.98 CURRENTLY AT:10.98/1.49
0
STABLE AT:0.00/10.98 CURRENTLY AT:10.98/1.86
0
STABLE AT:0.00/10.98 CURRENTLY AT:10.98/0.00
0
STABLE AT:0.00/21.30 CURRENTLY AT:21.30/0.63
1
STABLE AT:0.00/21.30 CURRENTLY AT:21.30/2.57
1
STABLE AT:0.00/21.30 CURRENTLY AT:21.30/2.70
1
STABLE AT:0.00/21.30 CURRENTLY AT:21.30/2.69
1
STABLE AT:0.00/31.95 CURRENTLY AT:31.95/2.56
1
STABLE AT:0.00/31.95 CURRENTLY AT:31.95/-0.00
1
STABLE AT:0.00/31.95 CURRENTLY AT:31.95/-0.00
1
as you can see, not only does the stable position update to 10.98 before the shake boolean gets set to two, but the placement is reversed as well.
float stablePos[1]; is an array of one element; the only valid index is stablePos[0]. By accessing stablePos[1], your program exhibits undefined behavior. Same with rot.

What is the correct formula to position my scroll bar slider?

This slider is used in my rpg to get rid of X amount of items so at pos 1 it will junk 1 item at max pos it will junk all the items.
slider image
My current formula is not correct
int pos_int = std::ceil(106.00 / (double)amount);
int base_pos = 318 - (amount - this->dj_slider_pos) * pos_int;
122 pixels is the total width of the draw area but after considering the width of the slider is 16 pixels the last draw position is at 106 pixels. Amount is the total number of items you have and dj_slider_pos tracks the position of the slider.
I have tried a few different variations but figured I might as well try and get help here instead of continuing to spin my wheels. Here is a little more code.
int amount = 1;
std::string itname = "";
UTIL_PTR_VECTOR_FOREACH(this->character->inventory_items,Character_Item,it)
{
if(it->id == this->character_inventory->selected_id)
{
itname = util::ucfirst(this->world->eif->Get(it->id)->name);
amount = it->amount;
break;
}
}
int pos_int = std::ceil(106.00 / (double)amount);
int base_pos = 318 - (amount - this->dj_slider_pos) * pos_int;
if(base_pos < 212) base_pos = 212;
else if(base_pos > 318) base_pos = 318;
this->DrawSplitBmp(base_pos,165, this->mouse_sliders,this->screen, &drop_junktabs[7]);
Problem solved! I initialized dj_slider_pos to 0 instead of 1 and changed the following lines.
double pos_int = 106.00 / (double)(amount-1);
int base_pos = 212 + (this->dj_slider_pos * pos_int);

For an Arduino Sketch based light meter, functions outside of 'loop' are not being set off/firing

I'm very new to Arduino. I have much more experience with Java and ActionScript 3. I'm working on building a light meter out of an Arduino Uno and a TAOS TSL235R light-to-frequency converter.
I can only find a tuturial using a different sensor, so I am working my way through converting what I need to get it all to work (AKA some copy and paste, shamefully, but I'm new to this).
There are three parts: this is the first tutorial of the series Arduino and the Taos TSL230R Light Sensor: Getting Started.
The photographic conversion: Arduino and the TSL230R: Photographic Conversions.
At first, I could return values for the frequency created by the TSL235R sensor, but once I tried to add the code for photographic conversions I only get zero returned, and none of the funcions outside of the main loop seem to fire being that my Serial.Println() doesn't return anything.
I am more concerned with making the functions fire than if my math is perfect. In ActionScript and Java there are event listeners for functions and such, do I need to declare the function for it to fire in C/C++?
Basically, how can I make sure all my functions fire in the C programming language?
My Arduino Sketch:
// TSL230R Pin Definitions
#define TSL_FREQ_PIN 2
// Our pulse counter for our interrupt
unsigned long pulse_cnt = 0;
// How often to calculate frequency
// 1000 ms = 1 second
#define READ_TM 1000
// Two variables used to track time
unsigned long cur_tm = millis();
unsigned long pre_tm = cur_tm;
// We'll need to access the amount of time passed
unsigned int tm_diff = 0;
unsigned long frequency;
unsigned long freq;
float lux;
float Bv;
float Sv;
// Set our frequency multiplier to a default of 1
// which maps to output frequency scaling of 100x.
int freq_mult = 100;
// We need to measure what to divide the frequency by:
// 1x sensitivity = 10,
// 10x sensitivity = 100,
// 100x sensitivity = 1000
int calc_sensitivity = 10;
void setup() {
attachInterrupt(0, add_pulse, RISING); // Attach interrupt to pin2.
pinMode(TSL_FREQ_PIN, INPUT); //Send output pin to Arduino
Serial.begin(9600); //Start the serial connection with the copmuter.
}//setup
void loop(){
// Check the value of the light sensor every READ_TM ms and
// calculate how much time has passed.
pre_tm = cur_tm;
cur_tm = millis();
if( cur_tm > pre_tm ) {
tm_diff += cur_tm - pre_tm;
}
else
if( cur_tm < pre_tm ) {
// Handle overflow and rollover (Arduino 011)
tm_diff += ( cur_tm + ( 34359737 - pre_tm ));
}
// If enough time has passed to do a new reading...
if (tm_diff >= READ_TM ) {
// Reset the ms counter
tm_diff = 0;
// Get our current frequency reading
frequency = get_tsl_freq();
// Calculate radiant energy
float uw_cm2 = calc_uwatt_cm2( frequency );
// Calculate illuminance
float lux = calc_lux_single( uw_cm2, 0.175 );
}
Serial.println(freq);
delay(1000);
} //Loop
unsigned long get_tsl_freq() {
// We have to scale out the frequency --
// Scaling on the TSL230R requires us to multiply by a factor
// to get actual frequency.
unsigned long freq = pulse_cnt * 100;
// Reset pulse counter
pulse_cnt = 0;
return(freq);
Serial.println("freq");
} //get_tsl_freq
void add_pulse() {
// Increase pulse count
pulse_cnt++;
return;
Serial.println("Pulse");
}//pulse
float calc_lux_single(float uw_cm2, float efficiency) {
// Calculate lux (lm/m^2), using standard formula
// Xv = Xl * V(l) * Km
// where Xl is W/m^2 (calculate actual received uW/cm^2, extrapolate from sensor size
// to whole cm size, then convert uW to W),
// V(l) = efficiency function (provided via argument) and
// Km = constant, lm/W # 555 nm = 683 (555 nm has efficiency function of nearly 1.0).
//
// Only a single wavelength is calculated - you'd better make sure that your
// source is of a single wavelength... Otherwise, you should be using
// calc_lux_gauss() for multiple wavelengths.
// Convert to w_m2
float w_m2 = (uw_cm2 / (float) 1000000) * (float) 100;
// Calculate lux
float lux = w_m2 * efficiency * (float) 683;
return(lux);
Serial.println("Get lux");
} //lux_single
float calc_uwatt_cm2(unsigned long freq) {
// Get uW observed - assume 640 nm wavelength.
// Note the divide-by factor of ten -
// maps to a sensitivity of 1x.
float uw_cm2 = (float) freq / (float) 10;
// Extrapolate into the entire cm2 area
uw_cm2 *= ( (float) 1 / (float) 0.0136 );
return(uw_cm2);
Serial.println("Get uw_cm2");
} //calc_uwatt
float calc_ev( float lux, int iso ) {
// Calculate EV using the APEX method:
//
// Ev = Av + Tv = Bv + Sv
//
// We'll use the right-hand side for this operation:
//
// Bv = log2( B/NK )
// Sv = log2( NSx )
float Sv = log( (float) 0.3 * (float) iso ) / log(2);
float Bv = log( lux / ( (float) 0.3 * (float) 14 ) ) / log(2);
return( Bv + Sv );
Serial.println("get Bv+Sv");
}
float calc_exp_tm ( float ev, float aperture ) {
// Ev = Av + Tv = Bv + Sv
// need to determine Tv value, so Ev - Av = Tv
// Av = log2(Aperture^2)
// Tv = log2( 1/T ) = log2(T) = 2^(Ev - Av)
float exp_tm = ev - ( log( pow(aperture, 2) ) / log(2) );
float exp_log = pow(2, exp_tm);
return( exp_log );
Serial.println("get exp_log");
}
unsigned int calc_exp_ms( float exp_tm ) {
unsigned int cur_exp_tm = 0;
// Calculate mS of exposure, given a divisor exposure time.
if (exp_tm >= 2 ) {
// Deal with times less than or equal to half a second
if (exp_tm >= (float) int(exp_tm) + (float) 0.5 ) {
// Round up
exp_tm = int(exp_tm) + 1;
}
else {
// Round down
exp_tm = int(exp_tm);
}
cur_exp_tm = 1000 / exp_tm;
}
else if( exp_tm >= 1 ) {
// Deal with times larger than 1/2 second
float disp_v = 1 / exp_tm;
// Get first significant digit
disp_v = int( disp_v * 10 );
cur_exp_tm = ( 1000 * disp_v ) / 10;
}
else {
// Times larger than 1 second
int disp_v = int( (float) 1 / exp_tm);
cur_exp_tm = 1000 * disp_v;
}
return(cur_exp_tm);
Serial.println("get cur_exp_tm");
}
float calc_exp_aperture( float ev, float exp_tm ) {
float exp_apt = ev - ( log( (float) 1 / exp_tm ) / log(2) );
float apt_log = pow(2, exp_apt);
return( apt_log );
Serial.println("get apt_log");
}
That is a lot of code to read, where should I start.
In your loop() you are assigning frequency but printing freq
// get our current frequency reading
frequency = get_tsl_freq();
-- snip --
Serial.println(freq);
in get_tsl_freq() you are creating a local unsigned int freq that hides the global freq and using that for calculation and returning the value, maybe that is also a source of confusion for you. I do not see a reason for frequency and freq to be globals in this code. The function also contains unreachable code, the control will leave the function on return, statements after the return will never be executed.
unsigned long get_tsl_freq() {
unsigned long freq = pulse_cnt * 100; <-- hides global variable freq
// re-set pulse counter
pulse_cnt = 0;
return(freq); <-- ( ) not needed
Serial.println("freq"); <-- Unreachable
}
Reading a bit more I can suggest you pick up a C++ book and read a bit. While your code compiles it is not technically valid C++, you get away with it thanks to the Arduino software that does some mangling and what not to allow using functions before they are declared.
On constants you use in your calculations
float w_m2 = (uw_cm2 / (float) 1000000) * (float) 100;
could be written as
float w_m2 = (uw_cm2 / 1000000.0f) * 100.0f;
or even like this because uw_cm2 is a float
float w_m2 = (uw_cm2 / 1000000) * 100;
You also seem to take both approaches to waiting, you have code that calculates and only runs if it has been more than 1000 msec since it was last run, but then you also delay(1000) in the same code, this may not work as expected at all.