text:
Q: How do I make a javascript loading screen for my website which will fade out once my sites loaded So I have been wondering for a while how to make a working javascript loading screen for my website, heres the code.

@import url(http://fonts.googleapis.com/css?family=Lato:300,700);
@import url(http://fonts.googleapis.com/css?family=Italianno);
@import url(http://fonts.googleapis.com/css?family=Indie+Flower);
@import url(http://fonts.googleapis.com/css?family=Poiret+One);
 body {
  background-image: url(images/rocket.jpg);
  background-repeat: no-repeat;
  background-attachment: fixed;
}
#menu {
  height: 60px;
  text-decloration: none;
  line-height: 60px;
  width: 100%;
  background: ;
  position: relative;
  margin: 0px;
  font-family: Lato;
}
#image {
  background-repeat: no-repeat;
  background-position: left top;
  width: 100%;
  height: 740px;
  -webkit-animation-duration: 1s;
  animation-duration: 1s;
  -webkit-animation-fill-mode: both;
  animation-fill-mode: both;
  -webkit-animation-timing-function: ease-in;
  animation-timing-function: ease-in;
}
@-webkit-keyframes fadeInUp {
  0% {
    opacity: 0;
    -webkit-transform: translateY(20px);
  }
  100% {
    opacity: 1;
    -webkit-transform: translateY(0);
  }
}
@keyframes fadeInUp {
  0% {
    opacity: 0;
    transform: translateY(20px);
  }
  100% {
    opacity: 1;
    transform: translateY(0);
  }
}
.fadeInUp {
  -webkit-animation-name: fadeInUp;
  animation-name: fadeInUp;
}
#specialbox {
  width: 300px;
  overflow: hidden;
  height: 300px;
  background-color: white;
  margin-right: 45px;
  margin-left: 47px;
  color: purple;
  clear: both;
  text-align: center;
  display: inline-block;
  padding: 3em;
  -webkit-box-shadow: 11px 11px 9px 0px rgba(36, 36, 36, 1);
  -moz-box-shadow: 11px 11px 9px 0px rgba(36, 36, 36, 1);
  box-shadow: 11px 11px 9px 0px rgba(36, 36, 36, 1);
}
#box {
  margin-top: 50px;
  width: 1100px;
  margin-bottom: 30px;
  background-color: white;
  margin-left: auto;
  margin-right: auto;
  color: purple;
  clear: both;
  text-align: center;
  padding: 5px;
  -webkit-box-shadow: 11px 11px 9px 0px rgba(36, 36, 36, 1);
  -moz-box-shadow: 11px 11px 9px 0px rgba(36, 36, 36, 1);
  box-shadow: 11px 11px 9px 0px rgba(36, 36, 36, 1);
  -webkit-animation-duration: 1s;
  animation-duration: 1s;
  -webkit-animation-fill-mode: both;
  animation-fill-mode: both;
  -webkit-animation-timing-function: ease-in;
  animation-timing-function: ease-in;
}
#textbox {
  width: 1100px;
  background-color: white;
  margin-left: auto;
  margin-right: auto;
  color: purple;
  clear: both;
  text-align: center;
  padding: 5px;
  -webkit-box-shadow: 11px 11px 9px 0px rgba(36, 36, 36, 1);
  -moz-box-shadow: 11px 11px 9px 0px rgba(36, 36, 36, 1);
  box-shadow: 11px 11px 9px 0px rgba(36, 36, 36, 1);
  transition: All 1s ease;
  -webkit-transition: All 1s ease;
  -moz-transition: All 1s ease;
  -o-transition: All 1s ease;
  transform: rotate(0deg) scale(1.5) skew(deg) translate(0px);
  -webkit-transform: rotate(0deg) scale(1) skew(0deg) translate(0px);
  -moz-transform: rotate(0deg) scale(1) skew(0deg) translate(0px);
  -o-transform: rotate(0deg) scale(1) skew(0deg) translate(0px);
  -ms-transform: rotate(0deg) scale(1) skew(0deg) translate(0px);
}
#textbox:hover {
  transform: rotate(0deg) scale(0) skew(1deg) translate(0px);
  -webkit-transform: rotate(0deg) scale(1.2) skew(1deg) translate(0px);
  -moz-transform: rotate(0deg) scale(1.2) skew(1deg) translate(0px);
  -o-transform: rotate(0deg) scale(1.2) skew(1deg) translate(0px);
  -ms-transform: rotate(0deg) scale(1.2) skew(1deg) translate(0px);
}
#footer {
  background-color: green;
  margin-left: auto;
  margin-right: auto;
  width: %;
  height: 10px;
  color: white;
  background-color: #303030;
  clear: both;
  text-align: center;
  padding: 5px;
}
/* Mini pictures in a circle */

.icon {
  position: relative;
}
.icon:before {
  -moz-osx-font-smoothing: grayscale;
  -webkit-font-smoothing: antialiased;
  font-family: FontAwesome;
  font-style: normal;
}
.icon.major {
  background-color: rgba(66, 138, 134, 0.7);
  border-radius: 100%;
  color: #ffffff;
  cursor: default;
  display: block;
  height: 4.5em;
  line-height: 4.5em;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 25px;
  text-align: center;
  width: 4.5em;
}
.icon.major:before {
  font-size: 32px;
}
/* Commands */

.alignleft {
  float: left;
}
.alignright {
  float: right;
}
.centered {
  position: absolute;
  top: 0%;
  left: 1%;
}
.undercentered {
  position: absolute;
  top: 95%;
  left: 85%;
}
.undercentered2 {
  position: absolute;
  top: 95%;
  left: 1%;
}
.button {
  font-size: 16px;
  color: rgba(0, 220, 0, 0.6);
  font-family: 'Indie Flower', cursive;
  font-weight: normal;
  padding: 0px 15px;
  text-decoration: none;
  background-color: rgba(0, 0, 0, 0);
  display: inline-block;
  float: right;
}
.button:hover {
  background-color: rgba(200, 0, 0, 0.5);
}
.button:active {
  position: relative;
  top: 1px;
}
.cbutton {
  font-size: 16px;
  font-family: 'Indie Flower', cursive;
  font-weight: normal;
  padding: 0px 15px;
  text-decoration: none;
  background-color: rgba(200, 0, 0, 0.2);
  color: rgba(220, 0, 0, 0.6);
  display: inline-block;
  float: right;
}
.button:active {
  position: relative;
  top: 1px;
}
.myButton {
  -moz-border-radius: 4px;
  -webkit-border-radius: 4px;
  border-radius: 4px;
  border: 1px solid rgba(66, 138, 134, 1);
  display: inline-block;
  cursor: pointer;
  color: red;
  font-family: arial;
  font-size: 15px;
  font-weight: bold;
  padding: 8px 30px;
  text-decoration: none;
}
.myButton:hover {
  background-color: rgba(66, 138, 134, 0.7);
}
.myButton:active {
  position: relative;
  top: 1px;
}
.myButton1 {
  -moz-border-radius: 4px;
  -webkit-border-radius: 4px;
  border-radius: 4px;
  border: 1px solid rgba(66, 138, 134, 1);
  display: inline-block;
  cursor: pointer;
  color: red;
  font-family: arial;
  font-size: 13px;
  font-weight: bold;
  padding: 4px 26px;
  text-decoration: none;
}
.myButton1:hover {
  background-color: rgba(66, 138, 134, 0.7);
}
.myButton1:active {
  position: relative;
  top: 1px;
}
.line {
  height: 1px;
  width: 300px;
  margin-left: 200px;
  background: rgba(226, 44, 44, 0.9);
  border: 1px solid rgba(226, 44, 44, 0.9);
}
/* Types of text */

body {
  font-size: 0.8em;
  font-family: sans-serif, Comic Sans MS;
  border: 1px;
  margin: 0px;
}
p {
  color: green;
  text-align: left;
}
h1l {
  color: rgba(226, 44, 44, 0.9);
  font-size: 400%;
  font-family: 'Italianno', cursive;
}
h1 {
  color: green;
  font-size: 300%;
  font-family: 'Poiret One', cursive;
  text-align: center;
}
air {
  color: red;
  text-align: center;
  font-family: Sans-serif;
  font-size: 14px;
}
s-air {
  color: green;
  text-align: center;
  font-family: Comic Sans MS;
  font-size: 17px;
}
sair {
  color: green;
  font-family: Arial;
  font-size: 17px;
  margin-left: 54px;
}
copyright {
  color: white;
  font-family: Sans-Serif;
  font-size: 15px;
}
warning {
  color: orange;
  text-align: center;
  font-size: 150%;
}
airh {
  color: green;
  font-family: Impact;
  text-align: center;
  font-size: 200%;
  text-shadow: 4px 4px 0px rgba(150, 150, 150, 1);
}
nav {
  line-height: 30px;
  background-color: #eeeeee;
  height: 300px;
  width: 100px;
  float: left;
  padding: 5px;
}
section {
  width: 350px;
  float: left;
  padding: 10px;
}
test {
  color: white;
  font-family: Lato;
  margin-left: 10px;
  font-size: 17px;
}
h2l {
  color: rgba(0, 220, 0, 0.6);
  font-family: 'Indie Flower', cursive;
  font-size: 150%;
  text-align: center;
}
h2 {
  font-family: 'Indie Flower', cursive;
  color: red;
}
h3 {
  font-family: 'Indie Flower', cursive;
  font-size: 130%;
  text-align: center;
}
unidentified {
  color: green;
  font-family: impact;
}
big {
  color: green;
  font-family: Sans-serif;
  font-size: 200%;
  text-align: center;
}
sub {
  font-size: 0.8em;
  position: relative;
  top: 0.2em;
}
sup {
  font-size: 0.8em;
  position: relative;
  top: -0.2em;
}
code {
  background: #f0f0f0;
  font-family: monospace;
  font-size: 0.9em;
  margin: 0 0.25em;
  padding: 0.25em 0.65em;
}
input[type=password] {
  border-radius: 5px;
  border: 1px;
  height: 17px;
  border-color: green;
}
input[type=submit] {
  border-radius: 5px;
  background-color: white;
  border: 1px green;
  height: 19px;
}
<!doctype html>

  <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
  <title>Blazin' - Home</title>
  <link rel="Shortcut Icon" href="icon.ico" />
  <link href="css/bootstrap.css" rel="stylesheet" />
  <link href="style.css" rel="stylesheet" type="text/css" />
  <link href="css/bootstrap-responsive.css" rel="stylesheet" />
  <link href="css/font-awesome.css" rel="stylesheet" />
  <link rel="stylesheet" media="screen and (min-width: 700px) and (max-width: 1000px)" href="mobile.css" />
  <link rel="stylesheet" media="screen and (min-width: 1500px) and (max-width: 10000px)" href="fstyle.css" />

     Admin
     Logs
     Rules

     Home

    <test class="alignleft" />

    <h1l class="centered">Blazin Gaming</h1l>
    <h2l class="undercentered2">Version 3.3.2</h2l>

I really need help on this, I have tried some different things but nothing seems to be working.

A: What you want to do is see when the page is ready. https://api.jquery.com/ready/
While that is happening do a jQuery animation, but you won't have much time unless your page is really big.


text:
Q: Sed command runs with hardcoded value in regex but fails with variable in script My file data Pattern is below and i need output as 6 or 3 or 8 or 4 based on the variable value which is eth0 and eth1
eth0RX:6:eth0TX:3|eth1RX:8:eth1TX:4|

Below code works well
sed 's/.*eth0RX:\([0-9]\+\).*/\1/g' $EMSTATE/packetdrop.txt

But fails when I use dynamic variable like below
rxfile=sed 's/.*$iRX:\([0-9]\+\).*/\1/g' $EMSTATE/packetdrop.txt

A: Variable expansion doesn't happen in single quoting. Use double quote instead. And if you want to set result to a variable, you need to run sed within command substitution syntax $(...) and better to quote this as well "$(...)". Plus as $iRX can be a valid variable name better do ${i}.
rxfile="$(sed "s/.*${i}RX:\([0-9]\+\).*/\1/g" "$EMSTATE/packetdrop.txt" )"

A: *

*Inside single quotes, everything is what it is.
$i is a dollar sign followed by an i.
If you want to use a variable,
you have to put the string into double quotes, somewhat like this:

"s/.*$iRX:\([0-9]\+\).*/\1/g"

*But that won't work, because it will look for a variable called iRX.
The simplest way to fix that is to put the variable name in braces, like this:

"s/.*${i}RX:\([0-9]\+\).*/\1/g"

*You should put $EMSTATE into double quotes, too.
You can use "$EMSTATE"/packetdrop.txt or "$EMSTATE/packetdrop.txt",
whichever you prefer.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How does Linux system handle CRLF in a file? I know CR LF (\r\n) would be interpreted as two characters, "carriage return" + "new line", but how would that affect different programs when it's for example, a source code--

*

*As a bash script to be executed?

*As a source code to be compiled? For example, .c file?

A: As it is a sequence of whitespace characters, CRLF is ignored in C, but not in Bash:
If the first line of a bash script (#!/bin/bash) has a CRLF line terminator, the script won't run. It will be looking for the file /bin/bash\r, which doesn't exist.
If any of the other lines of a script have a CRLF line terminator, the command on that line will either be not found (as bash is looking for a command named some_command\r), or will be passed a \r at the end of its last parameter.

A: Shell script
The shell does not treat CR as white space by default.
Source code (crlf67.sh) with CR marked by ^M:
#!/bin/sh^M
^M
echo "Hello^M
World!"^M

Running the command explicitly:
$ sh crlf67.sh
: command not found
Hello
World!
$ sh crlf67.sh 2>&1 | vis -r
crlf67.sh: line 2: ^M: command not found
Hello^M
World!^M
$

(The vis command is an extended version of the vis program from
Brian W Kernighan, Rob Pike
The Unix Programming Environment (Nov 1983).  It makes non-printing characters visible.)
If you make the script executable:
$  make crlf67
cat crlf67.sh >crlf67
chmod a+x crlf67
$ crlf67
-bash: ./crlf67: /bin/sh^M: bad interpreter: No such file or directory
$

The kernel doesn't treat the CR as white space either and fails to find the command.
C source code
In C source code, officially, you can't use backslash to continue lines in C if the line ending is CRLF because the character after the backslash isn't a newline (NL or LF); it's a CR.  Some compilers will ignore white space (at least the CR) after the last backslash on a line — GCC 9.1.0 for one, but also earlier versions.  It warns about spaces after a trailing backslash (unless you use -Werror as I do; then it's an error).  It isn't what the standard stipulates; however, even -pedantic doesn't stop it ignoring the erroneous notation.
Source code (crlf19.c) with CR marked by ^M and newline marked by ^J:
#include <stdio.h>^M^J
^M^J
int main(void)^M^J
{^M^J
    printf("Hello\   ^M^J
 world!\   ^M^J
\n");^M^J
    return 0;^M^J
}^M^J

Compilation by GCC 9.1.0 on macOS 10.14.5 Mojave:
$ gcc -O3 -g -std=c11 -Wall -Wextra -pedantic crlf19.c -o crlf19
crlf19.c: In function 'main':
crlf19.c:5:18: warning: backslash and newline separated by space
    5 |     printf("Hello\
      |
crlf19.c:6:8: warning: backslash and newline separated by space
    6 |  world!\
      |
$ gcc -O3 -g -std=c11 -Wall -Wextra -Werror crlf19.c -o crlf19
crlf19.c: In function 'main':
crlf19.c:5:18: error: backslash and newline separated by space [-Werror]
    5 |     printf("Hello\
      |
crlf19.c:6:8: error: backslash and newline separated by space [-Werror]
    6 |  world!\
      |
cc1: all warnings being treated as errors
$

This behaviour goes back at least as far as GCC 4.1.2 — that version was tested on an ante-diluvian RHEL 5 box.
If you remove the spaces after the backslash leaving just the CRLF line endings, GCC doesn't complain at all.

A: It depends on the program that's processing the file. I don't believe there's any general rule.
For example, I just created several shell scripts in an otherwise empty directory. One of them is named some_command with an ASCII CR as the last character of the file name.
I can invoke that command from a shell script by including that CR as part of the command name. The shell (sh, bash, or ksh) doesn't treat the CR character as white space.
$ ls -l
total 16
-rwxr-xr-x 1 kst kst 26 Jul  1 16:46  crlf.bash
-rwxr-xr-x 1 kst kst 25 Jul  1 16:46  crlf.ksh
-rwxr-xr-x 1 kst kst 24 Jul  1 16:46  crlf.sh
-rwxr-xr-x 1 kst kst 21 Jul  1 16:49 'some_command'$'\r'
$ cat -v crlf.bash
#!/bin/bash
some_command^M
$ cat -v crlf.ksh
#!/bin/ksh
some_command^M
$ cat -v crlf.sh
#!/bin/sh
some_command^M
$ cat -v some_command
#!/bin/sh
echo hello
$ ./crlf.bash
Hello
$ ./crlf.ksh
Hello
$ ./crlf.sh
Hello
$

The version of ls I'm using (GNU coreutils 8.28) has a special syntax for showing file names that contain special characters. cat -v shows CR characters as ^M.


text:
Q: Where do I enter the Homebrew Scala path /usr/local/opt/scala/idea in IntelliJ? When you install Scala using Homebrew you are told
To use with IntelliJ, set the Scala home to:
  /usr/local/opt/scala/idea

What exactly does this mean? Is there a global setting in IntelliJ where you enter this path?
Specifically I'm confused because I'm trying to create SBT-backed projects in IntelliJ. In IntelliJ I do New Project -> Scala:SBT and let the IDE create a default project for me. I get a build.sbt that looks like this:
name := "HelloScala"

version := "1.0"

which looks correct. However, the dependencies are on Scala 2.10.2, while the latest Homebrew-installed Scala on my machine (the one that gets used if I type scala at the command line) is 2.11.0. I assume the problem is that I don't have /usr/local/opt/scala/idea properly set, but I don't see where in the IntelliJ UI to enter this path information. Specifically, none of the IntelliJ Preferences have a text box for "path to Scala distribution" or some such.
How do I properly set up Homebrew Scala with IntelliJ?
IntelliJ 13.1.2, OS X 10.9.2

A: If you want to use the installed version of Scala instead of managed versions by Intelij you do the following:
Open Project Structure in Intelij and edit Dependencies (use a shortcut on mac:  ⌘+↓).
Then when you want to add a dependency, the finder won't show directories like /usr etc. A workaround is to temporarily add this folder to the shortcuts sidebar in Finder, like this:
open a terminal and run: open  /usr/local/opt/scala/. This will open a finder and show the idea directory. You can drag this to the shortcut sidebar.
Now go back to Intelij and add the directory to Dependencies. I decided to do this under Global Settings (in the left pane). Then next I went to Project Settings > Modules and removed any existing source of scala and clicked on + to add and selected "Library..". Here you should see the scala version you added under a section called Global Library.
Also see https://www.jetbrains.com/help/idea/2016.3/working-with-scala-tests.html

A: You need to set scalaVersion in your sbt file or else sbt will use the scala version it was built against.
scalaVersion := "2.11.0"

This will make sbt automagically download the scala 2.11 jars into your ivy cache. Both SBT and IDEA will then use that to compile and run your scala code.
So you wouldn't actually need to install it with homebrew at all unless you want to be able to run the scala repl in a console/manually run scalac etc.
It's only when you do not use the SBT integration you need to point out your scala installation in IDEA.

A: now is 2021 year, for my case:

*

*IntelliJ IDEA: IntelliJ IDEA 2020.3.2 (Community Edition)

*OS: macOS 10.14.6
answer is: NO need set scala location (such as /usr/local/opt/scala/idea)
just need:

*

*in IntelliJ IDEA, open *.scala file -> No Scala SDK in module -> click Setup Scala SDK -> Add Scala Support -> for No Library selected, clcik Create

*selected (here already use brew) installed (by brew install scala) scala SDK

*

*

*IntelliJ will auto recognize it -> after indexing then worked -> can debug scala

*

*

A: I'm using IntelliJ IDEA 2022.3.2
If you're managing packages on your Mac using Homebrew, the path to specify on x86 Mac is typically /usr/local/opt/scala/idea

Go to File > Project Structure > Global Libraries > Press the + button > Select Scala SDK > Browse > Specify the path "/usr/local/opt/scala/idea"

Select "Apply" and you should be all set!


text:
Q: Check if parent node exists I am trying to learn how to use Apache Zookeeper. A part of this is I need to check if the parent node has been created and if it hasn't, then I need to create the node, then populate the registry with information on the services currently running in the cluster. This is happening in the method initialise(). I cannot figure out the checking if the parent node exists. The code I have is what I have so far.
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class ServiceRegistry implements Watcher {

    private  String zookeeperAddress = "localhost:2181";
    private  int sessionTimeout = 3000;

    private ZooKeeper zooKeeper;

    private String currentZNodeName;

    private String serviceName = "";
    private String serviceAddress = "";

    private static final String SERVICES_NAMESPACE = "/services";

    public ServiceRegistry(String zookeeperAddress, int sessionTimeout) {
        this.sessionTimeout = sessionTimeout;
        this.zookeeperAddress = zookeeperAddress;
    }

   //Works
    public void connectToZookeeper() throws IOException {
        this.zooKeeper = new ZooKeeper(zookeeperAddress, sessionTimeout, this);
    }

    public void process(WatchedEvent event) {
        switch (event.getType()){
            case None:
            if(event.getState() == Watcher.Event.KeeperState.SyncConnected){
                System.out.println("Successfully connected to Zookeeper");
            }else{
                synchronized (zooKeeper){
                    System.out.println("Disconnected from Zookeeper");
                    zooKeeper.notifyAll();
                }
            }
            break;

            case NodeCreated:
                System.out.println("Node created");
                try {
                    initialise();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } catch (KeeperException e) {
                    throw new RuntimeException(e);
                }
                break;

            case NodeDataChanged:
                System.out.println("Node data changed");
                getServices();
                break;

        }
    }

    public void initialise() throws InterruptedException, KeeperException {
       Stat servicesStat = null;

       if(servicesStat == null){
           String znodePrefix = SERVICES_NAMESPACE + "/c_";
           String znodeFullPath = zooKeeper.create(znodePrefix, new byte[]{}, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
           System.out.println("znode name " + znodeFullPath);
           servicesStat = zooKeeper.exists(SERVICES_NAMESPACE + "/", this);
       }
    }

   public void run() throws InterruptedException {
        synchronized (zooKeeper){
            zooKeeper.wait();
        }
    }


text:
Q: How can i make an element to cover/overlap another element? I have an element (summary in this case) and right below there is a box.
When I click the details to see the content of the summary, the rest of the content is blocked by the box below, I can't see the rest of the summary because the box is on top of it.
How can I make my summary element to show all the content by covering anything on its path?


text:
Q: PHP MySQL Converting names to ID's and inserting is returning NULL values I have a form where the user can input the name (combined string of first and last names) of a member, student and/or instructor. They also input other data irrelevant to this question. This is all inserted into a table called games. A table called members, students and instructors already exists with fields including id, first_name and last_name for each. All the required foreign key constraints are in order. So when the user submits the form, I only want the corresponding id of the member, student and/or instructor to be inserted, not their name(s).
I have the following code, and it successfully submits all information besides the id of the member, student and/or instructor, which appear in the record as NULL.
If anyone could highlight the issue here I would greatly appreciate it.
Form:
<!DOCTYPE html>

<meta charset="UTF-8">
<title>Form</title>

<form action="action.php" method="post">

        Instructor:
        <input type="text" name="instructor_name" id="instructor_name">

        Student:
        <input type="text" name="student_name" id="student_name">

        Member:
        <input type="text" name="member_name" id="member_name">

        Exercises:
        <input type="text" name="exercises" id="exercises">

        Authorised By:
        <input type="text" name="auth_by" id="auth_by">

        Authorisation Duration:
        <input type="text" name="auth_duration" id="auth_duration">

    <input type="submit" value="Submit">
</form>

Action:
<?php

// connection information
include 'pdo_config.php';

try {
// new pdo connection
$conn = new PDO($dsn, $user, $pass, $opt);

// post data
$member_name = $_POST['member_name'];
$exercises = $_POST['exercises'];
$auth_by = $_POST['auth_by'];
$auth_duration = $_POST['auth_duration'];
$student_name = $_POST['student_name'];
$instructor_name = $_POST['instructor_name'];

// get corresponding id's of names
$name_m = explode(" ", $member_name);
$first_name_m = $name_m[0];
$last_name_m = $name_m[1];
$statement1 = $conn->prepare("SELECT member_id FROM tbl_members WHERE first_name = :first_name AND last_name = :last_name");
$statement1->execute(array(':first_name' => $first_name_m, ':last_name' => $last_name_m));
$row1 = $statement1->fetch();
$member_id = $row1['member_id'];

$name_i = explode(" ", $instructor_name);
$first_name_i = $name_i[0];
$last_name_i = $name_i[1];
$statement2 = $conn->prepare("SELECT instructor_id FROM tbl_instructors WHERE first_name = :first_name AND last_name = :last_name");
$statement2->execute(array(':first_name' => $first_name_i, ':last_name' => $last_name_i));
$row2 = $statement2->fetch();
$instructor_id = $row2['instructor_id'];

$name_s = explode(" ", $student_name);
$first_name_s = $name_s[0];
$last_name_s = $name_s[1];
$statement3 = $conn->prepare("SELECT student_id FROM tbl_students WHERE first_name = :first_name AND last_name = :last_name");
$statement3->execute(array(':first_name' => $first_name_s, ':last_name' => $last_name_s));
$row3 = $statement3->fetch();
$student_id = $row3['student_id'];

// prepare statements and bind parameters
$stmt = $conn->prepare("INSERT INTO tbl_games (member_id, exercises, auth_by, auth_duration, student_id, instructor_id) VALUES (:member_id, :exercises, :auth_by, :auth_duration, :student_id, :instructor_id)");

$stmt->bindParam(':member_id', $member_id);
$stmt->bindParam(':exercises', $exercises);
$stmt->bindParam(':auth_by', $auth_by);
$stmt->bindParam(':auth_duration', $auth_duration);
$stmt->bindParam(':student_id', $student_id);
$stmt->bindParam(':instructor_id', $instructor_id);

// execute statements
$stmt->execute();

// success or error message
echo "New record created successfully";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}

$conn = null;

?>

A: You may enter a member that does not exist and must be validated.
Or load combo with members first, and user select id from combo and send to server id member.


text:
Q: How to call an event in parent component from child component which is loaded using DCL loadintolocation()

I have an event in parent component. I want to call that event from the a child component created using DCL loadintolocation(). I am following this logic in the child component to raise the event
@Output() myevent1: EventEmitter;
onSubmit() {
  console.log(this.myForm.value);
  this.myevent1.emit();
}

I am able to raise the events for components which are already mentioned but not to components that are created using DCL. Please tell me how to raise the event in parent component from components created dynamically.
Here is the plunker demo i have worked till now http://plnkr.co/edit/2LJL4HxSc74XAyGmQMio?p=preview

A: update beta.16
dcl.loadIntoLocation() now needs a ViewContainerRef instead of a template variable name.
@Component({
    selector: 'dynamic',
    template: `

I'm the dynamic component

    <button (click)="someEvent.emit($event)">click me</button>
    `,
})
export class DynamicComponent {
  someEvent = new EventEmitter();
}

@Component({
    selector: 'my-app',
    template: `

Hello

clicked at (top): {{top}}

      dynamic component below

    `,
})
export class AppComponent {
  @ViewChild('target', {read: ViewContainerRef}) target;
  top;

  constructor(private dcl:DynamicComponentLoader) {}
  ngAfterViewInit() {
    this.dcl.loadNextToLocation(DynamicComponent, this.target)
    .then(ref => {
      ref.instance.someEvent
      .subscribe(value => {
        console.log(value.clientX);
        this.top = value.clientX;
        console.log(this.top);
      })
    });
  }
}

Plunker example beta.17
original
With
loadIntoLocation(
    SomeComponent,
    someElementRef,
    'someAnchor',
    [/*other providers, */
        provide(ParentComponent, useValue: this)]);

you can pass the parent component to the dynamically created component.
In the child component you just add the parent to the constructor parameter list
constructor(parent: ParentComponent) {}

To not couple parent and child so tightly you can also use a shared service and pass this instead of the parent component itself.

A: When you load the component, you can subscsribe to the event of the child from where you can call the parent function.
dcl.loadIntoLocation(ChildComponent, elementRef, 'child')
  .then((newComponent) => {
    newComponent.instance.event.subscribe(() => { .. call your parent ..});
  })

UPDATE
see the plunker here: http://plnkr.co/edit/DNmtl6TG5s2dsEUlVTvw?p=preview


text:
Q: How to copy an One2many field in an onchange method and modify it? I think I did this a thousand times, but today I am not able to achieve it and have a lot of doubts.
PURPOSE
I need to copy the records of an One2many field to my One2many field, but changing the value of a column. This action must be performed in an onchange method.
SCENARIO
I am in the model mrp.bom. It has an One2many field named bom_line_ids. It also has the Many2one field named product_id.
Each time product_id changes, I have to fill in automatically the bom_line_ids of the current bill of materials record, taking the data from the bom_line_ids field of other bill of materials. But these records will not be exactly the same, I need to modify a column.
EXAMPLE
In an onchange method, I need to copy the recordset mrp.bom.line(10, 11) to my One2many field, but in my One2many field both records will have the field line_type with the value 'standard' (it does not matter the line_type value of the source records).
MY ATTEMPT
I tried a lot of things. The closest attempt to the solution was this one. But this fails when the current bill of materials record has not been saved in the database yet, because of _origin. The error says that bom_id is NULL and it is mandatory... The problem is that if I do not write _origin, that error raises always, it does not matter if the current bill of material already exists or not. And if I remove the bom_id key from the default dictionary, the new lines are added to the source One2many instead of mine...
@api.onchange('product_id')
def onchange_product_id(self):
    if self.product_id and \
       self.product_id.product_tmpl_id.bom_ids:
        # Following lines are only for taking the source BoM
        bom_ids = self.product_id.product_tmpl_id.bom_ids.filtered(
            lambda r: not r.product_id)
        bom_id = bom_ids[0] if bom_ids else False
        # Following lines are for doing the copy
        new_lines = self.env['mrp.bom.line']
        for line in bom_id.bom_line_ids:
            new_lines += line.copy(default={
                'bom_id': self._origin.id,
                'line_type': 'standard',
            })
        self.bom_line_ids = [(6, 0, new_lines.ids)]

CONCLUSION
I think I am making this complexer than it is, there must be some easier solution... Does anyone know how to do this?

A: You can try with another options like add "active" field in bom.line object.
With that you can disable your previous bom line and add new bom lines in onchange method without disturb any other flow.
PS: I haven't try it.
EDIT:
Browse lines and prepare a list (0, 0,  { values }) to update one2many field.
@api.onchange('product_id')
def onchange_product_id(self):
    if self.product_id and \
       self.product_id.product_tmpl_id.bom_ids:
        bom_ids = self.product_id.product_tmpl_id.bom_ids.filtered(
            lambda r: not r.product_id)
        bom_id = bom_ids[0] if bom_ids else False
        new_lines = []
        for line in bom_id.bom_line_ids:
            vals = line.read()[0]
            vals.update({
                'line_type': 'standard',
            })
            vals.pop('bom_id', False)
            new_lines.append((0, 0, vals))
        self.bom_line_ids = new_lines


text:
Q: Docker Volumes on Mac with Postgres I'm attempting to run the following command on Mac OSX:
docker run --rm --name kong-database \
    --network=kong-net \
    -v /Volumes/docker/postgres:/var/lib/postgresql/data \
    -p 5432:5432 \
    -e "POSTGRES_USER=kong" \
    -e "POSTGRES_DB=kong" \
    postgres:9.6

With the intention that it will launch postgres in in a docker container, and persist the database data on my local file system in /Volumes/docker/postgres. However, I get the following error, and the container fails to run:
chown: changing ownership of '/var/lib/postgresql/data': Operation not permitted

Any idea what I can do to get this going?

A: Turns out that /Volumes was owned by root. When I switched this to something like /Users/JoshuaErney/Volumes, this ran successfully. Here's an example:
docker run --rm --name kong-database \
    --network=kong-net \
    -v /Users/JoshuaErney/Volumes/docker/postgres:/var/lib/postgresql/data \
    -p 5432:5432 \
    -e "POSTGRES_USER=kong" \
    -e "POSTGRES_DB=kong" \
    postgres:9.6

A: Answer by jerney is correct, here is what it looks like with docker-compose.yaml:
services:
  test-postgres-compose :
    ...
    volumes :
      - pgdata:/var/lib/postgresql/data
...
volumes :
  pgdata :

Docker compose volumes info


text:
Q: Why doesn't stack overflow encode c++ to c%2b%2b in its URL? When I go to https://stackoverflow.com/tags/c++ why doesn't it encode it to https://stackoverflow.com/tags/c%2b%2b. Shouldn't that be something that the browser does? How does stack overflow prevent the encoding.

A: + is not required to be percent-encoded when used as part of the path.
See: https://www.rfc-editor.org/rfc/rfc3986.txt
In particular the definitions of pchar and sub-delim.


text:
Q: col alignment is not fit in small screen I created a row and I put two columns (col-md-2 and col-md-10, col-sm-4). But in mobile view the content is overflowing out of frame.
In normal screen

In small screen

Code part

Class

Lab

Pane A

Pellentesque habitant morbi tristique senectus et netus et malesuada fames
       ac turpis egestas.

Pane B

Pellentesque habitant morbi tristique senectus et netus et malesuada fames
       ac turpis egestas.

A: Read the bootstrap docs. Layout should look like this


text:
Q: Kafka multiple topic consume    consumer.subscribe(Pattern.compile(".*"),new ConsumerRebalanceListener() {
            @Override
            public void onPartitionsRevoked(Collection<TopicPartition> clctn) {

            }

            @Override
            public void onPartitionsAssigned(Collection<TopicPartition> clctn) {
            }
        });

How to consume all topics with regex in apache/kafka?
I tried above code, but it didn't work.

A: For regex use the following signature
KafkaConsumer.subscribe(Pattern pattern, ConsumerRebalanceListener listener)

E.g. the following code snippet enables the consumer to listen to all topics with prefix my_topics_
ConsumerRebalanceListener listener = new ConsumerRebalanceListener() {

  @Override
  public void onPartitionsRevoked(Collection<TopicPartition> arg0) {
    // Don't need it now.
  }

  @Override
  public void onPartitionsAssigned(Collection<TopicPartition> arg0) {
    // Don't need it now.
  }
};

pattern = Pattern.compile("my_topics_.*");
kafkaConsumer.subscribe(pattern, listener);


text:
Q: TypeError: undefined is not an object (evaluating '_ref.navigation') I am not able to rectify this error.
I have reinstalled node_modules, but no use can anyone please help me with this issue??
Complete error is attached

A: are you using a functional component or class component? I think JS bundle is not able to find the reference for the navigation.
Try with this
this.navigation = React.createRef();

in the constructor.
Please post the error in detail.


text:
Q: How to get the current View Name in Vaadin I'm using Vaadin 7. I want to redirect my page to a previous one after a treatment is done. For that I need to know which View called my new View so I can redirect to it later. I'm aware that I have to add something in here:
 getNavigator().addViewChangeListener(new ViewChangeListener() {

  @Override
  public boolean beforeViewChange(ViewChangeEvent event) {

    myNewView.REDIRECT_TO = //here is the problem :)
}

Any Idea how can I do that ?

A: You can use the ViewChangeEvent.getOldView() method to retrieve the View object. Now, by default there's no way to get the name of the view from there, since in theory you could register the same View with multiple names. But assuming you have only one name for each view, here's what you could do:
Create an interface, HasName, like so:
public interface HasName {
    String getName();
}

Then implement HasName in all your View classes. When registering the views in your Navigator, use the getName() method to refer to the name of the View. After that you can simply do a cast in your ViewChangeListener and use the same method to access the name there.
getNavigator().addViewChangeListener(new ViewChangeListener() {
    @Override
    public boolean beforeViewChange(ViewChangeEvent event) {
        View oldView = event.getOldView();
        if (oldView != null) {
            String oldViewName = ((HasName) oldView).getName();
            // do stuff with oldViewName
        }
    }
}


text:
Q: Pattern matching in `Alternative` I have a function that pattern matches on its arguments to produce a computation in StateT () Maybe (). This computation can fail when run, in which case I want the current pattern match branch to fail, so to speak.
I highly doubt it's possible to have something like
compute :: Int -> StateT () Maybe Int
compute = return

f :: Maybe Int -> Maybe Int -> StateT () Maybe ()
f (Just n1) (Just n2) = do
  m <- compute (n1 + n2)
  guard (m == 42)
f (Just n) _ = do
  m <- compute n
  guard (m == 42)
f _ (Just n) = do
  m <- compute n
  guard (m == 42)

behave in the way I want it to: When the first computation fails due to the guard or somewhere in compute, I want f to try the next pattern.
Obviously the above can't work, because StateT (as any other monad might) involves an additional parameter when expanded, so I probably can't formulate this as simple pattern guards.
The following does what I want, but it's ugly:
f' :: Maybe Int -> Maybe Int -> StateT () Maybe ()
f' a b = asum (map (\f -> f a b) [f1, f2, f3])
  where
    f1 a b = do
      Just n1 <- pure a
      Just n2 <- pure b
      m <- compute (n1 + n2)
      guard (m == 42)
    f2 a _ = do
      Just n <- pure a
      m <- compute n
      guard (m == 42)
    f3 _ b = do
      Just n <- pure b
      m <- compute n
      guard (m == 42)

A call like execStateT (f (Just 42) (Just 1)) () would fail for f but return Just () for f', because it matches f2.
How do I get the behavior of f' while having elegant pattern matching with as little auxiliary definitions as possible like in f? Are there other, more elegant ways to formulate this?

Complete runnable example:
#! /usr/bin/env stack
-- stack --resolver=lts-11.1 script

import Control.Monad.Trans.State
import Control.Applicative
import Control.Monad
import Data.Foldable

compute :: Int -> StateT () Maybe Int
compute = return

f :: Maybe Int -> Maybe Int -> StateT () Maybe ()
f (Just n1) (Just n2) = do
  m <- compute (n1 + n2)
  guard (m == 42)
f (Just n) _ = do
  m <- compute n
  guard (m == 42)
f _ (Just n) = do
  m <- compute n
  guard (m == 42)

f' :: Maybe Int -> Maybe Int -> StateT () Maybe ()
f' a b = asum (map (\f -> f a b) [f1, f2, f3])
  where
    f1 a b = do
      Just n1 <- pure a
      Just n2 <- pure b
      m <- compute (n1 + n2)
      guard (m == 42)
    f2 a _ = do
      Just n <- pure a
      m <- compute n
      guard (m == 42)
    f3 _ b = do
      Just n <- pure b
      m <- compute n
      guard (m == 42)

main = do
  print $ execStateT (f (Just 42) (Just 1)) ()  -- Nothing
  print $ execStateT (f' (Just 42) (Just 1)) () -- Just (), because `f2` succeeded

Edit: I elicited quite some clever answers with this question so far, thanks! Unfortunately, they mostly suffer from overfitting to the particular code example I've given. In reality, I need something like this for unifying two expressions (let-bindings, to be precise), where I want to try unifying the RHS of two simultaneous lets if possible and fall through to the cases where I handle let bindings one side at a time by floating them. So, actually there's no clever structure on Maybe arguments to exploit and I'm not computeing on Int actually.
The answers so far might benefit others beyond the enlightenment they brought me though, so thanks!

Edit 2: Here's some compiling example code with probably bogus semantics:
module Unify (unify) where

import Control.Applicative
import Control.Monad.Trans.State.Strict

data Expr
  = Var String -- meta, free an bound vars
  | Let String Expr Expr
  -- ... more cases
  -- no Eq instance, fwiw

-- | If the two terms unify, return the most general unifier, e.g.
-- a substitution (`Map`) of meta variables for terms as association
-- list.
unify :: [String] -> Expr -> Expr -> Maybe [(String, Expr)]
unify metaVars l r = execStateT (go [] [] l r) [] -- threads the current substitution as state
  where
    go locals floats (Var x) (Var y)
      | x == y = return ()
    go locals floats (Var x) (Var y)
      | lookup x locals == Just y = return ()
    go locals floats (Var x) e
      | x `elem` metaVars = tryAddSubstitution locals floats x e
    go locals floats e (Var y)
      | y `elem` metaVars = tryAddSubstitution locals floats y e
    -- case in point:
    go locals floats (Let x lrhs lbody) (Let y rrhs rbody) = do
      go locals floats lrhs rrhs -- try this one, fail current pattern branch if rhss don't unify
      -- if we get past the last statement, commit to this branch, no matter
      -- the next statement fails or not
      go ((x,y):locals) floats lbody rbody
    -- try to float the let binding. terms mentioning a floated var might still
    -- unify with a meta var
    go locals floats (Let x rhs body) e = do
      go locals (Left (x,rhs):floats) body e
    go locals floats e (Let y rhs body) = do
      go locals (Right (y,rhs):floats) body e

    go _ _ _ _ = empty

    tryAddSubstitution = undefined -- magic

A: If you were using Maybe alone, you would be able to do this with pattern guards:
import Control.Monad
import Control.Applicative

ensure :: Alternative f => (a -> Bool) -> a -> f a
ensure p a = a <$ guard (p a)

compute :: Int -> Maybe Int
compute = return

f :: Maybe Int -> Maybe Int -> Maybe Int
f (Just m) (Just n)
    | Just x <- ensure (== 42) =<< compute (m + n)
    = return x
f (Just m) _
    | Just x <- ensure (== 42) =<< compute m
    = return x
f _ (Just n)
    | Just x <- ensure (== 42) =<< compute n
    = return x
f _ _ = empty

(ensure is a general purpose combinator. Cf. Lift to Maybe using a predicate)
As you have StateT on the top, though, you would have to supply a state in order to pattern match on Maybe, which would foul up everything. That being so, you are probably better off with something in the vein of your "ugly" solution. Here is a whimsical attempt at improving its looks:
import Control.Monad
import Control.Applicative
import Control.Monad.State
import Control.Monad.Trans
import Data.Foldable

ensure :: Alternative f => (a -> Bool) -> a -> f a
ensure p a = a <$ guard (p a)

compute :: Int -> StateT () Maybe Int
compute = return

f :: Maybe Int -> Maybe Int -> StateT () Maybe Int
f a b = asum (map (\c -> f' (c a b)) [liftA2 (+), const, flip const])
    where
    f' = ensure (== 42) <=< compute <=< lift

While this is an answer specific to the snippet I've given, the refactorings only apply limited to the code I was facing.

Perhaps it's not that far-fetched of an idea to extract the skeleton of the asum expression above to a more general combinator:
-- A better name would be welcome.
selector :: Alternative f => (a -> a -> a) -> (a -> f b) -> a -> a -> f b
selector g k x y = asum (fmap (\sel -> k (sel x y)) [g, const, flip const])

f :: Maybe Int -> Maybe Int -> StateT () Maybe Int
f = selector (liftA2 (+)) (ensure (== 42) <=< compute <=< lift)

Though it is perhaps a bit awkward of a combinator, selector does show the approach is more general than it might appear at first: the only significant restriction is that k has to produce results in some Alternative context.
P.S.: While writing selector with (<|>) instead of asum is arguably more tasteful...
selector g k x y = k (g x y) <|> k x <|> k y

... the asum version straightforwardly generalises to an arbitrary number of pseudo-patterns:
selector :: Alternative f => [a -> a -> a] -> (a -> f b) -> a -> a -> f b
selector gs k x y = asum (fmap (\g -> k (g x y)) gs)

A: When I need something like this, I just use asum with the blocks inlined. Here I also condensed the multiple patterns Just n1 <- pure a; Just n2 <- pure b into one, (Just n1, Just n2) <- pure (a, b).
f :: Maybe Int -> Maybe Int -> StateT () Maybe ()
f a b = asum

  [ do
    (Just n1, Just n2) <- pure (a, b)
    m <- compute (n1 + n2)
    guard (m == 42)

  , do
    Just n <- pure a
    m <- compute n
    guard (m == 42)

  , do
    Just n <- pure b
    m <- compute n
    guard (m == 42)

  ]

You can also use chains of <|>, if you prefer:
f :: Maybe Int -> Maybe Int -> StateT () Maybe ()
f a b

  = do
    (Just n1, Just n2) <- pure (a, b)
    m <- compute (n1 + n2)
    guard (m == 42)

  <|> do
    Just n <- pure a
    m <- compute n
    guard (m == 42)

  <|> do
    Just n <- pure b
    m <- compute n
    guard (m == 42)

This is about as minimal as you can get for this kind of "fallthrough".

A: It looks like you could get rid of the whole pattern match by relying on the fact that Int forms a Monoid with addition and 0 as the identity element, and that Maybe a forms a Monoid if a does. Then your function becomes:
f :: Maybe Int -> Maybe Int -> StateT () Maybe Int
f a b = pure $ a <> b >>= compute >>= pure . mfilter (== 42)

You could generalise by passing the predicate as an argument:
f :: Monoid a => (a -> Bool) -> Maybe a -> Maybe a -> StateT () Maybe a
f p a b = pure $ a <> b >>= compute >>= pure . mfilter p

The only thing is that compute is now taking a Maybe Int as input, but that is just a matter of calling traverse inside that function with whatever computation you need to do.

Edit: Taking into account your last edit, I find that if you spread your pattern matches into separate computations that may fail, then you can just write
f a b = f1 a b <|> f2 a b <|> f3 a b
  where f1 (Just a) (Just b) = compute (a + b) >>= check
        f1 _        _        = empty
        f2 (Just a) _        = compute a >>= check
        f2 _        _        = empty
        f3 _        (Just b) = compute b >>= check
        f3 _        _        = empty
        check x              = guard (x == 42)


text:
Q: Probability of inequality of Random variables Assume that $X_1,X_2,X_3$ are independent random variables with known distributions.
How can I calculate the distribution of $P(X_1<X_2<X_3)$.

A: \begin{align}
&\Pr[X_1 < X_2 < X_3] \\
=& \sum_{x_2}\Pr[X_1 < x_2\ \land\ x_2 < X_3\mid X_2 = x_2] \cdot \Pr[X_2 = x_2] \\
=& \sum_{x_2} \Pr[X_1 < x_2] \cdot \Pr[X_3 > x_2] \cdot \Pr[X_2 = x_2]
\end{align}
assuming $X_2$ is discrete.


text:
Q: Asterisk silence until agent answers Interesting issue I have never run into before with Asterisk.
Using Asterisk 1.8.x (please don't tell me to upgrade, it's not possible at this time).
When someone dial direct into the system to any of the numbers, we Answer, then push them to a queue and either play MOH on Ring sound.
This has always worked fine and still does. Most people forward calls to our numbers from their business line/phone system.
For this one customer and only one customer, there is complete silence for the caller once their phone system initiates the forward to our number. Our Asterisk box answers the call, we have even tried playing sounds using Playback etc but nothing, complete silence until one of the agents answers from the queue.
Really bizarre. canreinvite=no is set so, there shouldn't be any issues with Asterisk getting optimized out.
Any ideas a really appreciated. I know it's on their end but, it would be great to find a way to make Asterisk, make the customer's phone system behave correctly LOL.

A: You would have to take a wireshark trace at Asterisk box and check INVITE offer and 200OK response from asterisk. Then make sure that media RTP are sent to IP address in connection information line c= and port specified on m= media line. You also should check if rtp payload (codec) match the request and answer. Asterisk probably will respond with one codec from INVITE offer. When media are sent but caller does not hear anything before an agent answer the issue is probably on caller side. Hope helped a bit to tracę the issue.

A: I had the same problem once, but the other way around. I was the client dialing into someone else's system using my asterisk system. I tried everything in my hand, including pestering my (E1) telephony provider to no avail.
To this day I still don't know the reason for this behaviour, but I've managed to get around by Answering the call originated from my system BEFORE dialing the PSTN, thou this is far from ideal.
Something like this:
Answer()
...
Dial(YADAYADAYADA)

I know this isn't exactly the answer to your problem, but I hope it helps in any way.

A: Very likly you have issues with codecs. I.e customer use some codec you have no translation module, but agent's customer have


text:
Q: How to change the background color of select option's items on hover in react bootstrap I have tried changing the select option's items background color when the user hover over it. However, I couldn't find a way to fix the problem. My Code
    <label>Blood Group</label>
          <select className="custom-select form-control rounded-pill form-input-background" value={bloodGroup} onChange={(e) => setBloodGroup(e.target.value)}>
                <option value='A+'>A+</option>
                <option value='A-'>A-</option>
                <option value='B+'>B+</option>
                <option value='B-'>B-</option>
                <option value='O+'>O+</option>
                <option value='O-'>O-</option>
                <option value='AB+'>AB+</option>
                <option value='AB-'>AB-</option>
         </select>

My CSS
.form-input-background{
    background-color: #E6E6E6!important;
}
.custom-select option {
    background: #E6E6E6;
    border-radius: 1em!important;
}


text:
Q: Which Broadcom driver to use for BCM43142 adapter in Ubuntu 16.04 (xenial xerus) LTS? I recently upgraded to Ubuntu Xenial from Trusty, and am having trouble with my broadcom wireless adapter. I am currently using the bcmwl-kernel-source driver. The wifi works but keeps getting disconnected very frequently.
To troubleshoot I have tried to switch off the power management for the device. I have shifted from NetworkManager to wicd. I have tried the alternative, firmware-b43-installer, driver which doesn't work at all.
I understand that a comprehensive answer (Installing Broadcom Wireless Drivers) exists on installation of broadcom drivers but the information presented there might not be pertinent to Xenial.


text:
Q: IntelliJ imports Java Boolean and then throws error (First of all, yes, Minecraft plugin development. Live with it)
So, I'm developing Kotlin in IntelliJ IDEA Ultimate, but it really hates me when it comes to importing java.lang.Boolean instead of kotlin.Boolean automagically.
My Kotlin plugin is fully up to date, and so is IntelliJ according to JB Toolbox.
Every time I press CTRL+ALT+L to auto-format and auto-import it imports java.lang.Boolean and then throws errors all over in the file that I should use kotlin.Boolean. Indeed, it's as simple as removing the import, but that's extra effort for nothing, as it should be able to do this itself. It may have something to do with extending a Java class, which has methods returning a Java Boolean, but I don't see how this would be the case, as it's simply way too annoying and more users should have noted it before.
If I change the return type to java.lang.Boolean it says the overridden class, with no connection whatsoever to Kotlin STD-Lib, uses the Kotlin version and that I should change it to kotlin.Boolean. This has annoyed me a while now, so do anyone have any idea?
The file in question is by the way this: https://gitlab.com/proximyst/HellishSurvival/blob/master/Plugin/src/main/java/com/proximyst/hellishsurvival/Commands.kt


text:
Q: Showing an image with tkinter I need to show an image into a label or a checkButton, for this aim, I am using Pillow and Tkinter. But I am wondering what is going on with my codes, I mean, I have done two tests, the first one works perfectly but the second one doesn't show the required image, all what is shown is a blank background. Really, I have not found the problem yet. Would you help me, please?
Thank you in advance.
First code:
from tkinter import ttk
from tkinter.ttk import *
from tkinter import *
from PIL import ImageTk, Image

root = Tk()

myImg = ImageTk.PhotoImage(Image.open("firstFunction.png").resize([100, 100]))

ttk.Label(root, image=myImg).pack()

root.mainloop()

Second code:
from tkinter import ttk
from tkinter.ttk import *
from tkinter import *
from PIL import ImageTk, Image

class Gui:

    # Constructor function
    def __init__(self, title, width, height, foreground, background):

        # Attributes of the instance
        self.root = Tk()  # Root
        self.title = title  # Title
        self.height = height  # Height
        self.width = width  # Width
        self.foreground = foreground  # Foreground
        self.background = background  # Background color

    # Method of the class

    # Function for creating the appareance of Gui
    def appareance(self):

        # Setting tittle
        self.root.title(self.title)

        # Size of screen
        self.root.geometry(str(self.width) + "x" + str(self.height))

        # Changing background color
        self.root.configure(bg=self.background)

    # Function to create a menu
    def menu(self):

        # Creating main menu
        mainMenu = Menu(self.root)

        # Setting main menu
        self.root.config(menu=mainMenu)

        # Creating submenu of main menu
        plot = Menu(mainMenu, tearoff=FALSE)

        mainMenu.add_cascade(label="Plot", menu=plot)

        plot.add_command(label="test", command=self.secondMenu)

    # Function to create the second menu
    def secondMenu(self):

        # Creating a second window
        secondWindow = Toplevel(self.root, background="white")

        myImg = ImageTk.PhotoImage(Image.open("firstFunction.png").resize([100, 100]))

        ttk.Label(secondWindow, image=myImg).grid()

    # Function for calling each function from the class
    def gui(self):

        self.appareance()

        self.menu()

        # Creating infinite loop to show in screen
        self.root.mainloop()

# Main features of a GUI
title = "test"
width = 400
height = 450
foreground = "black"
background = "white"

# Creating an object from classGUI
a = Gui(title, width, height, foreground, background)

a.gui()


text:
Q: Comparing QUERY and EXECUTE in Dapper I would like to ask if what is the best to use when INSERTING, UPDATING, DELETING, REMOVING, QUERY SPECIFIC DATA using DAPPER? I'm really confused in using EXECUTE and QUERY command in DAPPER..

A: This should not be confusing at all, especially if you look at the signature of the methods exposed by the Dapper (as per documentation):
public static IEnumerable<T> Query<T>(this IDbConnection cnn, string sql, object param = null, SqlTransaction transaction = null, bool buffered = true)

Query method is specifically meant for executing a select statement internally, which can return the IEnumerable of a type T, there are options to execute it, if done using anonymous parameter, then you are not expecting any return value or Output parameter, it just takes input parameter and provide the result, which has schema matching to the properties of Type T. In case return value or Output parameter is required, then that needs to be bound using DynamicParameters
public static int Execute(this IDbConnection cnn, string sql, object param = null, SqlTransaction transaction = null)

Execute method is meant for executing the DML statements, like Insert, Update and Delete, whose purpose is to make changes to the data in the database. The return type is an integer, which should contain the value of number of rows updated, if in SQL Server we have set Set RowCount On, this call will not help in returning the Result Set, its only for DML calls.
In case you need multiple result set then we have QueryMultiple. which returns a GridReader and can be used to return the result of multiple Select statements, using a concept of MARS (Multiple active result set).
Practically if your aim is just to execute a procedure, any of them would do, but what is more important is what result set are looking forward to receive, they all have different return to provide results


text:
Q: How can we improve the experience for non-native speakers on Stack Overflow? It's obvious to me that there's a trend now on Stack Overflow of relatively low-quality questions from new users who are non-native speakers with low or intermediate fluency in English, or at least claim to be.
It doesn't take a genius to work out that this may be because some of them struggle to read and fully comprehend the various English-language notices and admonitions that Stack Overflow has put in place to try to deter low-quality questions over the years - from welcome pages, to automated content filters displaying terse rejection messages.
I am not saying that such non-native speakers always ask bad questions, of course - far from it! - I am saying that a noticeable number of the low-quality questions, are from such non-native speakers.
What could we do about this particular problem?

A: There's a bit of an update to this as part of the Stack Exchange Quality Project (related here | related on MSO). Some new review queues will be created, one of which is specifically designed for folks that enjoy helping people that want to ask good questions, but can't because they're struggling with improving their communication skills.
A language barrier is one reason someone might struggle and perhaps flail a bit while trying to communicate their ideas, plenty of native speakers simply choke when they need to express their thoughts in writing. This special queue will be designed specifically to assist those that have the time, skill and patience to help others to do so.
It'll be work, the system will do its best to help you make sure that you make 'angel' edits, or a single edit that is going to help the person nail the question. It's also going to help ensure that your process, or rather how you edited becomes a learning experience for the question author.
This queue (at least how it exists on our drawing board) will be fed from a sort of triage - a queue where folks can send great questions right to the front page, total crap to the rubbish bin, and diamonds in the rough to a place where they'll get help.
Nothing is carved in stone yet, but language barriers should only be show-stoppers when you simply can't reach people enough to tell them that they need to include the right kind of information (mostly, in code, what they searched, etc).

A: What you can do is to help them in understanding how to post here. Instead of criticizing their bad English grammar or the way they punctuate their spellings.
There are only 2 - 3 options for a beginner (well obviously like me) which are

*

*Edit the question, if you think that this can be made useful. Remove anything that is not related to the question, edit simple mistakes and typos, try to clarify the topic and the subject. But do not change the question.

*Flag it, so that moderator can help the user, by either deleting the question if it's too low quality or by editing the question. So that he can learn that I should use this type of subject or this topic in future to ask questions.

*Comment on the post, so that he can know where he is wrong.

*If you have enough reputation points, vote to close the post, and it might get closed as unclear.
Well believe me, when I started to use Stack Overflow I did not know how to ask, when to ask, where to ask. These three options are must-know for each. I am not an English or an American, but this community made me feel like I can speak this language and can understand how they use words. So you need to be patient and help them in learning this language.
It takes time in start, but as the community helps them, they learn it :)
You're somewhat right, since the low-quality posts for you at least are actually from non-natives. Because it's difficult for you to understand their English as they're making a lot of mistakes in their posts which is really frustrating and sometimes irritating too.
So on my choice, Stack Overflow is a well organised community where people not only learn how to code, they learn how to treat their fellow programmers, they learn how to speak English and how to be on-topic (as there is some strictness too :D..)

A: If the question being asked is bad, vote to close.
If the phrasing is bad, edit it to clean it up.
(If the original question is in a foreign language, vote to close.  No sense in struggling through a translator or having someone else transcribe the text.)
I don't take native language into account when I look at a question that needs to be cleaned up - if it needs to be fixed, I'd rather fix it if and when applicable.  If it can't be, or it shouldn't be, then vote-to-close and downvote would be a good approach.
I don't see a problem to the current way this is handled.

A: I can't begin to imagine how difficult the site must be for non-native English speakers who struggle with the language. Programming is difficult enough to begin with, and to express yourself, or even to understand the site you're participating on well enough to participate without problems can't be easy.
You could think of providing all kinds of localized support, and this has come up in various forms. One of the answers here speaks of translating the various notices into localized versions. And there have been proposals in the past to provide a form of translation service, where one could ask questions in their native language, and have them translated before being posted on the site. But I think neither of those options are a true solution.
The only real solution I see (besides the users actually learning the English language to a level where they can participate without any problem) is to create localized versions of the site. Start a Stack Overflow in Chinese, or whatever language can provide for an audience that is large enough for such a site to be sustainable.
And it's exactly this idea, and concerns regarding it that have been brought up in the past. It's quite an involved step to take, but it's not a stopgap measure. If done well, it provides those users who have difficulty participating purely due to language with a platform where they can do so without hesitation. And though it might not be comforting of satisfying to hear, if you really wish to participate on Stack Overflow, you might just have to work on your English.

A: I have an idea. How about we:

*

*identify the most problematic countries and regions by IP geolocation, possibly including any IP ranges that have previously been blocked due to the volume of bad quality questions that have originated from them in the past, then

*launch a crowdsourcing effort to translate the notices and admonitions that I mentioned in my question into the language(s) commonly spoken in these countries or regions, then

*place large, noticeable language buttons somewhere where new users will see them (e.g. in a new interstitial page immediately after account signup), allowing/forcing new users to choose their UI language?

Then new users would actually have a better chance of understanding our community norms. Maybe... we could even adjust the "bluntness" of the language to match cultural norms of each country...
What do you think?


text:
Q: Are there spam filters that check email headers? Are there spam filtering technologies that examine email headers?
For example; X-PHP-Origin header can contain an IP address that is on a blacklist; are there spam filters that would catch this?
I thought spam filters only checked the connecting client?

A: As far as I know most of them actually do.
This is actually a very basic way of filtering spam, looking at the header and compare the senders IP to black lists such as spamhaus's SBL list.

A: Well, SpamAssassin for one.
Here's a list of the checks it performs:
http://spamassassin.apache.org/tests_3_3_x.html
The list notes the "area" of the email that are tested, e.g., body, header, etc.
Glancing through the list, it's entirely possible that SpamAssassin will not catch a blacklisted IP address used in your non-standard X-PHP-Origin header, as the header tests tend to look at specific header lines, and your referenced header probably won't be one of those.

A: There are blacklists out there that use the mail headers to deny email.
In sendmail, there are many different tools available that you can configure for spam control as well.


text:
Q: Anylogic model stop without message I have created a model to generate a product that will be cycled through a list of machines. Technically the product list is for a single-day run, but I run the model for long durations to stabilise the model output.
The model can run properly for months until around 20 months, then suddenly stops without any error message as shown in the screenshot. I do not know how to debug this since I do not know where the error comes from.
Does anyone have a similar encounter and could advise on how to approach this issue? Could it be an issue of memory overload?

A: Without more details, it's hard to pinpoint the exact reason, but this generally happens if the run is stuck in an infinite While Loop or similar. So check all your loops where it's possible for such a scenario to happen and it's likely that one of them (or more) is causing the issue.


text:
Q: datetime time zone conversion in .net web service I have a web service (actually a silverlight enable wcf service, but for all intents and purposes, it's a web service) with a method taking a datetime parameter.  The method gets called from a client, which could be in a different time zone.  The service hosting the web service is in pacific standard time, and it appears the web service is converting the date time value to the servers time zone.  The intent of the web service is to compare the datetime value against a value in the database, but the value in the database is based on the clients timezone, so because of the conversion, the comparison is not working.
Is there any way to turn the conversion off?

A:
and it appears the web service is converting the date time value to the servers time zone.

I'm trying to make sure I have this correct: your web service method takes a parameter of type DateTime (as in, System.DateTime) and is converting the passed parameter?
DateTime objects don't carry an implicit timezone, so any determination by the web service to infer local time would be a logic flaw (at least without supporting timezone criteria.)
If you can supply your server and client code snippets, it would make the scenario easier to diagnose.
UPDATE: Not sure if this scenario is accurate, so please clarify:

*

*Client submits request with DateTime value of '12:00:00 00:00:00 PM CST'

*Server in PST receives/interprets request at '10:00:00 00:00:00 PM PST'

If this is the case, can you convert all data to UTC time? If you're executing a query lookup, this implies converting the stored data to UTC as well.

A: Not quite true that DateTime instances (structs) do not carry TimeZone info. There is a DateTimeKind property on each DateTime struct, as of .NET ... 3.0?  I don't know the version.  "Kind" is UTC, Local, or Unspecified.  so while it is not a TimeZone per se, it is an inidication that the time is either expressed in the local zone, or in the universal time zone. Check the doc for more info.
To answer the original question - convert everyone to a single standard timezonee. UTC works just fine, and is easy because there are methods built-in to the BCL, but it doesn't really matter what timezone you choose. Just get everyone to agree on a standard.
Another thing you can do is transmit the time values as "TotalSeconds" values since... some specific time in the past.  Like Jan 1 1970 (unix time_t), or Jan 1 1601 (windows FILETIME).  But implicit in this approach is that all cooperating parties agree that this beginning point in time is UTC.  So one million seconds since the beginning (the "epoch") refers to the same moment whether I am in El Paso or  Nashua or Tokyo or London.

A: Check out this question, it has some discussion of what you want.

*

*Override DateTime serialization for ASP.NET WebMethod parameters
It looks like the easiest way is to pass the client timezone as well in the webmethod, or just pass the whole time as a string rather than a DateTime


text:
Q: Java applet doesn't draw on mouse events this is the code:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.util.Vector;

public class PainterNN extends Applet implements MouseListener, MouseMotionListener{

    class MyShape{
    int mx;
    int my;
    Color mc;

    MyShape(int x, int y, Color c){
        mx=x;
        my=y;
        mc=c;
        }

    void Render(Graphics g){
          g.setColor(mc);
        g.fillOval (mx,my,10,10);
        }
}

    Vector<MyShape> vec = new Vector();

    public void init() {
        }

    public void paint(Graphics g) {
        for(int i =0; i < vec.size() ; i=i+1){

        MyShape s = vec.elementAt(i);
        s.Render(g);
        }
    }

    public void mouseEntered( MouseEvent e ) {
      // called when the pointer enters the applet's rectangular area
   }
           public void mouseExited( MouseEvent e ) {
      // called when the pointer leaves the applet's rectangular area
   }
           public void mouseClicked( MouseEvent e ) {
      // called after a press and release of a mouse button
      // with no motion in between
      // (If the user presses, drags, and then releases, there will be
      // no click event generated.)
   }
           public void mousePressed( MouseEvent e ) {  // called after a button is pressed down
      repaint();
      // "Consume" the event so it won't be processed in the
      // default manner by the source which generated it.
      e.consume();
   }
   public void mouseReleased( MouseEvent e ) {  // called after a button is released
       repaint();
      e.consume();
   }
   public void mouseMoved( MouseEvent e ) {  // called during motion when no buttons are down
      e.consume();
   }
   public void mouseDragged( MouseEvent e ) {  // called during motion with buttons down
     int mx = e.getX();
     int my = e.getY();

      vec.add(new MyShape(mx,my,new Color(0,255,0)));
      repaint();
      e.consume();
   }

}

It should draw circles at mouse drag but it didn't. Why?

A: You have to add the mouse listeners.
public void init()
{
    this.addMouseListener(this);
    this.addMouseMotionListener(this);
}

Hint: Try using Ctrl - Shift - F in your IDE. Normally, it will beautify your code. (Eclipse and NetBeans support this)


text:
Q: I sat primary key on name varchar it accepts one null value I sat primary key on name varchar it accepts one null value
It acts like unique constraint.
What's the problem?

A: I think you;re missing some details in ques but if you set any column to PK it doesn't allow null values into it.
But, Usually we will not set Primary Key constraint on anything(name column here) which are having a meaning in the system and instead have something like ID or GUID as primary key.


text:
Q: How to get GeoJSON into OpenLayers? I already tried to put the following function and new Vector Layer into my code. I uploaded the GeoJSON File into my BPlaced account to link the file in my code, is that right?
The Geojson has the same Coordinate System as the website. Also the code seems to work but I don't see any of the Geojson.
Or is there another way to embed GeoJSON into OpenLayers?
Here is my code:
var vectorLayerJSON = new ol.layer.Vector({
  source: new ol.source.Vector({
    format: new ol.format.GeoJSON(),
    url: 'http://kristinab.bplaced.net/ALDI_LIDL_Buffer_KBS_3857.geojson'
  }),
  style: new ol.style.Style({
    image: new ol.style.Circle(({
      radius: 20,
      fill: new ol.style.Fill({
        color: '#ffff00'
      })
    }))
  })
});

A: I believe that there are several ways to add vectors (geojson) data to map

*

*loading vectors using geojson file url:

    var vectorLayerJSON_1 = new ol.source.Vector({
       projection : 'EPSG:3857',
       url: 'myFolder/yourFile_1.geojson',
       format: new ol.format.GeoJSON()
    });

*generating vector layer from geojson object

      var geojsonObject = {
            'type': 'FeatureCollection',
            'crs': {
              'type': 'name',
              'properties': {
                'name': 'EPSG:3857'
              }
            },
            'features': [{
              'type': 'Feature',
              'geometry': {
                'type': 'Point',
                'coordinates': [0, 0]
              }
            }, {
              'type': 'Feature',
              'geometry': {
                'type': 'LineString',
                'coordinates': [[456, -256], [816, 226]]
              }...

    var vectorLayerJSON_2 = new ol.source.Vector({
            features: (new ol.format.GeoJSON()).readFeatures(geojsonObject)
          });

More detailed example on OpenLayer 3 example page Geojson Example

*reading vector features from ajax

        var vectorLayerJSON_3 = new ol.layer.Vector({
        renderMode: 'image',
        source: new ol.source.Vector({
            loader: function() {
                $.ajax({
                    type: 'GET',
                    url: 'myFolder/yourFile_2.geojson',
                    context: this
                }).done(function(data) {
                    var format = new ol.format.GeoJSON();
                    this.addFeatures(format.readFeatures(data));
                });
            }
        }),
        style: myDefinedStyle
    });

     var map = new ol.Map({
            layers: [
              new ol.layer.Tile({
                                source: new ol.source.OSM()
                            }),
                            vectorLayerJSON_1,
                            vectorLayerJSON_2,
                            vectorLayerJSON_3
            ],
            target: 'map',
            view: new ol.View({
              center: [0, 0],
              zoom: 2
            })
          });


text:
Q: MySQL Finding the MAX of the SUM of each month of the year [MYSQL] Currently i am able to get the sum for the highest amount for each month of the year. But what i want to do, is to be able to get the SUM of the month that has the highest value in amount for each year.
SELECT year(paymentDate), month(paymentDate) , SUM(amount)
FROM classicmodels.payments
GROUP BY year(paymentDate), month(paymentDate)
ORDER BY SUM(amount) DESC;

This orders the highest SUM(amount) in descending order but i only want to get the highest month for each year. there are only 3 years in my database.
Here's what happening on mysql workbench

A: One method uses a having clause:
SELECT year(p.paymentDate), month(p.paymentDate), SUM(p.amount)
FROM classicmodels.payments p
GROUP BY year(p.paymentDate), month(p.paymentDate)
HAVING SUM(p.amount) = (SELECT SUM(p2.amount)
                        FROM classicmodels.payments p2
                        WHERE year(p2.paymentDate) = year(p.paymentDate)
                        GROUP BY month(p2.paymentDate)
                        ORDER BY SUM(p2.amount) DESC
                        LIMIT 1
                       )
ORDER BY SUM(amount) DESC;


text:
Q: Vaadin - Internal error Please notify the administrator. Take note of any unsaved data, and click here or press ESC to continue I am developing an application in Vaadin where I have a view for Suppliers.
I am getting the error  Internal error Please notify the administrator. Take note of any unsaved data, and click here or press ESC to continue. due to the calling of the method categoriesToString in my View.
View
    public SupplierView(CrmService service) {
        this.service = service;
        addClassName("supplier-view");
        setSizeFull();
        configureGrid();

        form = new SupplierForm(service.findAllCategories(null));
        form.setWidth("25em");
        form.addListener(SupplierForm.SaveEvent.class, this::saveSupplier);
        form.addListener(SupplierForm.DeleteEvent.class, this::deleteSupplier);
        form.addListener(SupplierForm.CloseEvent.class, e -> closeEditor());

        FlexLayout content = new FlexLayout(grid, form);
        content.setFlexGrow(2, grid);
        content.setFlexGrow(1, form);
        content.setFlexShrink(0, form);
        content.addClassNames("content", "gap-m");
        content.setSizeFull();

        add(getToolbar(), content);
        updateList();
        closeEditor();
        grid.asSingleSelect()
                .addValueChangeListener(event -> editSupplier(event.getValue()));
    }

    private void configureGrid() {
        grid.addClassNames("supplier-grid");
        grid.setSizeFull();
        grid.setColumns("name", "address");
        grid.addColumn(supplier -> supplier.categoriesToString())
                .setHeader("Categories");
        grid.getColumns().forEach(col -> col.setAutoWidth(true));
    }
}

The said method belongs to the class Supplier that can be seen below. This class has a Set of Category that I am trying to go trough in order to return all categories present in it.
Supplier
@Entity
public class Supplier extends AbstractEntity {
    @NotEmpty
    private String name;
    @NotEmpty
    private String address;

    @OneToMany(mappedBy = "supplier")
    private Set<Category> categories = new LinkedHashSet<>();

    public String getName() {
        return this.name;
    }

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

    public String getAddress() {
        return this.address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

   public Set<Category> getCategories() {
        return categories;
    }

    public void setCategories(Set<Category> categories) {
        this.categories = categories;
    }

    public String categoriesToString(){
        String allCategories = "";
        for (Category c : this.categories)
        {
            allCategories += c.getDescription();
        }

        return allCategories;
    }
}

In order to do some testing I tried to make the method just return "test" and in that scenario the word was indeed added to "Categories" column and no error was shown.
Category class
@Entity
public class Category extends AbstractEntity{
    @NotBlank
    private String description;

    @ManyToOne
    @JoinColumn(name = "supplier_id")
    @JsonIgnoreProperties({"categories"})
    private Supplier supplier;

    public String getDescription() {
        return this.description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

Why is this happening? Am I iterating through the set in a incorrect way?

A: You have not specified the fetch mode for your Entity, so it is defaulting to Lazy mode. Your current logic will only work with Eager mode (that would fetch the "categories" one-to-many relationship), but this is bound to create performance issues down the road as your data grows.
I wouldn't use logic inside my entities either (your categoriesToString method), but that is a different topic altogether.
You can either specify Eager loading on your entity as:
@OneToMany(fetch = FetchType.EAGER, mappedBy = "supplier")
private Set<Category> categories = new LinkedHashSet<>();

Or perform an additional query to fetch the related categories. Or even better, create a POJO or Spring Data Projection to fetch/map the appropriate data to. You can check this link for more info on that matter.


text:
Q: When I use longtable, the table can't fit the whole text, is there any solution? Or is there a suitable way to change the page? Is there an effective way to automatically display text that cannot be accommodated to the next page?
For example, the code is
\documentclass{article}
\usepackage{longtable,lipsum}
\begin{document}

\begin{longtable}{|l|c|c|c|c|c|}
    \hline
    \multicolumn{6}{|p{10cm}|}{\lipsum } \\ \hline
\end{longtable}

\end{document}

The compilation result is as follows:

A: You have to add a \pagebreak from time to time.

\documentclass{article}
\usepackage{longtable,lipsum}
\begin{document}

\begin{longtable}{|l|c|c|c|c|c|}
    \hline
    \multicolumn{6}{|p{10cm}|}{1. \lipsum[1-4] } \\ \hline
    \pagebreak
    \hline
    \multicolumn{6}{|p{10cm}|}{5. \lipsum[5-8] } \\ \hline
\end{longtable}

\end{document}

With longtable you can run headers and footers that link the partial tables page by page.

\documentclass{article}
\usepackage{longtable,lipsum}

\begin{document}

\begin{longtable}{|l|c|c|c|c|c|}
    \hline
    \multicolumn{6}{|p{10cm}|}{\Large Main heading } \\
    \hline
    \endfirsthead

    \multicolumn{3}{l} {\footnotesize \emph{ \ldots{} from previous page.}} \\
    \hline
    \multicolumn{6}{|p{10cm}|}{ \Large Main heading } \\
    \hline
    \endhead

    \multicolumn{6}{r}{\footnotesize \emph{to be continued in the next page \ldots{} }} \\
    \endfoot

    \endlastfoot

    \multicolumn{6}{|p{10cm}|}{1. \lipsum[1-4] } \\ \hline
    \pagebreak
    \multicolumn{6}{|p{10cm}|}{5. \lipsum[5-8] } \\ \hline
\end{longtable}

\end{document}


text:
Q: Moq - Method evaluation with nullable parameter throws null exception I know that I can new up an object and pass it in but I'm trying to match the syntax and patterns since the value is never actually used.
Implementation:
public interface IDemoProvider
{
    string GetStringById(int? id);
}

public interface IDemoService
{
    bool Validate(ServiceRequest request);
}

public class ServiceRequest
{
    public string foo { get; set; }
    public int? bar { get; set; }
}

public class SomeDemoProvider : IDemoProvider
{
    public virtual string GetStringById(int? id)
    {
        if (id != null)
            return "success";
        else
            return "else";
    }
}

public class BaseDemoService : IDemoService
{
    public IDemoProvider Provider { get; set; }

    public virtual bool Validate(ServiceRequest request)
    {
        if (request.bar == null)
            return false;

        return true;
    }
}

public class SomeDemoService : BaseDemoService
{
    public SomeDemoService(IDemoProvider provider)
    {
        Provider = provider;
    }

    public virtual string Post(ServiceRequest request)
    {
        if (!Validate(request))
            throw new Exception("Invalid Request");
        return Provider.GetStringById(request.bar);
    }
}

Test Code:
[TestFixture]
public class ProgramTests
{
    [Test]
    public void SomeDemoServiceTest()
    {
        var mockProvider = new Mock<IDemoProvider>();
        mockProvider.Setup(p => p.GetStringById(It.IsAny<int?>())).Returns(() => "success");

        object[] args = { mockProvider.Object };

        var mockService = new Mock<SomeDemoService>(args) {CallBase = true};
        mockService.Setup(s => s.Validate(It.IsAny<ServiceRequest>())).Returns(true);

        string result = mockService.Object.Post(It.IsAny<ServiceRequest>());

        Assert.AreEqual("success", result);
    }
}

Issue
This results in a NullReferenceException which makes sense since it's trying to resolve request.Id while running which is null at the request level.
However, if I replace the parameter with null, it works fine:
return Provider.GetStringById(null);

My question here is whether there's some way to make the interceptor recognize before evaluating the expression that it should just return the value instead of trying to evaluate the expression.
I could mock out the rest of the request object but it seems silly since the values are never used according to the test. The real question here is whether I should be writing the code or the test differently to avoid this scenario or if I'm over complicating an issue with a simple workaround.

A: You are testing it wrong.
If you are trying to exercise the method under test then this line...
string result = mockService.Object.Post(It.IsAny<ServiceRequest>());

is being used incorrectly. You would use It.IsAny<ServiceRequest>() as part of the setup. In the case of how you are trying to use it, it will result in null in the Validate method
request.bar == null

because the It.IsAnyexpression is not actually passing anything into the method.
Read up on how to use Moq via the Moq Quickstart to get a better understanding of how to use it when testing.
Rewrite the test as
public void SomeDemoServiceTest() {
    //Arrange
    var mockProvider = new Mock<IDemoProvider>();
    mockProvider.Setup(p => p.GetStringById(It.IsAny<int?>())).Returns(() => "success");

    var mockService = new Mock<SomeDemoService>(mockProvider.Object) { CallBase = true };
    mockService.Setup(s => s.Validate(It.IsAny<ServiceRequest>())).Returns(true);

    var request = new ServiceRequest();

    //Act
    var result = mockService.Object.Post(request);

    //Assert
    Assert.AreEqual("success", result);
}

And the test should pass.


text:
Q: PhoneGap 2.1.0 iOS Mac Xcode CordovaLib Trying to get some solid documentation on how to get the iPhone emulator in Xcode running with my PhoneGap 2.1.0 project. I pulled it down from a git repo that I originally built on my Mac Pro, now want to run it on my Mac Air. There is a lot of confusion of the terminologies between PhoneGap and Cordova that make it near impossible for a beginner to figure out how to set up a project.
The problem I'm getting when I open my PhoneGap project in XCode is this error:
Lexical or Preprocessor Issue 'Cordova/CDVViewController.h' file not found

Clearly the Cordova class files aren't being seen by XCode, although I included the path to the CordovaLib classes in Preferences -> Source Trees (~/Documents/CordovaLib/.
Just want to get this thing running! Thanks!

A: Not sure if this will help you, but I am starting to try to get to grips with PhoneGap/Cordova, and found this excellent guide on getting it going.
It uses Cordova, which I am led to believe is the source of PhoneGap (Still SLightly Confused tbh), hopefully it will help you in one way or another, it certainly got me up and running :)
https://docs.google.com/viewer?a=v&pid=forums&srcid=MDUyNDQxMjA3MzY2NzYzNDU0MjgBMTAxMDE4ODcyODc5Njc4NDQwMzQBOWNxRFF3Z0UyX29KATQBAXYy


text:
Q: cytoscapeJS 3.2.5 - get graph object instance - .cytoscape('get') I have a question about cytoscapeJS. I upgraded my application to use the latest version of cytoscapeJS: v3.2.5. In the past, in my code, the network graph was initialised and node/edge data and appearance attributes were set.
Initialisation code changed from (the page has an empty <div> with id='cy'):
$('#cy').cytoscape({
  container: $('#cy'),
...
to:
var cy= cytoscape({ // in cytoscapeJS v3.2.5
  container: document.getElementById('cy'),
...
Later on, users could select what layout to use and the code would get the graph object and run the selected layout on the visible elements as below:
var cy= $('#cy').cytoscape('get');
var coseLayout= { name: 'cose', handleDisconnected: true, avoidOverlap: true };
cy.$(':visible').layout(coseLayout);
But the above now throws this error: Uncaught TypeError: $(...).cytoscape is not a function (on the first line).
I have gone through the updated website docs (Core API, collection, etc.) and demos over the last week but have found no way to do the same in the new cytoscapeJS 3.2.5, i.e., to get the graph outside the initialisation code and perform some operations on it.
I also posted this query at https://github.com/cytoscape/cytoscape.js/issues/2015 but got no response. Any suggestions would be very helpful. Thanks.

A: Keep the reference and pass it where need be or keep a global reference.


text:
Q: AVX is not faster than SSE? I have large block of data to calculate:
static float source0[COUNT];
static float source1[COUNT];
static float result[COUNT];    /* result[i] = source0[i] * source1[i]; */

s0 = (size_t)source0;
s1 = (size_t)source1;
r = (size_t)result;

They are all 32-byte aligned.
The related SSE code:
for(i = 0; i < COUNT; i += 16)
{
    __asm volatile
    (
        "movntdqa xmm0, [%0]\n\t"
        "movntdqa xmm1, [%1]\n\t"
        "mulps xmm1, xmm0\n\t"
        "movntps [%2], xmm1"
        : : "r"(s0 + i), "r"(s1 + i), "r"(r + i) : "xmm0", "xmm1"
    );
}

The related AVX code:
for(i = 0; i < COUNT; i += 32)
{
    __asm volatile
    (
        "vmovapd ymm0, [%0]\n\t"
        "vmovapd ymm1, [%1]\n\t"
        "vmulps ymm1, ymm1, ymm0\n\t"
        "vmovntps [%2], ymm1"
        : : "r"(s0 + i), "r"(s1 + i), "r"(r + i) : "ymm0", "ymm1"
    );
}

The result is that AVX code used time is always nearly the same as SSE code. But they are much faster then normal C code.
I think the major reason is that "vmodapd" does not support "NT" version, until AVX2 extension. This causes too much d-cache pollution.
Is there any better way to explore the power of AVX(not AVX2)?


text:
Q: posts disappearing from feed when like button is pressed I am using the following function to update posts in my feed:
func fetchPosts() {
    let query = COLLECTION_POSTS
        .order(by: "timestamp", descending: true)

    query.addSnapshotListener { snapshot, _ in
        guard let changes = snapshot?.documentChanges.filter({$0.type == .added}) else {return}

        self.posts = changes.compactMap {
            do {
                return try $0.document.data(as: Post.self)
            } catch {
                print("Error converting Firestore document to Post object: \(error)")
                return nil
            }
        }
        self.fetchUserPosts()
    }
}

When I like a post and update the like count the posts disappear from the feed, then I get a debug message via the self.fetchuserposts() function that there are no posts on the database. However, despite this, the likes still increase on the server side.
The following is the code that updates the like field when a user presses it:
func likePost(post: Post) {
    guard let uid  = Auth.auth().currentUser?.uid else { return }
    guard let postId = post.id else { return }
    let userLikesRef = Firestore.firestore().collection("users").document(uid).collection("user-likes")

    Firestore.firestore().collection("posts").document(postId)
        .updateData(["likes" : post.likes + 1]) { _ in
            userLikesRef.document(postId).setData([:]) { _ in
                self.isLiked = true
            }
        }
}

I have tried many different methods of updating the like field but I cannot seem to figure it out. I expect that there is maybe an issue where the model is not being updated but that does not make sense to me given that the snapshot listener is listening for changes.

A: I (jankily) fixed this issue using the folllowing code. However, all posts in the feed reload when pressing the like button, not ideal, I would still appreciate help if anyone has a better solution!
func fetchPosts() {

    let query = COLLECTION_POSTS
        .order(by: "timestamp", descending: true)

    query.addSnapshotListener { snapshot, _ in
        guard let changes = snapshot?.documentChanges else {return}

        for change in changes {

            if change.type == .added {
                do {
                    let post = try change.document.data(as: Post.self)
                    self.postsArray.append(post)
                } catch {
                    print("Error converting Firestore document to Post object: \(error)")
                }
            }
        }
        self.posts = self.postsArray
        self.fetchUserPosts()
    }
}


text:
Q: How to select rows with WHERE statement and COUNT(*) = 1 I am trying to combine a WHERE clause with a HAVING COUNT(*) clause. But I can't get the results I want.
I want to find all the customers that have placed only one order and the order is "inactive". Put another way, I am trying to select rows from an order table where the count of customer_name value is "1" and the order status equals "inactive".
I have this table:
orders_tbl
+----+--------------+-------------+---------+-------+
| ID |    cust_name |      status | item_no | price |
+----+--------------+-------------+---------+-------+
|  1 |        Scott |      active |       4 |   2.0 |
+----+--------------+-------------+---------+-------+
|  2 |        James |      active |       2 |   4.0 |
+----+--------------+-------------+---------+-------+
|  3 |         Eric |    inactive |       3 |   8.0 |
+----+--------------+-------------+---------+-------+
|  4 |        Polly |      active |       3 |   2.0 |
+----+--------------+-------------+---------+-------+
|  5 |        Peggy |    inactive |       6 |   4.0 |
+----+--------------+-------------+---------+-------+
|  6 |         Earl |    inactive |       1 |   5.0 |
+----+--------------+-------------+---------+-------+
|  7 |        Billy |      active |       4 |   2.0 |
+----+--------------+-------------+---------+-------+
|  8 |        Peggy |    inactive |       5 |   4.0 |
+----+--------------+-------------+---------+-------+
|  9 |        Jenny |    inactive |       4 |   8.0 |
+----+--------------+-------------+---------+-------+
| 10 |        Polly |      active |       2 |   2.0 |
+----+--------------+-------------+---------+-------+
| 11 |        Scott |    inactive |       2 |   4.0 |
+----+--------------+-------------+---------+-------+
| 12 |        James |    inactive |       1 |   8.0 |
+----+--------------+-------------+---------+-------+

I want the name of every client with only one order and the order is "inactive". From the table above, I want these results:
+----+--------------+-------------+---------+-------+
| ID | cust_name    |     status  | item_no | price |
+----+--------------+-------------+---------+-------+
|  3 |         Eric |    inactive |       3 |   8.0 |
+----+--------------+-------------+---------+-------+
|  6 |         Earl |    inactive |       1 |   5.0 |
+----+--------------+-------------+---------+-------+
|  9 |        Jenny |    inactive |       4 |   8.0 |
+----+--------------+-------------+---------+-------+

I tried this query, as well as many variations using WHERE and COUNT():
SELECT ID, cust_name, status, item_no, price, COUNT(*)
FROM orders_tbl
WHERE status = 'inactive'
GROUP BY cust_name
HAVING COUNT(*)<2;

The above query produced results close to what I want. But I am getting customers that have one "inactive" record even if they have one or more active records. There are the results I get:
orders_tbl
+----+--------------+-------------+---------+-------+
| ID |    cust_name |      status | item_no | price |
+----+--------------+-------------+---------+-------+
|  3 |         Eric |    inactive |       3 |   8.0 |
+----+--------------+-------------+---------+-------+
|  5 |        Peggy |    inactive |       6 |   4.0 |
+----+--------------+-------------+---------+-------+
|  6 |         Earl |    inactive |       1 |   5.0 |
+----+--------------+-------------+---------+-------+
|  9 |        Jenny |    inactive |       4 |   8.0 |
+----+--------------+-------------+---------+-------+
| 11 |        Scott |    inactive |       2 |   4.0 |
+----+--------------+-------------+---------+-------+
| 12 |        James |    inactive |       1 |   8.0 |
+----+--------------+-------------+---------+-------+

A: One solution would be to use aggregation, and to to move the logic to a HAVING clause.The following query can give you the names of the customers that satisfy the conditions : :
SELECT cust_name
FROM mytable
GROUP BY cust_name
HAVING COUNT(*) = 1 AND MAX(status) = 'inactive'

Returns :
| cust_name |
| --------- |
| Earl      |
| Eric      |
| Jenny     |

If you want to see the orders as well then you can turn this into a subquery :
SELECT *
FROM mytable
WHERE cust_name IN (
    SELECT cust_name
    FROM mytable
    GROUP BY cust_name
    HAVING COUNT(*) = 1 AND MAX(status) = 'inactive'
)

Results :
| ID  | cust_name | status   | item_no | price |
| --- | --------- | -------- | ------- | ----- |
| 3   | Eric      | inactive | 3       | 8     |
| 6   | Earl      | inactive | 1       | 5     |
| 9   | Jenny     | inactive | 4       | 8     |

Demo on DB Fiddle

Starting MySQL 8.0, window functions make it much easier, and more efficient. You can inline them to count the total number of orders by customer, along with the count of inactive orders ; then just fiter in records where both values are 1 :
SELECT * FROM (
    SELECT
        t.*,
        COUNT(*) OVER(PARTITION BY cust_name) cnt_total,
        SUM(status = 'inactive') OVER(PARTITION BY cust_name) cnt_inactive
    FROM mytable t
 ) x WHERE cnt_total = 1 AND cnt_inactive = 1;

Demo on DB Fiddle