text:
Q: Kotlin Coroutine - is there a default timeout I'm trying to reach a server, which is occasionally slow. The ktor client I'm using is crashing with an Exception in thread "main" kotlinx.coroutines.TimeoutCancellationException: Timed out waiting for 15000 ms, even though I never specified any limit. Is there a default timeout integrated?
Minimal example:
main.kt
import io.ktor.client.engine.cio.*
import io.ktor.client.features.*
import io.ktor.client.request.*

suspend fun main() {
    val client = HttpClient(CIO) {
        install(HttpTimeout) {
            requestTimeoutMillis = HttpTimeout.INFINITE_TIMEOUT_MS
            connectTimeoutMillis = HttpTimeout.INFINITE_TIMEOUT_MS
            socketTimeoutMillis = HttpTimeout.INFINITE_TIMEOUT_MS
        }
    }

    val foo = client.get<String>("http://slowwly.robertomurray.co.uk/delay/20000/url/http://www.google.co.uk")
    println(foo)

}

build.gradle.kts
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

plugins {
    kotlin("jvm") version "1.4.10"
    application
}
group = "me.oehmj"
version = "1.0-SNAPSHOT"

repositories {
    mavenCentral()
}

val ktor_version: String by project
val kotlin_serialization_version: String by project
val kotlin_coroutines_version: String by project

dependencies {
    implementation("io.ktor:ktor-client-cio:$ktor_version")
    implementation("io.ktor:ktor-client-auth-jvm:$ktor_version")
    implementation("io.ktor:ktor-client-logging-jvm:$ktor_version")
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:$kotlin_coroutines_version")
}

tasks.withType<KotlinCompile>() {
    kotlinOptions.jvmTarget = "1.8"
}
application {
    mainClassName = "MainKt"
}

gradle.properties
kotlin.code.style=official
ktor_version=1.4.2
kotlin_coroutines_version=1.4.1

The Ktor-HttpTimeout-Module seems to have no effect.
Are there any suggestions on how I can prolong the Timeout time?

A: Looking at the documentation you should do like that:
val client = HttpClient(CIO) {
    engine {
        requestTimeout = 0 // 0 to disable, or a millisecond value to fit your needs
    }
}

The default value is 15 seconds.
You can read more about ktor engines here


text:
Q: How do I use a couple of multi-dimensional arrays and one-dimentional arrays in a GUI program in Java? My teacher wants me to create a Java program that functions like a vending machine. She wants it to have multidimensional arrays and one-dimensional arrays. I already created the program but I failed because it doesn't have any array in it. It works perfectly fine but there are no arrays in it that's why I failed. She gave me another chance until tomorrow morning. I am really bad at using arrays, to be honest, and I don't really know how to use them in GUI apps. Thank you so much in advance for your help. Below is my code and the output of the current program I have so far.
import java.awt.EventQueue;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.SystemColor;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.Font;
import java.awt.Cursor;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextArea;
import javax.swing.JRadioButton;

public class Finals {
private JFrame frame;
private JTextField itemField;
private JTextField priceField;
private JButton pushButton, button1, button2, button3;
private JRadioButton  day1RB, day2RB, day3RB;
private JTextArea resultsTA;

//----Counter Variables for items A1, A2, and A3 for 3 days with 0 as the initial value
int A1d1=0; int A1d2=0; int A1d3=0;
int A2d1=0; int A2d2=0; int A2d3=0;
int A3d1=0; int A3d2=0; int A3d3=0;

//----Amount Variables for items A1, A2, and A3 for 3 days with 0 as the initial value
int A1d1Amount=0; int A1d2Amount=0; int A1d3Amount=0;
int A2d1Amount=0; int A2d2Amount=0; int A2d3Amount=0;
int A3d1Amount=0; int A3d2Amount=0; int A3d3Amount=0;

//----Variables for items B1, B2, and B3 for 3 days with 0 as the initial value
int B1d1=0; int B1d2=0; int B1d3=0;
int B2d1=0; int B2d2=0; int B2d3=0;
int B3d1=0; int B3d2=0; int B3d3=0;

//----Amount Variables for items B1, B2, and B3 for 3 days with 0 as the initial value
int B1d1Amount=0; int B1d2Amount=0; int B1d3Amount=0;
int B2d1Amount=0; int B2d2Amount=0; int B2d3Amount=0;
int B3d1Amount=0; int B3d2Amount=0; int B3d3Amount=0;

//----Variables used for storing total sales for all items for 3 days with 0 as the initial value
double A1total = 0; double A2total=0; double A3total=0;
double B1total = 0; double B2total=0; double B3total=0;

/**
 * Launching the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                Finals window = new Finals();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Creating the application.
 */
public Finals() {
    initialize();
}

/**
 * Initialize the contents of the frame.
 */
private void initialize() {
    frame = new JFrame();
    frame.setTitle("Vending Machine");
    frame.setResizable(false);
    frame.setBounds(100, 100, 914, 334);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

    JPanel itemsPanel = new JPanel();
    itemsPanel.setBackground(SystemColor.activeCaption);
    itemsPanel.setBounds(10, 11, 264, 191);
    frame.getContentPane().add(itemsPanel);
    itemsPanel.setLayout(null);

    JLabel a1Label = new JLabel();
    a1Label.setBounds(10, 11, 60, 57);
    ImageIcon a1Icon = new ImageIcon("cookie.png");
    a1Label.setIcon(a1Icon);
    itemsPanel.add(a1Label);

    JLabel a2Label = new JLabel();
    a2Label.setBounds(102, 11, 60, 57);
    ImageIcon a2Icon = new ImageIcon("gum.png");
    a2Label.setIcon(a2Icon);
    itemsPanel.add(a2Label);

    JLabel a3Label = new JLabel();
    a3Label.setBounds(195, 11, 60, 57);
    ImageIcon a3Icon = new ImageIcon("pretzel.png");
    a3Label.setIcon(a3Icon);
    itemsPanel.add(a3Label);

    JLabel b1Label = new JLabel("");
    b1Label.setBounds(10, 100, 60, 57);
    ImageIcon b1Icon = new ImageIcon("pretzel.png");
    b1Label.setIcon(b1Icon);
    itemsPanel.add(b1Label);

    JLabel b2Label = new JLabel();
    b2Label.setBounds(102, 100, 60, 57);
    ImageIcon b2Icon = new ImageIcon("cookie.png");
    b2Label.setIcon(b2Icon);
    itemsPanel.add(b2Label);

    JLabel b3Label = new JLabel();
    b3Label.setBounds(195, 100, 60, 57);
    ImageIcon b3Icon = new ImageIcon("soda.png");
    b3Label.setIcon(b3Icon);
    itemsPanel.add(b3Label);

    JLabel a1lbl = new JLabel("A1");
    a1lbl.setFont(new Font("Tahoma", Font.BOLD, 13));
    a1lbl.setBounds(27, 63, 25, 26);
    itemsPanel.add(a1lbl);

    JLabel a2lbl = new JLabel("A2");
    a2lbl.setFont(new Font("Tahoma", Font.BOLD, 13));
    a2lbl.setBounds(120, 63, 25, 26);
    itemsPanel.add(a2lbl);

    JLabel a3lbl = new JLabel("A3");
    a3lbl.setFont(new Font("Tahoma", Font.BOLD, 13));
    a3lbl.setBounds(213, 63, 25, 26);
    itemsPanel.add(a3lbl);

    JLabel b1lbl = new JLabel("B1");
    b1lbl.setFont(new Font("Tahoma", Font.BOLD, 13));
    b1lbl.setBounds(27, 154, 25, 26);
    itemsPanel.add(b1lbl);

    JLabel b2lbl = new JLabel("B2");
    b2lbl.setFont(new Font("Tahoma", Font.BOLD, 13));
    b2lbl.setBounds(120, 154, 25, 26);
    itemsPanel.add(b2lbl);

    JLabel b3lbl = new JLabel("B3");
    b3lbl.setFont(new Font("Tahoma", Font.BOLD, 13));
    b3lbl.setBounds(213, 154, 25, 26);
    itemsPanel.add(b3lbl);

    pushButton = new JButton("PUSH");
    pushButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            String selectedItem = itemField.getText();
            if(selectedItem.equals("A1") && day1RB.isSelected()) {
                A1d1Amount=A1d1Amount+10;
                A1d1+=1; A1total = A1d1Amount+A1d2Amount+A1d3Amount;
            }
            else if(selectedItem.equals("A1") && day2RB.isSelected()) {
                A1d2Amount=A1d2Amount+10;
                A1d2+=1; A1total = A1d1Amount+A1d2Amount+A1d3Amount;
            }else if(selectedItem.equals("A1") && day3RB.isSelected()) {
                A1d3Amount=A1d3Amount+10;
                A1d3+=1; A1total = A1d1Amount+A1d2Amount+A1d3Amount;
            }
            else if(selectedItem.equals("A2") && day1RB.isSelected()) {
                A2d1Amount=A2d1Amount+20;
                A2d1+=1; A2total = A2d1Amount+A2d2Amount+A2d3Amount;
            }
            else if(selectedItem.equals("A2") && day2RB.isSelected()) {
                A2d2Amount=A2d2Amount+20;
                A2d2+=1; A2total = A2d1Amount+A2d2Amount+A2d3Amount;
            }
            else if(selectedItem.equals("A2") && day3RB.isSelected()) {
                A2d3Amount=A2d3Amount+20;
                A2d3+=1; A2total = A2d1Amount+A2d2Amount+A2d3Amount;
            }
            else if(selectedItem.equals("A3") && day1RB.isSelected()) {
                A3d1Amount=A3d1Amount+30;
                A3d1+=1; A3total = A3d1Amount+A3d2Amount+A3d3Amount;
            }
            else if(selectedItem.equals("A3") && day2RB.isSelected()) {
                A3d2Amount=A3d2Amount+30;
                A3d2+=1; A3total = A3d1Amount+A3d2Amount+A3d3Amount;
            }
            else if(selectedItem.equals("A3") && day3RB.isSelected()) {
                A3d3Amount=A3d3Amount+30;
                A3d3+=1; A3total = A3d1Amount+A3d2Amount+A3d3Amount;
            }
            else if(selectedItem.equals("B1") && day1RB.isSelected()) {
                B1d1Amount=B1d1Amount+15;
                B1d1+=1; B1total = B1d1Amount+B1d2Amount+B1d3Amount;
            }
            else if(selectedItem.equals("B1") && day2RB.isSelected()) {
                B1d2Amount=B1d2Amount+15;
                B1d2+=1; B1total = B1d1Amount+B1d2Amount+B1d3Amount;
            }
            else if(selectedItem.equals("B1") && day3RB.isSelected()) {
                B1d3Amount=B1d3Amount+15;
                B1d3+=1; B1total = B1d1Amount+B1d2Amount+B1d3Amount;
            }
            else if(selectedItem.equals("B2") && day1RB.isSelected()) {
                B2d1Amount=B2d1Amount+25;
                B2d1+=1; B2total = B2d1Amount+B2d2Amount+B2d3Amount;
            }
            else if(selectedItem.equals("B2") && day2RB.isSelected()) {
                B2d2Amount=B2d2Amount+25;
                B2d2+=1; B2total = B2d1Amount+B2d2Amount+B2d3Amount;
            }
            else if(selectedItem.equals("B2") && day3RB.isSelected()) {
                B2d3Amount=B2d3Amount+25;
                B2d3+=1; B2total = B2d1Amount+B2d2Amount+B2d3Amount;
            }
            else if(selectedItem.equals("B3") && day1RB.isSelected()) {
                B3d1Amount=B3d1Amount+35;
                B3d1+=1; B3total = B3d1Amount+B3d2Amount+B3d3Amount;
            }
            else if(selectedItem.equals("B3") && day2RB.isSelected()) {
                B3d2Amount=B3d2Amount+35;
                B3d2+=1; B3total = B3d1Amount+B3d2Amount+B3d3Amount;
            }
            else if(selectedItem.equals("B3") && day3RB.isSelected()) {
                B3d3Amount=B3d3Amount+35;
                B3d3+=1; B3total = B3d1Amount+B3d2Amount+B3d3Amount;
            }

            double grandTotal = A1total+A2total+A3total+B1total+B2total+B3total;

            resultsTA.setText("Item        Day1        Day2        Day3        Sales Amount\n\n"
            +"A1            "+A1d1+"               "+A1d2+"               "+A1d3+"                ₱"+A1total+"0"
            +"\nA2            "+A2d1+"               "+A2d2+"               "+A2d3+"                ₱"+A2total+"0"
            +"\nA3            "+A3d1+"               "+A3d2+"               "+A3d3+"                ₱"+A3total+"0"
            +"\nB1            "+B1d1+"               "+B1d2+"               "+B1d3+"                ₱"+B1total+"0"
            +"\nB2            "+B2d1+"               "+B2d2+"               "+B2d3+"                ₱"+B2total+"0"
            +"\nB3            "+B3d1+"               "+B3d2+"               "+B3d3+"                ₱"+B3total+"0"
            +"\n\nTotal                                                             ₱"+grandTotal+"0"
            );
            clear();
        }
    });
    pushButton.setEnabled(false);
    pushButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    pushButton.setFont(new Font("Tahoma", Font.BOLD, 16));
    pushButton.setToolTipText("Press to buy.");
    pushButton.setBounds(10, 207, 264, 34);
    frame.getContentPane().add(pushButton);

    itemField = new JTextField();
    itemField.setFont(new Font("Tahoma", Font.BOLD, 16));
    itemField.setEditable(false);
    itemField.setBounds(293, 11, 218, 34);
    frame.getContentPane().add(itemField);
    itemField.setColumns(10);

    priceField = new JTextField();
    priceField.setFont(new Font("Tahoma", Font.BOLD, 16));
    priceField.setEditable(false);
    priceField.setColumns(10);
    priceField.setBounds(293, 56, 218, 34);
    frame.getContentPane().add(priceField);

    JPanel panel = new JPanel();
    panel.setBackground(SystemColor.activeCaption);
    panel.setBounds(293, 101, 218, 140);
    frame.getContentPane().add(panel);
    panel.setLayout(null);

    JLabel label1 = new JLabel("Select a Day of sale first and make");
    label1.setFont(new Font("Tahoma", Font.BOLD, 12));
    label1.setBounds(2, 2, 216, 14);
    panel.add(label1);

    JButton aButton = new JButton("A");
    aButton.setEnabled(false);
    aButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            priceField.setText(null);
            pushButton.setEnabled(false);
            itemField.setText("A");
            button1.setEnabled(true);
            button2.setEnabled(true);
            button3.setEnabled(true);
        }
    });
    aButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    aButton.setFont(new Font("Tahoma", Font.BOLD, 15));
    aButton.setBounds(62, 47, 46, 33);
    panel.add(aButton);

    JButton bButton = new JButton("B");
    bButton.setEnabled(false);
    bButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            priceField.setText(null);
            pushButton.setEnabled(false);
            itemField.setText("B");
            button1.setEnabled(true);
            button2.setEnabled(true);
            button3.setEnabled(true);
        }
    });
    bButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    bButton.setFont(new Font("Tahoma", Font.BOLD, 15));
    bButton.setBounds(118, 47, 46, 33);
    panel.add(bButton);

    button1 = new JButton("1");
    button1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            pushButton.setEnabled(true);
            String itemVal = itemField.getText();
            itemField.setText(itemVal+"1");
            button1.setEnabled(false);
            button2.setEnabled(false);
            button3.setEnabled(false);

            String newVal = itemField.getText();
            if(newVal.equals("A1")) {
                priceField.setText("₱10.00");
            }
            else {
                priceField.setText("₱15.00");
            }
        }
    });
    button1.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    button1.setEnabled(false);
    button1.setFont(new Font("Tahoma", Font.BOLD, 15));
    button1.setBounds(10, 91, 46, 33);
    panel.add(button1);

    button2 = new JButton("2");
    button2.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            pushButton.setEnabled(true);
            String itemVal = itemField.getText();
            itemField.setText(itemVal+"2");
            button1.setEnabled(false);
            button2.setEnabled(false);
            button3.setEnabled(false);

            String newVal = itemField.getText();
            if(newVal.equals("A2")) {
                priceField.setText("₱20.00");
            }
            else {
                priceField.setText("₱25.00");
            }
        }
    });
    button2.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    button2.setEnabled(false);
    button2.setFont(new Font("Tahoma", Font.BOLD, 15));
    button2.setBounds(87, 91, 46, 33);
    panel.add(button2);

    button3 = new JButton("3");
    button3.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            pushButton.setEnabled(true);
            String itemVal = itemField.getText();
            itemField.setText(itemVal+"3");
            button1.setEnabled(false);
            button2.setEnabled(false);
            button3.setEnabled(false);

            String newVal = itemField.getText();
            if(newVal.equals("A3")) {
                priceField.setText("₱30.00");
            }
            else {
                priceField.setText("₱35.00");
            }
        }
    });
    button3.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    button3.setEnabled(false);
    button3.setFont(new Font("Tahoma", Font.BOLD, 15));
    button3.setBounds(162, 91, 46, 33);
    panel.add(button3);

    JLabel label2 = new JLabel("a selection from the items.");
    label2.setFont(new Font("Tahoma", Font.BOLD, 12));
    label2.setBounds(2, 22, 171, 14);
    panel.add(label2);

    resultsTA = new JTextArea();
    resultsTA.setEditable(false);
    resultsTA.setBounds(521, 11, 368, 230);
    frame.getContentPane().add(resultsTA);

    day1RB = new JRadioButton("Day 1");
    day1RB.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            aButton.setEnabled(true);
            bButton.setEnabled(true);
            day2RB.setSelected(false);
            day3RB.setSelected(false);
        }
    });
    day1RB.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    day1RB.setFont(new Font("Tahoma", Font.BOLD, 12));
    day1RB.setBounds(531, 248, 64, 23);
    frame.getContentPane().add(day1RB);

    day2RB = new JRadioButton("Day 2");
    day2RB.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            aButton.setEnabled(true);
            bButton.setEnabled(true);
            day1RB.setSelected(false);
            day3RB.setSelected(false);
        }
    });
    day2RB.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    day2RB.setFont(new Font("Tahoma", Font.BOLD, 12));
    day2RB.setBounds(665, 248, 64, 23);
    frame.getContentPane().add(day2RB);

    day3RB = new JRadioButton("Day 3");
    day3RB.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            aButton.setEnabled(true);
            bButton.setEnabled(true);
            day1RB.setSelected(false);
            day2RB.setSelected(false);
        }
    });
    day3RB.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    day3RB.setFont(new Font("Tahoma", Font.BOLD, 12));
    day3RB.setBounds(797, 249, 64, 23);
    frame.getContentPane().add(day3RB);
}

//------Clearing everything after transaction
void clear() {
    itemField.setText(null);
    priceField.setText(null);
    button1.setEnabled(false);
    button2.setEnabled(false);
    button3.setEnabled(false);
    pushButton.setEnabled(false);
}

}
output

A: As a tip to get you started, you could replace your 3 by 3 set of variabls:
int A1d1=0; int A1d2=0; int A1d3=0;
int A2d1=0; int A2d2=0; int A2d3=0;
int A3d1=0; int A3d2=0; int A3d3=0;

With a multi dimensional array with 3 columns and 3 rows:
int[][] num = new int[3][3];

Or like this:
int[][] num = {{0,0,0},
               {0,0,0},
               {0,0,0}};

Then to replace the first value in the second column and first row we use:
num[1][0] = newValue;

Be careful because the first value of an array is at position num[0][0] not num[1][1]. So for example, when editing/getting a value the last value in an array it would be at position num[2][2], not at num[3][3]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Should I worry about repeating commit logs following rebase upstream/master? I'm a git newbie, and can't find the answer to my issue elsewhere. Apologies if it's a rather basic question.
So:
I've forked from a project, and then cloned my fork.
I've set my remotes up so that I have the upstream (originalproject/sitename.git) and an origin (myfork/sitename.git).
I've created a branch from my local master and I've been working in this branch. In the meantime, there have been updates on the upstream.
So I checked from my branch back into my local master and:
(master)$ git fetch upstream
(master)$ git rebase upstream/master
However, when I git log to check that I've got the latest upstream commits, it lists the same git commits tens of times over - so it lists commit logs from 6 weeks ago to now, then a semi-colon, then it lists the commit logs from 7 weeks ago to now, then a semi-colon, then it lists commits logs from 8 weeks ago to now, and so on.
My question is this:
Should I be worried about these repeating commit logs?
If I shouldn't be worried, to get the branch which I'd been working in up to date, do I then just 'git checkout branchname' and then 'git rebase master'?
Any help would be much appreciated.
Many thanks


text:
Q: Как запретить событие родителя дочернему элементу?

let offsetX;
let offsetY;
let parent = document.getElementById("parent");

function moveParent() {
  parent.addEventListener("dragstart", function(event) {
    offsetX = event.offsetX;
    offsetY = event.offsetY;
  })

  parent.addEventListener("dragend", function(event) {
    parent.style.top = (event.pageY - offsetY) + "px";
    parent.style.left = (event.pageX - offsetX) + "px";
  })
}
moveParent();
#parent {
  background-color: gray;
  height: 200px;
  width: 200px;
  position: absolute;
  top: 0;
  left: 0;
}

#son {
  background-color: yellow;
  height: 100px;
  width: 100px;
  position: absolute;
  top: 0;
  right: 0;
}

Как видно в коде есть Parent и внутри него элемент Son. Нужно сделать так, чтобы "хватая" за элемент Son Parent не передвигался, а передвигался только при хватании только его самого то есть то что серое(нажмите "Выполнить код").

A: добавьте в начало обработчиков событий
if(e.target!=parent)
    return;


text:
Q: Converting pdf to LaTeX?
Possible Duplicate:
How to convert PDF to (La)TeX?

is there a way to convert pdf to LaTeX? I don't need the conversion to be very accurate. It's fine for me as long as it is "almost there".
I found a project that looks promising
http://sourceforge.net/projects/pdf2latex/
but there are no files there.
Thank you.


text:
Q: Opencv 4.5.4 YoloV5 I export the Yolov5 .pt model to onnx with the command-line command python3 export.py --weights best.pt --include onnx --simplify
I am able to read the yolov5.onnx model with opencv 4.5.4 however I am unable to make predictions in the image. The output is a downscaled image without predictions.
My software is a simple main.cpp as it follows:
 * 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.
 */

/*
 * File:   main.cpp
 * Author: pauloasmendes
 *
 * Created on 24 de Novembro de 2021, 16:32
 */

#include <cstdlib>
#include <iostream>
#include <fstream>
#include <opencv4/opencv2/opencv.hpp>

using namespace std;

// YOLO
#include <stdexcept>
#include <opencv4/opencv2/dnn.hpp>
#include <opencv4/opencv2/dnn/all_layers.hpp>
constexpr float CONFIDENCE_THRESHOLD = 0;
constexpr float NMS_THRESHOLD = 0.4;
//number of classes to detect
//constexpr int NUM_CLASSES = 80;
constexpr int NUM_CLASSES = 5;// to detect only one class -> the first in the coco_names_txt file list ?!??
// colors for bounding boxes
const cv::Scalar colors[] = {
    {0, 255, 255},
    {255, 255, 0},
    {0, 255, 0},
    {255, 0, 0}
};
const auto NUM_COLORS = sizeof(colors)/sizeof(colors[0]);
//
/*
 *
 */
int main(int argc, char** argv) {
    cout << CV_VERSION<< endl;
    cv::Mat im_1;

    im_1 = cv::imread("im_14_RGB.jpg", cv::IMREAD_COLOR);
    if(!im_1.data){
        cout << "\n\t Could not open or find the image 1" << endl;
    }
    // let's downscale the image using new  width and height
    int down_width = 640;
    int down_height = 640;
   //resize down
   cv::resize(im_1, im_1, cv::Size(down_width, down_height), cv::INTER_LINEAR);

    // YOLO V5
    // read coco class names do ficheiro .txt
    std::vector<std::string> class_names;
    {
        std::ifstream class_file("coco_names.txt");
        if (!class_file)
        {
            std::cerr << "failed to open classes.txt\n";
            return 0;
        }

        std::string line;
        while (std::getline(class_file, line))
            class_names.push_back(line);
    }
    // Initialize the parameters para alocação de memoria for object detection using YOLOV4
    // faço load dos ficheiros de configuração do método YOLOV4
    //auto net = cv::dnn::readNetFromDarknet("custom-yolov4-detector.cfg", "custom-yolov4-detector_best.weights");
    //auto net = cv::dnn::readNetFromDarknet("yolov4.cfg", "custom-yolov4-tiny-detector_best.weights");
    //cv::dnn::Net net = cv::dnn::readNetFromONNX("best.onnx");
    auto net = cv::dnn::readNetFromONNX("yolov5.onnx");

    cout << "here" << endl;
    // using GPU for image processing
    //net.setPreferableBackend(cv::dnn::DNN_BACKEND_CUDA);
    //net.setPreferableTarget(cv::dnn::DNN_TARGET_CUDA);
    // using CPU for image processing
    net.setPreferableBackend(cv::dnn::DNN_BACKEND_OPENCV);
    net.setPreferableTarget(cv::dnn::DNN_TARGET_CPU);
    auto output_names = net.getUnconnectedOutLayersNames();
    cv::Mat blob;
    std::vector<cv::Mat> detections;
    std::vector<int> indices[NUM_CLASSES];
    std::vector<cv::Rect> boxes[NUM_CLASSES];
    std::vector<float> scores[NUM_CLASSES];

    // Creates 4-dimensional blob from image.
    cv::dnn::blobFromImage(im_1, blob, 0.00392, cv::Size(im_1.rows, im_1.cols), cv::Scalar(), true, false, CV_32F);
    net.setInput(blob);
    net.forward(detections, output_names);
    // object detection using YOLOV4
    for (auto& output : detections){
            const auto num_boxes = output.rows;
            for (int i = 0; i < num_boxes; i++){
                //calculo das 5 predições para cada bounding box: x, y, w, h , confiança
                auto x = output.at<float>(i, 0) * im_1.cols;
                auto y = output.at<float>(i, 1) * im_1.rows;
                auto width = output.at<float>(i, 2) * im_1.cols;
                auto height = output.at<float>(i, 3) * im_1.rows;
                cv::Rect rect(x - width/2, y - height/2, width, height);

                for (int c = 0; c < NUM_CLASSES; c++){
                    auto confidence = *output.ptr<float>(i, 5 + c);
                    if (confidence >= CONFIDENCE_THRESHOLD){
                        boxes[c].push_back(rect);
                        scores[c].push_back(confidence);
                    }
                }
            }
    }
    // Realiza a supressão não máxima das bounding boxes e das pontuações  de confiança correspondentes.
    // eliminação de bounding boxes repetidas que identificam o mesmo objecto.
    for (int c = 0; c < NUM_CLASSES; c++)
            cv::dnn::NMSBoxes(boxes[c], scores[c], 0.0, NMS_THRESHOLD, indices[c]);

    // identificação dos objectos e correspondentes pontuações de confiança através de bounding boxes.
    for (int c= 0; c < NUM_CLASSES; c++){
            for (size_t i = 0; i < indices[c].size(); ++i){
                const auto color = colors[c % NUM_COLORS];

                auto idx = indices[c][i];
                const auto& rect = boxes[c][idx];
                cv::rectangle(im_1, cv::Point(rect.x, rect.y), cv::Point(rect.x + rect.width, rect.y + rect.height), color, 3);

                // coloco a identificação da classe do objeto contido na bounding box - pedestre ou garrafa por ex.
                std::ostringstream label_ss;
                label_ss << class_names[c] << ": " << std::fixed << std::setprecision(2) << scores[c][idx];
                auto label = label_ss.str();

                int baseline;
                auto label_bg_sz = cv::getTextSize(label.c_str(), cv::FONT_HERSHEY_COMPLEX_SMALL, 1, 1, &baseline);
                // defino o rectangulo que define o objeto detectado
                cv::rectangle(im_1, cv::Point(rect.x, rect.y - label_bg_sz.height - baseline - 10), cv::Point(rect.x + label_bg_sz.width, rect.y), color, cv::FILLED);
                // coloco a identificação da classe do objecto detectado.
                cv::putText(im_1, label.c_str(), cv::Point(rect.x, rect.y - baseline - 5), cv::FONT_HERSHEY_COMPLEX_SMALL, 1, cv::Scalar(0, 0, 0));
            }
    }
    cv::namedWindow("YOLOV5 detection", cv::WINDOW_NORMAL);
    cv::imshow("YOLOV5 detection", im_1);
    cv::waitKey(0);
    cv::imwrite("YOLOV5_res.jpg", im_1);

    return 0;
}


text:
Q: From within Javascript (without JQuery), can I find if a function exists, that has a particular name? From within Javascript (without JQuery), I need to find if a function with a particular name exists.
I want to "replace" a function as described here (https://stackoverflow.com/a/3306973/606539). So, it would look something like this:
var fx='aFunctionName';
window['_o_'+fx]=window[fx];
window[fx]=function(){
  // do-whatever here
}

As best I can tell, in this example, it essentially renames a function named: 'aFunctionName' to a new name: '_o_aFunctionName', then creates a new function with the original name: 'aFunctionName'.
In my testing so far, this is working perfectly.
But, I want to add some code that will do some checking first, before performing these operations:

*

*Check to make sure the function named 'aFunctionName' (var fx) exists.

*Check to make sure a function named '_o_aFunctionName' (['_o_'+fx]) does not exist.

A: As long as you want to test global functions, you can use the typeof operator to find out what type the value is. Example:
typeof window[fx] === 'function'
// and
typeof window['_o_'+fx] !== 'function'

However, there is no way to test whether a local variable with a specific name exists (and what value it has).


text:
Q: Автоматическая отправка формы без перезагрузки страницы Здравствуйте, мне нужно отправить форму без перезагрузки страницы, с дальнейшими действиями на странице, то-есть после отправки формы нужно еще кликнуть подтверждающее выплывающее меню, как это можно реализовать посредством JS?

A: Это можно реализовать при помощи AJAX.
Для работы с AJAX можно использовать какую-нибудь библиотеку (например, jQuery) или написать всё на чистом JS. Первое, ИМХО, более предпочтительно.

A: Вам нужно в обработчик
   $(document).ready(function () {}); поместить функцию вызова ajax:

  $.ajax({
        type: "POST",
        url: "update.php",
        data: {
            Id: Data1,
            Name: Data2,
            Message: Data3
        },
        success: function (data) {
            $("#pro").html(data);
        }
    }
    )
};

Ну соответственно в ajax все что Вам требуется


text:
Q: i know password allthought i not get super user authentication I enter the known password  , but it does not permit me and gives below error in the display
su : Authentication failure.

A: You can not directly use su, as you can not use the root password (which is normally not set).
Use sudo su instead, with your own password.
For More Info , read RootSudo


text:
Q: How does a std::function object which return a std::function work when call by operator()? Sample:
#include "stdafx.h"
#include <functional>
#include <iostream>
#include <string>
std::function<void(int)> Foo()
{
    int v = 1;
    int r = 2;
    auto l = [v, r](int i)
    {
        std::cout << v << " " << r << " " << i << std::endl;
    };
    return l;
}

int main()
{
    auto func = Foo();
    func(3);
    return 0;
}

Why func(3) can pass 3 to i which is the formal argument of the lambda in Foo(). I can't think out. thanks.

A: TL;DR: You don't pass your argument 3 into a function Foo. You pass it to a method of an object func.
A bit more detailed explanation is below.

First of all, I would like to clarify what a lambda is. A lambda in C++ is nothing more than an anonymous functor class, so essentially just a syntactic sugar. A closure is an instance of a lambda type. However, quite often you can hear words "lambda" and "closure" being used interchangeably.
So within your function Foo() you create a closure object l
auto l = [v, r](int i)
{
    std::cout << v << " " << r << " " << i << std::endl;
};

which would be technically equivalent to this code:
struct Functor
{
    Functor(int v, int r) : v_(v), r_(r) {}

    void operator ()(int i) const {
        std::cout << v_ << " " << r_ << " " << i << std::endl;
    }

private:
    int v_;
    int r_;
};
Functor l(v, r);

Now, on the next line you return an std::function object.
return l; // actually creates std::function<void(int)>(l) and returns it

So in your main function a func is just an object which stores copies of values v, r obtained during a call to Foo() and defines operator(), similar to the struct above.
Therefore, calling func(3) you actually invoke an object method on a concrete object func, and without syntactic sugar it looks like func.operator()(3).
Here's a live example to illustrate my point.
Hope that helps to resolve your confusion.


text:
Q: Balance columns at new pages in multicol I am creating a document that uses a mixture of 1- and 2-column layouts with the multicol package. I would like to be able to balance the columns and have some text spanning both columns before resuming the 2-column layout. For example:
\documentclass{article}

\usepackage{multicol}
\usepackage{lipsum}

\begin{document}

\begin{multicols}{2}[Some text that will span both columns and fill the entire page width.]

\lipsum

% \end{multicols}
\newpage
% \begin{multicols}{2}[Some text that will span both columns and fill the entire page width.]

\lipsum

\end{multicols}

\end{document}

When \newpage is called, is immediately begins a new page and does not balance the column. The effect I would like to achieve is shown if the two lines above are uncommented. Then, ending the multicol environment and beginning it again (with the option argument to span both columns) works. However, this ends the current group, so local definitions are lost and I cannot proceed if this balancing happens within another environment.
Is it possible to achieve the desired effect, balancing the columns at a specific point with some interceding text?
[I am using the multicol 1.8a package from the SVN site.]

A: hmm this does what you ask, showing the split in the scope of a local declaration and a nested enumerate environment. However if your real case is as you show with a single line it would be simpler to consider the full width text as part of the page heading and just use a custom page style. Then it would also work with automatic page breaking.

\documentclass{article}

\usepackage{multicol}
\usepackage{lipsum}

\usepackage[italian]{babel}
\begin{document}

\setbox0\vbox{{\hsize\dimexpr(\textwidth-\columnsep)/2\relax
\columnwidth\hsize
\linewidth\hsize

\footnotesize% arbitray declaration to show scope
\lipsum

\begin{enumerate}
\item one
\pagebreak
\item two
\item three
\end{enumerate}

\lipsum
\par}}

\setbox2=\vsplit0 to \maxdimen

\begin{multicols}{2}[Some text that will span both columns and fill the entire page width.]
\unvbox2
\end{multicols}
\newpage
\newpage

\begin{multicols}{2}[Some text that will span both columns and fill the entire page width.]
\unvbox0
\end{multicols}

\end{document}


text:
Q: EditText won't write into single line I'm making a calculator and user input is contained in EditText. Input is typed through buttons on screen, so Android keyboard is disabled. However, I want it to write all input in one line and when line reaches border, it needs to be ellipsized and then horizontally scrollable so you can reach whole text.
I tried doing this by setting android:maxLines="1" and android:ellipsize="end", but that doesn't work. Text is still in multiple lines, but only one line is visible and you need to scroll vertically to see other lines. I also tried using android:singleLine="true", but that makes EditText completely unusable.
This is EditText XML:
<EditText
     android:id="@+id/textView"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:layout_gravity="end"
     android:background="@color/colorBlue"
     android:textAlignment="textEnd"
     android:textSize="40sp" />

A: For single line in EditText, you just need to set two properties:
android:inputType="text"
android:maxLines="1"

A: I think this will work for you. Let me know if it works.
<EditText
 android:id="@+id/textView"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:layout_gravity="end"
 android:background="@color/colorBlue"
 android:textAlignment="textEnd"
 android:textSize="40sp"
 android:inputType="text"
 android:maxLines="1"
 android:lines="1"
 android:scrollHorizontally="true"
 android:ellipsize="end"/>

This post might help you as well.

A: Adding this line in the edittext make scrollable singleline text.
android:inputType="textShortMessage"

A: **This example helps you to create multiline EditText in Android.**

<RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/rl"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="10dp"
        tools:context=".MainActivity"
        >

        <!--

            android:scrollbars="vertical"
                It will display a vertical scrollbar if the EditText text exceed
                3 lines (android:maxLines).
        -->
        <EditText
            android:id="@+id/et"
            android:layout_width="250dp"
            android:layout_height="wrap_content"
            android:padding="10dp"
            android:layout_marginBottom="10dp"
            android:hint="Multiline EditText by XML layout"
            android:fontFamily="sans-serif-condensed"
            android:background="#d3d7b6"
            android:minLines="2"
            android:maxLines="3"
            android:scrollbars="vertical"
            android:inputType="textMultiLine"
            />
        <EditText
            android:id="@+id/et2"
            android:layout_width="250dp"
            android:layout_height="wrap_content"
            android:padding="10dp"
            android:fontFamily="sans-serif-condensed"
            android:hint="Multiline EditText programmatically"
            android:background="#d4d7a5"
            android:layout_below="@+id/et"
            />
    </RelativeLayout>


text:
Q: How can i implement lazyload in the primeReact? I have a huge dataset thus i need to implement pagination for the Datatable in PrimeReact and for this i reffered the documentation which suggest to use lazyload to do so.But it is not working as well as my data is not displayed in the datatable but in console log it is getting displayed.
I have the following code implementation for achieving lazyload where i have added lazy attribute in the Datatable and called it onPage function using usestate in react.
Code:
import axios from 'axios'
import React, { useEffect, useState } from 'react'
import { DataTable } from 'primereact/datatable';
import { Button } from 'primereact/button';
import { Column } from 'primereact/column';
import "primereact/resources/themes/lara-light-indigo/theme.css";

//core
import "primereact/resources/primereact.min.css";

//icons
import "primeicons/primeicons.css";
import './App.css';

function App() {
const [data,setData]=useState([]);
const [loading, setLoading] = useState(false);
const [lazyState, setlazyState] = useState({
  first: 0,
  rows: 10,
  page: 1,
  sortField: null,
  sortOrder: null,
  filters: {
      name: { value: '', matchMode: 'contains' },
      'country.name': { value: '', matchMode: 'contains' },
      company: { value: '', matchMode: 'contains' },
      'representative.name': { value: '', matchMode: 'contains' }
  }});
  useEffect(()=>{
    console.log("use effect");
    getall();

  },[lazyState]);
  const getall=()=>{
    setLoading(true);
    axios.get("https://reqres.in/api/users").then((response)=>{
      setData(response.data);

    }).catch((error)=>{
      console.log(error);
    })
    setLoading(false);
  }
  const refresh=()=>{
    getall();
  }

  console.log(data)
   const header = (

        Employees
        <Button icon="pi pi-refresh" style={{marginLeft:'80%'}} rounded raised onClick={refresh}/>

);

    const onPage=(event)=>{
      setlazyState(event);
    }
  return (
    <>

    <DataTable value={data.data} header={header} lazy paginator row={2} dataKey="id" rowsPerPageOptions={[2, 10, 25, 50]}  showGridlines tableStyle={{ minWidth: '60rem' }} totalRecords={data.total} onPage={onPage} loading={loading}>
    <Column field="first_name" header="Name"></Column>
    <Column field="email" header="Email-id"></Column>

  </DataTable>

    </>
  );
}

export default App;

A: Working Code Sandbox demo of Lazying loading: https://codesandbox.io/s/primereact-demo-forked-m5yyhf


text:
Q: Extracting data from a text file to an output file I have alot of files which names are just number. (Starting from 1 to whatever is the maximum number) and each of these files are similar to each other by their "tags" (ObjectID =, X =, Y =, etc.), but the values after those tags are not the same at all.
I wanted to make my job easier from manually copy/pasting the data from one file to another and made a small script using Python (since I am slightly experienced in it).
This is the full script:
import os

BASE_DIRECTORY = 'C:\Users\Tom\Desktop\TheServer\scriptfiles\Objects'
output_file = open('output.txt', 'w')
output = {}
file_list = []

for (dirpath, dirnames, filenames) in os.walk(BASE_DIRECTORY):
    for f in filenames:
        if 'txt' in str(f):
            e = os.path.join(str(dirpath), str(f))
            file_list.append(e)

for f in file_list:
    print f
    txtfile = open(f, 'r')
    output[f] = []
    for line in txtfile:
        if 'ObjectID =' in line:
            output[f].append(line)
        elif 'X =' in line:
            output[f].append(line)
        elif 'Y =' in line:
            output[f].append(line)
tabs = []
for tab in output:
    tabs.append(tab)

tabs.sort()
for tab in tabs:
    for row in output[tab]:
        output_file.write(row + '')

Now, everything is working fine, the output file looks like this:
ObjectID = 1216
X = -1480.500610
Y = 2610.885742
ObjectID = 970
X = -1517.210693
Y = 2522.842285
ObjectID = 3802
X = -1512.156616
Y = 2521.116210
etc.

But I don't want it to be like that (each value has a new line). I need it to do this for every file:

*

*Read the file.

*Remove the tags infront of the values.

*Format a single line which will have those values in the output folder. (Let's say I want to make it look like this: "(1216,-1480.500610,2522.842285)" )

*Write that line in the output folder.

*Repeat for every file.

Any help please?

A: In your loop, keep track of whether you are 'in' a record:
records = []
in_record = False
id, x, y = 0, 0, 0
for line in txtfile:
    if not in_record:
        if 'ObjectID =' in line:
            in_record = True
            id = line[10:]
    elif 'X =' in line:
        x = line[3:]
    elif 'Y =' in line:
        y = line[3:]
        records.append((id, x, y))
        in_record = False

Then you'll have a list of tuples which you can easily write with the csv module.

A: Hope this helps.
data = open('sam.txt', 'r').read()

>>> print data
ObjectID = 1216
X = -1480.500610
Y = 2610.885742
ObjectID = 970
X = -1517.210693
Y = 2522.842285
ObjectID = 3802
X = -1512.156616
Y = 2521.116210
>>>

Now lets do some string replacements :)
>>> data = data.replace('ObjectID =', '').replace('\nX = ', ',').replace('\nY = ', ',')
>>> print data
 1216,-1480.500610,2610.885742
 970,-1517.210693,2522.842285
 3802,-1512.156616,2521.116210

A: Here is what you need. I did not have enough time to write the code for appending the result to a new file. Instead it just prints it, but you get the point.
import os.path

path = "path"

#getting the number of files in your folder
num_files = len([f for f in os.listdir(path)
                if os.path.isfile(os.path.join(path, f))])

#function that returns your desired output for a given file
def file_head_ext(file_path, file_num):
    with open(file_path + "/" + file_num) as myfile:
        head = [next(myfile).split("=") for x in range(3)]
        formatted_head = [elm[1].replace("\n",'').replace(" ","") for elm in head]
    return(",".join(formatted_head))

for filnum in range(1,num_files):
    print(file_head_ext(path, str(filnum)))

A: Find here a version of the loop you have generating the contents.
I rewrote it so the line contents ObjectId, X and Y are in the same line.
It looks that is what you want to do:
for f in file_list:
    print f
    txtfile = open(f, 'r')
    output[f] = []
    for line in txtfile:
        myline = ''
        if 'ObjectID =' in line:
            pos = line.rfind("ObjectID =") + len("ObjectID =")
            rest = line[pos:]
            # Here you set the delimiter after the ObjectID value. Can be ","
            numbers = rest.split(" ")
            if len(numbers) > 0:
                myline.append(numbers[0])

        elif 'X =' in line:
            pos = line.rfind("X =") + len("X =")
            rest = line[pos:]
            # Here you set the delimiter after the ObjectID value. Can be ","
            numbers = rest.split(" ")
            if len(numbers) > 0:
                myline.append(numbers[0])
        elif 'Y =' in line:
            pos = line.rfind("Y =") + len("Y =")
            rest = line[pos:]
            # Here you set the delimiter after the ObjectID value. Can be ","
            numbers = rest.split(" ")
            if len(numbers) > 0:
                myline.append(numbers[0])

        output[f].append(myline)

Note that you need to know which character (in the code the delimiter) separates the names you try to find: ObjectID = from the actual values you want to grab from the line.


text:
Q: Winform : How to show error icon on empty fields? I have a VB.Net application with forms with some bound fields.
When I type some wrong data in fields, the ErrorProvider shows a red ico automatically.
Is there any way that it shows the same icon when some required fields are empty ?
Here is the binding code of my controls :
Dim MyDataTable as datatable = GetDT
Me.Control.DataBindings.Add(New Binding(Me.BindingProperty, MyDataTable, FieldName, True, DataSourceUpdateMode.OnValidation))

Function GetDT() As DataTable
    Dim DT As New DataTable

    Dim i As Integer = 0
    DT.Columns.Add(New DataColumn("C1", i.GetType))
    DT.Columns(0).AllowDBNull = False

    Dim R As DataRow = DT.NewRow
    R.Item(0) = 15
    DT.Rows.Add(R)

    Return DT
End Function

The method ErrorProvider.SetError is not an option since the controls are created in a separate process and do not have access to the ErrorProvider.
Thanks.

A: You can use a custom class in your case:
Public Class customdatatable
        Implements IDXDataErrorInfo

        Private _value As String
        Public Sub New()
            MyBase.New()
        End Sub
        Public Property C1() As String
            Get
                Return _value
            End Get
            Set(ByVal value As String)
                _value = value
            End Set
        End Property

        Public Sub GetPropertyError(ByVal name As String, ByVal errorinfo As ErrorInfo) _
          Implements IDXDataErrorInfo.GetPropertyError
            If (name = "C1" And C1 = "") Then
                errorinfo.ErrorText = String.Format("Empty value")
            End If
        End Sub

        Public Sub GetError(ByVal errorinfo As ErrorInfo) Implements IDXDataErrorInfo.GetError
        End Sub
    End Class

then apply it to your form:
Dim DT = New customdatatable With {.C1 = 5} ''GetDT()
TextEdit1.DataBindings.Add(New Binding("EditValue", DT ,"C1", True))
DxErrorProvider1.DataSource = DT

If you don't care to lose focus control on your textfield just use this in your main.
Dim field2 = GetDT()
TextEdit1.DataBindings.Add(New Binding("EditValue", field2,"C1", True))
DxErrorProvider1.DataSource = field2


text:
Q: Force domain users to a single profile in a local machine In Windows XP, there is a way to configure it so that it would force every single domain users to a single profile in an local machine upon log in.
However I can't find the way to do this in Windows 7.
Does anyone have any recommendations?

A: Non-Sysprep Method

*

*Create "Test" or "Setup" account

*Make group policy changes
    Computer Config > Administrative Templates > System > User Profiles >

*

*Only Allow User Profiles = Enabled

*Set Roaming
Profile Path for all users logging onto this computer = Disabled

*Prevent Roaming Profile changes from propagating to the server =
Enabled

*Customize the Test or Setup account

*Enable built-in Administrator account

*Log on as Administrator

*Install RichCopy
from Technet

*Use Explorer to unhide system files and folders

*Use RichCopy to copy the profile from the account used to implement
customizations to "Default User"

*Join machine to the domain

*Reboot

*Log on domain user and all customizations should be applied to the users' profile

Sysprep Method - We may want to use this method because this method should be fully supported by MS

*

*Login as the setup account

*Enable Administrator Account

*Log on
as Administrator

*Go to Manage Users

*Delete Setup account andany other accounts that have a profile folder and choose "delete files"

*Make group policy changes

*

*Computer Config > Administrative Templates > System >
User Profiles >

*Only Allow User Profiles = Enabled

*Set Roaming
Profile Path for all users logging onto this computer = Disabled

*Prevent Roaming Profile changes from propagating to the server =
Enabled

*Complete all customizations

*Copy validated answer file
to C: root

*Go to windows\system32\sysprep

*Right click while holding shift and choose "open command window here"

*run "sysprep.exe /oobe /generalize /unattend:c:\yourunattendfile.xml

*Once the system reboots go through whatever portion of mini-setup your answer file dictates

*Join machine to the domain

*Log on as a
domain user

*Basic look and feel customizations should have been
applied from the local Defaul User profile

I have tested this method in a non AD environment and a bare AD virtual environment. If your organization uses Domain level gpo's you may need to make sure there are no gpo's that will over-write the local policies above.
Also, if you have a Network default profile in the Netlogon share you may need to set the permissions on that folder to deny all. I haven't tested yet to see the behavior if that share exists. So I still need to verify that the 3 local policies mentioned above will stop the profile search of the local machine from going to the network to trying to pull the Default Network Profile.
If you try that before I have posted an update please feel free to post your results here.

A: What you are looking for is called a mandatory profile. There is an MSDN article and an MS KB article on it. The latter has an explanation for exactly how to create and implement it.


text:
Q: Выделить строку DataGridView после обновления Есть DataGridView dgv,
 dgv.DataSource = myDateTable;

Есть код выделения строки
private static void SelectRowByOrderID(DataGridView dgv, string orderID)
    {
    dgv.Rows
             .OfType<DataGridViewRow>()
             .Where(x => (string)x.Cells["#"].Value == orderID)
             .ToArray<DataGridViewRow>()[0]
             .Selected = true;
    }

Действия:

*

*выбрать строку X;

*открыть форму редактирования;

*сохранить изменения в базе;

*закрыть форму редактирования;

*обновить таблицу myDateTable

*обновить dgv.DataSource
Вопрос:

*

*как после обновления dgv выделить строку Х ?

A: Если вы обновляете dgv через изменения DataSource И если myDateTable является ObservalableCollection И
то вас интересует ObservalableCollection.CollectionChanged

Подписываетесь на событие и выделяйте, что надо. Либо, если вас обычный event не устраивает, то создавайте свой и подписывайтесь на него.


text:
Q: Is there a way to gather three dataframes into one dataframe? I have three data frames and i want to gather them into only one data frame. I tried doing it with pandas package, however the third column does't appear.
For instance:
Fil1.txt
A   B    C
1   2    3
red blue gree

File2.txt
A    B   C
2    3   5
type dog cat

File3.txt
F   H   G
7   5   6
red dog blue

And when i try to gather them by:
all_dataframe=pd.concat([pd_table1, pd_table2, pd_table3], axis=1, sort=False, ignore_index=False)

I get this table:
Fil1.txt       …    File3.txt
A   B   C      …    F   H   G
1   2   3      …    7   5   6
red blue gree  …    red dog blue

To create this tables i used this code:
data_line=open("file1.txt", mode="r")

lines=[]
for line in data_line:
    lines.append(line)
for i, line in enumerate(lines):
    # print('{}={}'.format(i+1, line.strip()))
    file1_header=lines[0]
num_line=1
Dictionary_File1={}
Value_File1= data_type[0:6]
Value_File1_short=[]
i=1
for element in Value_File1:
    type=element.split(',')
    Value_File1_short.append(type[0] + ", " + type[1] + ", " + type[4])
    i += 1
Dictionary_File1[ file1_header]=Value_File1_short
pd_file1=pd.DataFrame.from_dict(Dictionary_File1)

The expected result would be:


text:
Q: POST data while when getting JSON with SwiftyJSON I'm developing an iOS app with Xcode and Swift.
I'm getting JSON data with SwiftyJSON.swift and the following code:
import UIKit

class ViewController: UIViewController {

    var dict = NSDictionary()

    @IBOutlet weak var firstLb: UILabel!
    @IBOutlet weak var secondLb: UILabel!

    override func viewDidLoad() {

        super.viewDidLoad()

        let urlString = "http://example.com/showUserInfo.php"

        if let url = NSURL(string: urlString) {

            if let data = try? NSData(contentsOfURL: url, options: []) {

                let json = JSON(data: data)

                print(json)

                let f = json[0]["name"].stringValue

                let s = json[0]["age"].stringValue

                firstLb.text = f

                secondLb.text = s
            }
        }
    }
}

That works fine but I want to be able to post to my PHP script. (My PHP script is ready for it. It can receive POST data and handle it.)
I normally use the following code to POST data to PHP:
let request = NSMutableURLRequest(URL: NSURL(string: "http://example.com/showUserInfo.php")!)
request.HTTPMethod = "POST"
let postString = "username=MyUserName"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)

That means: I know how to get data with JSON and I know how to POST a value to PHP. But unfortunately I'm not able to combine both.
Does anybody know how to combine them? How to POST a value to a PHP script where getting the JSON data?

A: To post data to Server you should use In-build APIs, or you can use a very famous library called : Alamofire
Sample Code:
    let params:[String:AnyObject] = [
        "foo" : 1,
        "bar" : 2
    ]

    request(.POST,  "URL", parameters: params)
        .responseJSON { response in

            switch response.result {
            case .Success(let JSON):
                print("JSON: \(JSON)")

            case .Failure(let error):
                print("Request failed with error: \(error)")
            }
    }


text:
Q: Assertion failure: ut0ut.cc:553 thread 140316173764352 [ERROR] [MY-012872] [InnoDB] [FATAL] enter image description here
nnoDB: ###### Diagnostic info printed to the standard error stream
2023-02-15T03:39:09.042343+05:30 0 [ERROR] [MY-012872] [InnoDB] [FATAL] Semaphore wait has lasted > 600 seconds. We intentionally crash the server because it appears to be hung.
2023-02-15T03:39:09.085843+05:30 0 [ERROR] [MY-013183] [InnoDB] Assertion failure: ut0ut.cc:553 thread 140316173764352
InnoDB: We intentionally generate a memory trap.
InnoDB: Submit a detailed bug report to http://bugs.mysql.com.
InnoDB: If you get repeated assertion failures or crashes, even
InnoDB: immediately after the mysqld startup, there may be
InnoDB: corruption in the InnoDB tablespace. Please refer to
InnoDB: http://dev.mysql.com/doc/refman/8.0/en/forcing-innodb-recovery.html
InnoDB: about forcing recovery.


text:
Q: Issue creating tables in JPA I am working an assignment for a class, and am having trouble getting tables to be created in my MySQL database from entities in java. I am trying to get the tables to be created by typing mvn clean install in the project folder in terminal (which is what was given to me as an example to create them once I had the entities in java). No errors or anything occur, and I get a "build successful" message in terminal, but no new tables are created in MySQL. I have confirmed that my endpoint/username/password are all working by setting up the project using jdbc to manually connect instead of JPA and everything works fine that way. Note: This isn't the actual content of the assignment just the initial setup. I've followed the instructions the professor has given multiple times and it is not working. Thanks for the help!
I created my project using the spring command line interface in terminal:
spring init --dependencies=web test
I then added a webapp directory with a index.html file in the src/main directory of the project. Then the project was imported to IntelliJ as a Maven project
I added the following to my application.properties file which is in src/main resources (and is the resources root of the project). The aws endpoint/schema name are also filled in as usual:
spring.datasource.url=jdbc:mysql://MyAWSEndpoint:3306/SchemaName
spring.datasource.username=MyUsername
spring.datasource.password=MyPassword
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.naming-strategy=org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect

I then have a class that I created called random which is contained in src/main/java which is my source root for the project.
package com.example.test;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class random {
  @Id
  @GeneratedValue (strategy = GenerationType.IDENTITY)
  private int id;
  private String name;

  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }
}

Additionally I have a Repository I made for the entity in java contained in the same package as the class above.
package com.example.test;

import org.springframework.data.repository.CrudRepository;

public interface RandomRepository extends CrudRepository<random, Integer> {
}

Here is my pom.xml file as well
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>test</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.45</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Additionally, I have a an application file in src/main/java:
package com.example.test;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

A: You might want to use the below property in the application.properties once:
spring.jpa.hibernate.ddl-auto=create

after the first run you can comment it out again.
To be sure your db user must have the correct privileges to create tables otherwise it won't work :-)
And you need to run the application either by using:
mvn clean package && java -jar target/test-0.0.1-SNAPSHOT.jar

or
mvn clean spring-boot:run

if your application is only build it will not run and not do anything except being compiled and tested.
It might be that your teacher had the setup of the database in the unit tests? then it would have been done...
Good luck


text:
Q: How to trigger a function that emits a livedata object? Here is my ViewModel code
private val logoutRequest = MutableLiveData<String>()

 // observing this livedata in activty

 val logoutUser = logoutRequest.switchMap {
        liveData(Dispatchers.IO) {
            emit(Resource.loading(data = null))
            try {
                emit(Resource.success(data = mainRepository.logout()))
            } catch (exception: Exception) {
                val errorMessage = BaseUtils.getError(exception)
                emit(Resource.error(data = null, message = errorMessage))
            }
        }
    }

    //calling this function from activity

    fun logoutCall(request: String = "logout") {
        logoutRequest.value = request
    }

I am calling logout API from main activity and observe that LiveData in that activity. But I don't want to trigger switchmap from logoutrequest livedata. I want to trigger switchmap automatically when logoutCall is called. Any workaround?


text:
Q: Shutil.copy2() Operation not permitted error I have created the basic script below that scans a directory for wav files and copies them into a nested directory based on file attributes.
"""
Script that copies data from Peersonic RPA3 into directory
using file name, date and time
"""

import datetime as dt
import os
import shutil
import time
from pathlib import Path

# Function to check if survey is dusk or dawn
def duskdawn(file):
    filetime = dt.datetime.fromtimestamp(os.path.getmtime(file))
    if file_time.time() > dt.time(12):
        return "Dusk"
    else:
        return "Dawn"

def file_date(file):
    return time.strftime('%d.%m.%Y', time.localtime(os.path.getmtime(file)))

def client(file):
    return file.name[0:3]

client_lst = ['IES', 'DEC', 'TEP']

# Directory of files
path = "/Volumes/BATrecorder/WAVFILES.DIR"
for entry in os.scandir(path):
    source = entry.path
    perm = os.stat(entry).st_mode
    client_name = (client(entry))
    if entry.name.endswith(".WAV"):
        if client_name in client_lst:
            client_name = client_name
        else:
            client_name = "unknown"
    destination = f"/Volumes/Seagate Exp/Work 2020/Bat recordings/{client_name}/{file_date(entry)}/{duskdawn(entry)}"
    Path(destination).mkdir(parents=True, exist_ok=True)
    shutil.copy2(source, destination)

Initially I used the standard shutil.copy() function and this worked fine. However, I need to keep the original file metadata so need to use shutil.copy2() instead. When I use this one I get the following error:
Traceback (most recent call last):
  File "/Volumes/Seagate Exp/Work 2020/file_copy.py", line 43, in <module>
    shutil.copy2(source, destination)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/shutil.py", line 258, in copy2
    copystat(src, dst, follow_symlinks=follow_symlinks)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/shutil.py", line 218, in copystat
    lookup("chflags")(dst, st.st_flags, follow_symlinks=follow)
PermissionError: [Errno 1] Operation not permitted: '/Volumes/Seagate Exp/Work 2020/Bat recordings/unknown/31.12.2014/Dusk/@AAA_000.WAV'

What is going on here that causes this issue?


text:
Q: VB.net Trim function I have an issue with trim the string method NOT working completely I have reviewed MS Docs and looked of forums but with no luck... It's probably something simple or some other parameter is missing. This is just a sample,
Please note I need to pick up text before and after #, hence than I was planning to use # as a separator. Trim start @ #, Trim End @ #. I can't use The last Index or Replace per my understanding they have no direction. But perhaps I am misunderstood MS docs regards to trim Start and End as well...
thanks!
 Dim str As String = "this is a #string"
        Dim ext As String = str.TrimEnd("#")
        MsgBox(ext)

ANSWER:
I found a solution for my problem, if you experience similar please see below:
1st: Trim end will NOT scan for the "character" from the Right as I originally thought it will just remove it from the right.... A weak function I would say:). IndexOf direction ID would be a very simple and helpful. Regards My answer was answered by Andrew, thanks!
Now there is another way around it if you try to split a SINGLE String INTO - QTY based on CHARACTER separation and populate fields accordingly.
Answer is ArrayList. Array List will ID each String so you can avoid repeated populations and etc. After you can use CASE or IF to populate accordingly.
Dim arrList As New ArrayList("this is a # string".Split("#"c)) ' Will build the list of your strings
Dim index As Integer = 1 ' this will help us index the strings 1st, 2nd and etc.
For Each part In arrList 'here we are going thru the list
Select Case index ' Here we are identifying which field we are populating

       Case 1 '1st string(split)
         MsgBox("1 " & arrList(0) & index) '1st string value left to SPLIT arrList(0).

       Case 2 '2nd string(split)
         MsgBox("2 " & arrList(1) & index) '2nd string value left to SPLIT arrList(1).
 End Select

         index += 1 'Here we adding one shift thru strings as we go

 Next

A: Rather than:
Dim str As String = "this is a #string"
Dim ext As String = str.TrimEnd("#")

Try:
Dim str As String = "this is a #string"
Dim ext As String = str.Replace("#", "")

A: Dim str As String = "this is a #string"
Dim parts = str.Split("#"c)

For Each part in parts
    Console.WriteLine($"|{part}|")
Next

Output:

|this is a |
|string|

A: Maybe there is a better way as we know there are multiple things to do the same thing.
The solution I used is below:
Dim arrList As New ArrayList("this is a # string".Split("#"c)) ' Will build the list of your strings
Dim index As Integer = 1 ' this will help us index the strings 1st, 2nd and etc.
For Each part In arrList 'here we are going thru the list
Select Case index ' Here we are identifying which field we are populating

       Case 1 '1st string(split)
         MsgBox("1 " & arrList(0) & index) '1st string value left to SPLIT arrList(0).

       Case 2 '2nd string(split)
         MsgBox("2 " & arrList(1) & index) '2nd string value left to SPLIT arrList(1).
 End Select

         index += 1 'Here we adding one shift thru strings as we go

 Next


text:
Q: Importando backup do PostgreSQL para MySQL Workbench Fiz um backup de um banco de dados no PostgreSQL e agora quero importa-lo para o MySQL Workbench no linux, como eu faço isso (tranformar .backup para .sql)?

A: Você pode usar o pg_dump que vem junto com o postresql, com o comando abaixo sem especificar o nome do banco de dados vai ser criado um arquivo .sql no diretório que você esta com o sql que esta no arquivo .bakcup
pg_restore -f database.sql database.backup


text:
Q: Use of vtkCylindricalTransform with paraview My code outputs a scalar and vector attributes in cylindrical coordinates and outputs them in an HDF5 file. There is a corresponding XDMF file that defines the Geometry like this:
<Geometry GeometryType="VXVYVZ">
    <DataItem Name="r" Dimensions="40" NumberType="Float" ...>
        my_file.hdf5:/coordinates/r
    </DataItem>
    <DataItem Name="theta" Dimensions="40" NumberType="Float" ...>
        my_file.hdf5:/coordinates/theta
    </DataItem>
    <DataItem Name="z" Dimensions="40" NumberType="Float" ...>
        my_file.hdf5:/coordinates/z
    </DataItem>
</Geometry>

Is it possible, inside Paraview, to use vtkCylindricalTransform, or any other means, to transform the StructuredMesh in cylindrical coordinates to an UnstructuredMesh in Cartesian coordinates?

A: The answer lies in using the Clean to Grid filter, which converts the structured grid to an unstructured one. Then, in the Calculator filter, it is possible to tick the Coordinate Results box and perform the transform there, i.e.:
coordsX*cos(coordsY)*iHat+coordsX*sin(coordsY)*jHat+coordsZ*kHat

which then allows to visualize the data in Cartesian coordinates.


text:
Q: How to generate a pdf invoice from mySQL table using FPDF for a specfic id I am facing a problem of getting the the data for a specific id. I want the user to get the link to download the data from a button. This is mysqldatatable name (add_courier):
id | order_inv | name | date | quantity of the items | price | payment mode.
Now, I am able to get the list of all the ids but I am not able to get the invoice for a specific id. Here is my code:
<?php
require('fpdf.php');
$con=mysqli_connect('localhost','root','');
mysqli_select_db($con,'lexipressdb');

class PDF extends FPDF {
    function Header(){
        $this->SetFont('Arial','B',15);

        //dummy cell to put logo
        //$this->Cell(12,0,'',0,0);
        //is equivalent to:
        $this->Cell(12);

        //put logo
        $this->Image('gift.jpg',10,10,10);

        $this->Cell(100,10,'Invoice',0,1);

        //dummy cell to give line spacing
        //$this->Cell(0,5,'',0,1);
        //is equivalent to:
        $this->Ln(5);

        $this->SetFont('Arial','B',11);

        $this->SetFillColor(180,180,255);
        $this->SetDrawColor(180,180,255);
        $this->Cell(40,5,'Order Invoice',1,0,'',true);
        $this->Cell(25,5,'Quantity',1,0,'',true);
        $this->Cell(65,5,'Weight',1,0,'',true);
        $this->Cell(60,5,'Cost',1,1,'',true);

    }
    function Footer(){
        //add table's bottom line
        $this->Cell(190,0,'','T',1,'',true);

        //Go to 1.5 cm from bottom
        $this->SetY(-15);

        $this->SetFont('Arial','',8);

        //width = 0 means the cell is extended up to the right margin
        $this->Cell(0,10,'Page '.$this->PageNo()." / {pages}",0,0,'C');
    }
}

//A4 width : 219mm
//default margin : 10mm each side
//writable horizontal : 219-(10*2)=189mm

$pdf = new PDF('P','mm','A4'); //use new class

//define new alias for total page numbers
$pdf->AliasNbPages('{pages}');

$pdf->SetAutoPageBreak(true,15);
$pdf->AddPage();

$pdf->SetFont('Arial','',9);
$pdf->SetDrawColor(180,180,255);

$query=mysqli_query($con,"select * from add_courier");
while($data=mysqli_fetch_array($query)){
    $pdf->Cell(40,5,$data['order_inv'],'LR',0);
    $pdf->Cell(25,5,$data['r_qnty'],'LR',0);
    $pdf->Cell(60,5,$data['r_weight'],'LR',0);
    $pdf->Cell(60,5,$data['r_costtotal'],'LR',1);

}

$pdf->Output();
?>

I want to have my format to be like this for each id so that the user can download it from the link:'
<?php
require('fpdf.php');

//A4 width : 219mm
//default margin : 10mm each side
//writable horizontal : 219-(10*2)=189mm

$pdf = new FPDF('P','mm','A4');

$pdf->AddPage();

//set font to arial, bold, 14pt
$pdf->SetFont('Arial','B',14);

//Cell(width , height , text , border , end line , [align] )

$pdf->Cell(130  ,5,'Lexipress.CO',0,0);
$pdf->Cell(59   ,5,'INVOICE',0,1);//end of line

//set font to arial, regular, 12pt
$pdf->SetFont('Arial','',12);

$pdf->Cell(130  ,5,'[Street Address]',0,0);
$pdf->Cell(59   ,5,'',0,1);//end of line

$pdf->Cell(130  ,5,'[City, Country, ZIP]',0,0);
$pdf->Cell(25   ,5,'Date',0,0);
$pdf->Cell(34   ,5,'[dd/mm/yyyy]',0,1);//end of line

$pdf->Cell(130  ,5,'Phone [+12345678]',0,0);
$pdf->Cell(25   ,5,'Invoice #',0,0);
$pdf->Cell(34   ,5,'[1234567]',0,1);//end of line

$pdf->Cell(130  ,5,'Fax [+12345678]',0,0);
$pdf->Cell(25   ,5,'Customer ID',0,0);
$pdf->Cell(34   ,5,'[1234567]',0,1);//end of line

//make a dummy empty cell as a vertical spacer
$pdf->Cell(189  ,10,'',0,1);//end of line

//billing address
$pdf->Cell(100  ,5,'Bill to',0,1);//end of line

//add dummy cell at beginning of each line for indentation
$pdf->Cell(10   ,5,'',0,0);
$pdf->Cell(90   ,5,'[Name]',0,1);

$pdf->Cell(10   ,5,'',0,0);
$pdf->Cell(90   ,5,'[Company Name]',0,1);

$pdf->Cell(10   ,5,'',0,0);
$pdf->Cell(90   ,5,'[Address]',0,1);

$pdf->Cell(10   ,5,'',0,0);
$pdf->Cell(90   ,5,'[Phone]',0,1);

//make a dummy empty cell as a vertical spacer
$pdf->Cell(189  ,10,'',0,1);//end of line

//invoice contents
$pdf->SetFont('Arial','B',12);

$pdf->Cell(130  ,5,'Description',1,0);
$pdf->Cell(25   ,5,'Taxable',1,0);
$pdf->Cell(34   ,5,'Amount',1,1);//end of line

$pdf->SetFont('Arial','',12);

//Numbers are right-aligned so we give 'R' after new line parameter

$pdf->Cell(130  ,5,'UltraCool Fridge',1,0);
$pdf->Cell(25   ,5,'-',1,0);
$pdf->Cell(34   ,5,'3,250',1,1,'R');//end of line

$pdf->Cell(130  ,5,'Supaclean Diswasher',1,0);
$pdf->Cell(25   ,5,'-',1,0);
$pdf->Cell(34   ,5,'1,200',1,1,'R');//end of line

$pdf->Cell(130  ,5,'Something Else',1,0);
$pdf->Cell(25   ,5,'-',1,0);
$pdf->Cell(34   ,5,'1,000',1,1,'R');//end of line

//summary
$pdf->Cell(130  ,5,'',0,0);
$pdf->Cell(25   ,5,'Subtotal',0,0);
$pdf->Cell(4    ,5,'$',1,0);
$pdf->Cell(30   ,5,'4,450',1,1,'R');//end of line

$pdf->Cell(130  ,5,'',0,0);
$pdf->Cell(25   ,5,'Taxable',0,0);
$pdf->Cell(4    ,5,'$',1,0);
$pdf->Cell(30   ,5,'0',1,1,'R');//end of line

$pdf->Cell(130  ,5,'',0,0);
$pdf->Cell(25   ,5,'Tax Rate',0,0);
$pdf->Cell(4    ,5,'$',1,0);
$pdf->Cell(30   ,5,'10%',1,1,'R');//end of line

$pdf->Cell(130  ,5,'',0,0);
$pdf->Cell(25   ,5,'Total Due',0,0);
$pdf->Cell(4    ,5,'$',1,0);
$pdf->Cell(30   ,5,'4,450',1,1,'R');//end of line

$pdf->Output();
?>

I don't know how to go about it. Can someone please help? I've also checked the other questions for the same issues but i'm not getting the resloution.'

A: $sql=mysqli_query($con,"select * from add_courier");
foreach loop starts here
<button > <a href="printme.php&id=<?php echo $row['id']?>">Print
</button>

for each loop ends here
in your FPDF page get the ID variable
//example//
require('fpdf.php');
$con=mysqli_connect('localhost','root','');
mysqli_select_db($con,'lexipressdb');
$id=$_GET['id'];

alter your query with this on FPDF page
$query=mysqli_query($con,"select * from add_courier where id='$id'");

A:

                              Tracking
                              Print Invoice

                 <?php
$ret=mysqli_query($con,"select *from add_courier");
$cnt=1;
while ($row=mysqli_fetch_array($ret)) {

?>

             <?php  echo $row['trackingid'];?>

              <a href="invoice/generate_pdf.php?id=<?php  echo $row['trackingid'];
              //this is your tracking primary key column name
              ?>">Generate

<?php
}
?>

          --------------------------------------------------------------------------------------------------------

generate_pdf.php code
 <?php
require('fpdf.php');
$con=mysqli_connect('localhost','root','');
mysqli_select_db($con,'lexipressdb');
$id=$_GET['id'];

// please first echo and check the id value
echo $id; exit;

// if you get the id on clicking generate link then comment the above line and enjoy
class PDF extends FPDF {
    function Header(){
        $this->SetFont('Arial','B',15);

        //dummy cell to put logo
        //$this->Cell(12,0,'',0,0);
        //is equivalent to:
        $this->Cell(12);

        //put logo
        $this->Image('gift.jpg',10,10,10);

        $this->Cell(100,10,'Invoice',0,1);

        //dummy cell to give line spacing
        //$this->Cell(0,5,'',0,1);
        //is equivalent to:
        $this->Ln(5);

        $this->SetFont('Arial','B',11);

        $this->SetFillColor(180,180,255);
        $this->SetDrawColor(180,180,255);
        $this->Cell(40,5,'Order Invoice',1,0,'',true);
        $this->Cell(25,5,'Quantity',1,0,'',true);
        $this->Cell(65,5,'Weight',1,0,'',true);
        $this->Cell(60,5,'Cost',1,1,'',true);

    }
    function Footer(){
        //add table's bottom line
        $this->Cell(190,0,'','T',1,'',true);

        //Go to 1.5 cm from bottom
        $this->SetY(-15);

        $this->SetFont('Arial','',8);

        //width = 0 means the cell is extended up to the right margin
        $this->Cell(0,10,'Page '.$this->PageNo()." / {pages}",0,0,'C');
    }
}

//A4 width : 219mm
//default margin : 10mm each side
//writable horizontal : 219-(10*2)=189mm

$pdf = new PDF('P','mm','A4'); //use new class

//define new alias for total page numbers
$pdf->AliasNbPages('{pages}');

$pdf->SetAutoPageBreak(true,15);
$pdf->AddPage();

$pdf->SetFont('Arial','',9);
$pdf->SetDrawColor(180,180,255);

$query=mysqli_query($con,"select * from add_courier where id='$id'");
while($data=mysqli_fetch_array($query)){
    $pdf->Cell(40,5,$data['order_inv'],'LR',0);
    $pdf->Cell(25,5,$data['r_qnty'],'LR',0);
    $pdf->Cell(60,5,$data['r_weight'],'LR',0);
    $pdf->Cell(60,5,$data['r_costtotal'],'LR',1);

}

$pdf->Output();
?>


text:
Q: how to show mapkit blue dot(user's location) at desired location? I am using MapKit. I want to know how to get current user's location. The MapKit shows a blue dot at current user location.
I want to do something like this: The user location is showed on the map. I have a button which, on clicking again, gets the current user location and shows the blue dot there.
Do I need to use locationManager or just call the mapView.showUserLocation=YES; on the button's click event?

A: When you want to show the current user location simply write

    [mapView setShowsUserLocation:YES];


text:
Q: Ontology where the same word has different meaning in different contexts? Are there any example ontologies where the same word has different meaning in different contexts?
For example, when building an ontology for a large company, it is not uncommon for different departments and systems to have a different definition and understanding of common words like "customer", "account", etc.
Is there a generally accepted way to model this in Protege that preserves the original words in their context, while also introducing a layer of disambiguating words for enterprise use?

A: This is a problem we encounter often in the biological community. I.e., the concept Eye is very dependent on the context, i.e. human eye vs fish vs spider eye etc. You can see a search for eye on the Ontology Lookup Service (OLS) and the results it return for eye from different ontologies. Disclosure: I am responsible for this tool.

*

*Provide an IRI for your concept. This IRI should be similar to a surrogate key for your concept. I.e., instead of giving your Account concept an IRI like http://MyBusiness/someBusinessContex/Account you give it an IRI like http://MyBusiness/someBusinessContex/Context0000001. For the Eye concept the IRI for a human eye is http://purl.obolibrary.org/obo/NCIT_C12401 and for an insect it is http://purl.obolibrary.org/obo/SIBO_0000086.

I explain in this StackOverflow question the reason for using "surrogate keys".

*Assign a context specific label and definition to your concept. You can use rdfs:label for label and rdfs:comment or skos:definition for definition.

*You may find that you need alternatives for you concept. I.e. may be you refer to customers also as members. In this case you can use skos:altlabel to provide alternative names for your concept and skos:preflabel to define a preferred label.
So how does this work? For user interfaces you make use of  rdfs:label/skos:preflabel and rdfs:comment/skos:definition for display purposes. From a data integration perspective you use the IRI.


text:
Q: Bootstrap 4: Display two lines followed by a Read More expandable link I am following this amazing guide to display two lines of text, and give the user a link to "Read More".
The transitions are not working as expected. Can someone point out what I am doing wrong here?

#module {
  font-size: 1rem;
  line-height: 1.5;
}

#module p.collapse[aria-expanded="false"] {
  display: block;
  height: 3rem !important;
  overflow: hidden;
}

#module p.collapse.show[aria-expanded="false"] {
  height: 3rem !important;
}

#module a.collapsed:after {
  content: '+ Show More';
}

#module a:not(.collapsed):after {
  content: '- Show Less';
}

Bacon Ipsum

    Bacon ipsum dolor amet doner picanha tri-tip biltong leberkas salami meatball tongue filet mignon landjaeger tail. Kielbasa salami tenderloin picanha spare ribs, beef ribs strip steak jerky cow. Pork chop chicken ham hock beef ribs turkey jerky. Shoulder
    beef capicola doner, tongue tail sausage short ribs andouille. Rump frankfurter landjaeger t-bone, kielbasa doner ham hock shankle venison. Cupim capicola kielbasa t-bone, ball tip chicken andouille venison pork chop doner bacon beef ribs kevin shankle.
    Short loin leberkas tenderloin ground round shank, brisket strip steak ham hock ham.

A: Your code might work in bootstrap 3. But since you're using bootstrap 4 try the below.
Replace this
#module p.collapse[aria-expanded="false"] {
  display: block;
  height: 3rem !important;
  overflow: hidden;
}

#module p.collapse.show[aria-expanded="false"] {
  height: 3rem !important;
}

with this
#module #collapseExample.collapse:not(.show) {
  display: block;
  height: 3rem;
  overflow: hidden;
}

#module #collapseExample.collapsing {
  height: 3rem;
}

Fiddle
Also just to remind you that ::after is a Pseudo-element so use it with double colon notation


text:
Q: Get partial results of map after exception How can you get the partial results from a map when an exception happens during execution?
i.e
(let [numbers [3 3 0 3]
  results (map #(/ 3 %) numbers)]
 results)

and return:
[3 3]

A: For example:
(let [numbers [3 3 0 3]
      results (map
               #(try (/ 3 %)
                     (catch Exception e e))
                   numbers)]
  (take-while #(not (instance? Exception %)) results))

A: since thrown exception unwinds the stack up to the place where exception is caught (in your case it goes up to the top level), you can't operate on result after if. What you can do, is to manually put some value where the error was caught:
(let [numbers [3 3 0 3]
      results (take-while number?
                          (map #(try
                                  (/ 3 %)
                                  (catch Throwable ex :error))
                               numbers))]
  results)

A: Here's an approach using the cats library's exception monad:
(ns your-project.core
  (:require [cats.monad.exception :as e]))

(let [numbers [3 3 0 3]
      results (->> numbers
                   (map #(e/try-on (/ 3 %))) ; wrap division result in a try
                   (take-while e/success?)   ; take values while successful
                   (mapv e/extract))]        ; unwrap the values from the trys
  results)

;; => [1 1]

And if you want to keep the values that come after the exception:
(let [numbers [3 3 0 3]
      results (->> numbers
                   (map #(e/try-on (/ 3 %)))
                   (filter e/success?)       ; filter all successful values
                   (mapv e/extract))]
  results)

;; => [1 1 1]

A: Use keep:
(let [numbers [3 3 0 3]]
  (keep #(try
          (/ 3 %)
          (catch RuntimeException _ nil)) numbers))


text:
Q: CRC32 of binary data in python without last 4 bytes I am trying to get the CRC32 of some binary data, except for the last 4 bytes.
My code so far:
with open('filename.ext','rb') as f:
    fileContent = f.read()
    file_size, = struct.unpack("i",f.read(:4))
    print hex(file_size)

I know that the :4 is wrong and I am still looking for how not to read the last 4 bytes and then get the crc32 for the other data.

A: You can use indexing like this:
fileContent[:-4]

to skip the last 4 bytes.


text:
Q: ruby on rails: can't understand code I'm newbie in ruby on rails, trying to rewrite rails project in PHP, can someone explain me please what next lines of code do?
  def payment_types_billing
    I18n.t("customer.payment_types_billing").inject({}){|memo,(k,v)|
      memo[k.to_s.to_i] = v; memo}.
        merge({
           PaymentType::ACCOUNTCREDIT => I18n.t("customer.payment_types_billing.#{PaymentType::ACCOUNTCREDIT}",
           :amount => number_to_currency(get_account_credit))
        })
  end

I don't understand part after .inject, if someone can just explain that part in human language, I will be very thankful. :)

A: These methods work in conjunction. By calling payment_types, the following will occur:
First it grabs a section of the localization yaml (likely in config/locales/en.yml). For more on internationalization/localization, see this!
I18n.t("customer.payment_types_billing")

Then it runs an inject block on the resulting enumerable (in this case a hash), with the intent of returning a newly-formed result (see about .inject here)
.inject({}){|memo,(k,v)| memo[k.to_s.to_i] = v; memo}

The result of this block appears to be a hash whose keys were the keys of the retrieved hash, converted to integers (without knowing the data being accessed, I can't know how this is meant to function).

Addendum:
I suspect the purpose of the above block is to assign integer keys to a new hash (something that is impossible otherwise). Seeing the later steps with the invert, this would mean that the final printed hash will have integer values, not strings.

It then adds two new key value pairs to the hash:
.merge({PaymentType::ACCOUNTCREDIT => I18n.t("customer.payment_types_billing.#{PaymentType::ACCOUNTCREDIT}", :amount => number_to_currency(get_account_credit))})

The first pair has a key equal to ACCOUNTCREDIT, with another value retrieved from the YAML. The second is the key :amount, with the value of "get_account_credit" (presumably a method with a decimal output) converted to currency for the current region.
As we reach the actual content of the payment_types method, the results from above (the newly-formed hash) is a block with a delete condition. If get_account_credit is returning a non-positive number, the ACCOUNTCREDIT keyed pair is deleted
.delete_if {|key, value|  (key == PaymentType::ACCOUNTCREDIT && get_account_credit <= 0) }

Finally, the hash is inverted (the keys become the values, and the values become the keys):
.invert


text:
Q: IIS - Application under default website redirects to root if I don't have a trailing slash I am using the 'Default Web Site' in IIS to add multiple applications underneath it, and I'm finding if I omit a trailing / (when I don't specify a page name) it redirects me to the root application. So for example, the 2 below links work:

*

*http://server/App1/Default.aspx

*http://server/App1/

But if I enter the below...

*

*http://server/App1

I get redirected to http://server/Default.aspx instead.
I've ensured the Default Document on my application is correct, but still no luck. Any ideas?


text:
Q: In MySQL 5, what's the convention for returning an error level and a resultset? In MySQL 5, a stored procedure can return any number of output parameters, like this:
CREATE PROCEDURE `test1`(IN in1 VARCHAR(64), IN in2, OUT out1  VARCHAR(64), OUT out2 INT, OUT out3 INT)

In MySQL 5, a stored procedure can also return/print a resultset, like this:
CREATE PROCEDURE `test2` ()
BEGIN
  SELECT * FROM `table`;
END$$

This is nice and flexible.  So in trying to communicate with the outside world, what's the convention for using this flexibility to give notice of the results (if any) and the errors (if any)?
Examples:

*

*Do we put error messages in our output parameters?  Do we put them in resultsets?

*Do we print out multiple successive resultsets?  Or do we limit ourselves to one resultset?

*Do we set the resultset to NULL if there are errors?

*Do we use output paramenter integers for the errors, with 0 being error free?

*Do we use output parameter VARCHARs for the errors, with '' (empty string) meaning error free?

A: I think it makes sense to use Signals for returning an error if it's supported by the server (5.5 and up).


text:
Q: Do you have to partition before running mkfs on a single partition disk? I see that some people don't use fdisk to create a partition on /dev/sdb... what is the difference between making and not making a partition for a single partition disk?
I just added a partition on a virtual disk, ran mkfs.ext4 and mounted it, but I just wondered what would have been different if I did not create the partition via fdisk first and just typed mkfs.ext4 /dev/sdb...

A: mke2fs would tell you that it is an entire device rather than a partition. It is still able to create the filesystem, but you need to confirm that you want to do this.
Is there any specific reason for not using LVM to manage your disks?  It really is easy and gives you a lot of benefit, especially if you need to expand later on.


text:
Q: Facebook API - Check if a user is suspended or has deactivated his profile Goal: Given a facebook alias or an id, to check which of the following is true:

*

*User is suspended by Facebook

*User has deactivated his profile

*User profile exists and is neither suspended not deactivated

It is especially important for me to identify whether case 1 (suspension) is true, since case 1 would be an indication that the user is potentially suspicious.
I observed that calling graph.facebook.com/username or graph.facebook.com/id on a known suspended account returns
{
   "error": {
      "message": "(#803) Some of the aliases you requested do not exist: kamran.haider.5494360",
      "type": "OAuthException",
      "code": 803
   }
}

while in the case of a known deactivated account, it returns
{
   "error": {
      "message": "Unsupported get request.",
      "type": "GraphMethodException",
      "code": 100
   }
}

Questions:

*

*Is it okay to assume that the above observation always holds? i.e. for any suspended account the call returns "OAuthException" with a code of 803 and for any deactivated account the call returns "GraphMethodException" with code 100 ?

*In what other cases does calling graph.facebook.com/username or graph.facebook.com/id return these 2 exceptions ?

*Is there a better way (assuming the above is a valid way) to accomplish the goal (especially of identifying if it is suspended)?

I have looked at both the docs and on the web, but found no mention about this.
Any help would be appreciated !!

A: *

*Is it okay to assume that the above observation always holds? i.e. for any suspended account the call returns "OAuthException" with a code of 803 and for any deactivated account the call returns "GraphMethodException" with code 100 ?
I think you can just check for "OAuthException"- and that would imply that you cannot access this user due to some possible reasons (in the next answer)

*In what other cases does calling graph.facebook.com/username or graph.facebook.com/id return these 2 exceptions ?

*

*User has blocked your app

*User has disabled all platform apps in their privacy settings, from here

*User has deactivated their account

*User has deleted their account

*Is there a better way (assuming the above is a valid way) to accomplish the goal?
I think OAuthException- is enough, since I dont think you want to club the deactivated/suspended and other users. You just want to check if you can access this particular user or not.


text:
Q: How can I view the config for a git branch? Is there a way I can check what branch a given local branch is tracking, and if it is setup to rebase automatically? These two are the main configuration options that I would like to check. I tried looking in my .git/config, but there's nothing in there about my local branch.

A: you can see the output of
git remote show origin


text:
Q: How to have a control to select a picture from local path instead of server on Infopath form Searched far and wide on Google for this..
Would really like to have a Picture column/control work like an Attachment column control, in that a user can select from local path instead of needing to upload to a separate library and then link.
Current:

Preferred:

I understand there are probably mechanical differences in how the files are handled by the server and where they are stored, but I would really like if the user could select from local path for the picture control.
Any thoughts? Thanks.

A: OOTB SharePoint does not provide this functionality but there are several third party tools available for this.
This link provides an Open Source solution to requirement in question.
It will basically create a custom column which will allow to upload picture from local drive.

A: There's nothing in InfoPath like that, your best choice is to use Attachment control, which will allow you to navigate into your local folder.


text:
Q: How to add fadeIn() method for each object in an array I have an Iframe whose source changes every 5 seconds:

$(window).load(function() {
  if (typeof $('.frame') != 'undefined' || null) {
    $(".frame").ready(function() {
      var locations = ['http://www.webstarts.com/support/2011/03/how-to-add-an-iframe-to-your-webstarts-website/', 'http://www.wix.com/app-market/html-iframe-embed/overview',
        'http://codepen.io/jmelgoza/pen/jEaGYg',
        'http://www.oddee.com/item_96986.aspx',
        'http://www.imdb.com/title/tt2488496/',
        'http://www.w3schools.com/tags/tag_iframe.asp'
      ];
      var len = locations.length;
      var iframe = $('.frame');
      var i = 0;
      setInterval(function() {
        iframe.attr('src', locations[++i % len]);
      }, 5000);
    });
  }
});

I would like to have it so that every time the source changes there is a fadeIn/fadeOut effect. How would I go about doing this? Currently the source is switching but it kind of pops in and out between the sources abruptly. I would like to have a more elegant transition between the sources when they switch. Any help would be great. Thanks.

A: Try this:
setInterval(function() {
    iframe.attr('src', locations[++i % len]);
    iframe.fadeOut(300, function() {
        iframe.fadeIn(300);
    });
}, 5000);

A: I ended up using something like this:

  setInterval(function () {
                iframe.attr('src', locations[++i % len]);
                iframe.fadeOut(300, function () {
                    iframe.fadeIn(300);
                });

and replaced the current interval function. I would have also 'up voted' whoever recommended this to me but I no longer see their post. Also if there are anymore recommendations as to how I should improve this code (even though it seems to be working) I am listening. I am sure it can be better.

A: I can update this answer as more issues with the code become relevant, but the first thing that stands out is this line:
if (typeof $('.frame') != 'undefined' || null) {

I think what you're looking for here is this for your defensive programming technique:
if ($('.frame') != null && $('.frame').length > 0) {


text:
Q: MacTeX installation, non-functioning TeXShop I used the MacTeX installation on a new MacBookPro and I find the folder /usr/texbin empty and the functionality not there, error message

"Can't find required tool."
"usr/texbin/pdflatex does not exist".

Can't find pdflatex anywhere else either.

A: I had a similar issue when I upgraded to Mavericks and then again to Yosemite. I found that the /usr/ folder had an alias for /texbin but that alias did not lead anywhere. This was resolved by allowing Read Only access to the local folder in usr for my user account. Perhaps the following would help:
Try going to /usr/ using Shift + ⌘ + G in Finder and allowing Read Only access to the local folder there. This can be done by using ⌘ + I to access folder Properties of local, and then adding your user account with Read Only access.