opengl – discard GLSL fragment values ​​that do not work with the template buffer

I'm trying to create a system that I can use to sketch sprites, but I can only make it work if I use a normally shaped texture. This is what an outlined regular texture looks like:

Work outline

However, here is an irregular texture with the same outline code:

broken outline

I have to say that the broken outline does Use changed texture coordinates, but this shouldn't matter because all pixels with alpha = 0 are discarded (the second image is transparent to the person) should Prevent the template buffer from receiving them. However, the template buffer continues to count the rejected pixels as "written". Here are my shaders that we are all the same across the two textures:

Texture vertex:

#version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec2 aTexCoord;

out vec2 TexCoord;

uniform mat4 transform;
uniform mat4 view;
uniform mat4 projection;

void main()
{
    gl_Position = projection * view * transform * vec4(aPos, 1.0);
    TexCoord = aTexCoord;
}

Texture fragment:

#version 330 core
out vec4 FragColor;

in vec2 TexCoord;

uniform sampler2D ourTexture;
uniform vec4 color;

void main()
{
    FragColor = texture(ourTexture, TexCoord) * color;
    if (FragColor.a == 0) discard;
}

Outline fragment (paired with texture vertex):

#version 330 core

out vec4 fragColor;

uniform vec4 color;

void main() {
    fragColor = color;
    if (fragColor.a == 0) discard;
}

Finally, here is the common render code:

void c2m::client::gl::Sprite::render() {
    // Set shader uniforms if the shader is initialized
    if (shader != nullptr) {
        if (outlineWidth > 0) {
            glStencilFunc(GL_ALWAYS, 1, 0xFF);
            glStencilMask(0xFF);
        }

        applyTransforms();
        // Texture vertex and fragment
        shader->useShader();
        shader->setMat4("transform", trans);
        shader->setVec4("color", color.asVec4());
    }

    // Rebind the VAO to be able to modify its VBOs
    glBindVertexArray(vao);

    // Reset vertex data to class array
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices);
    glBindBuffer(GL_ARRAY_BUFFER, 0);

    // Bind texture
    tex->bind();

    // Draw
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);

    // If the outline width is 0 return
    if (outlineWidth == 0) {
        return;
    }

    // Draw outline
    if (outlineShader != nullptr) {
        glStencilFunc(GL_NOTEQUAL, 1, 0xFF);
        glStencilMask(0x00);
        glDisable(GL_DEPTH_TEST);
        // Texture vertex and outline fragment
        outlineShader->useShader();

        outlineShader->setVec4("color", outlineRGBA.asVec4());
        // Temporary transform matrix to prevent pollution of user-set transforms
        glm::mat4 tempTransform = trans;
        tempTransform = glm::scale(tempTransform, glm::vec3(outlineWidth + 1, outlineWidth + 1, outlineWidth + 1));
        outlineShader->setMat4("transform", tempTransform);
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);

        glStencilMask(0xFF);
        glEnable(GL_DEPTH_TEST);
        glStencilFunc(GL_ALWAYS, 1, 0xFF);
    }
}

Here is my template buffer initialization code:

// Stencil
glEnable(GL_STENCIL_TEST);
// Disable stencil writing by default, to be enabled per draw cycle
glStencilFunc(GL_NOTEQUAL, 1, 0xFF);
glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);

Am I doing something wrong in my texture fragment shader that doesn't properly discard transparent pixels, haven't I configured the template buffer correctly, or have I missed something somewhere else?

Implementation of setting multiple values ​​/ objects as valid / invalid

I have a kind of modal in which I have to display data (each represents an object). Any date can be set as valid or invalid. I wonder what the user interface should look like. I think about two options:

  • Radio buttons:
    Enter the image description here
  • Transfer list:
    Enter the image description here

    I'm not sure what's the best solution here. Of course I'm open to other ideas. Any advice from a UX perspective? 🙂 🙂

Rost – Hamming distance in pairs for binary data with missing values

I have just started learning Rust, and my first project is a command line program that generates a paired distance matrix for binary data, ignoring missing values. The input files look like this:

001N0
011N0
10N10

With N indicates missing values ​​that should be ignored. The example shows

0,1,1
1,0,2
1,2,0

After parsing the command line, argues with clap Each sample (i.e. line in the input file) is analyzed into a structure BitArrNA Hold 2 bitvec;; one called bits for the data (with N how 0) and called one not_nas Indication of the positions of non-NA values ​​(0 if Notherwise 1). To get the Hamming distance between two BitArrNA Three bitwise operations are necessary: ​​I have chosen ^ between the two bits, & between the two not_nas and & between the two results. All samples are compared and the distances are stored in a triangular matrix (a vector of vectors) in the structure TriMat before being written to the output file as a comma-separated symmetric matrix.

error

After reading about error handling philosophies in Rust, I decided on two strategies:

  • Errors caused by invalid entries are handled unwrap_or_else and std::process::exit
  • Other errors indicate internal errors in my code / logic and should trigger a panic With expect

ask

  • What could have been made more idiomatic?
  • Are there low hanging fruits in terms of performance / efficiency / parallelism?
  • Is error handling suitable?

code

main.rs

use binary_hamming_dist::bitarr::BitArrNa;
use binary_hamming_dist::cli::parse_cmd_line;
use binary_hamming_dist::trimat::TriMat;
use indicatif::{ProgressBar, ProgressStyle};
use rayon::prelude::*;
use std::fs;
use std::io;
use std::io::BufRead;

type Dist = u32;

fn main() {
    // get command line arguments
    let (infname, na_char, output, threads): (String, char, Option, usize) =
        parse_cmd_line();

    // create thread pool
    rayon::ThreadPoolBuilder::new()
        .num_threads(threads)
        .build_global()
        .expect("Error initializing threadpool");

    // parse file into bitarr vec
    let mut bitarrs: Vec = Vec::new();
    let infile = fs::File::open(infname).unwrap_or_else(|err| {
        eprintln!("Error opening input file: {}", err);
        std::process::exit(1);
    });
    let infile = io::BufReader::new(infile);

    for (i, line) in infile.lines().enumerate() {
        if let Ok(line) = line {
            bitarrs.push(BitArrNa::from_string(&line, na_char).unwrap_or_else(|err| {
                eprintln!("Error generating bitarr at line {}: {}", i + 1, err);
                std::process::exit(1);
            }));
        } else {
            eprintln!("Error reading input file at line {}", i + 1);
            std::process::exit(1);
        }
    }

    // create Vec of Vecs for holding the distances (resembling a triangular matrix)
    let n = bitarrs.len();
    let mut dists: TriMat = TriMat::new(n - 1);

    // setup progress bar
    let pb = ProgressBar::new(n as u64);
    pb.set_style(
        ProgressStyle::default_bar()
            .template("({elapsed_precise}) ({bar:50.cyan/blue}) {pos}/{len} ({eta})")
            .progress_chars("#>-"),
    );

    // get the distances
    dists
        .mat
        .par_iter_mut()
        .zip(bitarrs(..n - 1).par_iter()) // skip last sample
        .enumerate()
        .for_each(|(i, (dists_i, bitarr_i))| {
            for bitarr_j in &bitarrs(i + 1..) {
                dists_i.push(bitarr_i.dist(bitarr_j));
            }
            pb.inc(1);
        });
    pb.finish_with_message("done");

    // write result to file
    if let Some(outfname) = output {
        let mut file = fs::File::create(&outfname).unwrap_or_else(|err| {
            eprintln!("Error opening output file: {}", err);
            std::process::exit(1);
        });
        dists.write_symmetric(&mut file);
        println!("Result written to {}", outfname);
    } else {
        dists.write_symmetric(&mut io::stdout());
    }
}

lib.rs – only declares modules for other lib files

pub mod bitarr;
pub mod cli;
pub mod trimat;

cli.rs – contains the function for parsing the command line

pub fn parse_cmd_line() -> (String, char, Option, usize) {
    let matches = clap::App::new("Binary Hamming Distance Calculator")
        .about(
            "Calculates the pairwise distance matrix of binary strings and 
             tolerates missing values. n
             The input file should hold one sample per line and look like: nn
             001X0 n
             011X0 t where 'X' denotes a missing value. This yields n
             10X10 nn
             0,1,1 n
             1,0,2 t as result.n
             1,2,0 n",
        )
        .version(clap::crate_version!())
        .arg(
            clap::Arg::with_name("input")
                .help("input file")
                .takes_value(true)
                .short("i")
                .long("input")
                .required(true)
                .value_name("FILE")
                .display_order(1),
        )
        .arg(
            clap::Arg::with_name("NA-char")
                .help("the character (A-Za-z2-9) specifying missing values")
                .takes_value(true)
                .default_value("X")
                .possible_values(&(
                    "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P",
                    "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f",
                    "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
                    "w", "x", "y", "z", "2", "3", "4", "5", "6", "7", "8", "9",
                ))
                .hide_possible_values(true)
                .short("n")
                .long("NA-value")
                .value_name("CHAR")
                .display_order(2),
        )
        .arg(
            clap::Arg::with_name("output")
                .help("output file; if missing, result is printed to STDOUT")
                .takes_value(true)
                .short("o")
                .long("output")
                .value_name("FILE")
                .display_order(3),
        )
        .arg(
            clap::Arg::with_name("threads")
                .help("number of threads; '0' will use all available CPUs")
                .takes_value(true)
                .short("t")
                .long("threads")
                .default_value("1")
                .value_name("NUM"),
        )
        .get_matches();

    // calling unwrap is safe here because `input` was `required` by clap
    // and `NA-char` has a default as well as allowed arguments.
    let infname = matches.value_of("input").unwrap().to_string();
    let na_char = matches.value_of("NA-char").unwrap().chars().next().unwrap();
    let output = match matches.value_of("output") {
        None => None,
        Some(fname) => Some(fname.to_string()),
    };
    let threads: usize = matches
        .value_of("threads")
        .unwrap()
        .parse()
        .unwrap_or_else(|err| {
            eprintln!(
                "Error parsing command line arguments: {}. n
                 Please provide a valid integer value for the threads argument",
                err
            );
            std::process::exit(1);
        });
    (infname, na_char, output, threads)
}

bitarr.rs – holds BitArrNA struct

use bitvec::prelude as bv;
use itertools::izip;
use std::fmt;

pub struct BitArrNa {
    pub bits: bv::BitVec,
    pub not_nas: bv::BitVec,
}

impl BitArrNa {
    // create new `BitArrNa` with all-zero bits and all-one not_nas
    pub fn new(size: usize) -> BitArrNa {
        let bits = bv::bitvec!(0; size);
        let not_nas = bv::bitvec!(1; size);

        BitArrNa { bits, not_nas }
    }

    pub fn from_string(string: &str, na_char: char) -> Result {
        let mut bitarr = BitArrNa::new(string.len());
        for (i, c) in string.chars().enumerate() {
            if c == '0' {
                continue;
            } else if c == '1' {
                bitarr.bits.set(i, true);
            } else if c == na_char {
                bitarr.not_nas.set(i, false);
            } else {
                return Err(format!(
                    "Char at position {} was '{}'; expected '0', '1' or '{}'.",
                    i + 1,
                    c,
                    na_char
                ));
            }
        }

        Ok(bitarr)
    }

    pub fn dist(&self, other: &BitArrNa) -> T
    where
        T: num_traits::Num + num_traits::cast::FromPrimitive,
    {
        let mut result: T = T::zero();

        for (bits, not_nas, other_bits, other_not_nas) in izip!(
            self.bits.as_slice(),
            self.not_nas.as_slice(),
            other.bits.as_slice(),
            other.not_nas.as_slice()
        ) {
            let res_bits = bits ^ other_bits;
            let res_not_nas = not_nas & other_not_nas;
            let incr = T::from_u32((res_bits & res_not_nas).count_ones())
                .expect("Error converting distance to requested type");
            result = result + incr;
        }

        result
    }
}

impl fmt::Display for BitArrNa {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "bits:tt{}nnot_nas:t{}", self.bits, self.not_nas)
    }
}

trimat.rs – holds TriMat struct

use std::cmp;
use std::io;
use std::ops;

#(derive(Debug))
pub struct TriMat {
    pub mat: Vec>,
}

impl TriMat {
    pub fn new(n: usize) -> TriMat {
        let mut mat: Vec> = Vec::with_capacity(n);
        for i in 0..n {
            mat.push(Vec::with_capacity(n - i));
        }
        TriMat { mat }
    }
}

impl TriMat
where
    T: num_traits::Zero + std::string::ToString + Copy,
{
    pub fn write_symmetric(&self, buffer: &mut Buffer) {
        let n = self.mat.len();
        for i in 0..n + 1 {
            let mut line: Vec = Vec::with_capacity(n);
            for j in 0..n + 1 {
                let dist: T;
                if i == j {
                    dist = T::zero();
                } else {
                    let smaller = cmp::min(i, j);
                    let larger = cmp::max(i, j);
                    dist = self(smaller)(larger - smaller - 1);
                }
                line.push(dist);
            }
            let line: Vec = line.into_iter().map(|i| i.to_string()).collect();
            writeln!(buffer, "{}", &line.join(","))
                .expect(&format!("Error writing result at i: {}", i));
        }
    }
}

impl ops::Index for TriMat {
    type Output = Vec;

    fn index(&self, i: usize) -> &Self::Output {
        &self.mat(i)
    }
}

impl ops::IndexMut for TriMat {
    fn index_mut(&mut self, i: usize) -> &mut Self::Output {
        &mut self.mat(i)
    }
}

load.toml

(package)
name = "binary_hamming_dist"
version = "0.1.0"
edition = "2018"

(dependencies)
bitvec = "0.17.4"
itertools = "0.9.0"
rayon = "1.3.0"
indicatif = "0.14.0"
clap = "~2.27.0"
num-traits = "0.2.11"
```

c ++ – Sum of all values ​​contained in the path of a diagram

I wrote a code. In which I created a diagram. Then use DFS to drive from source to destination. I summarize all the values ​​of the nodes that I visited.

But I couldn't know why it's a wrong answer and later it shows Segmentation fault (core dumped).

I took help from here: https://www.geeksforgeeks.org/find-paths-given-source-destination/

My code:

#include 
#include 
using namespace std;


vector v1;

class Graph
{
    int V;          // No. of vertices in graph
    list *adj; // Pointer to an array containing adjacency lists

    // A recursive function used by printAllPaths()
    void printAllPathsUtil(int, int, bool(), int(), int &);

public:
    Graph(int V); // Constructor
    void addEdge(int u, int v);
    void printAllPaths(int s, int d);
};

Graph::Graph(int V)
{
    this->V = V;
    adj = new list(V);
}

void Graph::addEdge(int u, int v)
{
    adj(u).push_back(v); // Add v to u’s list.
}

// Prints all paths from 's' to 'd'
ll sum = 0;

void Graph::printAllPaths(int s, int d)
{
    // Mark all the vertices as not visited
    bool *visited = new bool(V);

    // Create an array to store paths
    int *path = new int(V);
    int path_index = 0; // Initialize path() as empty

    // Initialize all vertices as not visited
    for (int i = 0; i < V; i++)
        visited(i) = false;

    // Call the recursive helper function to print all paths
    printAllPathsUtil(s, d, visited, path, path_index);
}

// A recursive function to print all paths from 'u' to 'd'.
// visited() keeps track of vertices in current path.
// path() stores actual vertices and path_index is current
// index in path()
void Graph::printAllPathsUtil(int u, int d, bool visited(),
                              int path(), int &path_index)
{
    // Mark the current node and store it in path()
    visited(u) = true;
    path(path_index) = u;
    path_index++;

    // If current vertex is same as destination, then print
    // current path()
    if (u == d)
    {
        for (int i = 0; i < path_index; i++)
        {
            sum = sum + v1(i-1);
            // cout << path(i) << " ";
        }
        cout << sum << endl;
    }
    else // If current vertex is not destination
    {
        // Recur for all the vertices adjacent to current vertex
        list::iterator i;
        for (i = adj(u).begin(); i != adj(u).end(); ++i)
            if (!visited(*i))
                printAllPathsUtil(*i, d, visited, path, path_index);
    }

    // Remove current vertex from path() and mark it as unvisited
    path_index--;
    visited(u) = false;
}

// Driver code
int main()
{
    Graph g(5);
    g.addEdge(1, 2);
    g.addEdge(1, 3);
    g.addEdge(2, 4);
    g.addEdge(2, 5);

    v1.push_back(2);
    v1.push_back(6);
    v1.push_back(4);
    v1.push_back(3);
    v1.push_back(5);

    g.printAllPaths(1, 4);
    g.printAllPaths(2, 2);

    return 0;
}

unit – How to get multiple string values ​​by overriding ToString ()?

I want to get multiple string values ​​(selectedNameand selectedCurrency) individually public override string ToString()below.
How do I proceed?

    using System.Collections;
       using System.Collections.Generic;
       using UnityEngine;  

       (CreateAssetMenu(fileName = "Country", menuName = "Country/Country", order = 0))
       public class country : ScriptableObject
       {
           (System.Serializable)
           public class Item
           {
               public string Name;
               public string Currency;
               public string Capital;
               public string() City;

    public override string ToString()
    {
    string selectedName = this.name;
    string selectedCurrency = this.currency;
    return selectedName + selectedCurrency; 
    }

           }

           public Item() m_Items;
       public Item PickRandomly()
    {
        int index = Random.Range(0, m_Items.Length);
        return m_Items(index);
    }
}

I need to use the selected string values ​​in the following script.

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.UI;

    public class GameController: MonoBehaviour
    {   public country country; //This is the scriptable object country
    public Text countryText;
    public Text currencyText;

    void Start(){
    countryText.text = country.PickRandomly().ToString(); // This is where I need the country name string to show up.
currencyText.text = country.PickRandomly().ToString(); // This is where I need the currency string to show up.
    }
    }

At the moment, only a random country name and a random currency are displayed in both fields, e.g. B. USA USD.

postgresql – Fill a table with an X number of rows with default values ​​with a large insert query? Or can it be done somehow by default?

I have a table, let's say calendar

Table Calendar --> idCal (int) , numberOfFields (int)

And each calendar has assigned a number of fields

Table Field --> idField(int), textField(text), idCal (int) *fk

The point is now, every time a user registers, they are assigned a calendar. Once the number of fields is filled in, I select this value and generate an insert query similar to the following:

INSERT INTO Field (textField, idCal) Values ("","idOfTheGeneratedCalendar") , ("","idOfTheGeneratedCalendar") ...... 

Until I have a number of rows that correspond to numberOfFields from the table calendar. Each idField (int) begins with 0 and an automatic increment up to any number of fields takes place

I do this for every user. The point is … is there a better way to do this without building large insert queries, each with around 3000 values, using a for iteration? Should I be concerned?

Web forms – Add additional values ​​to the "next submission value".

Every time a web form is submitted, a submission value is created. H. 30, and when this is passed to the notification email, it looks like this:

http: // localhost / locationname / admin / structure / webform / manage / contact / submission / 30

I want to be able to create a unique / random ID for this URL, i.e. H.

http: // localhost / site-name / admin / structure / webform / manage / contact / submission / 30-abcd81091010

I want to link the client to the submitted web form, but anyone can access any submitted web form simply by changing the number in the URL.

Can someone help?

Google Sheets – Instead, split a column into multiple columns with TRUE / FALSE values

Here's a very small version of what I want to accomplish but can't figure out exactly what to look for on Google –

Column A | Column B
Alice    |  Present
Bob      |  Absent

Should translate into –

          Present    Absent
Alice      True
Bob                   True

So basically every unique value in column B should become a new column and the intersection of the row and column should be True.

Further expansion –
It's more complicated, but is that achievable? –

Convert this –

Column A |  HashTag 1 | HashTag 2 | HashTag 3
Alice    |   corona   | staySafe  | 
Bob      |   lucky    | corona    |  blessed  

to

          corona    staySafe   lucky   blessed 
Alice      True       True
Bob        True                 True    True

Here all HashTag columns have the same weight, but each tag is in a different column.

Thank you in advance.