text:
Q: How to make complex conditions in mod_rewrite? I need to deny access to the whole site for everyone except some IPs.
Also, I need to permit access to one folder of site for everyone:
Options +FollowSymLinks
Options +Indexes
RewriteEngine on

# Allow access only for devs
RewriteCond %{REMOTE_ADDR} !10.10.10.10 [NC] # First dev id
RewriteCond %{REMOTE_ADDR} !11.11.11.11 [NC] # Second dev id

# Allow direct access to files
RewriteCond %{REQUEST_FILENAME} !-f

# Redirecting guests
RewriteRule (.*) /coming/soon/index.html [R=307]

# But where to place this condition?
RewriteRule ^/?preview/?$ /preview/index.html [NC]

# Other rules for main site structure
# ...

So, I need the whole site loading only for devs. Other users (guests) will see the /coming/soon/ page
And also guests are allowed to see /preview/ page of the site.
How to do this?

A: If your /preview/ rewrite is suitable for all users and does not depend on subsequent rewrite rules, the simplest way is to put this RewriteRule first with the [L] flag, so that subsequent rewrites will not be applied.
Otherwise, exceptions for RewriteRule may be specified as RewriteCond matching with %{REQUEST_URI}:
RewriteCond %{REQUEST_URI} !^/?preview/?$ [NC]

Also note that your suggested rule would rewrite both /preview and /preview/ into /preview/index.html, and the first of these rewrites may break relative links unless a redirect is performed.


text:
Q: Error when trying to open localhost/phpmyadmin Opening the http://localhost/phpmyadmin page results in a Fatal error:
Namespace declaration statement has to be the very first statement or after any declare call in the script in F:\xampp\phpMyAdmin\libraries\classes\DatabaseInterface.php on line 8

I have tried commenting out the line to solve the problem but nothing happens.
/* Locale for messages */
       /* $locale = LanguageManager::getInstance()->getCurrentLanguage()->getMySQLLocale();
        if (! empty($locale)) {
            $this->query(
                "SET lc_messages = '" . $locale . "';",
                DatabaseInterface::CONNECT_USER,
                self::QUERY_STORE
            );
        }*/

but i got error

Fatal error: Namespace declaration statement has to be the very first
  statement or after any declare call in the script in
  F:\xampp\phpMyAdmin\libraries\classes\DatabaseInterface.php on line 8

please solve the issue

A: Once phpMyAdmin is installed point your browser to http://localhost/phpmyadmin to start using it. You should be able to login using any users you've setup in MySQL. If no users have been setup, use admin with no password to login. Then select Apache 2 for the webserver you wish to configure.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to read this .txt into R (efficiently)? I want to read the following .txt file into R where the first rows look like this:
"Mark"  "Name des Unternehmens" "Ort"   "ID 1"  "ID 2"  "Straße und Hausnummer (*)" "Postleitzahl"  "ID 3"  "ID 4"  "Value of interest" "Value of interest 2"
"1" "VOLKSWAGEN AKTIENGESELLSCHAFT" "Wolfsburg" "2070000543"    "38100 HRB 100484"  ""  "38440" "03103" "031"   "2910"  "3361"
"2" "Daimler AG"    "Stuttgart" "7330530056"    "70190 HRB 19360"   ""  "70327" "08111" "081"   "2910"  "3361"
"3" "E.ON SE"   "Essen" "5050056484"    "40227 HRB 69043"   ""  "45131" "05113" "051"   "7010"  "5511"

that is, the first row gives the headers as usual and the next rows, starting with the numbers "1", "2", "3" feed in specific observations.
Unfortunately, whenever I want to read this into R, either using import tools or read.table, R does not recognise the different columns as different variables, and just gives one completely useless variable. In addition I get the error message "line x contains embedded nuls" for each line.
I tried the following, I imported the .txt in Excel, and saved it as a csv, which then allowed me to import it. This works, but is not there a better way to do this in R? The .txt data does not look so outlandish.
Thanks!

A: Yes your approach is correct:
read.table("data.txt", header = TRUE, stringsAsFactors = FALSE)

However you likely have encoding issues that are causing you grief. The text in your example includes non ASCII characters and therefore check the encoding of the text file. and check the encoding of your R session.
I'm guessing that the text is UTF-8 and you're importing in a native non-UTF-8 encoding. Try this:
read.table("data.txt", header = TRUE, stringsAsFactors = FALSE, encoding = "UTF-8")


text:
Q: Get substring using regex I have some strings Like
1.IND_FROM_ONE_TO_FIVE
2.IND_FROM_FIVE_TO_TEN
3.BS_FROM_ONE_TO_FIVE
4.BS_FROM_FIVE_TO_TEN
5.OP_FROM_ONE_TO_FIVE
6.OP_FROM_FIVE_TO_TEN

And I want to cut from all of them everything before the first "" include ""!!!.
Something like :
1.IND_FROM_ONE_TO_FIVE => FROM_ONE_TO_FIVE

2.IND_FROM_FIVE_TO_TEN => FROM_FIVE_TO_TEN

3.BS_FROM_ONE_TO_FIVE => FROM_ONE_TO_FIVE

4.BS_FROM_FIVE_TO_TEN => FROM_FIVE_TO_TEN etc.

I have tried /[^_]*/ but it returns IND_FROM_ONE_TO_FIVE => _FROM_ONE_TO_FIVE (did not cut first "_")
How could I make it on java?

A: You can prepend an anchor and match the underscore after is as well. In the replacement use an empty string.
^[^_]*_

Regex demo | Java demo
Using replaceFirst you can omit the anchor:
System.out.println("IND_FROM_ONE_TO_FIVE".replaceFirst("[^_]*_", ""));

Output
FROM_ONE_TO_FIVE

A: You could use a capturing group to extract substring that you want to.
^[^_]+_(.*)

I also tried to test result on Java.
import java.util.regex.*;
public class MyClass {
    public static void main(String args[]) {
        String mydata = "BS_FROM_FIVE_TO_TEN";
        Pattern pattern = Pattern.compile("^[^_]+_(.*)");
        Matcher matcher = pattern.matcher(mydata);
        if (matcher.find())
        {
            System.out.println(matcher.group(1));
        }
    }
}

Result
FROM_FIVE_TO_TEN

A: You can use matching rather than replacing: take the first and only capture from this regex (multiline): ^\d+\.[^_]+_(.*)$ (https://regex101.com/r/Y3Ztv4/1).


text:
Q: Format numbers as thousands,millions,billions with Zero i want to use format number with 00K for thousands & 00M for millions & 00B for billions & - for zero
I used the following format
[<999999] #, "K";[<999999999]#,, "M";#,,, "B"
but the problem is in cells that contain zeros it shows K
As you can see in the yellow cells

How do I solve this problem?

A: The basic issue that you're running into is that the custom formatting can only handle two conditionals at once (see Exceljet for a good breakdown of how custom number formatting works). You already have two conditions; less than 999,999 and less than 999,999,999.
To get a third condition of equal to zero we need to turn to conditional formatting. Select the array you would like to format, open conditional formatting and select "new rule", select "format only cells that contain" and set it to "cell value equal to 0". You can than click "format" and in that menu set custom number formatting to just "-".
Let me know if that helps!


text:
Q: Spring Boot maven unit tests not being executed I have a Spring Boot project. I have written unit tests in the .../src/test/java/... directories. All of my unit tests are of the form *Test.java. When I run 'mvn test', I get the following output:
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ frm-api ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 6 source files to /Users/JoelRives/Projects/fasor/fasor-service/fatality-review/target/test-classes
[INFO]
[INFO] --- maven-surefire-plugin:2.22.0:test (default-test) @ frm-api ---
[INFO]
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 0, Failures: 0, Errors: 0, Skipped: 0
[INFO]

Clearly, maven sees the unit tests as it is compiling them. However, as you can see, it does not run them.
I have the following relevant maven dependencies in my pom:
  <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
      <version>1.5.3.RELEASE</version>
  </dependency>

  <dependency>
      <groupId>com.h2database</groupId>
      <artifactId>h2</artifactId>
      <scope>test</scope>
      <version>1.4.194</version>
  </dependency>

My pom also includes the following plugin:
       <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.22.0</version>
            <dependencies>
                <dependency>
                    <groupId>org.junit.platform</groupId>
                    <artifactId>junit-platform-surefire-provider</artifactId>
                    <version>1.3.0-M1</version>
                </dependency>
                <dependency>
                <groupId>org.junit.jupiter</groupId>
                    <artifactId>junit-jupiter-engine</artifactId>
                    <version>5.2.0-M1</version>
                </dependency>
            </dependencies>
        </plugin>

Any help regarding this is greatly appreciated.
I did not show my entire POM. Here is the Junit stuff:
<dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
  </dependency>

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

  <dependency>
      <groupId>com.h2database</groupId>
      <artifactId>h2</artifactId>
      <scope>test</scope>
      <version>1.4.194</version>
  </dependency>

A: Using recent surefire you can configure it to use JUnit 4:
  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>3.0.0-M5</version>
    <dependencies>
      <dependency>
        <groupId>org.apache.maven.surefire</groupId>
        <artifactId>surefire-junit47</artifactId>
        <version>3.0.0-M5</version>
      </dependency>
    </dependencies>
  </plugin>

A: It looks like if you are using Junit4 and the surefire plugin version 2.22 and above, the tests dont get picked up. I had a similar issue and using surefire V2.21.0 seemed to work.
Below is my surefire config
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.21.0</version>
            </plugin>

A: For me, I had written this in my pom.xml and I was using JUnit4
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

Once I removed the exclusions, it started executing.

A: Try updating the surefire-plugin to pick the test classes explicitly as:
<plugins>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <configuration>
            <includes>
                <include>**/*Test*.java</include>
            </includes>
        </configuration>
    </plugin>
</plugins>

You can look into this as well, may be duplicated!!

A: Note, this is a partial answer. I as able to get the unit tests to run by removing the surefire plugin from the POM. I have never had problems with surefire in the past. O well..., at least the tests are running -- broken as they may be :-) I will investigate the surefire issue later. Thanks for the suggestions.

A: The key here is to understand the test engines that Spring uses.
In my case, I coded API tests with @RunWith(SpringRunner.class), which is under JUnit4, which runs with junit-vintage-engine.
But the unit tests are coded with JUnit Jupiter, which is under JUnit5, which runs with junit-jupiter-engine.
The default engine of SpringBoot is the junit-jupiter-engine. So we have to tell to Spring that we also want to use junit-vintage-engine.
We can simply add the dependency in our pom.xml:
<dependency>
  <groupId>org.junit.vintage</groupId>
  <artifactId>junit-vintage-engine</artifactId>
  <scope>test</scope>
</dependency>

Or, if we want to use maven-surefire, we can add the dependency inside the plugin:
<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-surefire-plugin</artifactId>
  <version>3.0.0-M7</version>
  <dependencies>
    <dependency>
      <groupId>org.junit.vintage</groupId>
      <artifactId>junit-vintage-engine</artifactId>
      <version>5.7.0</version>
    </dependency>
  </dependencies>
</plugin>


text:
Q: How to convert these GPS co-ordinates into valid Google Maps cordinates? I am getting GPS values from my GPS logger like this:
3250193.00 E
1115573.00 N

What type of GPS co-ordinates are these? They look like UTM co-ordinates. How to decode them to proper Google Maps co-ordinates?

A: Coordinate conversion isn't a trivial thing - you need to know what format your data is in before you start, and then use the appropriate geographic transformation.
Intro to the topic:
http://help.arcgis.com/en/sdk/10.0/arcobjects_net/conceptualhelp/index.html#//0001000002mq000000
Once you establish what data you're starting with you can use a library like GDAL to do the transformations:
Link


text:
Q: How to do inheritance using yaml in Doctrine 2 Im trying to use FOS UserBundle And I need to create an user entiy with extending BaseUser from the FOSUserBundle.
Here is my User.orm.yml
Acme\UserBundle\Entity\User:
  type: entity
  id:
    id:
      type: integer
      generator: { strategy: AUTO }
inheritanceType: SINGLE_TABLE
discriminatorColumn:
  name: discr
  type: string
  length: 255
discriminatorMap:
  user: User
  baseUser: BaseUser

I didnt forget to extends BaseUser but I just dont know how to do that.
The doctrine documentation only show how to do that using annotation.
Could you help me please ?
Thanks

A: This is example of SINGLE_TABLE inheritance.
This is also some useful information.
Hope it helps.


text:
Q: meaning of $C_4$ tree in graph theory I was reading a paper. There a term was defined as $C_4$ tree. It was written that a graph is $C_n$ tree if it can b constructed from $C_n$ by a finite number of applications of the following theorem : add a new $C_n$ and identify an edge of this graph with an edge of existing graph. Can anybody explain me what it means? thanks a lot :)

A: First let's make sure that you understand the operation. I start with the copy of $C_4$ at the left in the picture below. I then add to it a second copy of $C_4$, shown immediately to its right, by identifying the edge $e$ of the first copy with the edge $e'$ of the second copy; the result is the graph shown at $(2)$. If I perform the operation again by adding a third copy of $C_4$, this time identifying its top edge with the lower right edge of $(2)$, I get $(3)$.
       *---*     *---*      *---*---*        *---*---*
       |   |e  e'|   |      |  e|e' |        |   |   |
       *---*     *---*      *---*---*        *---*---*
                                                 |   |
                                                 *---*
             (1)               (2)              (3)

Suppose that I replace each copy of $C_4$ by a vertex and join two vertices by an edge if the corresponding copies of $C_4$ have been sewn together by this operation. My original $C_4$, the graph in $(2)$ and the graph in $(3)$ turn into these trees:
              *               *---*            *---*
                                                   |
                                                   *

More generally, suppose that $G$ is a $C_n$ tree graph. That means that $G$ is constructed from a copy of $C_n$ in some finite number $m$ of steps, each of which is an application of the attaching operation. We can describe it this way. For $k=0,1,\ldots,m$ let $A_k$ be a copy of $C_n$. I start with $G_0=A_0$. Then I form $G_1$ by adding $A_1$, the second $C_n$, graph, identifying one of its edges with one edge of $G_0$. Then I form $G_2$ by adding $A_2$, identifying one of its edges with one edge of $G_1$. I continue in this fashion until I've formed $G_m=G$ by adding $A_m$ to $G_{m-1}$. Note that at stage $k$ the $C_n$ copy $A_k$ is attached along an edge to exactly one $A_j$ with $j<k$.
Now let $V=\{v_0,v_1,\ldots,v_m\}$ be a set of $m+1$ vertices; the idea is that $v_k$ is to correspond to $A_k$ for $k=0,\ldots,m$. $V$ is to be the vertex set of a new graph $T$; if $1\le j<k\le m$, $\{v_j,v_k\}$ is an edge of $T$ iff $A_k$ was attached along an edge of $A_j$ when it was added at stage $k$ to produce $G_k$. If $n=4$ and $m=2$, for instance, the graphs in the top picture are $G_0,G_1$, and $G_2$, and the graph at the right in the lower picture is $T$.
You can think of $T$ as being a sort of skeleton of $G$, and the reason for the name $C_n$ tree graph is that this skeleton $T$ is always a tree. (This isn't too hard to prove.)


text:
Q: Python SVG parser I want to parse an SVG file using python to extract coordinates/paths (I believe this is listed under the "path" ID, specifically the d="..."/>).  This data will eventually be used to drive a 2 axis CNC.
I've searched on SO and Google for libraries that can return the string of such paths so I can further parse it, but to no avail.  Does such a library exist?

A: Ignoring transforms, you can extract the path strings from an SVG like so:
from xml.dom import minidom

doc = minidom.parse(svg_file)  # parseString also exists
path_strings = [path.getAttribute('d') for path
                in doc.getElementsByTagName('path')]
doc.unlink()

A: Getting the d-string can be done in a line or two using svgpathtools.
from svgpathtools import svg2paths
paths, attributes = svg2paths('some_svg_file.svg')

paths is a list of svgpathtools Path objects (containing just the curve info, no colors, styles, etc.).
attributes is a list of corresponding dictionary objects storing the attributes of each path.
To, say, print out the d-strings then...
for k, v in enumerate(attributes):
    print(v['d'])  # print d-string of k-th path in SVG

A: The question was about extracting the path strings, but in the end the line drawing commands were wanted. Based on the answer with minidom, I added the path parsing with svg.path to generate the line drawing coordinates:
#!/usr/bin/python3
# requires svg.path, install it like this: pip3 install svg.path

# converts a list of path elements of a SVG file to simple line drawing commands
from svg.path import parse_path
from svg.path.path import Line
from xml.dom import minidom

# read the SVG file
doc = minidom.parse('test.svg')
path_strings = [path.getAttribute('d') for path
                in doc.getElementsByTagName('path')]
doc.unlink()

# print the line draw commands
for path_string in path_strings:
    path = parse_path(path_string)
    for e in path:
        if isinstance(e, Line):
            x0 = e.start.real
            y0 = e.start.imag
            x1 = e.end.real
            y1 = e.end.imag
            print("(%.2f, %.2f) - (%.2f, %.2f)" % (x0, y0, x1, y1))


text:
Q: Getting user input for QGIS FieldCalculator parameters I'm trying to calculate and output a virtual field -- something that is a straightforward function of fields from a vector layer in QGIS 3. The FieldCalculator does the trick, but I need to manually specify parameters (e.g. coefficients in the function).
That's easy via FieldCalculator, but if I want others to use this calculation, what's the easiest way to prompt the user to input parameters?
A plugin seems like overkill for something this simple.

A: You can use the QGIS Model Designer for that, which is a powerful tool to make input dialogs for such tasks. Also the field calculator is available within the Model Designer:

The example above takes a vector layer and two numerical inputs and makes the sum of the two numerical inputs and write it into the field NewField, not very complex but shows the possibilities:

here is is a small video which explains the steps above: https://files.wheregroup.com/index.php/s/dKnZRibgymAe6oM


text:
Q: pandas contains exact string from a list I have 2 dataframes df1 and df2.
I would like to get all rows in df1 that has exact string match in column B of df2
This is df1:
df1={"columnA":['apple,cherry','pineple,lemon','banana, pear','cherry, pear, lemon']}
df1=pd.DataFrame(df1)

This is df2:
df2={"columnB":['apple','cherry']}
df2=pd.DataFrame(df2)

Below code output incorrect result:
df1[df1['columnA'].str.contains('|'.join(df2['columnB'].values))]

Pineapple is not supposed to appear as this is not exact match.
How can i get result like this:

A: Without actual reproducible code it's harder to help you, but I think this should work:
words = [rf'\b{string}\b' for string in df2.columnB]
df1[df1['columnA'].str.contains('|'.join(words))]

A: df1={"columnA":['apple,cherry','pineple,lemon','banana, pear','cherry, pear, lemon']}
df1=pd.DataFrame(df1)

df2={"columnB":['apple','cherry']}
df2=pd.DataFrame(df2)

Larger way of doing it ,but correct and simpler
list1=[]
for i in range(0,len(df1)):
    for j in range(0,len(df2)):
        if(df2["columnB"][j] in df1["columnA"][i]):
            list1.append(i)
            break
df=df1.loc[list1]

Answer
ColumnA
0   apple,cherry
3   cherry, pear, lemon

A: You were very close, but you will need to apply the word-operator of regex:
df1[df1['columnA'].str.contains("\b(" + '|'.join(df2['columnB'].values) + ")\b")]
This will look for the complete words.


text:
Q: Correct cursor position in Vim Consider this situation:
    foo
A   B

I just entered "foo" (notice the indent) and moved to the next line. The cursors is in position B. I'm done with editing and I hit Esc which brings my cursor to position A. How can I exit the insertion mode and keep the cursor at position B, or jump immedietly from A to B?
This vim's behavior is annoying when I'm editing something deep in a function, with few indents.

A: If you're at the end of the document, o will put you into insert mode at the correct indent level on the next line down. If you're on a row that contains nothing but a newline, cc will erase anything in the line and put you into insert mode at the correct indent level.


text:
Q: how to check if number in vector is ODD or EVEN Say you have:
vector <- c(1,2,3,4,5)

Using if else statements, and a for loop - how can I check if the number is ODD in the if statement?

A: Let's rename the vector (as vectoris a function) and define all odd numbers in a new vector oddand then subset vector1on those values that are contained in odd:
vector1 <- c(1,2,3,4,5)
odd <- c(1,3,5,7,9)
vector1[vector1 %in% odd]
[1] 1 3 5

If your vector contains multiple digit numbers, ou can use grepand regex to get the odd numbers:
vector2 <- c(1,27,32,44445,50,4,6666)
grep("\\d{0,}[13579]$", vector2, value = T)
[1] "1"     "27"    "44445"

You can use greplto test which numbers are odd:
grepl("\\d{0,}[13579]$", vector2)
[1]  TRUE  TRUE FALSE  TRUE FALSE FALSE FALSE

If you need to use an ifelse statement to find out which numbers are odd and which are even, you can do this:
ifelse(grepl("\\d{0,}[13579]$", vector2), TRUE, FALSE)
[1]  TRUE  TRUE FALSE  TRUE FALSE FALSE FALSE


text:
Q: Understanding what happens during apt-get update apt-cache search jdk returns zero results before apt-get update but several results after the update although the update output makes no mention of jdk installs. I am trying to find what I am missing.
I fire up a Ubuntu Docker container on the command line (docker run --rm -it ubuntu bash). A JDK search yields no results:
root@2bc9920836d1:/# apt-cache search jdk
root@2bc9920836d1:/#

I update:
root@2bc9920836d1:/# apt-get update
Get:1 http://security.ubuntu.com/ubuntu jammy-security InRelease [110 kB]
Get:2 http://archive.ubuntu.com/ubuntu jammy InRelease [270 kB]
Get:3 http://archive.ubuntu.com/ubuntu jammy-updates InRelease [109 kB]
Get:4 http://security.ubuntu.com/ubuntu jammy-security/main amd64 Packages [84.2 kB]
Get:5 http://security.ubuntu.com/ubuntu jammy-security/universe amd64 Packages [61.0 kB]
Get:6 http://archive.ubuntu.com/ubuntu jammy-backports InRelease [90.7 kB]
Get:7 http://archive.ubuntu.com/ubuntu jammy/universe amd64 Packages [17.5 MB]
Get:8 http://security.ubuntu.com/ubuntu jammy-security/restricted amd64 Packages [61.3 kB]
Get:9 http://archive.ubuntu.com/ubuntu jammy/multiverse amd64 Packages [266 kB]
Get:10 http://archive.ubuntu.com/ubuntu jammy/restricted amd64 Packages [164 kB]
Get:11 http://archive.ubuntu.com/ubuntu jammy/main amd64 Packages [1792 kB]
Get:12 http://archive.ubuntu.com/ubuntu jammy-updates/universe amd64 Packages [97.6 kB]
Get:13 http://archive.ubuntu.com/ubuntu jammy-updates/restricted amd64 Packages [68.6 kB]
Get:14 http://archive.ubuntu.com/ubuntu jammy-updates/main amd64 Packages [157 kB]
Fetched 20.8 MB in 56s (374 kB/s)
Reading package lists... Done

Then search for JDK:
root@2bc9920836d1:/# apt-cache search jdk
default-jdk - Standard Java or Java compatible Development Kit
default-jdk-doc - Standard Java or Java compatible Development Kit (documentation)
default-jdk-headless - Standard Java or Java compatible Development Kit (headless)
openjdk-11-dbg - Java runtime based on OpenJDK (debugging symbols)
openjdk-11-doc - OpenJDK Development Kit (JDK) documentation
...

Apparently, the JDK was installed during the update. But the output of update doesn't say anything anything to the effect of having installed a jdk. What am I missing here?
PS:
root@2bc9920836d1:/# cat /etc/issue
Ubuntu 22.04 LTS \n \l # Before and after update

root@2bc9920836d1:/#

A: apt-get update doesn't install anything.
It updates package lists. So it is expected. After you updated the list, you can see available packages.


text:
Q: Return remaining values when query returns no rows I have written a SQL query that will display the CourseId and Total Marks as shown below.
Scenario 1 and Scenario 2:
When I use WHERE CourseMarks.User_Id = 1 or WHERE CourseMarks.User_Id = 3 it returns results.
Scenario 3
However, it doesn't return any rows when using WHERE CourseMarks.User_Id = 2.
What I want to do is to display the UserName, UserId, and then use some default value (let's say 0) for Total marks. I have shown the expected output for Scenario 3 below.
Expected output:

This is the query I wrote:
SELECT
    User.Name, User.Id, CourseMarks.Id,
    SUM(CourseMarks.Marks) AS "Total marks"
FROM
    User
INNER JOIN
    Tutors ON User.TutorId = CourseMarks.Id
WHERE
    CourseMarks.User_Id = 2
GROUP BY
    CourseMarks.Id, User.id, User.Name

Database:

A: Seems like what you want is just a LEFT JOIN, if I am honest:
SELECT U.[Name],
       U.ID,
       ISNULL(SUM(CM.Marks),0) AS TotalMarks
FROM dbo.[User] U -- USER is a reserved keyword and should NOT be used for object names
     LEFT JOIN dbo.CourseMarks CM ON U.ID = CM.UserID
     --JOIN dbo.Tutors T ON U.TutorId = CM.ID --This isn't used in the query so I doubt it is needed.
                                              --Also joining on the value of the CourseMark's ID on the Tutor ID (in the User Table) literally makes no sense.
WHERE U.ID = 2
GROUP BY U.[Name],
         U.ID;


text:
Q: $\mathbb{P}^n_k$ is irreducible as a scheme How do I show that $\mathbb{P}^n_k$ is irreducible as a scheme? I am still quite confused with the definition by gluing affine schemes. I tried to show that nonempty open sets intersect, but got lost.

A: Actually, it's not a scheme question, it really is a topological one.
There are open subsets $U_0,\ldots,U_n$, all homeomorphic and irreducible (they're the $D(X_i) \cong \mathbb{A}^n_k$) with nonempty global intersection $V$ such that they cover $\mathbb{P}^n_k$.
Let $A,B \subset \mathbb{P}^n_k$ be nonempty open subsets.
Say, $A'=A \cap U_i \neq \emptyset$. Then $A'$ is a nonempty open subset of $U_i$ which is irreducible; moreover, $V \subset U_i$ is a nonempty open subset so $V \cap A'=V \cap A$ is nonempty.
Let $j$ be such that $B''=B \cap U_j$ is nonempty. Let $A'' = A \cap U_j \supset A \cap V$. Then $B'', A''$ are both nonempty open subsets of $U_j$ so they must meet; as $A \cap B \supset A'' \cap B''$, $A$ and $B$ meet and we are done.


text:
Q: System.InvalidOperationException: 'Nullable object must have a value.' I'm only starting my adventure with programming, and currently im working on a e-commerce type of aplication in mvc. Recently i tried to make it possible to apply more then one photo and since then i have problems with controller that after clicking on the card was redirecting user to the product page. After click the error appears "System.InvalidOperationException: 'Nullable object must have a value.'" and it points to the values that have "null" value in database, but are not required and before it worked well, also it started showing a page with information that controller could not be found.
Below im showing my code. Thank you everyone in advance.
View
@model roomie.Models.Adviewmodel

@Styles.Render("~/Content/view_ad.css")
@Styles.Render("~/Content/layout.css")

<meta name="viewport" content="width=device-width" />

<title>ViewAd</title>

 <p2> @Model.pro_name </p2>

 <p3> AD-ID: @Model.pro_id </p3>

                @foreach (var image in Model.pro_img_path)
                {

                }

            <p4> Opis: </p4>

 @Model.pro_description

  Cena: 	  @Model.pro_price

  Kategoria: 	  @Model.pro_type

  Adres: 	  @Model.nazwa_miasta, @Model.pro_address_street @Model.pro_address_building_num, Piętro: @Model.pro_address_floor

  Kontakt: 	  @Model.user_contact

 <p4> Co w mieszkaniu: </p4>

                    @if (@Model.pro_TV == true)
                    {

                    }

                    @if (@Model.pro_ac == true)
                    {

                    }

                    @if (@Model.pro_elevator == true)
                    {

                    }

                    @if (@Model.pro_handicapped == true)
                    {

                    }

                    @if (@Model.pro_internet == true)
                    {

                    }

                    @if (@Model.pro_parking == true)
                    {

                    }

                    @if (@Model.pro_pet == true)
                    {

                    }

                    @if (@Model.pro_smoking == true)
                    {

                    }

    @if (Convert.ToInt32(Session["user_id"]) == Convert.ToInt32(Model.pro_fk_user))
    {

        @Html.ActionLink("Close this Ad", "DeleteAd", new { @class = "button", id = Model.pro_id })
    }
    else
    {

 Ogłoszenie opublikowane przez:

                    @if (String.IsNullOrEmpty(Model.user_image))
                    {

                    }
                    else
                    {

                    }

  Użytkownik: 	  @Model.user_name

  Kontakt: 	  @Model.user_contact

  O użytkowniku: 	  @Model.user_description

                            @if (Model.user_smoke == true)
                            {

                            }

                            @if (Model.user_pet == true)
                            {

                            }

    }

Model
namespace roomie.Models
{
public class Adviewmodel
{

    public int pro_id { get; set; }
    public string pro_name { get; set; }
    public string pro_image { get; set; }
    public string pro_address_street { get; set; }
    public int pro_address_building_num { get; set; }
    public int pro_address_floor { get; set; }
    public int pro_price { get; set; }
    public string pro_description { get; set; }
    public string pro_type { get; set; }
    public int pro_room_size { get; set; }
    public int pro_room_num { get; set; }
    public int pro_bathroom_num { get; set; }
    public int pro_roommates { get; set; }
    public string pro_room_gender { get; set; }
    public bool pro_TV { get; set; }
    public bool pro_internet { get; set; }
    public bool pro_ac { get; set; }
    public bool pro_parking { get; set; }
    public string pro_heating { get; set; }
    public bool pro_elevator { get; set; }
    public bool pro_balcony { get; set; }
    public bool pro_handicapped { get; set; }
    public bool pro_smoking { get; set; }
    public bool pro_pet { get; set; }
    public int pro_prefe_gender { get; set; }

    public int pro_fk_user { get; set; }
    public int user_id { get; set; }
    public string user_name { get; set; }
    public string user_image { get; set; }
    public string user_contact { get; set; }
    public string user_description { get; set; }
    public bool user_smoke { get; set; }
    public bool user_pet { get; set; }

    public int pro_fk_address_city { get; set; }
    public string nazwa_miasta { get; set; }
    public string nazwa_województwa { get; set; }

    public IEnumerable<string> pro_img_path { get; set; }
    public IEnumerable<string> pro_img_fk_pro_id { get; set; }
}

}
Controller
 public ActionResult ViewAd(int id)
    {
        Adviewmodel ad = new Adviewmodel();

        tbl_product p = db.tbl_product.Where(x => x.pro_id == id).SingleOrDefault();
        ad.pro_id = p.pro_id;
        ad.pro_name = p.pro_name;
        //ad.pro_fk_images = p.pro_fk_images;
        //ad.pro_fk_address_city = p.pro_fk_address_city;
        ad.pro_address_street = p.pro_address_street;
        ad.pro_address_building_num = (int)p.pro_address_building_num;
        ad.pro_address_floor = (int)p.pro_address_floor;
        ad.pro_price = (int)p.pro_price;
        ad.pro_description = p.pro_description;
        ad.pro_type = p.pro_type;
        ad.pro_room_size = (int)p.pro_room_size;
        ad.pro_room_num = (int)p.pro_room_num;
        ad.pro_roommates = (int)p.pro_roommates;
        ad.pro_TV = (bool)p.pro_TV;
        ad.pro_internet = (bool)p.pro_internet;
        ad.pro_ac = (bool)p.pro_ac;
        ad.pro_parking = (bool)p.pro_parking;
        ad.pro_heating = p.pro_heating;
        ad.pro_elevator = (bool)p.pro_elevator;
        ad.pro_balcony = (bool)p.pro_balcony;
        ad.pro_handicapped = (bool)p.pro_handicapped;
        ad.pro_smoking = (bool)p.pro_smoking;
        ad.pro_pet = (bool)p.pro_pet;
        //ad.pro_prefe_gender = (int)p.pro_prefe_gender;

        tbl_user u = db.tbl_user.Where(x => x.user_id == p.pro_fk_user).SingleOrDefault();
        ad.user_name = u.user_name;
        ad.user_image = u.user_image;
        ad.user_contact = u.user_contact;
        ad.pro_fk_user = u.user_id;

        tbl_wojewodztwa_miasta wm = db.tbl_wojewodztwa_miasta.Where(x => x.id == p.pro_fk_address_city).SingleOrDefault();
        ad.nazwa_miasta = wm.nazwa_miasta;
        ad.nazwa_województwa = wm.nazwa_województwa;

        ad.pro_img_path = Directory.EnumerateFiles(Server.MapPath("~/ Content / user_upload")).Select(x => "~/ Content / user_upload" + Path.GetFileName(x));

        return View(ad);
    }

Okay, so i solved my issue, i don't know will it be any help to someone.
In the Model and Controller i added the "?" to the int values that were not required.


text:
Q: Possible for templates to calculate largest order of magnitude for N-dimensional grid storage and operations? Disclaimer: this is for hobby development - I wouldn't over-engineer this much in a professional endeavor unless asked to do so.
Imagine an N-dimensional surface, such as a line (1D), grid/circle (2D), cube/sphere (3D), etc., where each axis of this surface is finite in that it has a start and end, or wraps around.  A good example is the Earth, where there is longitude (wraps around), latitude (starts and ends), and if necessary, height and time (assume a specific start/end for these).
The generalized structure to handle this scenario could be something like this:
typedef NoAxis End;
typedef Axis<End>::NoWrap<0, 365> Time; // one year, if units are in days
typedef Axis<Time>::NoWrap<0, 35000> Height; // sea level to 35k meters
typedef Axis<Height>::NoWrap<-90, 90> Latitude;
typedef Axis<Latitude>::Wrap<-180, 180> Longitude;

The "Axis" class takes a template parameter that is the next axis; this forms a chain of axes, where a special type "NoAxis" begins the chain.  Geometric operations, e.g. finding the distance between two points, are performed by accumulating the calculations for each axis.
My question: is there a way, preferably via template metaprogramming, to programatically find the largest order of magnitude that could be multiplied to the extrema of each axis - the idea being to maximize the surface resolution - but not overflow the storage for the type used to contain the values (e.g. don't overflow 32 bits on a 32-bit system, etc.).  This order of magnitude must take into account calculating the distance between points on the surface, which involves finding the squared distance.
Once again, the reason to find this order of magnitude is to get the highest resolution possible for a given storage type.


text:
Q: Problem with running React Native app with WebStorm I cloned a git repository React Native app. I'm using WebStorm on Mac and I am having this issue when I try to build it.

CompileC /Users/lediomalaj/Library/Developer/Xcode/DerivedData/AirbnbClone-grlvfcjfyepxacbsfheikfltqqow/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Flipper-Folly.build/Objects-normal/x86_64/DistributedMutex.o /Users/lediomalaj/AirbnbClone/ios/Pods/Flipper-Folly/folly/synchronization/DistributedMutex.cpp normal x86_64 c++ com.apple.compilers.llvm.clang.1_0.compiler (in target 'Flipper-Folly' from project 'Pods')
(1 failure)

Anyone could help?


text:
Q: Display by default the name in an autocomplete field with his id in hidden field I tried to use a field city with autocomplete. I use twitter bootstrap style and function typeahead but I do not know if my work is good.
For my example, I have 2 entities: Person and City (with approximately 37,000 communes of France).
The Person entity has a OneToMany relationship with the City field Birthplace.
So I create a hidden field type city_typeahead to add a DataTransformer "CityToIdTransformer" to persist an object from the City id sent by the form.
Until then, the autocomplete works perfectly for the creation and editing.
However, in the edit form, I want to show in the autocomplete field the name of the city registered in my hidden field.And this is where I stuck.
I thought trying with a listener, but I'm not sure of the solution to apply. If someone could guide me I shall be grateful.
Thank you.
Edit : I did similar test with autocomplete field country and I arrived after several test.
I create a listener that checks if the hidden field has a value and from it I get the name and load my field autocomplete.
I do not know if the method is clean, but it works, my autocomplete field now displays the name of the country on edit form.
FormType :
<?php

namespace Myapp\PersonBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

use Myapp\PersonBundle\Form\EventListener\AddNationalitySearchSubscriber;

class PersonType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('firstname')
            ->add('lastname')
            ->add('nationality', 'country_typeahead', array(
                'attr' => array('class' => 'country-toset'),
                'required' => false))
            ->add('nationality_search','text', array(
            'attr' => array(
                'class' => 'country-tosearch',
                'name' => 'term',
                'autocomplete' => true,
            'required' => false,
            'mapped' => false));

        $builder->addEventSubscriber(new AddNationalitySearchSubscriber());
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Myapp\PersonBundle\Entity\Person'
        ));
    }

    public function getName()
    {
        return 'person_person_type';
    }
}

Script js in view :
<script type="text/javascript">
            $('.country-tosearch').typeahead({
                source: function(query, process){
                    $.ajax({
                        url: "/ajax/country",
                        type: "post",
                        data: "term="+query,
                        dataType: "json",
                        async: false,
                        success: function(data){
                            countries = []
                            mapped = {}
                            $.map(data, function(country, i){
                                mapped[country.name] = country;
                                countries.push(country.name);
                            });
                            process(countries);
                        }
                    })
                },
                minLength: 3,
                property: 'enriched',
                items:15,
                updater: function (obj) {
                    if(mapped[obj].id){
                        $('.country-toset').val(mapped[obj].id);
                    }
                    return mapped[obj].name;
                }
            });
        </script>

DataTransformer :
<?php
namespace Myapp\PersonBundle\Form\DataTransformer;

use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;
use Doctrine\Common\Persistence\ObjectManager;

use Myapp\GeoBundle\Entity\Country;

class CountryToIdTransformer implements DataTransformerInterface
{
    /**
     * @var ObjectManager
     */
    private $om;

    /**
     * @param ObjectManager $om
     */
    public function __construct(ObjectManager $om)
    {
        $this->om = $om;
    }

    /**
     * Transforms an object (country) to a string (id).
     *
     * @param  Country|null $country
     * @return string
     */
    public function transform($country)
    {
        if (null === $country) {
            return "";
        }

        return $country->getId();
    }

    /**
     * Transforms a string (id) to an object (country).
     *
     * @param  string $id
     * @return Country|null
     * @throws TransformationFailedException if object (country) is not found.
     */
    public function reverseTransform($id)
    {
        if (!$id) {
            return null;
        }

        $country = $this->om
            ->getRepository('MyappGeoBundle:Country')->findOneBy(array('id' => $id))
        ;

        if (null === $country) {
            throw new TransformationFailedException(sprintf(
                'A country with id "%s" does not exist!',
                $id
            ));
        }

        return $country;
    }
}

the listener :
<?php

namespace Myapp\PersonBundle\Form\EventListener;

use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class AddNationalitySearchSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return array(FormEvents::PRE_SET_DATA => 'preSetData');
    }

    public function preSetData(FormEvent $event)
    {
        $country = '';
        $data = $event->getData();
        $form = $event->getForm();

        if (null === $data) {
            return;
        }

        if ($data->getNationality()) {
            $country = $data->getNationality();
        }

       $form->add('nationality_search','text', array(
            'attr' => array(
                'class' => 'country-tosearch',
                'name' => 'term',
                'autocomplete' => true,
            'data' => $country,
            'required' => false,
            'mapped' => false));
    }
}


text:
Q: What is the root word of "unforgivable"? I'm learning about morphology and got confused by the word "unforgivable" when identifying its root. Is it "forgive" or "give"? Thanks for your help!

A: The root is forgive (From Old English forgiefan : for + giefan)
Unforgivable:

1549s from un (not) + forgivable.

Forgivable:

forgive +able

(Etymonline)

A: OED:

Forgive (v.) Etymology: Old English forgiefan ( < for- prefix[1] + giefan : see give v.)

The sense of "for" is quite difficult to understand as it has a variety of effects upon its verb: in this case, it is probably

b. With the sense of prohibition, exclusion, or warding off, as in forbid n.   Also with the sense of concealing from view:


text:
Q: How to add validation attributes to md-autocomplete angular material directive I'm using version 0.7.1 of angular material. I'm using the autocomplete as described here:
Autocomplete demo
However, it doesn't seem to support validation logic, even though it generates a textarea:
Autocomplete directive documentation
I imagine that I can add logic in the querySearch function to switch ng-valid to ng-invalid. Is this correct? If this is the case, then I need a handle on the md-autocomplete, but this is difficult, because the name attribute gets removed.

A: Quick update, got the solution on Angular Material site (Latest release 1.0.0-),
https://material.angularjs.org/latest/demo/autocomplete.
You will find that 'required' and 'ng-messages' are supported now.

<md-content class="md-padding">
<form ng-submit="$event.preventDefault()" name="searchForm">

The following example demonstrates floating labels being used as a normal form element.

    <md-input-container flex>
      Name
      <input type="text"/>
    </md-input-container>
    <md-autocomplete flex required
        md-input-name="autocompleteField"
        md-input-minlength="2"
        md-input-maxlength="18"
        md-no-cache="ctrl.noCache"
        md-selected-item="ctrl.selectedItem"
        md-search-text="ctrl.searchText"
        md-items="item in ctrl.querySearch(ctrl.searchText)"
        md-item-text="item.display"
        md-floating-label="Favorite state">
      <md-item-template>
        {{item.display}}
      </md-item-template>

You must have a favorite state.

Your entry is not long enough.

Your entry is too long.

    </md-autocomplete>

</form>

A: Read documentation
you need these options

You can use above as below to run yr custom validation :
Update yr template as below
 template:'yr msg here<md-autocomplete\
               md-no-cache="noCache"\
               md-selected-item="selectedItem"\
               md-search-text="searchText"\
               md-items="item in querySearch(searchText)"\
               md-item-text="item.display"\
               placeholder="search query"\
               md-selected-item-change="validate2(searchText)"\
               md-search-text-change="validate(searchText)">\
               {{item.display}}\
             </md-autocomplete>'

and add following yr md-auto-complate controller
$scope.validationCheck=false;
  $scope.validate=function(data){
    $scope.validationCheck=true;
    console.log('validation : '+data);
  }
  $scope.validate2=function(data){
    console.log('validation2 :'+data);
  }

A: I was working with same approach with the form validation using auto-complete in angular materials.But unfortunately, validation on this directive is not so smooth as input components. So I made up my mind to overcome this issue and did some R&D for this component. Please find below code snippets and they will help you out on this.
HTML:

<md-content class="md-padding">
<form ng-submit="$event.preventDefault()" name="registerForm" novalidate>

Use md-autocomplete to search for matches from local or remote data sources.

  <md-autocomplete md-input-name="Country" ng-disabled="ctrl.isDisabled" md-no-cache="ctrl.noCache" md-selected-item="ctrl.selectedItem" md-search-text-change="ctrl.searchTextChange(ctrl.searchText)" md-search-text="ctrl.searchText" md-selected-item-change="ctrl.selectedItemChange(item)" md-items="item in ctrl.querySearch(ctrl.searchText)" md-item-text="item.display" md-min-length="0" placeholder="What is your favorite US state?" ng-class="{'validate': registerForm.Country.$touched && !vm.country1}">
    <md-item-template>
      {{item}}
    </md-item-template>
    <md-not-found>
      No states matching "{{ctrl.searchText}}" were found.
      Create a new one!
    </md-not-found>
  </md-autocomplete>

      Country field is required

      Please enter valid Country

  <md-button class="medium-button success-button" aria-label="submit" ng-disabled="registerForm.$invalid || registerForm.$pristine || !ctrl.country1" ng-click="ctrl.registerUser()">
    Submit
  </md-button>
</form>
</md-content>

SCRIPT:
(function () {
'use strict';
angular
  .module('MyApp',['ngMaterial', 'ngMessages', 'material.svgAssetsCache'])
  .controller('DemoCtrl', DemoCtrl);

function DemoCtrl ($timeout, $q, $log) {
var self = this;

self.simulateQuery = false;
self.isDisabled    = false;

// list of `state` value/display objects
self.states        = loadAll();
self.querySearch   = querySearch;
self.selectedItemChange = selectedItemChange;
self.searchTextChange   = searchTextChange;

self.newState = newState;

 function newState(state) {
  alert("Sorry! You'll need to create a Constituion for " + state + " first!");
}

function querySearch (query) {
  var results = query ? self.states.filter( createFilterFor(query) ) : self.states,
      deferred;
  if (self.simulateQuery) {
    deferred = $q.defer();
    $timeout(function () { deferred.resolve( results ); }, Math.random() * 1000, false);
    return deferred.promise;
  } else {
    return results;
  }
}

function searchTextChange(text) {
  //$log.info('Text changed to ' + text);
  if(text)
    self.country1 = text.match(/^[a-zA-Z0-9\_\- ]*$/);
  else
    self.country1 = '';

  if (text)
    self.country = text;

  $log.info('Item changed to ' + self.country1);
}

function selectedItemChange(item) {
  if(item)
    self.country1 = item.match(/^[a-zA-Z0-9\_\- ]*$/);
  else
    self.country1 = '';

  if (item)
    self.country = item;

  $log.info('Item changed to ' + self.country1);
}

/**
 * Build `states` list of key/value pairs
 */
function loadAll() {
  var allStates = 'Alabama, Alaska, Arizona, Arkansas, California, Colorado, Connecticut, Delaware,\
          Florida, Georgia, Hawaii, Idaho, Illinois, Indiana, Iowa, Kansas, Kentucky, Louisiana,\
          Maine, Maryland, Massachusetts, Michigan, Minnesota, Mississippi, Missouri, Montana,\
          Nebraska, Nevada, New Hampshire, New Jersey, New Mexico, New York, North Carolina,\
          North Dakota, Ohio, Oklahoma, Oregon, Pennsylvania, Rhode Island, South Carolina,\
          South Dakota, Tennessee, Texas, Utah, Vermont, Virginia, Washington, West Virginia,\
          Wisconsin, Wyoming';

  return allStates.split(/, +/g).map( function (state) {
    return state;
  });
}

/**
 * Create filter function for a query string
 */
function createFilterFor(query) {
  var lowercaseQuery = angular.lowercase(query);

  return function filterFn(state) {
    return (state.value.indexOf(lowercaseQuery) === 0);
  };

  }
 }
})();

See the full example of codepen here

A: It seems that I am not the only one to find this tricky. There will be a solution to this soon:
Autocomplete validation improvements in progress


text:
Q: Heteroscedasticity in Linear Regression I implemented a linear regression model on some dataset. When I plotted the scatter plot of residual v/s predicted y (i.e., yhat), I observed heteroscedasticity in the plot. What can I do about it?
x-axis -> yhat
y-axis -> Residual

A: Before doing anything about heteroscedasticity, first you must establish whether it even exists.
The scatterplot in the question is not evidence of heteroscedasticity.
"Heteroscedasticity" refers to any important variation in the dispersion of one variable (here plotted on the vertical axis) when another variable (here plotted on the horizontal axis) is varied.
The problem with this plot is that it does not enable us to make accurate estimates of the dispersion.  The reason why not is that because there are so many points, essentially all we can see are the ranges of the vertical variable, but the range is both a highly unstable estimate of dispersion as well as dependent on the amount of data.  As you scan left to right across this plot, it is possible for there to be much, much more data in the middle compared to the ends.  That can give rise to a false impression of greater dispersion of $y$ for middling $x$-values.
To illustrate this problem, I generated 400,000 $(x,y)$ values where the coordinates are independent--and therefore $y$ is as homoscedastic (non-heteroscedastic) as possible.
n <- 4e5
x <- pmax(-8, pmin(8, abs(rnorm(n, sd=7/6))^1.25 * sample(c(-1,1), n, replace=TRUE)))
y <- sample(c(-1,1), n, replace=TRUE) * rgamma(n, 1/3, 1/20)

Whether or not you are familiar with R (the language used for this simulation), it should be apparent that the x values and y values have been separately generated.  But here's their scatterplot, shown using the overplotting method of the question:

It sure looks like the y-values are spread out less near the extremes than in the middle, doesn't it?  This mistaken impression is the cause of many related questions (and incorrect answers) on this site.
A better way to look at heteroscedasticity is to split the $x$ values into groups and robustly estimate the dispersion of each group.  There are many ways to do this.  John Tukey observed that generally there's not a whole lot going on in the middle of a batch of data: the interesting changes tend to occur out in the extremes.  In his "wandering schematic plot" he proposed splitting the $x$ data (essentially) into the most extreme halves, quarters, eighths, and so on, and plotting some of the extremes of the $y$ values found within each such group.  This leads to a quick, simple plot.

The vertical bars in this figure demark the boundaries between the groups of $x$ values used to estimate the dispersion of the corresponding $y$ values.  Thus, the middle half of all points falls within the two vertical strips surrounding $x=0.$ (Each of those strips contains about 100,000 points.)  Thereafter, as you move away from $0,$ each vertical strip includes one-half as many points as previously.  Ultimately the outer strips (roughly from $x=-8$ to $-5.4$ and $x=5.4$ to $8$) contain only $200$ points each.
The horizontal black graphs trace out the 1%, 5%, 25%, 50%, 75%, 95%, and 99% quantiles of the corresponding $y$ values.  We can't distinguish the middle quantiles because they are so close, but it's nevertheless clear that these "wandering traces" are essentially horizontal.  This shows, contrary to what the original figure suggested, that the dispersion of $y$ does not appreciably vary with $x.$  Indeed, it shows that the entire (conditional) distribution of $y$ appears to be independent of $x.$  That's what you're looking for when you assess the relationship between regression residuals and predicted values.
What does heteroscedasticity look like?  Here's an example.  The preceding $y$ values were divided by the larger of $1$ and $x^2,$ thereby reducing their dispersion (greatly) near the extremes of $x.$  The schematic traces are no longer horizontal: they contract towards the left and right to reflect the decreasing dispersion with large values of $x.$

(This time I plotted only a random sample of 10,000 points, because plotting all 400,000 requires a wait.   But the traces are based on all 400,000 points.)
Finally, I suspect you might be correct that there is heteroscedasticity: but before we can say anything about what to do, it still needs to be represented clearly, quantified, and accurately characterized.  Creating a wandering schematic plot or one of its newer variants (such as quantile regression) would be a good first step.

References
For an example of the wandering schematic plot used to diagnose heteroscedasticity, see https://stats.stackexchange.com/a/166267/919.  Other examples of this plot can be found at https://stats.stackexchange.com/a/106083/919 (with working R code) and Measures of residuals heteroscedasticity (also with code).
Tukey describes this method in his book Exploratory Data Analysis (Addison-Wesley 1977).  He provides many more ways to depict and diagnose heteroscedasticity, as well as methods to "cure" it, such as Box-Cox transformations.

A: The existence of heteroscedasticity gives rise to certain problems in the regression analysis as the assumption says that error terms are uncorrelated and, hence, the variance is constant. The presence of heteroscedasticity can often be seen in the form of a cone-like scatter plot for residual vs fitted values.
One of the basic assumptions of linear regression is that heteroscedasticity is not present in the data. Due to violation of the assumptions, the Ordinary Least Squares (OLS) estimators are not the Best Linear Unbiased Estimators (BLUE). Hence, they do not give the least variance than other Linear Unbiased Estimators (LUEs).
There is no fixed procedure to overcome heteroscedasticity. However, there are some ways that may lead to the reduction of heteroscedasticity. They are —
Logarithmising the data: A series that is increasing exponentially often results in increased variability. This can be overcome using the log transformation.
Using weighted linear regression: Here, the OLS method is applied to the weighted values of X and Y. One way is to attach weights directly related to the magnitude of the dependent variable.


text:
Q: listView builder inside listview builder is not updating list value on button click I have a dropdown menu that adds a Container in list  with onChange function, which is displayed by listview.builder, and this container has another ListView.builder this second list view builder has a list listParticipantsSelected displayed and a button that adds some value to a list listParticipantsSelected.add("some value");that is displayed in the second ListView.builder. when I click this button it adds the value but does not show it in the second list view builder when I remove the whole container and add it again from the dropdown it shows the added value but not instantly.
 list.add(Container());

This list shown on main listview builder
second list view builder code here
ListView.builder(
    itemCount: listParticipantsSelected.length,
    itemBuilder: (BuildContext context, int index) {
      return GestureDetector(
        onTap: (){
          setState(
                () {
              listParticipantsSelected.add("some value");
            },
          );
        },
        child: Container(
          child: Row(
            children: [
              Text(listParticipantsSelected[index])
            ],
          ),
        ),
      );
    });

In this second list view builder hot reload is also not working I have to hit hot restart.
I need to update the inner list instantly.
I tried with the set state but it is not working. I am confused where I am missing something.
Edited : Build method : It is a long file but related code is here
Widget build(BuildContext context) {
return Scaffold(
  body: Form(
    autovalidateMode: AutovalidateMode.onUserInteraction,
    child: ListView(
      children: [
        Center(
          child: SizedBox(
            width: 500,
            child: Column(
              children: [
                Container(
                  child: DropdownButtonHideUnderline(
                    child: DropdownButton(
                      isExpanded: true,
                      value: "initial value",
                      icon: const Icon(Icons.keyboard_arrow_down),
                      items: elements.map((String items) {
                        return DropdownMenuItem(
                          value: items,
                          child: Text(items),
                        );
                      }).toList(),
                      onChanged: (String? newValue) {
                        if (newValue == 'Participants') {
                          list.add(Container(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Container(
                                  height: 100,
                                  child: ListView.builder(
                                      itemCount: listParticipantsSelected.length,
                                      itemBuilder: (BuildContext context, int index) {
                                        return GestureDetector(
                                          onTap: () {
                                            setState(() {listParticipantsSelected.add("some value");},
                                            );
                                          },
                                          child: Container(
                                            child: Row(
                                              children: [
                                                Icon(Icons.account_circle_rounded),
                                                Text(listParticipantsSelected[index])
                                              ],
                                            ),
                                          ),
                                        );
                                      }),
                                ),
                                Row(
                                  children: [
                                    Expanded(child: Container()),
                                    Container(
                                      margin: EdgeInsets.only(top: 100),
                                      child: TextButton(
                                        onPressed: () {
                                          showDialog(
                                            context: context,
                                            builder: (BuildContext context) {
                                              return AlertDialog(
                                                content: Column(
                                                  children: <Widget>[
                                                    Row(
                                                      children: [
                                                        IconButton(icon: const Icon(Icons.close), // clear text
                                                          onPressed: () {Navigator.pop(context);},
                                                        ),
                                                      ],
                                                    ),
                                                    Expanded(
                                                      child:
                                                          ListView.builder(
                                                              itemCount: listParticipants.length,
                                                              itemBuilder: (BuildContextcontext, int index) {
                                                                return GestureDetector(
                                                                  onTap: () {
                                                                    setState(() {listParticipantsSelected.add(listParticipants[index]);},);
                                                                  },
                                                                  child:
                                                                      Container(
                                                                    child: Row(
                                                                      children: [
                                                                        Icon(Icons.account_circle_rounded),
                                                                        Text(listParticipants[index])
                                                                      ],
                                                                    ),
                                                                  ),
                                                                );
                                                              }),
                                                    )
                                                  ],
                                                ),
                                              );
                                            },
                                          );
                                        },
                                        child: Text('Add'),
                                      ),
                                    )
                                  ],
                                ),
                              ],
                            ),
                          ));
                        }
                      },
                    ),
                  ),
                ),
                const SizedBox(height: 20),
                Container(
                  height: 400,
                  child: ListView.builder(
                    itemCount: list.length,
                    itemBuilder: (BuildContext context, int index) {
                      return list[index];
                    },
                  ),
                ),
              ],
            ),
          ),
        ),
      ],
    ),
  ),
);

}
      var elements = [
    'initial value',
    'Participants',
  ];
  List listParticipantsSelected = ["Name of member"];
  List<Widget> list = [];

  List listParticipants = [
    "Name of member",
    "Name of member"
        "Name of member"
        "Name of member"
        "Name of member"
  ];

A: Seems like you were just missing to call setState end of onChanged
child: DropdownButton(
  ....
  onChanged: (String? newValue) {
    if (newValue == 'Participants') {
         list.add(Container(..);

          setState(() {}); //this


text:
Q: Get Max item in jinja2 groupby? I am trying to get the max item from a groupby statement in jinaj2.
For example
from flask import Flask, render_template
app = Flask(__name__)

@app.route('/')
def index():
    data = [
        {'var': 1, 'var2': 2},
        {'var': 2, 'var2': 2},
        {'var': 3, 'var2': 2},
        {'var': 1, 'var2': 4},
        {'var': 2, 'var2': 4},
        {'var': 3, 'var2': 4},
    ]
    return render_template('test.html', data=data)

if __name__ == '__main__':
    app.run(debug=True)

{% for group in data|groupby('var2') %}
 {{ group.grouper }}

{% endfor %}

This just prints
2
4

I would like it to just print 4.
This sort of works
{% set l = [] %}
{% for group in data|groupby('var2') %}
 {{l.append(group.grouper)}}

{% endfor %}
{{ l|max}}

But it prints
None
None
4

A: You can add do extension in the environment of Jinja2 in your flask app.
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def index():
    data = [
        {'var': 1, 'var2': 2},
        {'var': 2, 'var2': 2},
        {'var': 3, 'var2': 2},
        {'var': 1, 'var2': 4},
        {'var': 2, 'var2': 4},
        {'var': 3, 'var2': 4},
    ]

    app.jinja_env.add_extension("jinja2.ext.do")

    return render_template('test.html', data=data)

if __name__ == '__main__':
    app.run(debug=True)

{% set l = [] %}
{% for group in data | groupby("var2") %}
    {% do l.append(group.grouper) %}
{% endfor %}
{{ l | max }}

Or you can do groupby and max in view function and pass the max item to the template file directly.

A: You can define your own filter in your Flask app and then call that filter in your HTML template like the one below. Take note, the function name you created must be the same as the filter name.
@app.route('/')
def index():
    data = [
        {'var': 1, 'var2': 2},
        {'var': 2, 'var2': 2},
        {'var': 3, 'var2': 2},
        {'var': 1, 'var2': 4},
        {'var': 2, 'var2': 4},
        {'var': 3, 'var2': 4},
    ]
    return render_template('test.html', data=data)

@app.template_filter()
def maximum(_list):
    try:
        return max(_list)[0]
    except Exception as e:
        print(str(e))

test.html
{{ data|groupby('var2')|maximum }}


text:
Q: Why is there a "there" when Dickens say "After that there gallop from Temple Bar"? In Book 1, Chapter 2 of A tale of two cities, Dickens wrote the following:

"After that there gallop from Temple Bar, old lady, I won't trust your fore-legs till I get you on the level," said this hoarse messenger, glancing at his mare.

In the story, the messenger had just gotten the message and ridden the horse from Temple Bar. The sentence seems perfectly interpretable without the word "there", going as "After that gallop from Temple Bar, I won't trust your fore-legs till I get you on the level."
I am not sure what the word "there" is meant for. To me, it makes the sentence seems very unnatural.
But as I searched around, nobody seems to be taking notice of it.
One potential reason I thought about is that "there" is meant for exclamation, and conveying a similar meaning as in "After that gallop there from Temple Bar".
I am not sure whether it is a common practice, though. I am not a native speaker. I tried searching for similar usages, and the only likely candidate I found is here.

Some dog gone bit that there kitty, and he don't take that from nobody.

The writer explained that this is nonstandard grammar, but I don't know where I may be able to find any reference for this nonstandard grammar.

A: There is a nice entry on the subject on the Grammarphobia Blog, dated June 9, 2012 that states, in part:

The English essayist and poet Samuel Taylor Coleridge complained in the mid-19th century that uneducated British speakers were committing the same misdemeanor.
In a treatise on grammar in the Encyclopaedia Metropolitana: Or, Universal Dictionary of Knowledge (1845), Coleridge criticized the redoubling of word elements "for the sake of emphasis, which is a habit common to barbarous nations, and to the illiterate in all countries."
And he meant all countries. Coleridge didn't exempt the English, grumbling that "our own rustics commonly say this here, that there." This usage (at least in English) is still considered rustic today.
As Merriam-Webster's Dictionary of English Usage says: "Our evidence from published sources shows that writers in general have no need to be told that this here and that there are something less than standard English."
"The use of here and there for emphasis following a demonstrative adjective is a characteristic of dialectal and uneducated speech," M-W continues. "It does not occur in writing except when such speech is being recorded, evoked, or imitated."

More than likely, Dickens made that word choice to give definition to the character of Jerry.


text:
Q: how to work with collections implementing IReduceInit The plan function of next.jdbc returns collections which implement IReduceInit, what does that mean ? Trying to wrap my head around it, what is the difference between having a regular collection and then applying transducers to it, rather than having a coll which implements the above interface.
Also how do you work with a coll which implements the above interface, cant find any material on it.
In the below code -
(def results (jdbc/plan @datasource2 ["select * from cabs"]))

(into [] (map :name) results) => ["a", "b"]

(into [] (map identity) results) => gives an error - [..... missing `map` or `reduce` {row}]

Why does the first transducer work while the second one fails ?

A: identity simply returns its argument without touching it so (map identity) doesn't "touch" the rows and they are not realized.
jdbc/plan requires that each row be "touched" to either select elements from it (which does not realize a Clojure data structure, it simply extracts fields from the current row of the underlying ResultSet), or to force realization through various hash map operations: assoc, cons (which implicitly calls seq), dissoc, iterator, seq, etc.
This is not just about collections and IReduceInit -- jdbc/plan adds an additional layer which is the "lazy" representation of the current row of the underlying mutable ResultSet object.


text:
Q: Save data to file and close window on single button click I've got some data i need to save to a file. On a button click i need to save it and then close the window. However when i call a save() function and a close() function the window will close without having saved anything.
I have tried calling two functions on an event. I have tried creating one function where the data is saved and then window is closed.
const button = document.getElementById('done');
button.addEventListener('click', () => {
  closeWin();
});

function closeWin(){
  saveData();
  const remote = require('electron').remote;
  var window = remote.getCurrentWindow();
  window.close();
}

function saveData(){
  const fs = require('fs');
  fs.writeFile('data.txt', 'Test Data Output', function (err) {
    if (err) throw err;
  });
}

Expected: Data saved to file (txt in this case)
Output: Window closed and blank file created with no data

A: For the save function you should either return a promise, or callback, or use writeFileSync(not recommended);
Using Promise:
function saveData() {
  return new Promise((res, rej) => {
    fs.writeFile('data.txt', 'Test Data Output', function (err) {
      if (err) return rej(err);
      res();
    });
  })
}

then close the window, you can use async-await here also:
function closeWin() {
  saveData()
  .then(()=>{
    const remote = require('electron').remote;
    var win= remote.getCurrentWindow();
    win.close();
  })
}

Async-await version:
async function closeWin() {
  await saveData();
  const remote = require('electron').remote;
  var win= remote.getCurrentWindow();
  win.close();
}

A: Try to use callback:
function saveData(callback) {
// Write code for save your data here
  callback();
}
function closeWin(callback) {
  callback();
 }

closeWin( function() {
 saveData(function() {
   const remote = require('electron').remote;
   var win= remote.getCurrentWindow();
   win.close();
 });

});


text:
Q: can I reform an array with push values / hash data in PHP My php code is here:
    $ora_result = ora_submit_query($ora_conn, $sql);

if ($ora_result) {
      while ($row = oci_fetch_array($ora_result, OCI_BOTH)) {
      print_r($row[0]." ".$row[1]." ".$row[2]."\n");
  }

And I got a result like this
=============================
2018-06-09 item1 73.8
2018-06-09 item2 83.2
2018-06-09 item3 83.2
2018-06-10 item4 33.1
2018-06-10 item5 80.2
2018-06-10 item6 77.2

I wonder if it could reform an array into
2018-06-09 73.8 83.2 83.2
2018-06-10 33.1 80.2 77.2

and "item" consider as neglectable. The best way would be array push $row[2] value somewhere else / do a hash on key "2018-06-09"?

A: I would suggest creating an array using the date as the key and pushing the values into the array list.  This would look like so:
$output = array();
while($row = oci_fetch_array($ora_result, OCI_BOTH)) {
    if(!is_array($output[$row[0]]) $output[$row[0]] = array();
    array_push($output[$row[0]], $row[2]);
}

if(!empty($output)) foreach($output as $date => $number_list) {
    echo $date." ".implode(" ", $number_list);
}


text:
Q: Pyinstaller - Failed to execute script pyi_rth__tkinter I'm trying to convert my Python tkinter notepad to exe with pyinstaller.
But when I open created exe file i get error:
Failed to execute script pyi_rth__tkinter

I tried changing pyinstaller version to 5.0 developer from github and importing pkg_resources.py2_warn but that didn't work and I get the same error.
I'm using python 3.9.1
Here's my code:
  from tkinter import *
from tkinter import filedialog
from PIL import ImageTk
from PIL import Image

root = Tk()
root.geometry("600x375")
root.resizable(False, False)
root.title("NetNote")
root.iconbitmap("ikona.ico")
#liczba globalna zapisz
global open_status_name
open_status_name = False

def usuwanie():
    text.delete(1.0, END)
    global open_status_name
    open_status_name = False

def open_txt():

    text_file = filedialog.askopenfilename(title="Open Text File", filetypes=(("Text Files", "*.txt"),))
    if text_file:
        global open_status_name
        open_status_name = text_file
    text_file = open(text_file, "r")
    stuff = text_file.read()
    text.delete("1.0", END)
    text.insert(END, stuff)
    text_file.close()
#fukcja - save as
def save_as():
    text_file=filedialog.asksaveasfilename(defaultextension=".*", title="Zapisz jako", filetypes=(("Text Files", "*.txt"),))
    if text_file:
        name = text_file
        name = name.replace("","")
        text_file = open(text_file, "w")
        text_file.write(text.get(1.0, END))
        text_file.close()

def save_file():
    global open_status_name
    if open_status_name:
        text_file = open(open_status_name, "w")
        text_file.write(text.get(1.0, END))
        text_file.close()
    else:
        save_as()

frame = LabelFrame(root, text="Menu",padx=2, pady=2)
frame.grid(row=0, column=0, sticky=S, padx=10, pady=10)

my_logo = Image.open("logo.png")

resized = my_logo.resize((110, 138), Image.ANTIALIAS)
my_logo = ImageTk.PhotoImage(file="logo.png")
new_pic = ImageTk.PhotoImage(resized)

my_label = Label(root, image=new_pic)
my_label.grid(row=0, column=0, sticky=N, pady=20)

przycisk1 = Button(frame, text="Nowy",width=8, height=1, command=usuwanie,)
przycisk1.grid(row=0,column=0, sticky=N, padx=10, pady=10,)

przycisk2 = Button(frame, text="Otwórz", width=8,height=1, command=open_txt)
przycisk2.grid(row=1, column=0,)
root.mainloop

przycisk3 = Button(frame, text="Zapisz jako", width=8,height=1,command=save_as)
przycisk3.grid(row=2, column=0, padx=10, pady=10)

text = Text(root, height=20, width=57, font=("Calibri, 11"))
text.grid(row=0, column=1, padx=10, pady=10)

przycisk4 = Button(frame, text="Zapisz", width=8, height=1, command=save_file)
przycisk4.grid(row=3, column=0, pady=(0, 10))

root.mainloop

A: You can try this method:
pyinstaller --onefile -w
Even I had created a notepad using Tkinter, and this method did the work for me


text:
Q: PathNotFound error message: openFileForRead must be used with files and not directories I am using below code to read excel file using Azure databricks:
dfSource = spark \
  .read \
  .format("com.crealytics.spark.excel") \
  .option("Header", "true") \
  .option("inferSchema", "true") \
  .load(sSourcePath)#.withColumn("SourceFile",F.input_file_name())

But I get the error below:

PathNotFound error message: openFileForRead must be used with files and not directories

When I give the full filename, Spark properly read the file.
Note: I want to read all the files present in the folder.

A: If you need to read multiple Excel files from a directory, then you just need to iterate over the files, read each file into a dataframe, and union all these dataframes.  On Databricks you can use dbutils.fs.ls function to list files in the given directory, something like this:
all_data = None
sSourcePath = "path_to_directory"
for f in dbutils.fs.ls(sSourcePath):
  if not f.isFile or not f.name.endswith(".xlsx"):
    continue
  df = spark \
    .read \
    .format("com.crealytics.spark.excel") \
    .option("Header", "true") \
    .option("inferSchema", "true") \
    .load(f.path)
  if all_data:
    all_data = all_data.union(df)
  else:
    all_data = df

There is a chance that dataframes may not be compatible by structure, in this case you may need to do some explicit casting, etc.


text:
Q: SQL show all rows that have certain columns duplicated in a given time period I have one table containing the following data: ID, name, barcode, status, time_created
I need to check if the same barcode exists multiple times in a given time period (e.g. one week) and if the last status has changed from 0 to 1.
Question: How can I get the correct results according to given timestamps?
With the following query I can list the duplicated lines:
SELECT id, name, barcode, status, time_created
FROM table_name WHERE barcode
IN (SELECT barcode
FROM table_name
GROUP BY
barcode HAVING COUNT(*)>1);

Results are:

id
name
barcode
status
time_created

34
testname
123456789
1
2022-06-22 11:25:17

36
testname2
123456789
1
2022-06-22 03:58:35

37
testname3
test
0
2022-06-22 03:57:46

40
testname3
test
1
2022-07-04 10:48:25

41
testname
123456789
1
2022-07-04 11:19:20

42
testname
123456789
0
2022-07-02 12:26:39

43
testname
123456789
0
2022-02-09 03:03:40

If I add time interval to the query it still displays results from BEFORE the given interval:
SELECT id, name, barcode, status, time_created
FROM table_name WHERE barcode
IN (SELECT barcode
FROM table_name
    WHERE (time_created BETWEEN '2022-07-02 00:00:00' AND '2022-07-04 23:59:59')
    GROUP BY
barcode HAVING COUNT(*)>1);

id
name
barcode
status
time_created

34
testname
123456789
1
2022-06-22 11:25:17

40
testname3
test
1
2022-07-04 10:48:25

41
testname
123456789
1
2022-07-04 11:19:20

42
testname
123456789
0
2022-07-02 12:26:39

43
testname
123456789
0
2022-02-09 03:03:40

Is there an error in my logic or the query?

A: So, to get desired results you need to

*

*Get all duplicate barcode values in given interval as you do

*Get previous status and row number for each duplicate barcode ordered
by time_created. This will give you the ability to get the latest
values in time and find out the current and previous status values.

*Get the rows with the current status equal to 1 and the previous value equal to 0 and the maximum row number
Final query would be like this
WITH cte AS (
    SELECT
        table_name.*,
        LAG(table_name.status) OVER (PARTITION BY table_name.barcode ORDER BY time_created) AS prev_status,
        ROW_NUMBER() OVER (PARTITION BY table_name.barcode ORDER BY time_created) AS rn
    FROM table_name
    JOIN (
        SELECT barcode
        FROM table_name
        WHERE time_created BETWEEN '2022-07-02 00:00:00' AND '2022-07-04 23:59:59'
        GROUP BY barcode
        HAVING COUNT(*) > 1
    ) t ON table_name.barcode = t.barcode
)
SELECT id, name, barcode, status, time_created
FROM cte t
WHERE status = 1
      AND prev_status = 0
      AND rn = (
          SELECT MAX(rn)
          FROM cte
          WHERE barcode = t.barcode
      )

Demo


text:
Q: Error when converting XSD to Java using jaxb It has been some time since I used XSD, XML and JAXB. Now I'd like to use it again. Unfortunately I have a strange error that I cannot resolve.
Here is my build.gradle.
configurations {
    jaxb
}

dependencies {
    jaxb 'org.glassfish.jaxb:jaxb-xjc:2.3.6'
}

task genJaxb {
    ext.sourcesDir = "${buildDir}/generated-sources/jaxb"
    // that works!
    // ext.schema = 'https://raw.githubusercontent.com/spring-guides/gs-producing-web-service/main/complete/src/main/resources/countries.xsd'

    // that DOES NOT work!
    ext.schema = 'https://cwe.mitre.org/data/xsd/cwe_schema_latest.xsd'

    outputs.dir sourcesDir

    doLast() {
        project.ant {
            taskdef(
                name: 'xjc',
                classname: 'com.sun.tools.xjc.XJCTask',
                classpath: configurations.jaxb.asPath
            )
            mkdir(dir: sourcesDir)

            xjc(destdir: sourcesDir, schema: schema)
        }
    }
}

My schema comes from Mitre https://cwe.mitre.org/data/xsd/cwe_schema_latest.xsd. The overall task should work as the result is fine for a different sample schema https://raw.githubusercontent.com/spring-guides/gs-producing-web-service/main/complete/src/main/resources/countries.xsd. Unfortunately I'm getting the following error when using the Mitre schema.

[ant:xjc] [ERROR] Property "Lang" is already defined. Use <jaxb:property> to resolve this conflict.
[ant:xjc]   line 302 of http://www.w3.org/2002/08/xhtml/xhtml1-strict.xsd
[ant:xjc]
[ant:xjc] [ERROR] The following location is relevant to the above error
[ant:xjc]   line 303 of http://www.w3.org/2002/08/xhtml/xhtml1-strict.xsd

I did some research and I sounds like I have to use some custom binding. However I do not even find "Lang" in the XSD file.
Any ideas how I can generate the Java code? Thank you very much!


text:
Q: Trying to display javascript number with commas <SCRIPT language="JavaScript">
    height = screen.height;
    width = screen.width;
    document.write( width*height + " pixels");
</SCRIPT>

I would like my answer to return with commas separating the numbers rather than one full number.

A: Here's a fun way to do it:
function format(num) {
    return ("" + num).split("").reverse().reduce(function(acc, num, i, orig) {
        return  num + (i && !(i % 3) ? "," : "") + acc;
    }, "");
}

format(777782374);

Prints:
"777,782,374"

Or, if you want to support decimals:
function format(num, fix) {
    var p = num.toFixed(fix).split(".");
    return p[0].split("").reduceRight(function(acc, num, i, orig) {
        var pos = orig.length - i - 1
        return  num + (pos && !(pos % 3) ? "," : "") + acc;
    }, "") + (p[1] ? "." + p[1] : "");
}

format(777782374, 4);

Prints:
"777,782,374.0000"

A: Than you shouldn't multiply them?
document.write( width + ", " + height + " pixels");


text:
Q: FlatList onPress redirecting to wrong page I have 3 screens. Screen one contains the FlatList:
const navigation = useNavigation()

    function whereTo(id) {

        console.log(id)

        switch(id) {

            case 1:
                navigation.navigate('Malko')

            case 2:
                navigation.navigate('TRY2')
        }
    }

    const renderItem = ({ item }) => {

        return (
            <TouchableOpacity onPress={() => whereTo(item.id)}>

                <CalculatorCard text={item.text} image={item.imageurl} border={item.bordercolor} />

            </TouchableOpacity>
        )
    }

    return (

        <View style={styles.container}>

            <FlatList

                data={DATA}
                renderItem={renderItem}
                keyExtractor={item => item.id}
            />

        </View>
    )

The CalculatorCard is just a simple information card component.
Data for the FlatList:
const DATA = [

    {
        id: 1,
        text: "EXAMPLE 1",
        imageurl: "https://maisgeek.com/wp-content/uploads/2020/10/shutterstock_1006988770.png",
        bordercolor: "rgb(0, 100, 180)"
    },
    {
        id: 2,
        text: "EXAMPLE 2",
        imageurl: "https://images.ctfassets.net/lzny33ho1g45/T5qqQQVznbZaNyxmHybDT/b76e0ff25a495e00647fa9fa6193a3c2/best-url-shorteners-00-hero.png?w=1520&fm=jpg&q=30&fit=thumb&h=760",
        bordercolor: "rgb(0, 180, 255)"
    },
    {
        id: 3,
        text: "EXAMPLE 3",
        imageurl: "https://neilpatel.com/wp-content/uploads/2019/05/imagem-de-tela-de-uma-url.jpeg",
        bordercolor: "rgb(0, 160, 140)"
    },
]

Both the Malko and the TRY2 screen are empty screens with just a Text component. The problem is that when I click the first CalculatorCard, the id that gets passed to whereTo() is 1, however I get redirected to TRY2 instead of Malko.

A: You need to add break in case;
 switch(id) {

        case 1:
            navigation.navigate('Malko');
            break;

        case 2:
            navigation.navigate('TRY2');
            break;
    }


text:
Q: jQuery click on or off
Possible Duplicate:
jQuery bind click ANYTHING but ELEMENT

I have this HTML
<div id="outer">
  <input id="input1" type="text" value="button1"/>
  <input id="input2" type="text" value="button2"/>
</div>

And I am trying to use this
var insideOuter = "";

jQuery('#outer').live('click', function (e) {
    if(insideOuter != "" && insideOuter != 'outer'){
        alert('Inside');
    }
    insideOuter = "outer";
    return false;
});

jQuery('body').live('click', function (e) {
    if(insideOuter != ""&& insideOuter != 'body'){
        alert('Outside');
    }
    insideOuter = "body";
    return false;
});

Basically, I am trying to

*

*If user clicks inside
id="outer" then do nothing else

*If user clicks outside
id="outer"do something

Can someone recommend something better ?

A: I'd recommend not using live() if you are not trying to bind events to elements that don't already exist in the DOM.  Use bind() or click() instead.
Also, instead of checking for non-empty strings, use the length property:
if (insideOuter.length > 0 && ...

A: $("body").live('click', function (e) {
    if ( $(e.srcElement).attr("id") !== 'outer' && $(e.srcElement).parents("#outer").length == 0)
        alert('foo');
});

A: This is a duplicate question from one asked recently...I'll find that answer and post a link.
$(document).bind('click', function (e) {
 // Do whatever you want; #outer click event has been stopped
});

$('#outer').bind('click', function(e) {
    e.stopPropagation();
});

jQuery bind click *ANYTHING* but *ELEMENT*
How do I detect a click outside an element?


text:
Q: MIC5158 how to avoid MOSFET heating I have implemented DC-DC converter with mic5158 (schematic like in datasheet, no current limit, adjustable output), all work fine, except mosfet heating while medium load.
After investigation of this problem, i have found that gate-source voltage always keep near threshold (~4v). So mosfet always partially open instead of close-open cycle. With higher load voltage raising, so charge pump working.
I wondeder why Vgs does not fall  below threshold and not raising to full-open mosfet level.
Any idea how to make mosfet fully open-close to avoid heating?

A: Your regulator is a linear regulator. This means that the voltage across the MOSFET will change as required to keep output volts at 3.3 volts.
If the MOSFET turned on fully, you would output the full supply voltage, not 3.3 volts.

A:
I have implemented DC-DC converter with mic5158

The MIC5156/5157/5158 is not a DC to DC converter but an LDO voltage regulator therefore, whatever voltage is needed on the MOSFET's gate \$\color{red}{\text{is}}\$ the Goldilocks value for precise operation of this linear circuit to produce the required output voltage.

Any idea how to make mosfet fully open-close to avoid heating?

Use a switching converter such as a buck regulator.


text:
Q: Using Jsoup connect() in a loop. The first request is always much slower than all other subsequent ones I'm creating a small app to measure how long it takes an HTML document to load, checking every x number of seconds.
I'm using jsoup in a loop:
    Connection.Response response = null;

    for (int i = 0; i < totalGets; i++) {
        long startTime = System.currentTimeMillis();

        try {
            response = Jsoup.connect(url)
                    .userAgent(USER_AGENT)  //just using a Firefox user-agent
                    .timeout(30_000)
                    .execute();
        } catch (IOException e) {
            if (e.getMessage().contains("connect timed out")) {
                System.out.println("Request timed out after 30 seconds!");
            }
        }

        long currentTime = System.currentTimeMillis();

        System.out.println("Response time: " + (currentTime - startTime) + "ms" + "\tResponse code: " + response.statusCode());

        sleep(2000);
    }

The issue I'm having is that the very first execution of the jsoup connection is always slower than all subsequent once, no matter what website.
Here is my output on https://www.google.com
Response time: 934ms    Response code: 200
Response time: 149ms    Response code: 200
Response time: 122ms    Response code: 200
Response time: 136ms    Response code: 200
Response time: 128ms    Response code: 200

Here is what I get on http://stackoverflow.com
Response time: 440ms    Response code: 200
Response time: 182ms    Response code: 200
Response time: 187ms    Response code: 200
Response time: 193ms    Response code: 200
Response time: 185ms    Response code: 200

Why is it always faster after the first connect? Is there a better way to determine the document's load speed?

A: 1.
Jsoup must run some boiler plate code before the first request can be fired. I would not count the first request into your measurements, since all that initialization will skew the first request time.
2.
As mentioned in the comments, many websites cache responses for a couple of seconds. Depending on the website you want to measure you can use some tricks to get the webserver to produce a fresh site each time. Such a trick could be to add a timestamp parameter. Usually _ is used for that (like http://url/path/?pameter1=val1&_=ts). Or you could send along no cache headers in the HTTP request. however, none of these tricks can force a webserver to behave the way you want it. So you can wait longer than 30 seconds in between each request.

A: I think that in addition to @luksch points there is another factor, I think Java is keeping connection alive for a few seconds, maybe saving time in protocol trips.
If you use .header("Connection", "close") you'll see more consistent times.
You can check that connections are kept alive with a sniffer. At least I can see port numbers (I mean source port, of course) reused.
EDIT:
Another thing that may add time to first request is DNS lookup ...

A: Another potential reason is JVM is doing JIT optimization in background which turns java byte code into native instructions to improve speed.
The first time you run the code it's slow because the code haven't been optimized. The following rounds are faster because the optimization is already done.
Parsing html page is a pretty computationally intensive job.


text:
Q: OpenRefine Merging column values into a single Row i have a column with multiple rows that i would like to combine and have them as comma seperated values in a list. How would this be done?
enter image description here

A: The concept you are looking for is called "multi-valued cells" in OpenRefine.
OpenRefine offers to split multi-valued cells or what you are looking for is to join multi-valued cells.
In the corresponding dialogs you can provide a separator like a comma or a string sequence.


text:
Q: Akka: Creating many child actors vs. reusing a single child actor I'm quite new to Akka and I have a (hopefully) simple question. I have an actor that needs to repeatedly do a certain small subtask - that is, each time this actor receives a message, it will have to do N subtasks. This subtask is something that I've designated to a child actor. My question is, should I be creating a new instance of a child actor for each of these subtasks? Or should I simply spawn a single child actor, and send it N messages? What's the best practice in such a situation?
To better illustrate my question, here are two dumbed-down examples (In Java - but hopefully simple enough for you Scala guys!):
This first actor class creates a single child actor upon construction, and then sends many messages to that single child actor.
public class ParentActor extends UntypedActor {

    private final ActorRef childActor;

    public ParentActor() {
        this.childActor = getContext().actorOf(Props.create(childActor.class));
    }

    @Override
    public void onReceive(Object msg) {
        for (int i=0; i<1000; i++) {
            this.childActor.tell("Some message", getSelf());
        }
    }
}

Now, compare it to the following actor, which spawns a new child actor for each message that needs to be sent.
public class ParentActor extends UntypedActor {

    @Override
    public void onReceive(Object msg) {
        for (int i=0; i<1000; i++) {
            final ActorRef childActor = getContext().actorOf(Props.create(childActor.class));
            childActor.tell("Some message", getSelf());
        }
    }
}

Thanks!

A: Distributing work to actors can be done in akka using Routers.
The idea is to move the selection of the child rsp worker actor into the message-flow.
See the top example in the referenced doc. The master creates a set of child-actors, called routees and adds them to a router:
router = new Router(new RoundRobinRoutingLogic(), routees);

the router can be configured to use a set of different routing-logic implementations, here a simple round-robin logic.
When a message is sent to one of the child actors, you can just sent it to the router and it cares for selecting the right child and sending it there:
router.route(msg, getSender());

The getSender can be used to pass the message sender in case the message is orginally received in the worker, or you just pass the result of 'getSelf()' (or maybe just nothing, unsure) to send it directly.