text:
Q: PyQt5 Button signal doesnt work in a Layout inside a Widget I am trying to implement a layout inside a Widget which is then added to the Main Window. If I declare the buttons and the layout inside the Main Window it works without a problem. However, if I create a class that inherits QWidget and add the layout and buttons, the signal is not working. I am adding the widget by using the setLayout method.I tried passing the parent as well to the buttons but it was the same result.
I am not sure what else could I be doing wrong, any orientation or hints on what is the problem are appreciated.
from PyQt5.QtWidgets import QApplication,QMainWindow,QWidget,\
                            QVBoxLayout,\
                            QLineEdit,\
                            QPushButton
from PyQt5 import QtCore
from PyQt5.uic import loadUi
import sys

class MyWidget(QWidget):
    def __init__(self,parent):
        super(MyWidget, self).__init__()
        self.start=QPushButton("Start",parent)
        self.pause=QPushButton("Pause",parent)
        self.end=QPushButton("End",parent)
        self.line=QLineEdit()

        self.start.pressed.connect(self.OnStart)
        self.pause.clicked.connect(self.OnPause)
        self.end.clicked.connect(self.OnEnd)

        self.layout=QVBoxLayout()
        self.layout.addWidget(self.start)
        self.layout.addWidget(self.pause)
        self.layout.addWidget(self.end)
        self.layout.addWidget(self.line)
        self.line.textChanged.connect(self.doSomething)

    def doSomething(self):
        print("do")

    def OnStart(self):
        print("start")
    def OnPause(self):
        print("pause")
    def OnEnd(self):
        print("end")

class TheWindow(QMainWindow):
    def __init__(self):
        super(TheWindow, self).__init__()
        self.setWindowFlags(QtCore.Qt.WindowCloseButtonHint | QtCore.Qt.WindowMinimizeButtonHint)
        loadUi('template.ui', self)
        the_widget=MyWidget(self)
        self.horizontalLayout.addLayout(the_widget.layout)

QApplication.setAttribute(QtCore.Qt.AA_Use96Dpi)
app = QApplication([])
app.aboutToQuit.connect(app.deleteLater)
widget = TheWindow()
widget.show()
sys.exit(app.exec_())

The UI template I made with Qt Designer is located here
https://github.com/vChavezB/PyQt5_Button_layout

A: The problem has to do with the ownership of the variables and the behavior of the signals when the sender or receiver is removed. the_widget is a variable that will be destroyed unless some object takes possession of that variable but none does so it will destroy instantly, and since that object is the receiver of the connection then the connection will also be eliminated. And why are the buttons and layout not destroyed? Well, because the layout is established in another layout, the second layout takes ownership, and since the buttons are managed by the layout, then they will be children of the widget to which the layout was added, and that relationship of kinship makes the parent widget take the ownership of the buttons.
Note: there is no point in creating a class that inherits from QWidget if it is only going to be used to create other widgets.
In this case it is better if the layout is established in the same class and then add the widget to the layout:
class MyWidget(QWidget):
    def __init__(self, parent=None):
        super(MyWidget, self).__init__(parent)
        self.start = QPushButton("Start")
        self.pause = QPushButton("Pause")
        self.end = QPushButton("End")
        self.line = QLineEdit()

        self.start.pressed.connect(self.OnStart)
        self.pause.clicked.connect(self.OnPause)
        self.end.clicked.connect(self.OnEnd)

        lay = QVBoxLayout(self)
        lay.addWidget(self.start)
        lay.addWidget(self.pause)
        lay.addWidget(self.end)
        lay.addWidget(self.line)
        self.line.textChanged.connect(self.doSomething)

    def doSomething(self):
        print("do")

    def OnStart(self):
        print("start")

    def OnPause(self):
        print("pause")

    def OnEnd(self):
        print("end")

class TheWindow(QMainWindow):
    def __init__(self):
        super(TheWindow, self).__init__()
        self.setWindowFlags(
            QtCore.Qt.WindowCloseButtonHint | QtCore.Qt.WindowMinimizeButtonHint
        )
        loadUi("template.ui", self)
        the_widget = MyWidget()
        self.horizontalLayout.addWidget(the_widget)


text:
Q: How to prevent strings from beeing multiple times in PROGMEM I am trying to safe some program space by trying to reduce the count strings in progmem. So i started to put all stings which are needed multiple times into a file with a namespace:
#include <avr/pgmspace.h>
#ifndef __PSTRINGS__
#define __PSTRINGS__
namespace p_strings
{
//golbal
const char right_arrow[] PROGMEM = ">";
const char procent[] PROGMEM = "%";
const char start[] PROGMEM = "Start";
const char speed[] PROGMEM = "Speed: ";
//... more here
}
#endif

I am using the strings by including them into the file where i need them and for example call Display::out_p(1, 0) << p_strings::right_arrow;. Which reads the byte out of the progmem and put them at the right position of the display.
But if i look into the .Iss i see that they are still included multiple times into the ASM.
000000a8 <_ZN9p_stringsL5startE>:
      a8:   53 74 61 72 74 00                                   Start.
...
000000de <_ZN9p_stringsL5startE>:
      de:   53 74 61 72 74 00                                   Start.

So i guess this isnt the right solution to safe storage.
My questions now are:

*

*Why does it still included (in the asm) multiple times? (Maybe some preaty simple failur of my thinking)

*How to i create "something" which prevents this? (Do i need somehow a class which i pass as reference?)

If more information is needed let me know.

A: In C++, a const variable has internal linkage by default (as if it was static)—which normally means that each translation unit (each .cpp file) gets its own copy. This may very well be why you're seeing them multiple times.
What you'd want to do is declare the variables as extern, and then define them in exactly one source file.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to send to custom error pages Zend Framework? I have members that can be blocked and when the member is blocked I want to send them to a custom error page, how would I do that in zend framework? I tried
throw new Zend_Controller_Dispatcher_Exception('Your message here');

but it doesn't say "your message here", it says "page not found" when I do this.
here is my error controller.
<?php

class ErrorController extends Zend_Controller_Action
{

public function errorAction()
{
    $errors = $this->_getParam('error_handler');

    switch ($errors->type) {
        case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE:
        case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
        case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:

            // 404 error -- controller or action not found
            $this->getResponse()->setHttpResponseCode(404);
            $this->view->message = 'Page not found';
            break;

            // 666 error -- controller or action not found
            $this->getResponse()->setHttpResponseCode(666);
            $this->view->message = 'Blocked';
            break;
        default:
            // application error
            $this->getResponse()->setHttpResponseCode(500);
            $this->view->message = 'Application error';
            break;
    }

    // Log exception, if logger available
    if ($log = $this->getLog()) {
        $log->crit($this->view->message, $errors->exception);
    }

    // conditionally display exceptions
    if ($this->getInvokeArg('displayExceptions') == true) {
        $this->view->exception = $errors->exception;
    }

    $this->view->request   = $errors->request;
}

public function getLog()
{
    $bootstrap = $this->getInvokeArg('bootstrap');
    if (!$bootstrap->hasPluginResource('Log')) {
        return false;
    }
    $log = $bootstrap->getResource('Log');
    return $log;
}

}

Here is the documentation, http://framework.zend.com/manual/en/zend.exception.using.html I don't understand it :(

A: Here are a few suggestions on making it work.
First you need to differentiate your error from the standard no_route/no_controller/no_action errors.  To do this, you can throw your own custom exception (you can extend this from PHP's Exception class.
throw new My_Exception_Blocked('You are blocked');

Then, modify the error controller to look like this:
public function errorAction()
{
    $errors = $this->_getParam('error_handler');

    switch ($errors->type) {
        case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE:
        case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
        case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:

            // 404 error -- controller or action not found
            $this->getResponse()->setHttpResponseCode(404);
            $this->view->message = 'Page not found';
            break;

        // check for any other exception
        case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_OTHER:
            if ($errors->exception instanceof My_Exception_Blocked) {
                $this->getResponse()->setHttpResponseCode(403);
                $this->view->message = $errors->exception->getMessage();
                break;
            }
            // fall through if not of type My_Exception_Blocked

        default:
            // application error
            $this->getResponse()->setHttpResponseCode(500);
            $this->view->message = 'Application error';
            break;
    }
}

I also changed the response code from 666 to 403 as there are no 6xx HTTP error codes and this could upset the server and/or client.
Hope that helps.

A: You should not use error controller plugin to manage programatic errors.  I would suggest just redirect user to a controller where they'll see required message. Error controller implementation in Zend Framework is unnecessarily complicated. You can solve the problem easily by redirecting.
Using error controller for programatic errors is also discouraged. Details from documentation is bellow.

Zend_Controller_Plugin_ErrorHandler provides a drop-in plugin for
  handling exceptions thrown by your application, including those
  resulting from missing controllers or actions; it is an alternative to
  the methods listed in the MVC Exceptions section.
The primary targets of the plugin are:

*

*Intercept exceptions raised when no route matched

*Intercept exceptions raised due to missing controllers or action
  methods

*Intercept exceptions raised within action controllers
In other words, the ErrorHandler plugin is designed to handle HTTP
  404-type errors (page missing) and 500-type errors (internal error).
  It is not intended to catch exceptions raised in other plugins.


text:
Q: How to move the button focus to a different section I am using Zerif wordpress theme. The theme is having 2 buttons namely Features and Get in Touch. Here is the link. The first button scrolls down to features tab whixh was already there in the theme. I want the second button to scroll down to Get In Touch section but unable to do so. Here is how its going to features in customize options. What to do if I want it to move to Get In Touch section.?

A: You just need to focus on id of that section to which you want to target , Please put following in option Green button link as per your shown image :
http://www.systroplex.com/#contact

#contact is id of Get In Touch Section.


text:
Q: Storing input from user in different variables Hi I'm trying to read an input from the user like "Bananas apples oranges" but I want to store each fruit in a different String variable. Is there a way to do this?
Thank you in advance.

A: I guess you should split the text.
Well, I think this may be a intuitive example that I found:
    String str = "Bananas apples oranges";
    String[] arrOfStr = str.split(" ", 2);

    for (String a : arrOfStr)
        System.out.println(a);

The second argument in Split method is the limit which is used for the result being produced and it can be either positive, negative or zero.


text:
Q: Ionic 1 : Delay in alpha indexed list with large data I am getting issue while redirecting to ion-list template with approx. 700 items. There comes a delay of around 4-5 seconds which is decreasing performance.Below is my code. Can someone please suggest me the solution?
<ion-modal-view class="bgImg">
<ion-view>
    <ion-header-bar class="bar-light">

              <button class="button button-clear" ng-click="refreshList()" style="margin-top:40px;"></button>

    </ion-header-bar>
    <ion-content scroll="true" >

            <ion-item class="item item-divider" id="index_{{letter}}">
                {{letter}}
            </ion-item>
            <ion-item ng-repeat="author in authors" ng-click="getSelectedUser(author.user_id,author.passcode,author.gesturecode,author.username)">
                {{author.last_name}} {{author.first_name}}
            </ion-item>

    </ion-content>

            {{letter}}

</ion-view>


text:
Q: Convert JSON string to "Object.class" I am currently trying to use Jackson to turn an object into a JSON string this was easily done by
public byte[] toJSON(Object obj) throws IOException {
        ObjectMapper map = new ObjectMapper();
        return map.writeValueAsString(obj).getBytes();
    }

Where i run into trouble is when i was to take the array of bytes and turn them into an Object.  Currently i have:
public Object toObject(byte[] bytes) throws IOException, ClassNotFoundException {
    ObjectMapper map = new ObjectMapper();
    return (Object)map.readValue(bytes, Object.class);
}

I successfully convert an object to a JSON string but the Object returned from the toObject method is always a LinkedHashMap instead of the object that was initially turned into the JSON string.
Sorry if i did a poor job communicating my problem but ill try to sum it up simply.  I want my code to be able to do the following:
MyClass someObject = new MyClass();
String json = toJSON(someObject);
Object tempObject = toObject(json);
MyClass sameObject = (MyClass) tempObject;

this code currently throws the following:
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.MyClass

Any help on the matter would be appreciated!

A: You are requesting an Object, so Jackson creates one Object it knows it can create: a Map. JSON array would become a List and so on.
If you want MyClass, you must request it explicitly, or, if you want a general-purpose serialization/deserialization, for inclusion of type identifier, as suggested by @csd.

A: First, I'm a little confused why you need to deal with byte[] at all.  objectMapper.writeVaueAsString(obj) gives you a perfectly good String with the JSON representation of your object.  If you need to convert to byte[] then you need to convert back to String before calling readValue.
But putting that aside for now, let's suppose you've got that String containing the JSON.  By default, Jackson isn't smart enough to know (from looking at the JSON alone) what Java class to instantiate when you call readValue.  In your example, you pass in Object.class, which isn't very helpful for Jackson since EVERY object in Java extends from Object.  So in that case, it chooses its built-in default, which is to build a Map (in particular, a LinkedHashMap) with keys and values as listed in the JSON.
As one commenter pointed out, you can give Jackson a hint and pass MyClass.class as the second parameter to readValue (instead of Object.class).  If you did that, then JSON will create an instance of MyClass at the beginning of readValue.  And when it sees something like "foo: 43" in the JSON, it'll try to find a field or setter (i.e. public int foo; or public void setFoo(int f)) in MyClass and set the value accordingly.
If you don't know ahead of time what type of object it is (i.e. what value to pass as the second parameter to readValue) then there are other options.  One of example of this is to require that your JSON objects have a class property that Jackson will use as a hint for which type of Java object to create.  Here's what that code might look like:
// This annotation tells Jackson to include the class name as
// a "class" property when *writing* JSON.
@JsonTypeInfo(include=As.PROPERTY, use=Id.CLASS, property="class")
public class MyClass {
    public int foo;
}

This will make your JSON look like this:
{ "class":"MyClass", foo:0 }

Then in your code to read the object, do this:
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enableDefaultTypingAsProperty(DefaultTyping.JAVA_LANG_OBJECT, "class");
// Note Object.class as second parameter.  Jackson will find the "class"
// property in the JSON and use it to determine which class to make.
MyClass foo = (MyClass) objectMapper.readValue(jsonString, Object.class);


text:
Q: Operator associativity using Scala Parsers So I've been trying to write a calculator with Scala's parser, and it's been fun, except that I found that operator associativity is backwards, and that when I try to make my grammar left-recursive, even though it's completely unambiguous, I get a stack overflow.
To clarify, if I have a rule like:
    def subtract: Parser[Int] = num ~ "-" ~ add { x => x._1._1 - x._2 }
then evaluating 7 - 4 - 3 comes out to be 6 instead of 0.
The way I have actually implemented this is that I am composing a binary tree where operators are non-leaf nodes, and leaf nodes are numbers.  The way I evaluate the tree is left child (operator) right child.  When constructing the tree for 7 - 4 - 5, what I would like for it to look like is:
-
-   5
7   4   NULL   NULL

where - is the root, its children are - and 5, and the second -'s children are 7 and 4.
However, the only tree I can construct easily is
-
7   -
NULL   NULL   4   5

which is different, and not what I want.
Basically, the easy parenthesization is 7 - (4 - 5) whereas I want (7 - 4) - 5.
How can I hack this?  I feel like I should be able to write a calculator with correct operator precedence regardless.  Should I tokenize everything first and then reverse my tokens?  Is it ok for me to just flip my tree by taking all left children of right children and making them the right child of the right child's parent and making the parent the left child of the ex-right child?  It seems good at a first approximation, but I haven't really thought about it too deeply.  I feel like there must just be some case that I'm missing.
My impression is that I can only make an LL parser with the scala parsers.  If you know another way, please tell me!

A: Scala's standard implementation of parser combinators (the Parsers trait) do not support left-recursive grammars. You can, however, use PackratParsers if you need left recursion. That said, if your grammar is a simple arithmetic expression parser, you most definitely do not need left recursion.
Edit
There are ways to use right recursion and still keep left associativity, and if you are keen on that, just look up arithmetic expressions and recursive descent parsers. And, of course, as, I said, you can use PackratParsers, which allow left recursion.
But the easiest way to handle associativity without using PackratParsers is to avoid using recursion. Just use one of the repetition operators to get a List, and then foldLeft or foldRight as required. Simple example:
trait Tree
case class Node(op: String, left: Tree, right: Tree) extends Tree
case class Leaf(value: Int) extends Tree

import scala.util.parsing.combinator.RegexParsers

object P extends RegexParsers {
  def expr = term ~ (("+" | "-") ~ term).* ^^ mkTree
  def term = "\\d+".r ^^ (_.toInt)
  def mkTree(input: Int ~ List[String ~ Int]): Tree = input match {
    case first ~ rest => ((Leaf(first): Tree) /: rest)(combine)
  }
  def combine(acc: Tree, next: String ~ Int) = next match {
    case op ~ y => Node(op, acc, Leaf(y))
  }
}

You can find other, more complete, examples on the scala-dist repository.

A: I'm interpreting your question as follows:
If you write rules like def expression = number ~ "-" ~ expression and then evalute on each node of the syntax tree, then you find that in 3 - 5 - 4, the 5 - 4 is computed first, giving 1 as a result, and then 3 - 1 is computed giving 2 as a result.
On the other hand, if you write rules like def expression = expression ~ "-" ~ number, the rules are left-recursive and overflow the stack.
There are three solutions to this problem:

*

*Post-process the abstract syntax tree to convert it from a right-associative tree to a left-associative tree. If you're using actions on the grammar rules to do the computation immediately, this won't work for you.

*Define the rule as def expression = repsep(number, "-") and then when evaluating the computation, loop over the parsed numbers (which will appear in a flat list) in whichever direction provides you the associativity you need. You can't use this if more than one kind of operator will appear, since the operator will be thrown away.

*Define the rule as def expression = number ~ ( "-" ~ number) *. You'll have an initial number, plus a set of operator-number pairs in a flat list, to process in any direction you want (though left-to-right is probably easier here).

*Use PackratParsers as Daniel Sobral suggested. This is probably your best and simplest choice.


text:
Q: Default Ubuntu Desktop with TightVnc and Windows Linux Subsystem I have successfully installed WLS (ubuntu 18) on windows 10 machine. I want to access its UI features using TightVnc. With default settings the .vnc/xstartup contains the following lines
xrdb $HOME/.Xresources
xsetroot -solid grey
#x-terminal-emulator -geometry 80x24+10+10 -ls -title "$VNCDESKTOP Desktop" &
#x-window-manager &
# Fix to make GNOME work
export XKL_XMODMAP_DISABLE=1
/etc/X11/Xsession

and I can connect to it using Tight vnc viewer from windows but the UI looks like

But, I want to use the default desktop that ships with Ubuntu 18. I installed gnome and changed xstartup file to the following (suggested by someone on the web)
#!/bin/sh

#Uncommment this line if using Gnome and your keyboard mappings are incorrect.
#export XKL_XMODMAP_DISABLE=1

# Load X resources (if any)
if [ -r "$HOME/.Xresources" ]
then
        xrdb "$HOME/.Xresources"
fi

gnome-session --disable-acceleration-check --session=ubuntu &

But when I start vncserver after making these changes, I am able to connect but it shows a grey screen with no visual controls like

Please note that I had no .Xresources file on my machine so I created an empty one manually but it made no difference. Below is the output of ls /usr/share/xsessions
ubuntu-communitheme-snap.desktop  ubuntu.desktop  xfce.desktop

I can see some errors in .vnc/CS-63341DT:5.log file. Below are the contents of this file
05/04/19 12:49:17 Xvnc version TightVNC-1.3.10
05/04/19 12:49:17 Copyright (C) 2000-2009 TightVNC Group
05/04/19 12:49:17 Copyright (C) 1999 AT&T Laboratories Cambridge
05/04/19 12:49:17 All Rights Reserved.
05/04/19 12:49:17 See http://www.tightvnc.com/ for information on TightVNC
05/04/19 12:49:17 Desktop name 'X' (CS-63341DT:5)
05/04/19 12:49:17 Protocol versions supported: 3.3, 3.7, 3.8, 3.7t, 3.8t
05/04/19 12:49:17 Listening for VNC connections on TCP port 5905
Font directory '/usr/share/fonts/X11/75dpi/' not found - ignoring
Font directory '/usr/share/fonts/X11/100dpi/' not found - ignoring
gnome-session-binary[1645]: WARNING: Using null backend for session tracking
_IceTransmkdir: Owner of /tmp/.ICE-unix should be set to root
GNOME_KEYRING_CONTROL=/home/adeel/.cache/keyring-FKBRZZ
GNOME_KEYRING_CONTROL=/home/adeel/.cache/keyring-FKBRZZ
GNOME_KEYRING_CONTROL=/home/adeel/.cache/keyring-FKBRZZ
SSH_AUTH_SOCK=/home/adeel/.cache/keyring-FKBRZZ/ssh
Window manager warning: Unsupported session type
gnome-session-binary[1645]: WARNING: App 'org.gnome.Shell.desktop' exited with code 1
Window manager warning: Unsupported session type
gnome-session-binary[1645]: WARNING: App 'org.gnome.Shell.desktop' exited with code 1
gnome-session-binary[1645]: WARNING: App 'org.gnome.Shell.desktop' respawning too quickly
gnome-session-binary[1645]: CRITICAL: We failed, but the fail whale is dead. Sorry....

What can I do to make default ubuntu 18 deskto work with TightVnc viewer from windows?

A: According to Microsoft WSL is designed only for developers who want to run Linux terminal utilities. This is indicated in this similar question.
It's been reported that you can obtain possibly successful results by
1) Installing an Xserver like Xming or VcXsrv.
2) Installing the graphical software you wish to run under WSL via apt-get or apt
3) Exporting your display environment variable with export DISPLAY=:0 every time you want to run a graphical application.
4) launch a graphical application by typing the name of its executable
Note:
This subsystem (WSL) is not capable of running all Linux software, such as 32-bit binaries, or those that require specific Linux kernel services not implemented in WSL.
It is possible to run some graphical (GUI) applications (such as Mozilla Firefox) by installing an X11 server within the Windows (host) environment (such as VcXsrv or Xming), as mentioned above although not without caveats, such as the lack of audio support or hardware acceleration (resulting in poor graphics performance). Support for OpenCL and CUDA is also not being implemented currently, although it may be implemented in future releases.
IMHO this exercise is more work than it's worth. The end result suffers from poor graphics performance and I/O bottlenecks. It's far prefereable to simply run Ubuntu on a VM or dual-boot than to deal with the possibility that the Linux system calls an application requires may not be fully supported by the Windows Subsystem for Linux.
Sources:
What's the easiest way to run GUI apps on Windows Subsystem for Linux as of 2018?
How do I install Ubuntu alongside a pre-installed Windows with UEFI?
https://www.howtogeek.com/261575/how-to-run-graphical-linux-desktop-applications-from-windows-10s-bash-shell/
https://en.wikipedia.org/wiki/Windows_Subsystem_for_Linux
https://blogs.msdn.microsoft.com/wsl/2016/06/08/wsl-system-calls/

A: I use VcXsrv because it's free and is frequently updated. See my answer here:

*

*What's the easiest way to run GUI apps on Windows Subsystem for Linux as of 2018?.

The important thing is to install it accepting the defaults and then (for me) to edit /etc/environment and change this:
PATH="/mnt/e/bin:/mnt/e/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:"

to this:
PATH="/mnt/e/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games"
export LIBGL_ALWAYS_INDIRECT=Yes
export DISPLAY=localhost:0.0

*

*Adding /mnt/e/bin: at beginning of path is only important for shared scripts stored on NTFS partition that both Ubuntu natively runs and WSL Bash runs.

*export LIBGGL... is important for GUI to paint properly

*export DISPLAY... is important for X-Server to run properly
Then I can use yad and zenity for all my GUI scripts.

A:
The following instructions were copied and pasted from an article I wrote but it lost the original formatting, links, and screenshots:
Source: How to Install Ubuntu Desktop with a Graphical User Interface in WSL2

Download VcXsrv:
Visit the official website
Click "Download"

Install VcXsrv:
Open "vcxsrv-64.1.20.8.1.installer.exe"
Click "Next"
Click "Install"
Click "Close"

Allow Access to VcXsrv:
Check "Private Networks"
Click "Allow Access"

Open PowerShell:
Press "⊞ Windows"
Enter "PowerShell" into the search bar
Right-click "Windows PowerShell"
Click "Run as Administrator"

Open WSL2:
Copy the command from below these instructions
Paste the command into PowerShell
Press "Enter"
wsl

Install Ubuntu Desktop:
Copy the command from below these instructions
Paste the command into PowerShell
Press "Enter"
sudo apt --yes install ubuntu-desktop

Set the Username Variable:
Copy the command from below these instructions
Paste the command into PowerShell
Press "Enter"
username=$(wslvar USERNAME)

Create the Ubuntu Directory:
Copy the command from below these instructions
Paste the command into PowerShell
Press "Enter"
mkdir --parents /mnt/c/users/$username/.ubuntu/

Open the Ubuntu Directory:
Copy the command from below these instructions
Paste the command into PowerShell
Press "Enter"
cd /mnt/c/users/$username/.ubuntu

Download Linux Software Repository for Microsoft Products:
Copy the command from below these instructions
Paste the command into PowerShell
Press "Enter"
Ubuntu 20.04:
wget https://packages.microsoft.com/config/ubuntu/20.04/packages-microsoft-prod.deb --output-document packages-microsoft-prod.deb
Ubuntu 18.04:
wget https://packages.microsoft.com/config/ubuntu/18.04/packages-microsoft-prod.deb --output-document packages-microsoft-prod.deb

Install Linux Software Repository for Microsoft Products:
Copy the command from below these instructions
Paste the command into PowerShell
Press "Enter"
sudo dpkg --install packages-microsoft-prod.deb

Update the Repositories:
Copy the command from below these instructions
Paste the command into PowerShell
Press "Enter"
sudo apt update

Install APT Transport for HTTPS:
Copy the command from below these instructions
Paste the command into PowerShell
Press "Enter"
sudo apt install --yes apt-transport-https

Update the Repositories:
Copy the command from below these instructions
Paste the command into PowerShell
Press "Enter"
sudo apt update

Install .Net:
Copy the command from below these instructions
Paste the command into PowerShell
Press "Enter"
sudo apt install --yes dotnet-sdk-5.0

Add Arkane Systems to the Source List Directory:
Copy the command from below these instructions
Paste the command into PowerShell
Press "Enter"
sudo sh -c 'echo "deb [trusted=yes] https://wsl-translinux.arkane-systems.net/apt/ /" > /etc/apt/sources.list.d/wsl-translinux.list'

Update the Repositories:
Copy the command from below these instructions
Paste the command into PowerShell
Press "Enter"
sudo apt update

Install Genie:
Copy the command from below these instructions
Paste the command into PowerShell
Press "Enter"
sudo apt install --yes systemd-genie

Create the Sudoers File:
Copy the command from below these instructions
Paste the command into PowerShell
Press "Enter"
echo "$USER ALL=(ALL) NOPASSWD:/usr/bin/genie" | sudo EDITOR="tee" visudo --file /etc/sudoers.d/$USER

Create the Desktop Script:
Copy the code from below these instructions
Paste the code into PowerShell
Press "Enter"

# CREATE BASH SCRIPT

# Store block of text with here document
create_bash_script=$(cat << end_of_string

# Define necessary environment variables
export DISPLAY="\$(cat /etc/resolv.conf | grep nameserver | awk '{ print \$2 }'):1.0"
export DESKTOP_SESSION="ubuntu"
export GDMSESSION="ubuntu"
export XDG_SESSION_DESKTOP="ubuntu"
export XDG_CURRENT_DESKTOP="ubuntu:GNOME"
export XDG_SESSION_TYPE="x11"
export XDG_BACKEND="x11"
export XDG_SESSION_CLASS="user"
export XDG_DATA_DIRS="/usr/local/share/:/usr/share/:/var/lib/snapd/desktop"
export XDG_CONFIG_DIRS="/etc/xdg"
export XDG_RUNTIME_DIR="\$HOME/xdg"
export XDG_CONFIG_HOME="\$HOME/.config"
export XDG_DATA_HOME="\$HOME/.local/share"
export XDG_CACHE_HOME="\$HOME/.cache"
export XDG_DESKTOP_DIR="\$HOME/Desktop"
export XDG_DOCUMENTS_DIR="\$HOME/Documents"
export XDG_DOWNLOAD_DIR="\$HOME/Downloads"
export XDG_MUSIC_DIR="\$HOME/Music"
export XDG_PICTURES_DIR="\$HOME/Pictures"
export XDG_PUBLICSHARE_DIR="\$HOME/Public"
export XDG_TEMPLATES_DIR="\$HOME/Templates"
export XDG_VIDEOS_DIR="\$HOME/Videos"

# Start desktop environment
gnome-session

end_of_string
)

# Store username environment variable in lowercase
username=$(wslvar USERNAME | awk '{ print tolower($0) }') &&

# Save block of text in bash file
echo "${create_bash_script}" > "/mnt/c/users/$username/.ubuntu/02_start_desktop.sh"

Download the Shortcut Images:
Copy the command from below these instructions
Paste the command into PowerShell
Press "Enter"
wget https://assets.ubuntu.com/v1/9fbc8a44-circle-of-friends-web.zip

Unzip the Shortcut Images:
Copy the command from below these instructions
Paste the command into PowerShell
Press "Enter"
unzip -o 9fbc8a44-circle-of-friends-web.zip

Create the Shortcut Icon:
Copy the command from below these instructions
Paste the command into PowerShell
Press "Enter"
convert -resize 64x64 ./circle-of-friends-web/png/cof_orange_hex.png ubuntu.ico

Exit WSL2:
Copy the command from below these instructions
Paste the command into PowerShell
Press "Enter"
exit

Create the VcXsrv Script:
Copy the code from below these instructions
Paste the code into PowerShell
Press "Enter"

# RELOAD VCXSRV SCRIPT

# Store username environment variable in lowercase
$username = $env:username.tolower()

# Store block of text with here-string
$reload_vcxsrv_script = @"

# Stop vcxsrv proccess that contains "1.0" in the program window title
get-process vcxsrv | where { `$_.mainwindowtitle -like "*1.0*" } | stop-process

# Start vcxsrv process in a large program window on display number one
start-process "c:\program files\vcxsrv\vcxsrv.exe" -argument ":1 -ac -nowgl -multimonitors -dpms"

"@

# Save block of text in powershell file
echo "${reload_vcxsrv_script}" > $env:userprofile/.ubuntu/reload_vcxsrv.ps1

Create the Ubuntu Script:
Copy the code from below these instructions
Paste the code into PowerShell
Press "Enter"

# CREATE VISUAL BASIC SCRIPT

# Store username environment variable in lowercase
$username = $env:username.tolower()

# Store block of text with here-string
$create_vbs_script = @"

' Run PowerShell script in background
set application = createobject("shell.application")
application.shellexecute "powershell", "-file c:\users\admin\.ubuntu\01_reload_vcxsrv.ps1", "", "", 0

' Allow PowerShell script to complete
wscript.sleep 3000

' Run Bash script in background
set shell= createobject("wscript.shell")
shell.run "wsl sudo genie -c bash /mnt/c/users/admin/.ubuntu/02_start_desktop.sh", 0

"@

# Save block of text in bash file
echo "${create_vbs_script}" > $env:userprofile/.ubuntu/03_start_ubuntu.vbs

Create the Shortcut Script:
Copy the code from below these instructions
Paste the code into PowerShell
Press "Enter"

# Store block of text with here-string
$create_shortcut_script = @"

# Define location variables
`$shortcut_location = "`$env:userprofile\.ubuntu\Ubuntu.lnk"
`$program_location = "`$env:userprofile\.ubuntu\03_start_ubuntu.vbs"

# Create shortcut
`$object = new-object -comobject wscript.shell
`$shortcut = `$object.createshortcut(`$shortcut_location)
`$shortcut.targetpath = `$program_location
`$shortcut.iconlocation = "`$env:userprofile\.ubuntu\ubuntu.ico"
`$shortcut.save()

"@

# Save block of text in powershell file
echo $create_shortcut_script > $env:userprofile/.ubuntu/04_create_shortcut.ps1

Open the Ubuntu Directory:
Copy the command from below these instructions
Paste the command into PowerShell
Press "Enter"
cd c:\users\admin\.ubuntu

Create the Shortcut:
Copy the command from below these instructions
Paste the command into PowerShell
Press "Enter"
powershell.exe -file .\04_create_shortcut.ps1

Open the Directory in Explorer:
Copy the command from below these instructions
Paste the command into PowerShell
Press "Enter"
explorer .

Launch the Ubuntu Desktop:
Double-click the "Ubuntu" shortcut

Open Terminal:
Click "Activities" in the top-left corner
Enter "Terminal" into the search bar
Click "Terminal"

Disable the Screen Lock:
Copy the command from below these instructions
Paste the command into Terminal
Press "Enter"
gsettings set org.gnome.desktop.screensaver lock-enabled false

Install the Snap Store:
Copy the command from below these instructions
Paste the command into Terminal
Press "Enter"
sudo snap install snap-store


text:
Q: MySQL - fixing consistency Problems in URL column I have a column called url in my database. When creating the tuples, I made a mistake that created an inconsistency.
Half of my data is saved as
../api/data/image.png, the other half is saved as ./data/image.png
| id     |     url          |
|    ... | ../api/data/image
|    ... | ../api/data/image
|    ... | ./data/image

I want every url in the column to look like /api/data/somefile_or_directory what would be the SQL Code for that?

A: You could try a simple replacement:
UPDATE yourTable
SET url = REPLACE(url, "/data/", "/api/data/")
WHERE url NOT LIKE '%/api/%';

Demo

A: test expressions in a SELECT statement before incorporating them into an UPDATE statement. e.g.
SELECT t.url
     , IF(t.url LIKE './data/%', CONCAT('../api/data/',SUBSTR(t.url,8)), t.url)  AS new_url
  FROM ( SELECT '../api/data/image' AS url
         UNION ALL SELECT './data/foo'
         UNION ALL SELECT './data'
         UNION ALL SELECT 'foo'
       ) t

results:
url                new_url
-----------------  -----------------
../api/data/image  ../api/data/image
./data/foo         ../api/data/foo
./data             ./data
foo                foo

when we have an expression tested, and it gives the results we need, we can use it in an UPDATE statement
UPDATE mytable t
   SET t.url = IF(t.url LIKE './data/%', CONCAT('../api/data/',SUBSTR(t.url,8)), t.url)


text:
Q: Classic asp and ajax I have problem with getting value from ajax to asp. I have form with select input field and if I select one option (from select options). I want to change my form action tag value.
$(document).ready(function() {
     $("#preLin").change(function(){
        if ($('#preLin option:selected').val() === "Test" ) {
              var actionTag = "printHosp.his";
             $.ajax({
                 type: "POST",
                 url: "http://local:8001/Default.his",
                 data: {actionTag: "test.asp"},
                 success: function(data) {
                 alert(actionTag);}
             });
});

ASP
dim actionTag
actionTag = Request.form("actionTag")

<form action="<%=actionTag%>" name="input" method="post" target="_blank">

            <select name="preLin" id="preLin">
                <optgroup >
                        <option value="Test"></option>
                        <option value=""></option>
                 </optgroup>

    </form>

A: There's best practices to do what you want, but i suggest you to solve this problem by adding a "ajax error function", then analyzing the responseText.
Change your ajax call for something like:
      $.ajax({
          type: "POST",
          url: "http://eli.local:8001/priemimas/Default.his",
          data: {actionTag: "test.asp"},
          success: function(data) {alert(actionTag);},
          error: function(xhr) {alert(xhr.responseText);}
      });


text:
Q: "redefinition different basic types" problem with my flush function at the top of my program i wrote this line of code
#define FLUSH myFlush()

then, i later wrote out the myFlush function as follows.
void myFlush() {
    while (getchar() != '\n');
}

This way whenever i need to flush, i just type FLUSH; and it does it. like so
scanf("%i", voters[i].favoriteNumber); FLUSH;

The problem is, i'm getting an error at the line of myFlush function. The error is "redefinition different basic types." C2371. What am i doing wrong?


text:
Q: in ipad simulator how to set screen size to 1x 2x format For my App I have set the target device family=iPhone/iPad
and in project-> Set Active executable to iPad simulator and it was opening my App in iPad simulator in 1x/2x format so i could change the size by using option 1x 2x.
now i have upgrated my IOS SDK to 4.2 from 4.1
the probleam is: now my App opens in the iPad simulator with full screen size(instead of 1x 2x format) and all controls'  position on the screen has been changed  and it spoiled whole look of app.
now I want to open my app in iPad simulator again in the same 1x 2x scrren sizes format.
so now How I can do that?
please help and suggest
thanks

A: The 1x/2x option is only a compatibility option for iPhone-only apps.  If you set the targeted device family to iPhone/iPad, then it is a universal app and will always display at full resolution on the iPad.


text:
Q: How can I update the style of block element and pass an argument to PHP funciton I'm sure I am over complicating things but I am trying to accomplish 2 things with the referenced HTML.  When user selects an option, I want to toggle the display style of the leaderTable from hidden to visible if it meets the criteria (this I have done successfully with the JS that follows)
I also want to pass the value of the selected option as an argument to a PHP function that will set a $_SESSION variable which I can use.
From my understanding I would have to use an AJAX request to  communicate the value to the php script but I don't fully understand AJAX POST vs GET.
HTML
<select id="rate_type" name="rate_type">
<option value="">Select One</option>
<option value="1">Non-Supervisors</option>
<option value="2">Supervisors</option>
<option value="3">Manager</option>
<option value="4">Director</option>
<option value="5">Sales</option>
<option value="6">Executive</option>
</select>

JS
<script>
window.onload = function() {
      var eSelect = document.getElementById('rate_type');
        var leaderTable = document.getElementById('leadership');

        eSelect.onchange = function() {
            if((eSelect.selectedIndex == 2) || (eSelect.selectedIndex == 3) || (eSelect.selectedIndex == 4) || (eSelect.selectedIndex == 5) || (eSelect.selectedIndex == 6)){

                leaderTable.style.display= 'block';

                } else {

                leaderTable.style.display = 'none';

            }

        }
    }

</script>

A: First of all, almost nobody writes "raw" JS anymore. Use a JS library that makes life easy. I recommend jQuery. It will take you a few minutes to understand it, but it can implement AJAX in 1 line.
Regarding the difference between AJAX POST and GET, it doesn't matter for you. You can do either one. In your PHP script look for the parameter using $_REQUEST[..] and you will cover both cases.
Last, here are some ideas:

*

*If you need to communicate the value immediately to the server, you will have to use AJAX

*If you don't mind refreshing the page when you communicate the value to the server, you can skip AJAX and do it by changing window.location in JS and including the parameter in the URL. AJAX is simple to use and avoids the refresh, so it's better..

*If you don't need to communicate the value to the server immediately, you can save it in JS as a cookie (using document.cookie), and it will arrive to the server with the next request the user makes. Then just look for it in PHP using $_COOKIE[..]

A: The code below will add the jquery src from google, and make an ajax request to the server on change.  See jQuery POST for more info.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
        $('#rate_type').change(function() {
            if(($(this).val() == 2) || ($(this).val() == 3) || ($(this).val() == 4) || ($(this).val() == 5) || ($(this).val() == 6)){
                $('#leadership').show();
            } else {
                $('#leadership').hide();
            }

            // this is the shorthand post
            $.post(
                // the url
                '<?php echo $_SERVER['PHP_SELF'] ?>',
                // the request parameters to send
                {
                    rate_type: $('#rate_type').val(),
                    some_other_var: 'junk'
                },
                function(data) {
                    // do something here
                    console.log(data);
            });
        });
        // fire the change event on load if needed
        $('#rate_type').change();
});
</script>


text:
Q: Faster methods for set intersection I am facing a problem where for a number of words, I make a call to a HashMultimap (Guava) to retrieve a set of integers. The resulting sets have, say, 10, 200 and 600 items respectively. I need to compute the intersection of these three (or four, or five...) sets, and I need to repeat this whole process many times (I have many sets of words). However, what I am experiencing is that on average these set intersections take so long to compute (from 0 to 300 ms) that my program takes a very long time to complete if I look at hundreds of thousands of sets of words.
Is there any substantially quicker method to achieve this, especially given I'm dealing with (sortable) integers?
Thanks a lot!

A: If you are able to represent your sets as arrays of bits (bitmaps), you can intersect them with AND operations. You could even implement this to run in parallel.
As an example (using jlordo's question): if set1 is {1,2,4} and set2 is {1,2,5}
Then your first set would be represented as: 00010110 (bits set for 1, 2, and 4).
Your second set would be represented as: 00100110 (bits set for 1, 2, and 5).
If you AND them together, you get: 00000110 (bits set for 1 and 2)
Of course, if you had a larger range of integers, then you will need more bytes. The beauty of bitmap indexes is that they take just one bit per possible element, thus occupying a relatively small space.
In Java, for example, you could use the BitSet data structure (not sure if it can do operations in parallel, though).

A: One problem with a bitmap based solution is that even if the sets themselves are very small, but contain very large numbers (or even unbounded) checking bitmaps would be very wasteful.
A different approach would be, for example, sorting the two sets, merging them and checking for duplicates. This can be done in O(nlogn) time complexity and extra O(n) space complexity, given set sizes are O(n).
You should choose the solution that matches your problem description (input range, expected set sizes, etc.).

A: The post http://www.censhare.com/en/aktuelles/censhare-labs/yet-another-compressed-bitset describes an implementation of an ordered primitive long set with set operations (union, minus and intersection). To my experience it's quite efficient for dense or sparse value populations.


text:
Q: SQL return distinct values and their combined count in one query Using MySQL and am supposed to return the number of absentees and their names. I do a query for all students and subtract the subquery of ones who showed up that day.
Is this even possible to do in 1 query? I know how to do it with 2 separate ones and they return statements of different sizes so I'm not sure these are compatible.
For list of names:
select distinct name
from submissions join hacker
on submissions.hacker_id=hacker.hacker_id
where name not in
(
  select distinct name
from submissions join hacker
on submissions.hacker_id=hacker.hacker_id
where sub_date = '2019-12-07'
  )

For count:
select count(name)
from submissions join hacker
on submissions.hacker_id=hacker.hacker_id
where name not in
(
  select distinct name
from submissions join hacker
on submissions.hacker_id=hacker.hacker_id
where sub_date = '2019-12-07'
  )

A: You can use a CTE to perform the query once, then use UNION to combine the count and names into a single result.
WITH absentees as (select distinct name
    from submissions join hacker
    on submissions.hacker_id=hacker.hacker_id
    where name not in
    (
      select distinct name
    from submissions join hacker
    on submissions.hacker_id=hacker.hacker_id
    where sub_date = '2019-12-07'
    )
)
SELECT * FROM absentees
UNION ALL
SELECT COUNT(*) FROM absentees

This will put the total as the last line in the result.


text:
Q: Oracle - How to use pivot key word in a stored procedure I m getting this error while I m trying to create a stored procedure in Oracle,
"ERROR line 96, col 9, ending_line 96, ending_col 13, Found 'PIVOT', Expecting: )  ..."
When I run my query out of the stored procedure template it is ok, my procedure does not take any parameters.
create table my_table (LOAN_NUMBER varchar2(20), DOCUMENT_TYPE varchar2(20),
                       DOCUMENT_ID varchar(20));
insert into my_table(LOAN_NUMBER,DOCUMENT_TYPE,DOCUMENT_ID) values
('992452533663','Voters ID','XPD0355636');
insert into my_table(LOAN_NUMBER,DOCUMENT_TYPE,DOCUMENT_ID) values
('992452533663','Pan card','CHXPS5522D');
insert into my_table(LOAN_NUMBER,DOCUMENT_TYPE,DOCUMENT_ID) values
('992452533663','Drivers licence','DL-0420110141769');

insert into my_table(LOAN_NUMBER,DOCUMENT_TYPE,DOCUMENT_ID) values
('692452533663','Voters ID','yPD0355636');
insert into my_table(LOAN_NUMBER,DOCUMENT_TYPE,DOCUMENT_ID) values
('692452533663','Pan card','dHXPS5522D');
insert into my_table(LOAN_NUMBER,DOCUMENT_TYPE,DOCUMENT_ID) values
('692452533663','Drivers licence','DLx-0420110141769');

CREATE OR REPLACE PROCEDURE my_procedure(pData OUT SYS_REFCURSOR)
   IS
   BEGIN
      OPEN pData FOR
    select * from (
       select LOAN_NUMBER, DOCUMENT_TYPE, DOCUMENT_ID
       from my_table t
    )
    pivot
    (
       MIN(DOCUMENT_ID)
       for DOCUMENT_TYPE in ('Voters ID','Pan card','Drivers licence')
    );
    end;

Can anyone please explain how to use pivot key word directly in a stored procedure?
If it is not possible, what is the logic behind that situation ?


text:
Q: How to send a classic report as mail body in oracle Apex 19.2 I have a dynamic report built using PL/SQL function returning SQL, I allow the user to enter some variables and I construct the SQL statement dynamically. I also format the background color according to a column value using JavaScript dynamic action on page load. What I need to do is to add a button to send the generated report via email (in the email body not as attachment) to a specific address. I would hugely appreciate assistance on how to do this.

A: If not already done, you'll want to move the logic that generates the SQL query to a stored function so it can be called from more than one place. Then you'll want to create a new PL/SQL function that returns the data as an HTML table.
This isn't as trivial as it seems at first. You'd need to send the CSS along with the HTML - and some mail clients require inline CSS. There are some tools to help you line the CSS, such as this one: https://templates.mailchimp.com/resources/inline-css/
Once that's in place, you can use it to get the HTML for the table and add it to an email body.
Regarding the dynamic SQL, this can often lead to SQL injection vulnerabilities if you're not careful. If you share that code with us (after changing the names of tables and other identifiers), we can help ensure it's safe.


text:
Q: undefined response , facebook javascript SDK I am trying to import some Photos from a Facebook page that I own.
I am following this answer on Stack Overflow, more specifically the Client-Side part.
In the answer 3 steps are suggested.

*

*Add the javascript SDK , which i do.

*Something about Authentication but the link is wrong...

*A piece of code for rendering the photos.

I skipped the 2nd step , cause I am not sure what to do there and I implemented the code in 3rd step :
FB.api('593959083958735/photos', function(response) {
                if(!response || response.error) {
                    // render error
                    alert("Noo!!");
                } else {
                    // render photos
                    alert("Yeah! " + response.status);
}

From here I get the alert "Yeah! undefined". The response is always undefined. I think maybe because I should have done something in the authentication part.
All I am trying to do here , is to import some photos from a public Facebook page. Is this the correct way to do that? If yes why would I need any authentication for it. And what exactly should I do in the authentication part?

A:
From here I get the alert "Yeah! undefined". The response is always undefined. I think maybe because I should have done something in the authentication part.

You are querying the photos from a page, so there is no status field in the response.

All I am trying to do here , is to import some photos from a public Facebook page. Is this the correct way to do that? If yes why would I need any authentication for it.

You don't need authentication for that – as you can see here in the Graph API Explorer, you get results even without an access token (after clearing the field). And you can see the structure of the response there as well.


text:
Q: PacMan Grid 2D Array JAVA I'm supposed to make a simple type text PacMan game in Java and for the board I have to use a 2D array to make the grid. Here are the exact directions: At program startup, constructs and displays a 2-dimensional grid using standard array(s) (no collection classes allowed) with the size dynamically specified by the user (X and Y sizes can be different). Places the PacMan in the upper-left corner of the grid facing left All grid cells should have the empty cell character of '.'
This is my code so far, but I keep getting errors and I'm not sure how to fix it:
public class myPacMan {
public static void main(String[] args){
    Scanner input = new Scanner (System.in);
    System.out.print("Choose an x value:");
    int x = input.nextInt();
    System.out.print("Choose a y value:");
    int y = input.nextInt();
    int grid [][] = new int [x][y];
    int i, j = 0;
    for(i=0; i<x; i++);
    for(j=0; j<y; j++);
    System.out.print(grid[x][y] + ".");
}

}

A: Two things.   First, remove the semicolons after your for loops.  Second, your print statement should use i and j, instead of x and y.  X and Y will always be one more than your array, so you'll get an index out of bounds exception.


text:
Q: Can I have a window showing small live preview of another workspace? Is it possible to mirror a live section of one workspace so that it is visible in the current workspace as a window that can be moved around?
The other day I had a Windows 10 VM running on my Ubuntu 16.04 host that took a really long time to complete updating.  I kept checking on its progress via Expo (Super+S) on Ubuntu.  That got me thinking that this problem has most likely been solved already since tools such as simplescreenrecorder can be configured to record just a portion of the screen.  However, I don't know the proper terminology to use for my Google search.
I'd like to see the 300x150 screenshot below in the form of a floating window (with live updates) in the top right corner of whichever workspace happens to be current.

A: EDIT
(New answer)
DONE.
The answer below is now available in a polished form, as an indicator, as a ppa for Trusty, Xenial, Yakkety and Zesty :
sudo apt-add-repository ppa:vlijm/windowspy
sudo apt-get update
sudo apt-get install windowspy

Th indicator (including preview window) is now nicely low on juice. Options include a settings window, setting window border size/color, window size.

In the meantime, I found it useful to keep an eye on the AU window; see if there are any messages :)

OLD ANSWER
(first second rough concept)
Have a minimized representation of a window on another workspace
To my own (big) surprise, it can be effectively done, be it with
trickery and deceit; have an updated representation of a window on another workspace. Not fit to watch a movie, definitely good enough to keep an eye on a window elsewhere (example: my tv-card window):
How it works in practice

*

*With the window in front, press a shortcut key:

(the window will minimize)

*Move to another workspace, press the shortcut key again, a small representation of the window will appear, updated every 4 seconds:

The window always shows on top of other windows. As it is, the window is 300px (width), but can be set to any size.

*To end it, press (again) the shortcut key. The small window will close, you will move to the viewport of the original window, which will appear again, unminimized.
The scripts

*

*The control script
#!/usr/bin/env python3
import subprocess
import os
import sys
import time

# paths
imagepath = os.path.join(os.environ["HOME"], ".showcase")
wfile = os.path.join(imagepath, "currentwindow")
vpfile = os.path.join(imagepath, "last_vp")
# setup path
if not os.path.exists(imagepath):
    os.mkdir(imagepath)

def get(command):
    try:
        return subprocess.check_output(command).decode("utf-8").strip()
    except subprocess.CalledProcessError:
        pass

def get_vp():
    open(vpfile, "wt").write(get(["wmctrl", "-d"]).split()[5])

def run(command):
    subprocess.Popen(command)

def convert_tohex(widxd):
    return widxd[:2]+((10-len(widxd))*"0")+widxd[2:]

def check_windowtype(wid):
    check = get(["xprop", "-id", wid])
    return not any([s in check for s in [
        "_NET_WM_WINDOW_TYPE_DOCK",
        "_NET_WM_WINDOW_TYPE_DESKTOP"]])

def edit_winprops(wid, convert=True):
    run(["xdotool", "windowminimize", wid])
    if convert:
        widxd = convert_tohex(hex(int(wid)))
    else:
        widxd = wid
    run(["wmctrl", "-i", "-r", widxd, "-b", "add,sticky"])
    get_vp()
    open(os.path.join(imagepath, "currentwindow"), "wt").write(widxd)

def initiate_min():
    # if not, minmize window, write the file
    wid = get(["xdotool", "getactivewindow"])
    if check_windowtype(wid):
        edit_winprops(wid)
    else:
        pidinfo = [l.split() for l in wlist.splitlines()]
        match = [l for l in pidinfo if all([
            get(["ps", "-p", l[2], "-o", "comm="]) == "VirtualBox",
            not "Manager" in l])]
        if match:
            edit_winprops(match[0][0], convert=False)

# windowlist
wlist = get(["wmctrl", "-lp"])

if "Window preview" in wlist:
    # kill the miniwindow
    pid = get(["pgrep", "-f", "showmin"])
    run(["kill", pid])
    window = open(wfile).read().strip()
    viewport = open(vpfile).read().strip()
    run(["wmctrl", "-o", viewport])
    time.sleep(0.3)
    run(["wmctrl", "-i", "-r", window, "-b", "remove,sticky"])
    run(["wmctrl", "-ia", window])
    os.remove(wfile)

else:
    # check if windowfile exists
    wfileexists = os.path.exists(wfile)
    if wfileexists:
        # if file exists, try to run miniwindow
        window = open(wfile).read().strip()
        if window in wlist:
            # if the window exists, run!
            run(["showmin", window])
        else:
            # if not, minmize window, write the file
            initiate_min()
    else:
        # if not, minmize window, write the file
        initiate_min()

*The window representatiom
#!/usr/bin/env python3
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GObject
from PIL import Image
import os
import subprocess
import time
from threading import Thread
import sys

wid = sys.argv[1]
xsize = 300

imagepath = os.path.join(os.environ["HOME"], ".showcase")
if not os.path.exists(imagepath):
    os.mkdir(imagepath)
img_in = os.path.join(imagepath, "image.png")
resized = os.path.join(imagepath, "resized.png")

def get_img():
    subprocess.Popen([
        "import", "-window", wid, "-resize", str(xsize),  resized
        ])

get_img()

class Splash(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self, title="Window preview")
        maingrid = Gtk.Grid()
        self.add(maingrid)
        self.image = Gtk.Image()
        # set the path to the image below
        self.resized = resized
        self.image.set_from_file(self.resized)
        maingrid.attach(self.image, 0, 0, 1, 1)
        maingrid.set_border_width(3)
        self.update = Thread(target=self.update_preview)
        self.update.setDaemon(True)
        self.update.start()

    def update_preview(self):
        while True:
            get_img()
            time.sleep(3)
            GObject.idle_add(
                self.image.set_from_file, self.resized,
                priority=GObject.PRIORITY_DEFAULT
                )

def miniwindow():
    window = Splash()
    window.set_decorated(False)
    window.set_resizable(False)
    window.set_keep_above(True)
    window.set_wmclass("ShowCase", "showcase")
    window.connect("destroy", Gtk.main_quit)
    GObject.threads_init()
    window.show_all()
    window.move(70, 50)
    Gtk.main()

miniwindow()

How to use

*

*Install python3-pil, xdotool and wmctrl
sudo apt-get install xdotool wmctrl python3-pil

*Create, if it doesn't exist yet, the directory ~/bin.

*Copy script 1, he control script, as (exactly) showcase_control (no extension) in ~/bin, and make it executable.

*Copy script 2, the mini- window script, as (exactly) showmin (no extension) in ~/bin, and make it executable.

*Log out and back in, and add the following command to a shortcut of your choice:
showcase_control

Choose: System Settings > "Keyboard" > "Shortcuts" > "Custom Shortcuts". Click the "+" and add the command:
showcase_control

and it should work!

*

*Press the key once to grab the current window

*move to the other workspace where you'd like the mini-window

*Press again to show the miniwindow

*Press again to move back to the original workspace, (automatically)  un-minimize the original window and close the mini -one.

Downsides?

*

*The setup, as it is currently,  adds some work for your processor. On my (very) old system however, it adds (on average) appr. 4-5% I reckon, which I did not notice in any way.
Update: It turns out import can resize the image in one step, together with fetching the window image. This means a substantial reduction in processor load. At the same time the refresh time is shorter (3 seconds now), still at lower "costs".
Explanation

*

*My starting point was the way OP mentioned he wanted to use the option to keep an eye on a window on another workspace, waiting for either something to finish.

*While literally having an exact (mini) copy of a window on another workspace seems impossible, we can make an image of an existing window with the import -command, once we have the window id. While this both works on minimized windows or windows without focus, there is however one issue: the window needs to be on the current workspace.

*The trick is then to temporarily (while the mini- window is used) make the window "sticky" (be virtually available on all workspaces) with wmctrl, but minimized at the same time.

*Since all is done automatically, the difference effectively is none, since also returning to the initial viewport, "un-" sticky the original window and un- minimizing it, is done automatically.

In short:

*

*Pressing the shortcut once: targeted window is made sticky, but minimized

*Pressing it again (presumably on another workspace): a small mini- version of the window appears in the upper left corner, updated once per four seconds.

*Pressing it again: mini- window is closed, the desktop moves to the initial workspace of the window, the window is restored un- sticky and un- minimized.

Specifically for VirtualBox
When the VBox window is in front, it turns out Ubuntu shortcut keys are disabled(!), so the control script needs to be launched in another way. Below a few brief ones.
Option 1
I edited the control script. Now only in the case of VirtualBox:

*

*Click anywhere on the desktop, Then press your shortcut key. After that, simply use the shortcut key to show the window and exit.
Explanation: The control script was made to exit if the window was of type "desktop", since you wouldn't want to minimize the desktop. Now the script first looks for possibly existing VirtualBox windows, to target, if the currently active window is the desktop.
Option 2

*

*Copy the icon below (right- click -> save as), save it as minwinicon.png

*Copy the lines below into an empty file, save it as minwin.desktop in ~/.local/share/applications:
[Desktop Entry]
Type=Application
Name=Window Spy
Exec=showcase_control
Icon=/path/to/minwinicon.png
StartupNotify=false

You'd need to log out and back in for the launcher to "find" the local ~/bin path!
Drag the icon on to the launcher to use it.
The second solution has an important downside: after using it from the launcher, it will keep blinking for a few seconds, waiting for a window to appear. During that, clicking again won't have any effect. That can be solved, as described here, but including that in this answer would really make it too long. If you want to use option two, please look into the link.

A: Something that seems like overkill but totally works for this purpose is Open Broadcaster. In the "Sources" list box, click the plus, select "Window Capture", then follow the prompts to select the window you're interested in. No point in hitting record; just use the preview. It's available for pretty much any OS, with instructions for Ubuntu here, which I've copied below.
sudo apt-get install ffmpeg
sudo add-apt-repository ppa:obsproject/obs-studio
sudo apt-get update
sudo apt-get install obs-studio

If you feel like it, you can then go into the "View" menu and hide all the UI elements.


text:
Q: JBoss authentication issue I am newbie to JBoss and I have the application running in JBoss 6.2.
We usually have the login set up using JSF. It's showing a screen with username and password (created by JSF) and that's an internal part of the application and that works fine.
But I came to know there is basic authentication setup available in JBoss. We can configure it in a way that it requires to pass through authentication.
I searched on the internet and I found a way to introduce it like below:
D:\workspace_Csmart\jboss-eap-6.2\bin>add-user
What type of user do you wish to add?
 a) Management User (mgmt-users.properties)
 b) Application User (application-users.properties)
(a): b
Enter the details of the new user to add.
Using realm 'ApplicationRealm' as discovered from the existing property files.

Username : prabhu
User 'prabhu' already exits, would you like to update the existing user password and roles
Is this correct yes/no? yes
Password :
Re-enter Password :

What groups do you want this user to belong to? (Please enter a comma separated list, or leave blank for none)[user]: prabhu
Updated user 'prabhu' to file 'D:\workspace_Csmart\jboss-eap-
6.2\standalone\configuration\application-users.properties'
Updated user 'prabhu' to file 'D:\workspace_Csmart\jboss-eap-6.2\domain\configuration\application-users.properties'
Updated user 'prabhu' with groups prabhu to file 'D:\workspace_Csmart\jboss-eap-6.2\standalone\configuration\application-roles.prope
Updated user 'prabhu' with groups prabhu to file 'D:\workspace_Csmart\jboss-eap-6.2\domain\configuration\application-roles.propertie
Is this new user going to be used for one AS process to connect to another AS process?
e.g. for a slave host controller connecting to the master or for a Remoting connection for server to server EJB calls.
yes/no? yes
To represent the user add the following to the server-identities definition <secret value="cHJhYmh1QDEyMw==" />

And you see the user and password is updated in properties, so I ran the server with my local setup and it's up and running. But I didn't see any popup asking JBoss basic credentials. It's just directly going to the login page: http://10.17.195.15:8080/Proj/home.xhtml
Do I have to do anything with standalone.xml? security tag?
I would really appreciate it if anyone can point out what I am missing here? What do I need to do to make it work for JBoss Basic Authentication? Thanks!

A: 1) First you need to move all your jsf files (that need protection) in some folder, for example secured folder.
2) Create index.jsf that redirects to protected start page and place it outside secured folder.
3) Create logout.jsf which does session.invalidate() and redirects to index.jsf page.
<html>
<body>
<%
        if(session!=null)
         {
               session.invalidate();%>
              <jsp:forward page="index.jsp" />
  <%
                } else{
  %>
           Logged Out Successfully....
 <% }%>
</body>
</html>

4) Add security constraints to web.xml.
<security-constraint>
    <web-resource-collection>
        <web-resource-name>MySecureResources</web-resource-name>
        <description>Some Description</description>
        <url-pattern>/secured/*</url-pattern>
        <http-method>GET</http-method>
        <http-method>POST</http-method>
    </web-resource-collection>
    <auth-constraint>
        <role-name>TestRole</role-name>
    </auth-constraint>
</security-constraint>
<login-config>
    <auth-method>BASIC</auth-method>
</login-config>
<security-role>
    <role-name>TestRole</role-name>
</security-role>

5) Create jboss-web.xml file inside projects WEB_INF folder.
<?xml version="1.0"?>
<!DOCTYPE jboss-web PUBLIC
    "-//JBoss//DTD Web Application 5.0//EN"
    "http://www.jboss.org/j2ee/dtd/jboss-web_5_0.dtd">
<jboss-web>
 <security-domain>java:/jaas/BasicAuthWebAppPolicy</security-domain>
 <context-root>/basicSecurityWebApp</context-root>
</jboss-web>

6) Create a file with some name like basicSecurityWebApp-roles.properties. and place it in WEB_INF/classes folder. Define role there and assign that role to some user.
TestUserOne=TestRole

7) Create another file with some name like basicSecurityWebApp-users.properties and place it in WEB-INF/classes folder and define username and password.
TestUserOne=TestPassword

8) Now you should modify login-config.xml in $PROFILE/conf/ folder. Add application-policy with the same name as BasicSecurityWebApp.
<application-policy name="BasicAuthWebAppPolicy">
 <authentication>
   <login-module code="org.jboss.security.auth.spi.UsersRolesLoginModule"       flag="required">
     <module-option name="usersProperties">basicSecurityWebApp-users.properties</module-option>
     <module-option name="rolesProperties">basicSecurityWebApp-roles.properties</module-option>
   </login-module>
 </authentication>

9) Deploy application to JBoss.
10) Now every time you have to access our website you have to enter user and password you provided in credentials file (username as "TestUserOne" and password as "TestPassword").

For more details see This

A: Yes. This somehow helped me to solve this I just did following things:
Under WebContent folder:
step1: change in web.xml
<security-constraint>

        <web-resource-collection>
            <web-resource-name>All resources</web-resource-name>
            <description>Protects all resources</description>
            <url-pattern>/*</url-pattern>
        </web-resource-collection>

        <auth-constraint>
            <role-name>prabhu</role-name>
        </auth-constraint>
    </security-constraint>

    <security-role>
        <role-name>prabhu</role-name>
    </security-role>

    <login-config>
        <auth-method>BASIC</auth-method>
        <realm-name></realm-name>
    </login-config>

step2 : change in jboss-web.xml
<jboss-web>
    <context-root>C-SMART</context-root>
    <security-domain>java:/jaas/other</security-domain>
 </jboss-web>

step 3 : creating user and password for jboss basic authentication
D:\workspace_Csmart\jboss-eap-6.2\bin>add-user
What type of user do you wish to add?
 a) Management User (mgmt-users.properties)
 b) Application User (application-users.properties)
(a): b

Enter the details of the new user to add.
Using realm 'ApplicationRealm' as discovered from the existing property files.
Username : prabhu
User 'prabhu' already exits, would you like to update the existing user password and roles
Is this correct yes/no? yes
Password :
Re-enter Password :
What groups do you want this user to belong to? (Please enter a comma separated list, or leave blank for none)[prabhu]: prabhu
Updated user 'prabhu' to file 'D:\workspace_Csmart\jboss-eap-6.2\standalone\configuration\application-users.properties'
Updated user 'prabhu' to file 'D:\workspace_Csmart\jboss-eap-6.2\domain\configuration\application-users.properties'
Updated user 'prabhu' with groups prabhu to file 'D:\workspace_Csmart\jboss-eap-6.2\standalone\configuration\application-roles.properties'
Updated user 'prabhu' with groups prabhu to file 'D:\workspace_Csmart\jboss-eap-6.2\domain\configuration\application-roles.properties'
Is this new user going to be used for one AS process to connect to another AS process?
e.g. for a slave host controller connecting to the master or for a Remoting connection for server to server EJB calls.
yes/no? yes
To represent the user add the following to the server-identities definition <secret value="cHJhYmh1QDEyMw==" />
Press any key to continue . . .

Step 4: verified above user changes reflected in following files
'D:\workspace_Csmart\jboss-eap-6.2\standalone\configuration\application-users.properties'
'D:\workspace_Csmart\jboss-eap-6.2\domain\configuration\application-users.properties'
'D:\workspace_Csmart\jboss-eap-6.2\standalone\configuration\application-roles.properties'
'D:\workspace_Csmart\jboss-eap-6.2\domain\configuration\application-roles.properties'
And its worked fine for me.. Thanks all your help..


text:
Q: Is it possible to ping a host and get a delay? Developing an app that uses data synchronization. Sending images (even resized) takes time if it's done over slow internet connection. Thinking, it would be best first to check internet speed, and sent data only if the speed is acceptable. There's Apple Reachability class but it only has method for checking wifi is on. I guess for me, it would be enough to ping a host and grab delay information out of the ping cmd result. That delay info I would use for deciding is it worth to send data now or to wait.

A: Doing this is fairly involved, however Apple has a complete working example program here:
https://developer.apple.com/library/mac/#samplecode/SimplePing/Introduction/Intro.html#//apple_ref/doc/uid/DTS10000716-Intro-DontLinkElementID_2

A: Reachability or ping won't tell you how fast or slow the file will be transmitted. That is a function of ping_time + (file_size / bandwidth). For any large file, the ping_time is much smaller than file_size/bandwidth.
The easiest way to measure this is for the app to download and upload a not-too-small-not-too-large file and decide if in fact the upload and download speeds are "fast enough".


text:
Q: Typescript Declaration Merging not working across projects My main goal is to be able to use typings across the Front- and Back-end of my application.
I have already read about references and added them to my tsconfig.json. The problem is that the declaration merging I've made to the Express Response Object is not being recognized by the Front-end and being returned as any.
Example:
I have a dashboard.ts (controller), that has for now a single function to return the dashboard data.
dashboard.ts
import * as userModel from '../entities/user';
import * as modelModel from '../entities/model';

export const getData = async (req: Express.Request, res: Express.Response) => {
    const model = await modelModel.getActive();
    const availableStaff = await userModel.count();

    return res._json(200, {
        model,
        availableStaff,
    });
};

export type GetDataReturnType = Unpacked<ReturnType<typeof getData>>;
/**
 * Gives me
 *
 * type GetDataReturnType = {
    model: Model & {
        committees: (Committee & {
            delegations: Delegation[];
            directors: User[];
        })[];
        registrations: Registration[];
    };
    availableStaff: number;
}
 */

Then I export the type GetDataReturnType, so the Front-end could use it as well.
Notes:

*

*I created a Unpacked type to get the ReturnType without the Promise<>

*The _json is the declaration merging I created to the Express.Response Object (code bellow)

server/src/@types/express/index.d.ts
declare global {
    namespace Express {
        interface Response {
            _json: <T>(status: number, body: T) => T;
        }
    }
}

export {};

res._json implementation in
server/src/server.ts
app.response._json = (status, body) => {
    app.response.status(status).json(body);

    return body;
};

On the Back-end, everything works fine.
Nevertheless, when I import GetDataReturnType in the Client, the type comes as any
/web/src/hooks/useDashboard.ts
import { useQuery } from 'react-query';
import { api } from '../services/api';

import type { GetDataReturnType } from '@controller/dashboard';
/**
 * Gives me
 *
 * type GetDataReturnType = any
 */

import * as DateFns from 'date-fns';

const fetchDashboard: QueryFn<GetDataReturnType> = async () => {
    const response = await api.get<GetDataReturnType>('/dashboard');

    return response.data;
};

export const useDashboard = () => {
    const { data: dashboard, status } = useQuery(
        ['dashboard'],
        fetchDashboard,
        {
            staleTime: DateFns.hoursToMilliseconds(5),
        }
    );

    return { dashboard, status };
};

Here's my server/tsconfig.json
{
    "compilerOptions": {
        "target": "es6" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */,
        "module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */,
        "moduleResolution": "node",
        "sourceMap": false /* Generates corresponding '.map' file. */,
        "outDir": "../build" /* Redirect output structure to the directory. */,
        "removeComments": true /* Do not emit comments to output. */,

        /* Strict Type-Checking Options */
        "strict": true /* Enable all strict type-checking options. */,
        "noImplicitAny": true /* Raise error on expressions and declarations with an implied 'any' type. */,
        "strictNullChecks": true /* Enable strict null checks. */,
        "strictFunctionTypes": true /* Enable strict checking of function types. */,
        "strictBindCallApply": true /* Enable strict 'bind', 'call', and 'apply' methods on functions. */,
        "strictPropertyInitialization": true /* Enable strict checking of property initialization in classes. */,
        "noImplicitThis": true /* Raise error on 'this' expressions with an implied 'any' type. */,
        "alwaysStrict": true /* Parse in strict mode and emit "use strict" for each source file. */,

        "baseUrl": "./" /* Base directory to resolve non-absolute module names. */,
        "paths": {
            "@schemas/*": ["./src/schemas/*"],
            "@server/*": ["./src/*"]
        } /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */,
        "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,

        "skipLibCheck": true /* Skip type checking of declaration files. */,
        "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */,
        "composite": true
    },
    "include": ["src", "src/@types/index.d.ts", "src/@types/express/index.d.ts"]
}

Here's my web/tsconfig.json
{
    "compilerOptions": {
        "target": "es5",
        "lib": ["dom", "dom.iterable", "esnext"],
        "allowJs": true,
        "skipLibCheck": true,
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true,
        "forceConsistentCasingInFileNames": true,
        "noFallthroughCasesInSwitch": true,
        "module": "esnext",
        "moduleResolution": "node",
        "resolveJsonModule": true,
        "noEmit": true,
        "jsx": "react-jsx",
        "isolatedModules": true,
        "sourceMap": false,
        "strict": true,
        "noImplicitAny": true,
        "strictNullChecks": true,
        "strictFunctionTypes": true,
        "strictPropertyInitialization": true,
        "noImplicitThis": true,
        "rootDir": "./src",
        "paths": { "@controller/*": ["../server/src/controller/*"] }
    },
    "references": [{ "path": "../server" }],
    "include": ["src"]
}

*

*server and web are in the same directory

A: Reviewing this question, I realized I forgot to add "../server/src/@types/**/*" to the include option in web/tsconfig.json. Now, it works perfectly.


text:
Q: Обработка error'ов с помощью if Возникла такая проблема, мне нужно обработать событие, но его нельзя сформулировать ни в python, ни в поисковике. Из-за этого возникает error. Как мне обработать определённую ошибку, с помощью if?
Пример:
if 'ошибка/код ошибки':
    print('возникла ошибка: ', 'ошибка/код ошибки')

Заранее спасибо.

A: Для обработки исключений предназначена конструкция try - except. Делать это через if довольно странно. Если только проверять типы данных, но возможность сделать это зависит от задачи, которую вы решаете


text:
Q: sending parameters from one Facelets page to another Whenever we want to send  parameters from one jsp page to another we use the following lines of codes, what if we want to send parameters in JSF, like sending one parameter from one Facelets page to another.
1)First Page

    <title>Test Page 1</title>

        <%String forwardToPage="/2.jsp?Key=1234568&Schema=COM";%>
        <jsp:forward page = "<%=forwardToPage%>" />

2) Second Page

    <title>Test page 2</title>

        <%
            out.println(request.getParameter("Key") + " KEY " + request.getParameter("Schema") + "   SCHEMA " );
        %>

A: There are two commons ways: using a <f:viewParam> and using an embedded #{flash} object. Both ways are covered in the answers to jsf2.0 - How to get the values in other jsf page's bean in request scope, the first one by partlov, and the second one by myself.
Also, BalusC's answer to What can <f:metadata> and <f:viewParam> be used for? question is a great starting step.


text:
Q: Find all nearby customers within a given distance using longitude and latitude I have a db contain customers longitude and latitude, I have a search form in which the user will enter log/lat and distance dropdown contain 50miles, 100miles,.... and when the user click search I want to write a linq query to get all customers from the db which are in this distance radius. How to make this using C# and linq?
Update:
I found this https://stackoverflow.com/a/1654365/20126 but this gives a square not radius

A: A little modification of my answer to a similar question:
// radius is the distance in meters
var center = new GeoCoordinate(latitude, longitude);
var result = customers.Select(x => new GeoCoordinate(x.Latitude, x.Longitude))
                      .Where(x => x.GetDistanceTo(center) < radius);

You need to add reference to System.Device.dll.

A: Using haversine formula
User will have current location, customer location and distance So using haversine formula calculate distance (d1) using current location and customer location Then compare calculated distance (d1) with required distance.
Logic is calculated distance <= required distance then it means current customer is in required distance else customer is outside the radial distance


text:
Q: Excel Custom Sorting for alphanumeric data I have data in Excel file:
Brandon 1
Brandon 10
Brandon 11
Brandon 2
Brandon 3
Brandon 4
John 1
John 2
John 20
John 21
John 22
John 3
John 4

I want to sort it by Name first and then the number:
Brandon 1
Brandon 2
Brandon 3
Brandon 4
Brandon 10
Brandon 11
John 1
John 2
John 3
John 4
John 20
John 21
John 22

Any suggestions? I don't want to add leading zeros to numbers.

A: Create a second colum with the numbers. You can use a second formula to fill the column
If the numbers don't exceed 99

*

*A1: Brandon 1

*B1: =VALUE(RIGHT(A1;2))
Else first find the last space

*

*B1: =VALUE(RIGHT(A1,LEN(A2)-FIND("@",SUBSTITUTE(A2," ","@",LEN(A2)-LEN(SUBSTITUTE(A2," ",""))),1)))
https://trumpexcel.com/find-characters-last-position/

A: One option is:

*

*Splitting your column into 2 columns.
This can be done with:
1.1.  Data -> Text to columns -> ...
1.2. Formulas (my Excel is in Spanish, so I may slightly miss the names of the functions). Assuming your datum is in D1, for the name use =LEFT(D1,FIND(" ",D1)-1) and for the number use =INT(RIGHT(D1,LEN(D1)-FIND(" ",D1))) or  =VALUE(RIGHT(D1,LEN(D1)-FIND(" ",D1))). Then copy down the formulas.

*Using Data -> Sort and Add level to sort by the two criteria.
You can record a macro while you are doing that, to automate the process via VBA.
You can even condensate all this into a User Defined Function via VBA.

A: Your problem can be solved by using Helper Column:

How it works:

*

*I'm assuming that Names are in A2:A9.

*Enter this Formula in C2 & fill down.
=TEXT(A2,"###")

*Select Range A1:C9.

*From Home Tab click on Sort Icon &
Select Custom Sort.

*Set Sort Order & others as shown in Screen Shot
below.

*

*Finish with Ok.

You find Names in expected order.

Edited:
I'm editing since OP has got new set of Sample Data.

*

*New set of Data can be Sorted in desire order, using few Helper Columns.

*

*Enter this Formula in B2 & fill down.
=VALUE(RIGHT(A2,LEN(A2) - MIN(SEARCH({0,1,2,3,4,5,6,7,8,9}, A2&"0123456789")) +1))

*Write this one in C2 & fill down.
=LEFT(A2,MIN(FIND({1,2,3,4,5,6,7,8,9,0},A2&1234567890))-1)

*

*Now select A1:C14 & From Home Tab click Sort Command and hit Custom Sort.

*Set Order and Others as shown in Screen Shot below.

*Finish with Ok
You get new set of Data in desire order.

Note, Later on you may hide Helper Column.


text:
Q: "because of" and "due to" with an example I would like to know which sentence below is correct:

*

*Because of the heterogeneity of smartphone users and their immense base, the relevant users of our software are not really segmented by sectors or professions.

*Due to the heterogeneity of smartphone users and their immense base, the relevant users of our software are not really segmented by sectors or professions.

A: It is correct to say Due to. Rather relying on my linguistic instinct of course, but I will try to explain it logically. The first option is rather used for pain, for example.


text:
Q: Should I buy server or build it? I need a server for a small company with about 20 people. The server will be used as a fileserver for many MS Office files simultaneously. I tried to look at complete servers but I don't like any of the ones I've looked at. They require you to buy HDDs and an OS, which adds about 300 (currency unknown) more than I want to pay.
The server is for Windows but i already own a license and have a CD.
Is there real economy if I build it and can someone estimate what hardware I need for this kind of server?

A: File server? That's it? Buy a NAS.
NewEgg NAS Store

A: For such things people usually use MS SharePoint Server. If you have licensed Windows 2008 Server OS 64-bit you can install MS SharePoint 2010 Foundation and use it for document collaboration. Consider buying small barebone server and adding hardware (HDD, Memory) as load on server demands


text:
Q: GLSL - unresolved external on Visual C++ I'm getting started with the GLSL. What should i do to resolve this:
error LNK2001: unresolved external symbol _pglLinkProgram
error LNK2001: unresolved external symbol _pglAttachShader
error LNK2001: unresolved external symbol _pglCompileShader
error LNK2001: unresolved external symbol _pglShaderSource
error LNK2001: unresolved external symbol _pglCreateShader
error LNK2001: unresolved external symbol _pglCreateProgram
error LNK2001: unresolved external symbol _pglGetProgramInfoLog
error LNK2001: unresolved external symbol _pglGetProgramiv
error LNK2001: unresolved external symbol _pglUseProgram

A: You seem to be using some form of library that wraps GL entrypoints (the entrypoints you list are not direct GL entrypoints).
This library (GLEE ?) likely is coming with a .lib file that you need to link against.
Coming from the project page of GLEE (my guess, based on a quick googling of who is using the prefix p for GL calls):

Usage examples
To use GLee, include
  GLee.h, then simply link to GLee.lib
  or alternatively add GLee.c to your
  project.

A: You have to link your program against opengl32.lib, see here.

A: I recommend you start using GLEW since OpenGL > 1.5 on Windows is a bit of a pain in the ass. This will get you all OpenGL entry points without messing with extension pointers.


text:
Q: Prove $\lim_{x\to 0}x^{2}\cos\left(\frac{1}{x^{2}}\right) = 0.$ so I have to prove that $$\lim_{x\to 0}x^{2}\cos\left(\frac{1}{x^{2}}\right) = 0.$$
What I did is: $0 < |x| < \delta \implies \left|x^{2}\cos\left(\frac{1}{x^{2}}\right)\right| < \epsilon$
\begin{align*}
|x^2| &< \frac{\epsilon}{\cos(1/x^2)}\\
|x| &< \sqrt{\frac{\epsilon}{\cos(1/x^2)}}
\end{align*}
So, $\delta = \sqrt{\frac{\epsilon}{\cos(1/x^2)}}$.
Is that right? I mean, did I do it all correct? Can I pass an $x$ to the other side? Or what am I supposed to do?
Thank you!

A: Let start by the well-known double inequality,
$$\forall x\ne 0 \;\;-1\le \cos(\frac {1}{x^2})\le 1$$
then after multiplication by $x^2$,
$$-x^2\le x^2\cos (\frac {1}{x^2})\le x^2$$
and by Squeeze theorem,
$$0\le \lim_{x\to 0}x^2\cos (\frac {1}{x^2})\le 0$$

A: Hint
Note that
$$
|x^{2}cos(1/x^{2})|\leq |x|^2.
$$
Hence, given $\varepsilon>0$, let $\delta=\sqrt{\varepsilon}$ and suppose $0<|x|<\delta.$ Then
$$
|x^{2}cos(1/x^{2})|\leq |x|^2<\varepsilon.
$$


text:
Q: Some postgress connections timing-out while others don't I have an AWS EC2 machine running a Laravel 5.2 application that connects to a Postgress 9.6 databse running in RDS. While most of the connections work, some of them are getting rejected when trying to stablish, which causes a Timeout and consequently an error in my API. I don't know what is causing them to be rejected. Also, it is very random when it happens, when it does happen it may be in any API endpoint and inside the endpoint in any query.
When the timeout is handled by PHP, it shows a message like:
SQLSTATE[08006] [7] timeout expired (SQL: ...)

Sometimes the Nginx handles the timeout and replies with a 504 Error. When Nginx handles the timeout I get an error like:
2019/04/24 09:48:18 [error] 20657#20657: *3236 upstream timed out (110: Connection timed out) while reading response header from upstream, client: {client-ip-here}, server: {my-url-here}, request: "GET {my-endpoint-here} HTTP/2.0", upstream: "fastcgi://unix:/var/run/php/php7.0-fpm.sock", host: "{}", referrer: "https://app.cartoriovirtual.com/"

All usage charts on the RDS and EC2 seems ok, I have plenty of RAM, storage, CPU and available connections for RDS. I also checked inner VPC Flows and they seem alright, however I have many IPs (listed as attackers) scanning my network interfaces, most of them been rejected. Some (to port 22) accepted but stoped at authentication, I use a .pem Key File for auth.
The RDS network interface only accepts requests from inner VPC machines. In its logs, every 5 minutes I have a Checkpoint like this:
2019-04-25 01:05:29 UTC::@:[22595]:LOG: checkpoint starting: time
2019-04-25 01:05:34 UTC::@:[22595]:LOG: checkpoint complete: wrote 43 buffers (0.1%); 0 transaction log file(s) added, 0 removed, 1 recycled; write=4.393 s, sync=0.001 s, total=4.404 s; sync files=19, longest=0.001 s, average=0.000 s; distance=16515 kB, estimate=16515 kB

Anyone has tips on how to find a solution? I looked at all possible logs that came in mind, fixed a few little issues but the error persists. I am running out of ideas.


text:
Q: Hiding image for mobile devices I'm trying to hide a certain image for mobile devices on my website. I've tried a various of html and css code and i cannot get it to work. It might have something to do with my div class's and Id tags.
please can someone try and get it to work for me?
HTML:

CSS:
@media (max-width: 600px) {
    #left-sidebar .logo .nav  {
        display:none;
    }
}

A: You have to use @Media screen:

screen  Used for computer screens, tablets, smart-phones etc.

Combine it with pixel-ratio to fit your needs. Check more examples here
For example (for Samsung Galaxy S3):
/* ----------- Galaxy S3 ----------- */

/* Portrait and Landscape */
@media screen
  and (device-width: 320px)
  and (device-height: 640px)
  and (-webkit-device-pixel-ratio: 2)
{
    // insert here your custom styles
    #left-sidebar .logo .nav  {
       display:none;
    }
}

A:

A: instead using display:none try this
@media (max-width: 600px) {
    #left-sidebar .logo .nav  {
        display:hidden !important;
    }
}

this code will work if isn't still not working please check device width and go on

A: I run  your HTML and CSS on JSFiddle. I just change your CSS to:
  img {
            display:none;
        }

and got this
not sure if its this what you are looking for

A: This seemed to work for me, which was odd
@media (max-width: 768px) {
      #left-sidebar .logo .nav  {
            display:none;
   }
 }

A:


text:
Q: Javascript performance: Fastest way of building and injecting html This is for a single page, mobile web-app....
For readability I've been concatenating my html, then injecting. I'm pretty certain there's a more efficient way, and would like to get a js expert's opinion!
heres an example of one of my concatenated html strings...
var html_str = '';
$.each(events_array, function(k, ev_type){
    if( localStorage.getItem('show_type'+ev_type.type_num) !== 'false' ){
        $.each(ev_type, function(k2, e){
            if(typeof e != 'string'){
                if(fav_mode && last_date_num != e.date){
                    html_str += '
'+e.date_text+'
';
                    last_date_num = e.date;
                }
                html_str += '
= 0) ){
                    html_str += ' class="fav"';
                }
                html_str += '>';
                html_str +=     '

';
                html_str +=     '
'+e.venue+' : '+e.nameofnight+'
';
                html_str += '
';
            }
        });
    }
});
return html_str

A: There is no "Fastest". There is only "Fastest" for a browser.
There are 3 common techniques. HTML string manipulation, templating and DOM manipulation.
Because templating can use both HTML string manipulation and the DOM internally I would recommend it for readability / maintainability.
Here are a few benchmarks
Templating
More templating
Templating with data for mobile platforms
Loads of templates
Dust js benchmark

A: If you're talking huge amounts of HTML and perf is paramount
Definitely Don't:

*

*Inject dom nodes iteratively in a loop. This can mess with perf even in not-gigantic HTML scenarios.

*Try to save work by using live existing HTML by tweaking attributes and swapping out content across a large variety of elements. As with the previous point this can get ugly even in things not involving thousands of elements. Large tables that don't have table-layout set to fixed can get particularly nasty when you trigger a ton of reflow.

*Use jQuery's direct string to dom building - which, IMO, is actually excellent for most uses since it does a great job of validating for nasty escape sequences if injecting data from sources that may one day not be that secure. Use the html method to build from and inject from strings instead if you're going with strings. Although really for max perf, I'd probably just drop JQ if I 100% trusted my data.
Do:

*

*Build it all out in a document fragment and append with that. Or build an HTML string and drop it all in at once. I prefer the hybrid method described below under "Maybe" but haven't tested in 2-3 years. That way the browser only has to repaint the page once. Google "CSS reflow" for more on that.

*If you have to make lots of tweaks to a large volume of HTML, just change data and rebuild the whole set for same reason as above.

*If you build from strings, minimize concatenation with the '+' operator and use array joins instead. Templating with arrays works great in a pinch.

*Worry about the loops vs iterators that take a function argument if IE<=8 is a concern. Repeated function calls can get expensive without a JIT compiler. They can actually help you in JITs if they're inline (defined inside another function without any references returned outside).

*Test everything you try. There's gray areas in everything but the multiple vs. one giant append rule. Multiple will always be slower.
Maybe:
An excellent trick in legacy browsers was to innerHTML large strings to document fragments and append those via DOM methods. This wasn't the fastest for all browsers but it was the best approach across the board back when IE7 mattered and the difference in modern JIT browsers between one-block innerHTML, DOM methods only into document fragment, and the hybrid approach were mostly negligible.

A: I would totally recommend templating too.
But I think you already make use of best practices about injecting HTML: it's far better to build the HTML, then inject it at one time, rather than injecting many times small bits of HTML, as the browser may repaint/reflow the document on each injection.

A: An explicit for loop will definitely be much faster than $.each(), mainly since that executes a function call for each element, but also for other reasons, e.g. with the new execution frame the lookup time for html_str will be longer.
There is some empirical evidence to suggest (I think this was valid with older browsers, I'm not sure what is faster nowadays or on mobile devices, it's worth checking out) that adding the elements to an array (with the loop variable html_str[i], and not html_str.push()) and then calling .join is faster than string concatenation.
As has been mentioned, adding one large DOM string is faster than small appends, and much faster than using DOM methods (appendChild, insertBefore, etc.).
A good templating engine would do these things for you (at a small extra cost), although I'm not sure if many of them do. And if it's only a small amount of "templating" then it might be overkill to use a library, when a simple loop does the trick.

A: You might as well consider using documentFragment, though it may not as readable as html string, it is very much effective (performance-wise) and readable maybe in object-oriented way.
you can visit this page for details: http://ejohn.org/blog/dom-documentfragments/


text:
Q: "to school" versus "to garage"
Possible Duplicate:
Is there a reason the British omit the article when they "go to hospital"?

Why is "I am going to town" or "I am going to school" acceptable but "I am going to garage" not acceptable?  Is there a term for this kind of exception on the use of definite/indefinite articles?

A: The zero article is used when places are regarded as institutions, so we talk about going to church, going to jail, going to university and going to school. It might just about be possible to argue that going to town fits the same pattern, but it must otherwise be regarded as anomalous. A garage clearly cannot be seen as an institution and so requires the definite or indefinite article, depending on context.

A: Some nouns are arthrous, some are anarthrous, that's just the way it is in English. You say "the Nile river" but "Lake Michigan". You say "the Ronald Reagan Library" but "Carnegie Hall".
So, it's "school", but it's "the garage".

I'm going to school.
  I'm going to the garage.
  I'm going to Albany.
  I'm going to the Holland Tunnel.
  I'm going to Lake Michigan.
  I'm going to the library.
  I'm going to Mount Rushmore.
  I'm going to the Bronx.
  I'm going to Manhattan.