compiler – is the relocatable machine code essentially the text segment of the virtual address?

Sorry if this is a basic question, I’m studying for my operating systems class and compiler theory class at the same time and this is confusing me. From what I do understand, virtual memory is larger than RAM and the virtual memory of a process looks like this:

(stack)(heap)(uninitialized data segment)(initialized data)(text segment)

where the text segment basically contains the code that needs to be run. Anything that the CPU needs from the virtual address will be loaded into the RAM when needed.

And the relocatable machine code is code that can be ran from any address. Does this mean it can be pretty much anythere in the virtual address (if that address is not already used by another section)?

Thanks

8 – Why is my code called again written on build form?

I have a form and i call an API tahta brings huge data on build form.
But when i call Ajax on other form elements , the whole code for form(buildForm, constructor ) is called again and again. There is a way to check triggering element but the code is called twice again once due to ajax Callback and once due to validateForm. I want a solution so that the Api are only called once, what solution i can use for this

<?php

namespace Drupalfapi_exampleForm;

use DrupalCoreFormFormStateInterface;

/**
 * Implements the ajax demo form controller.
 *
 * This example demonstrates using ajax callbacks to populate the options of a
 * color select element dynamically based on the value selected in another
 * select element in the form.
 *
 * @see DrupalCoreFormFormBase
 * @see DrupalCoreFormConfigFormBase
 */
class AjaxDemo extends DemoBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'fapi_example_ajax_demo';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form('temperature') = (
      '#title' => $this->t('Temperature'),
      '#type' => 'select',
      '#options' => $this->getColorTemperatures(),
      '#empty_option' => $this->t('- Select a color temperature -'),
      '#ajax' => (
        // Could also use (get_class($this), 'updateColor').
        'callback' => '::updateColor',
        'wrapper' => 'color-wrapper',
      ),
    );
    print("API call");
    $form('color_wrapper') = (
      '#type' => 'container',
      '#attributes' => ('id' => 'color-wrapper'),
    );

    $temperature = $form_state->getValue('temperature');
    if (!empty($temperature)) {
      $form('color_wrapper')('color') = (
        '#type' => 'select',
        '#title' => $this->t('Color'),
        '#options' => $this->getColorsByTemperature($temperature),
      );
    }

    // Add a submit button that handles the submission of the form.
    $form('actions') = (
      '#type' => 'actions',
      'submit' => (
        '#type' => 'submit',
        '#value' => $this->t('Submit'),
      ),
    );

    return $form;
  }

  /**
   * Ajax callback for the color dropdown.
   */
  public function updateColor(array $form, FormStateInterface $form_state) {
    return $form('color_wrapper');
  }

  /**
   * Returns colors that correspond with the given temperature.
   *
   * @param string $temperature
   *   The color temperature for which to return a list of colors. Can be either
   *   'warm' or 'cool'.
   *
   * @return array
   *   An associative array of colors that correspond to the given color
   *   temperature, suitable to use as form options.
   */
  protected function getColorsByTemperature($temperature) {
    return $this->getColors()($temperature)('colors');
  }

  /**
   * Returns a list of color temperatures.
   *
   * @return array
   *   An associative array of color temperatures, suitable to use as form
   *   options.
   */
  protected function getColorTemperatures() {
    return array_map(function ($color_data) {
      return $color_data('name');
    }, $this->getColors());
  }

  public function validateForm(array &$form, FormStateInterface $form_state) {
    $form_values = $form_state->getValues();
    print("Sssaaa");
  }

  /**
   * Returns an array of colors grouped by color temperature.
   *
   * @return array
   *   An associative array of color data, keyed by color temperature.
   */
  protected function getColors() {
    return (
      'warm' => (
        'name' => $this->t('Warm'),
        'colors' => (
          'red' => $this->t('Red'),
          'orange' => $this->t('Orange'),
          'yellow' => $this->t('Yellow'),
        ),
      ),
      'cool' => (
        'name' => $this->t('Cool'),
        'colors' => (
          'blue' => $this->t('Blue'),
          'purple' => $this->t('Purple'),
          'green' => $this->t('Green'),
        ),
      ),
    );
  }

}

I installed my printer, but I keep getting an error and it won’t print :( HP DeskJet 4100 Error code 5012

I installed hplip and there were no problems. I installed the printer via USB and there were no problems.
But when I try to print I get an error that there’s no communication with the printer?
I get "device communication error 5012"
Man, I really need to print lol.

Drupal 8 Ajax form, Code called again written on build form

I have a form and i call an API tahta brings huge data on build form.
But when i call Ajax on other form elements , the whole code for form(buildForm, constructor ) is called again and again. There is a way to check triggering element but the code is called twice again once due to ajax Callback and once due to validateForm. I want a solution so that the Api are only called once, what solution i can use for this

<?php

namespace Drupalfapi_exampleForm;

use DrupalCoreFormFormStateInterface;

/**
 * Implements the ajax demo form controller.
 *
 * This example demonstrates using ajax callbacks to populate the options of a
 * color select element dynamically based on the value selected in another
 * select element in the form.
 *
 * @see DrupalCoreFormFormBase
 * @see DrupalCoreFormConfigFormBase
 */
class AjaxDemo extends DemoBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'fapi_example_ajax_demo';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form('temperature') = (
      '#title' => $this->t('Temperature'),
      '#type' => 'select',
      '#options' => $this->getColorTemperatures(),
      '#empty_option' => $this->t('- Select a color temperature -'),
      '#ajax' => (
        // Could also use (get_class($this), 'updateColor').
        'callback' => '::updateColor',
        'wrapper' => 'color-wrapper',
      ),
    );
    print("API call");
    $form('color_wrapper') = (
      '#type' => 'container',
      '#attributes' => ('id' => 'color-wrapper'),
    );

    $temperature = $form_state->getValue('temperature');
    if (!empty($temperature)) {
      $form('color_wrapper')('color') = (
        '#type' => 'select',
        '#title' => $this->t('Color'),
        '#options' => $this->getColorsByTemperature($temperature),
      );
    }

    // Add a submit button that handles the submission of the form.
    $form('actions') = (
      '#type' => 'actions',
      'submit' => (
        '#type' => 'submit',
        '#value' => $this->t('Submit'),
      ),
    );

    return $form;
  }

  /**
   * Ajax callback for the color dropdown.
   */
  public function updateColor(array $form, FormStateInterface $form_state) {
    return $form('color_wrapper');
  }

  /**
   * Returns colors that correspond with the given temperature.
   *
   * @param string $temperature
   *   The color temperature for which to return a list of colors. Can be either
   *   'warm' or 'cool'.
   *
   * @return array
   *   An associative array of colors that correspond to the given color
   *   temperature, suitable to use as form options.
   */
  protected function getColorsByTemperature($temperature) {
    return $this->getColors()($temperature)('colors');
  }

  /**
   * Returns a list of color temperatures.
   *
   * @return array
   *   An associative array of color temperatures, suitable to use as form
   *   options.
   */
  protected function getColorTemperatures() {
    return array_map(function ($color_data) {
      return $color_data('name');
    }, $this->getColors());
  }

  public function validateForm(array &$form, FormStateInterface $form_state) {
    $form_values = $form_state->getValues();
    print("Sssaaa");
  }

  /**
   * Returns an array of colors grouped by color temperature.
   *
   * @return array
   *   An associative array of color data, keyed by color temperature.
   */
  protected function getColors() {
    return (
      'warm' => (
        'name' => $this->t('Warm'),
        'colors' => (
          'red' => $this->t('Red'),
          'orange' => $this->t('Orange'),
          'yellow' => $this->t('Yellow'),
        ),
      ),
      'cool' => (
        'name' => $this->t('Cool'),
        'colors' => (
          'blue' => $this->t('Blue'),
          'purple' => $this->t('Purple'),
          'green' => $this->t('Green'),
        ),
      ),
    );
  }

}

unity – How to create a Decisecond(0.1second) function that can use in the code?

I create a circular object and pivot the minute and second pointer on the middle of the object as below.
enter image description here
Below is the code I use.

using System;
using UnityEngine;

public class Pivot_minute : MonoBehaviour
{
    long x;

    void Update()
    { //1complete revolution for minute pointer=3600000millisecond
        x = DateTime.Now.Minute*60*1000+DateTime.Now.Second*1000+DateTime.Now.Millisecond;
        transform.eulerAngles = new Vector3(0, 0, -(x*0.0001f));
        
    }
}

using System;
using UnityEngine;

public class Pivot_second : MonoBehaviour
{
    long x;

    void Update()
    {// 1 complete revolution for second pointer=60000millisecond,then x millisecond=x/60000*360degree
        x = (DateTime.Now.Second*1000+DateTime.Now.Millisecond);
        transform.eulerAngles = new Vector3(0, 0, -x*0.006f);
    }
}

As tested, taking the millisecond precision is definitely showing a smoother pointer movement(not discrete movement) compare to the code below using “second” accuracy as calculation.

using System;
using UnityEngine;

public class Pivot_second : MonoBehaviour
{
    int x;

    void Update()
    {// 1 complete revolution for second pointer=60 second, then x second= x/60*360 degree
        x = (DateTime.Now.Second);
        transform.eulerAngles = new Vector3(0, 0, -x*6);
   
    }
}

Now I want to test the Decisecond(0.1second) accuracy to find out at this precision, can I still distinguish between the discrete movement and continuous movement of the pointer? Search through internet and so far do not have any luck.

programming challenge – Advent of Code 2020 – Day 3: tobogganing down a slope

Previous: Advent of Code 2020 – Day 2: validating passwords

I decided to take a shot at Advent of Code 2020 to exercise my Rust knowledge. Here’s the task for Day 3:

Day 3: Password Philosophy

(…)

Due to the local geology, trees in this area only grow on exact
integer coordinates in a grid. You make a map (your puzzle input) of
the open squares (.) and trees (#) you can see. For example:

..##.......
#...#...#..
.#....#..#.
..#.#...#.#
.#...##..#.
..#.##.....
.#.#.#....#
.#........#
#.##...#...
#...##....#
.#..#...#.#

These aren’t the only trees, though; due to something you read about
once involving arboreal genetics and biome stability, the same pattern
repeats to the right many times:

..##.........##.........##.........##.........##.........##....... --->
#...#...#..#...#...#..#...#...#..#...#...#..#...#...#..#...#...#..
.#....#..#..#....#..#..#....#..#..#....#..#..#....#..#..#....#..#.
..#.#...#.#..#.#...#.#..#.#...#.#..#.#...#.#..#.#...#.#..#.#...#.#
.#...##..#..#...##..#..#...##..#..#...##..#..#...##..#..#...##..#.
..#.##.......#.##.......#.##.......#.##.......#.##.......#.##..... --->
.#.#.#....#.#.#.#....#.#.#.#....#.#.#.#....#.#.#.#....#.#.#.#....#
.#........#.#........#.#........#.#........#.#........#.#........#
#.##...#...#.##...#...#.##...#...#.##...#...#.##...#...#.##...#...
#...##....##...##....##...##....##...##....##...##....##...##....#
.#..#...#.#.#..#...#.#.#..#...#.#.#..#...#.#.#..#...#.#.#..#...#.# --->

You start on the open square (.) in the top-left corner and need to
reach the bottom (below the bottom-most row on your map).

The toboggan can only follow a few specific slopes (you opted for a
cheaper model that prefers rational numbers); start by counting all
the trees
you would encounter for the slope right 3, down 1:

From your starting position at the top-left, check the position that
is right 3 and down 1. Then, check the position that is right 3 and
down 1 from there, and so on until you go past the bottom of the map.

The locations you’d check in the above example are marked here with
O where there was an open square and X where there was a tree:

..##.........##.........##.........##.........##.........##....... --->
#..O#...#..#...#...#..#...#...#..#...#...#..#...#...#..#...#...#..
.#....X..#..#....#..#..#....#..#..#....#..#..#....#..#..#....#..#.
..#.#...#O#..#.#...#.#..#.#...#.#..#.#...#.#..#.#...#.#..#.#...#.#
.#...##..#..X...##..#..#...##..#..#...##..#..#...##..#..#...##..#.
..#.##.......#.X#.......#.##.......#.##.......#.##.......#.##..... --->
.#.#.#....#.#.#.#.O..#.#.#.#....#.#.#.#....#.#.#.#....#.#.#.#....#
.#........#.#........X.#........#.#........#.#........#.#........#
#.##...#...#.##...#...#.X#...#...#.##...#...#.##...#...#.##...#...
#...##....##...##....##...#X....##...##....##...##....##...##....#
.#..#...#.#.#..#...#.#.#..#...X.#.#..#...#.#.#..#...#.#.#..#...#.# --->

In this example, traversing the map using this slope would cause you
to encounter 7 trees.

Starting at the top-left corner of your map and following a slope of
right 3 and down 1, how many trees would you encounter?

(…)

Part Two

Time to check the rest of the slopes – you need to minimize the
probability of a sudden arboreal stop, after all.

Determine the number of trees you would encounter if, for each of the
following slopes, you start at the top-left corner and traverse the
map all the way to the bottom:

  • Right 1, down 1.
  • Right 3, down 1. (This is the slope you already checked.)
  • Right 5, down 1.
  • Right 7, down 1.
  • Right 1, down 2.

In the above example, these slopes would find 2, 7, 3, 4, and
2 tree(s) respectively; multiplied together, these produce the
answer 336.

What do you get if you multiply together the number of trees
encountered on each of the listed slopes?

The full story can be found on the website.

src/day_3.rs

use {
    anyhow::{anyhow, bail, ensure, Result},
    itertools::Itertools,
    ndarray::prelude::*,
    std::io::{self, prelude::*},
};

pub const PATH: &str = "./data/day_3/input";

#(derive(Clone, Copy, Debug, Eq, Hash, PartialEq))
pub enum Pixel {
    Empty,
    Tree,
}

impl Pixel {
    pub fn from_char(c: char) -> Result<Self> {
        match c {
            '.' => Ok(Self::Empty),
            '#' => Ok(Self::Tree),
            _ => bail!("invalid pixel"),
        }
    }
}

#(derive(Clone, Debug, Eq, Hash, PartialEq))
pub struct Terrain {
    pixels: Array2<Pixel>,
}

impl Terrain {
    pub fn parse_from<R: BufRead>(reader: R) -> Result<Self> {
        TerrainParser::parse(reader.lines())
    }

    pub fn slope_count(&self, delta_x: usize, delta_y: usize) -> usize {
        assert!(delta_y != 0, "delta_y is zero");

        let pixels = &self.pixels;

        (0..pixels.nrows())
            .step_by(delta_y)
            .zip((0..).step_by(delta_x).map(|x| x % pixels.ncols()))
            .filter(|pos| pixels(*pos) == Pixel::Tree)
            .count()
    }
}

#(derive(Debug))
struct TerrainParser {
    pixels: Vec<Pixel>,
    width: usize,
    height: usize,
}

impl TerrainParser {
    fn parse<R: BufRead>(mut lines: io::Lines<R>) -> Result<Terrain> {
        let first_line =
            lines.next().ok_or_else(|| anyhow!("empty terrain"))??;
        let mut parser = Self::parse_first_line(&first_line)?;

        for line in lines {
            parser = parser.parse_line(&line?)?;
        }

        let TerrainParser {
            pixels,
            width,
            height,
        } = parser;

        Ok(Terrain {
            pixels: Array2::from_shape_vec((height, width), pixels)?,
        })
    }

    fn parse_first_line(line: &str) -> Result<Self> {
        let pixels: Vec<_> =
            line.chars().map(Pixel::from_char).try_collect()?;

        let width = pixels.len();
        ensure!(width != 0, "zero-width terrain");

        Ok(Self {
            pixels,
            width,
            height: 1,
        })
    }

    fn parse_line(mut self, line: &str) -> Result<Self> {
        let expected_len = self.pixels.len() + self.width;
        self.pixels.reserve_exact(self.width);

        itertools::process_results(
            line.chars().map(Pixel::from_char),
            |pixels| self.pixels.extend(pixels),
        )?;
        ensure!(self.pixels.len() == expected_len, "jagged terrain");

        self.height += 1;
        Ok(self)
    }
}

#(cfg(test))
mod tests {
    use {super::*, std::io::BufReader};

    #(test)
    fn pixel_from_char() {
        assert_eq!(Pixel::from_char('.').unwrap(), Pixel::Empty);
        assert_eq!(Pixel::from_char('#').unwrap(), Pixel::Tree);
        assert!(Pixel::from_char(' ').is_err());
    }

    #(test)
    fn terrain_parse_from() -> anyhow::Result<()> {
        fn parse(input: &str) -> Result<Terrain> {
            Terrain::parse_from(BufReader::new(input.as_bytes()))
        }

        let expected = Array2::from_shape_vec(
            (3, 3),
            (Pixel::Empty, Pixel::Tree)
                .iter()
                .copied()
                .cycle()
                .take(9)
                .collect(),
        )?;
        assert_eq!(parse(".#.n#.#n.#.n")?.pixels, expected);

        assert!(parse("").is_err());
        assert!(parse(". #").is_err());
        assert!(parse(".n##").is_err());

        Ok(())
    }

    #(test)
    fn terrain_slope_count() -> anyhow::Result<()> {
        // .#.
        // #.#
        // .#.
        // #.#
        let pixels = Array2::from_shape_vec(
            (4, 3),
            (Pixel::Empty, Pixel::Tree)
                .iter()
                .copied()
                .cycle()
                .take(12)
                .collect(),
        )?;
        let terrain = Terrain { pixels };

        assert_eq!(terrain.slope_count(1, 1), 1);
        assert_eq!(terrain.slope_count(2, 1), 3);
        assert_eq!(terrain.slope_count(3, 1), 2);
        assert_eq!(terrain.slope_count(1, 2), 1);

        Ok(())
    }
}

src/bin/day_3_1.rs

use {
    anyhow::Result,
    aoc_2020::day_3::{self as lib, Terrain},
    std::{fs::File, io::BufReader},
};

fn main() -> Result<()> {
    let file = BufReader::new(File::open(lib::PATH)?);

    let count = Terrain::parse_from(file)?.slope_count(3, 1);
    println!("{}", count);

    Ok(())
}

src/bin/day_3_2.rs

use {
    anyhow::Result,
    aoc_2020::day_3::{self as lib, Terrain},
    std::{fs::File, io::BufReader},
};

const SLOPES: &((usize; 2)) = &((1, 1), (3, 1), (5, 1), (7, 1), (1, 2));

fn main() -> Result<()> {
    let file = BufReader::new(File::open(lib::PATH)?);
    let terrain = Terrain::parse_from(file)?;

    let product: usize = SLOPES
        .iter()
        .map(|&(delta_x, delta_y)| terrain.slope_count(delta_x, delta_y))
        .product();
    println!("{}", product);

    Ok(())
}

Crates used: anyhow 1.0.37 itertools 0.10.0 ndarray 0.14.0

cargo fmt and cargo clippy have been applied.

Working code examples for stack or heap buffer overflows?

Exploit-DB is a well-known repository for exploit code and includes a number of overflows. For example, here’s one against socat which includes the steps required to exercise the overflow. Some exploits have more information, some less, but if you browse enough you should find the sort of shared exploit you’re looking for.

algorithm – Making code faster. BITWISE OR operator

Problem:
Given an array A of N integers, you will be asked Q queries. Each query consists of two integers L and R. For each query, find whether bitwise OR of all the array elements between indices L and R is even or odd.

My approach:
Accept the array of N integers. For any query (Qi) scan the array of integers between the given limit. If an odd number is found (x%2==1) then raise a flag and terminate scanning. If flag is found raised tell that the result is odd, else say that it’s even.

On thinking further, I find myself at the dead end. I can’t optimize the code anymore. Only thing I can think of is instead of doing mod 2 I will check the last digit of each number and see if it is one of (0,2,4,6,8). Upon trying that, the time limit still expired (in context to competitive programming (1); Note: the competition has ended a day ago and results declared). Anyways, my question is to find a better method if it exists or optimize the code below.

I assume that the time complexity is O(nQ) where n is the number of elements in the given range.


Assume array is 1-indexed.
Input
First line consists of two space-separated integers N and Q.
Next line consists of N space-separated array elements.
Next Q lines consist of two space-sepaprated integers L and R in each line.

#include<stdio.h>
#pragma GCC optimize("O2") 

int main()
{
    long int c,d,j,N,Q;
    int fagvar=0;
    scanf("%ld %ldn",&N,&Q);
    int a(N);
    int i=0;
    while(N--)
    {
        scanf("%ld",&a(i));
        i++;
    }
    while(Q--)
    {
        scanf("%ld %ld",&c,&d);
        for(j=c-1;j<d;j++)
        {
            if (a(j)%2==1)
            {
                fagvar=1;
                break;
            }
        }
        if (fagvar==1)
        {
            printf("%dn",0);
            fagvar=0;
        }
        else
        {
            printf("%dn",1);
        }
    }
    return 0;
}

plotting – How to ask to attach the plots vertically in the given code?

I use this code

{P1 = RegionPlot[0 <= Cos[y x] <= 1/2, {y, 0, 3}, {x, 0, 5}, 
   PlotStyle -> LightBlue, 
   FrameLabel -> {{Style[Rotate["F", 270 Degree], 15], 
      None}, {Style["y", 15], None}}, BaseStyle -> 15],

 P2 = RegionPlot[0 <= Cos[-y x] <= 1/2, {y, 0, 3}, {x, 0, -5}, 
   PlotStyle -> LightBlue, 
   FrameLabel -> {{Style[Rotate["G", 270 Degree], 15], 
      None}, {Style["y", 15], None}}, BaseStyle -> 15]}

and the result is

enter image description here

How can I ask Mathematica to attach the two plots vertically as follows

enter image description here

CVE submission – Denial of Service vs. Remote code execution

I wanted to ask how to deal with a new remote code execution vulnerability that has the same origin as an already found Denial of Service vulnerability? Can I apply for a new CVE ID for this? This is because the original vulnerability focuses on a Denial of Service and does not contain any remote code execution instructions. Does this count as a separate exploit even though they exploit the same parameter? Or more generally, can I apply for ‘similar’ but different CVEs?