text:
Q: ifelse statement with factor variable output I have a dataframe df
  SNP           Effect   A1 A2
8  rs12145743    -0.0203  T  G
31  rs4650994    -0.0210  A  G
26  rs2602836     0.0192  A  G
34  rs4976033     0.0215  A  G
10 rs12525163    -0.0215  T  C
1  rs10282707    -0.0250  T  C
33  rs4917014    -0.0222  T  G
23  rs2293889    -0.0312  T  G
32  rs4871137    -0.0209  T  G
43   rs970548    -0.0258  A  C
27  rs2923084     0.0256  A  G
24  rs2303975     0.0279  A  G
36   rs499974    -0.0263  A  C
35  rs4983559    -0.0197  A  G
13 rs16942887     0.0831  A  G
16 rs17695224    -0.0290  A  G
18   rs181362    -0.0379  T  C

I am creating a new variable new_A1 that will be different depending on the value of Effect.
If Effect>0, new_A1 should contain the value of A1.
If Effect<0, new_A1 should contain the value of A2.
I am trying to do this using the following ifelse statement:
df$new_A1 <- ifelse(df$Effect>0, df$A1, df$A2)

However, the output is not as expected. new_A1 contains 1s and 2s, instead of maintaining the values of the factors in the original variables A1 and A2
  SNP           Effect   A1 A2 new_a1
8  rs12145743    -0.0203  T  G      2
31  rs4650994    -0.0210  A  G      2
26  rs2602836     0.0192  A  G      1
34  rs4976033     0.0215  A  G      1
10 rs12525163    -0.0215  T  C      1
1  rs10282707    -0.0250  T  C      1
33  rs4917014    -0.0222  T  G      2
23  rs2293889    -0.0312  T  G      2
32  rs4871137    -0.0209  T  G      2
43   rs970548    -0.0258  A  C      1
27  rs2923084     0.0256  A  G      1
24  rs2303975     0.0279  A  G      1
36   rs499974    -0.0263  A  C      1
35  rs4983559    -0.0197  A  G      2
13 rs16942887     0.0831  A  G      1
16 rs17695224    -0.0290  A  G      2
18   rs181362    -0.0379  T  C      1

A: Handling the factor variables A1 and A2 as character variables gives appropriate output.
hdl.dir$new_A1 <- ifelse(hdl.dir$HDL_Effect<0, as.character(hdl.dir$A2), as.character(hdl.dir$new_A1))

A: You could try row/col index.  This should work even without converting explicitly 'factor' to 'character' class.
 df$new_a1 <- df[3:4][cbind(1:nrow(df),(df$Effect<=0)+1L)]


text:
Q: Css the problem of rotating the centered rectangle inside the box I'm planning to make an animated hamburger button. First of all, I made rectangles in the box. If rectangle rotate center in the box, rectangle does not rotating properly. For testing, I centered one of the rectangles and rotate 90 degrees. But rectangle doesn't fit in the box. How can I rotate properly rectangles center of the box?

*,
*::after,
*::before {
  margin: 0;
  padding: 0;
  box-sizing: inherit;
}

html {
  font-size: 62.5%;
  box-sizing: border-box;
}

body {
  background-color: #272B30;
}

.wrapper {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-items: center;
  justify-content: center;

  width: 100vw;
  height: 100vh;
}

.boxes {
  width: 15rem;
  height: 15rem;
  background-color: #fff;
  position: relative;
}
.boxes .box {
  display: block;
  width: 15rem;
  height: 3rem;
  position: absolute;
}
.boxes .box__top {
  top: 0;
  background-color: #6f42c1;
}
.boxes .box__center {
  top: 50%;
  transform: translateY(-50%);
  transform-origin: center center;
  transform: rotate(90deg);
  background-color: #fd7e14;
}
.boxes .box__bottom {
  bottom: 0;
  background-color: #5bc0de;
}

A: You could  rotate the wrapper .boxes instead of .boxes .box__center, just like
.boxes {
  /* ... */
  transform: rotate(90deg);
}

OR you could use CSS calc() to fully centralize the element, just like:
.boxes .box__center {
  top: calc(50% - 1.5em);
  transform: rotate(90deg);
  background-color: #fd7e14;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Undefined control sequence when using tufte-latex package I have a pandoc grid table in an otherwise brand-new bookdown project:
# Hello bookdown

All chapters start with a first-level heading followed by your chapter title, like the line above. There should be only one first-level heading (`#`) per .Rmd file.

+---------------+---------------+--------------------+
| Fruit         | Price         | Advantages         |
+===============+===============+====================+
| Bananas       | $1.34         | - built-in wrapper |
|               |               | - bright color     |
+---------------+---------------+--------------------+
| Oranges       | $2.10         | - cures scurvy     |
|               |               | - tasty            |
+---------------+---------------+--------------------+

Rendering to html and normal pdf via bookdown::gitbook and bookdown::pdf_book are fine, however rendering to a tufte format via tufte::tufte_book or bookdown::tufte_book2 fails with:
! Undefined control sequence.
<argument> @{} >{\raggedright \arraybackslash
                                              }p{(\columnwidth - 4\tabcolsep...
l.93 ...umnwidth - 4\tabcolsep) * \real{0.29}}@{}}

The table structure is different to the other tables generated:
\begin{longtable}[]{@{}
  >{\raggedright\arraybackslash}p{(\columnwidth - 4\tabcolsep) * \real{0.22}}
  >{\raggedright\arraybackslash}p{(\columnwidth - 4\tabcolsep) * \real{0.22}}
  >{\raggedright\arraybackslash}p{(\columnwidth - 4\tabcolsep) * \real{0.29}}@{}}
\toprule
Fruit & Price & Advantages \\
...

Therefore I think the source of the problem is in the tufte-latex package which tufte_book relies on, but I am unable to narrow it down further.
The tex code of the document is here - the culprit section starts at line 96.

A: This was an issue in the tufte package.
It has now been fixed in dev version 0.10.2 one can install from github
remotes::install_github("rstudio/tufte")

The fix will be on CRAN for next version 0.11

A: If you have a vary similar error as OP but outside of tufte-latex, you might have run into changed pandoc table width calculation as described in this related issue. The suggested solution is adding arrray and calc to your template, e.g.:
\usepackage{array,calc}


text:
Q: Creating Spark Session throws exception traceback I'm new to jupyter notebook, and I'm trying to run a pyspark code, which is shorted as below:
import pyspark as ps
from pyspark.sql import SQLContext
from pyspark.sql import Row

spark = ps.sql.SparkSession.builder \
            .master("local") \
            .appName("Book Recommendation System") \
            .getOrCreate()

I get errors for creating pyspark session with following statements:

*

*"This SparkContext may be an existing one"

*"Do not update SparkConf for existing SparkContext, as it's shared by all sessions"

Full error explanation looks like below:
> ---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
<ipython-input-21-cd9ecd052473> in <module>
----> 1 spark = ps.sql.SparkSession.builder.master("local").appName("Book").getOrCreate()
      2
      3 sc = spark.sparkContext
      4 sqlContext = SQLContext(sc)

c:\program files (x86)\python\lib\site-packages\pyspark\sql\session.py in getOrCreate(self)
    184                             sparkConf.set(key, value)
    185                         # This SparkContext may be an existing one.
--> 186                         sc = SparkContext.getOrCreate(sparkConf)
    187                     # Do not update `SparkConf` for existing `SparkContext`, as it's shared
    188                     # by all sessions.

c:\program files (x86)\python\lib\site-packages\pyspark\context.py in getOrCreate(cls, conf)
    369         with SparkContext._lock:
    370             if SparkContext._active_spark_context is None:
--> 371                 SparkContext(conf=conf or SparkConf())
    372             return SparkContext._active_spark_context
    373

c:\program files (x86)\python\lib\site-packages\pyspark\context.py in __init__(self, master, appName, sparkHome, pyFiles, environment, batchSize, serializer, conf, gateway, jsc, profiler_cls)
    126                 " is not allowed as it is a security risk.")
    127
--> 128         SparkContext._ensure_initialized(self, gateway=gateway, conf=conf)
    129         try:
    130             self._do_init(master, appName, sparkHome, pyFiles, environment, batchSize, serializer,

c:\program files (x86)\python\lib\site-packages\pyspark\context.py in _ensure_initialized(cls, instance, gateway, conf)
    318         with SparkContext._lock:
    319             if not SparkContext._gateway:
--> 320                 SparkContext._gateway = gateway or launch_gateway(conf)
    321                 SparkContext._jvm = SparkContext._gateway.jvm
    322

c:\program files (x86)\python\lib\site-packages\pyspark\java_gateway.py in launch_gateway(conf, popen_kwargs)
    103
    104             if not os.path.isfile(conn_info_file):
--> 105                 raise Exception("Java gateway process exited before sending its port number")
    106
    107             with open(conn_info_file, "rb") as info:

Exception: Java gateway process exited before sending its port number

Does anyone know what should I do?
I have no idea what's the problem!

A: You don't need ps.sql.. Try this instead.
import pyspark as ps
from pyspark.sql import SparkSession
from pyspark.sql import Row

spark = SparkSession.builder \
            .master("local") \
            .appName("Book Recommendation System") \
            .getOrCreate()


text:
Q: How can i reduce the table width or make the table responsive for chrome?(Django/Python deployed web-app) This is the code for the page that is being viewed in those images, is there any changes that need to be made to make it more responsive in a mobile chrome browser?

TimetableMatch

          Module
          Day
          Time
          Area
          Actions

        {% for entry in entrys %}

          {{ entry.module }}
          {{ entry.day }}
          {{ entry.time }}
          {{ entry.location }}

          Edit

            Delete

        {% endfor %}

      Add Timetable Entry

        <button type="button" class="btn btn-primary btn-xs"> Back to home</button>

        <button type="button" class="btn btn-primary">Logout</button>

IOS chrome browser
Laptop chrome browser


text:
Q: Parsing data with awk I make script for bash, but I need to help with one part of the script. I have values in this format
1,12, 3,70, 2,29
1,12, 3,78, 2,79
1,12, 3,27, 2,25

and I need to convert to this format
1.12 3.70 2.29
...
...

So I need to change comma for dot, and remove comma behind the number. I would like to do it with awk, but I have no idea how to do it. I can to parse it to 3 different file, and then split to one by command paste , but I would like to do it more effective. Thank you.

A: Using sed:
sed 's/,\([0-9]\)/.\1/g;s/,//g;' file
1.12 3.70 2.29
1.12 3.78 2.79
1.12 3.27 2.25

This is basically 2 phase approach where 1st operation replaces commas that are followed by digit with dot and 2nd operation just strips remaining commas.

A: perl -pE '$_=~s/(\d+),(\d+)/$1.$2/g; $_=~s/,//g'

A: This sed command will also work,
sed 's/, / /g;s/,/./g' file

*

*s/, / /g - replaces comma and space with space only.

*s/,/./g - From the output of above command, it replaces , with .
Example:
$ echo "1,12, 3,70, 2,29" | sed 's/, / /g;s/,/./g'
1.12 3.70 2.29

A: Here is one using awk:
$ awk -F', ' '{$1=$1;gsub(/,/,".")}1' file
1.12 3.70 2.29
1.12 3.78 2.79
1.12 3.27 2.25

*

*Set the Field Separator to comma and space.

*Re-construct the entire line to allow fields to be separated by default OFS (space).

*Using gsub replace the , to .

A: awk -F, '{for (i=1; i<NF; i+=2) {printf "%s.%s", $i, $(i+1)}; print ""}' <<END
1,12, 3,70, 2,29
1,12, 3,78, 2,79
1,12, 3,27, 2,25
END

1.12 3.70 2.29
1.12 3.78 2.79
1.12 3.27 2.25

A: and this works, too. with the -e option you can add sed commands to the same instance:
sed -e s/", "/" "/g -e s/","/./g file1

A: An awk solution.
awk '{sub(/, /," ");gsub(/,/,".")}1' file
1.12 3.70. 2.29
1.12 3.78. 2.79
1.12 3.27. 2.25


text:
Q: acessing network shared folder with a username and password string in vb.net i am using the following code to read the details from a network folder which is restricted for only one user
shell("net use q: \\serveryname\foldername /user:admin pwrd", AppWinStyle.Hide, True, 10000)
            Process.Start(path)
shell("net use q: /delete")

when i run this to open any pdf or jpg or any other files except word/excel/powerpoint, everything is working fine. but the problem comes only when i access a word file.
in the step one, i am giving permission to access the word file.
in the step two, word file is open.
in the third, i am deleting the q drive.
the problem is the word file is still open. so i am getting a dos window, saying that "some connections of still connected or searching some folders, do you want to force disconnect"
please help.... how to access a word file (editable files) providing user name and password from the code and at the same time he shoud not have access to any other folders directly.

A: Why not just copy the word file to the local drive, then close the share and then open the file.
Though I'd suggest that it might be worth looking at some other kind of access control. This seems fairly unsafe (for example, what if your process crashes after the first command but before the second, then the share would be left open for anyone to use).

A: This seems like a really bad way to do it. There are a number of problems with it:

*

*As you discovered, Word keeps the file open for as long as you're using the file, so you can't just pull the share out from under it.

*You cannot reliably know when Word has finished with the file (for example, you can't just wait for the process to exit, because it might just be a wrapper that starts up for a second, notify the "original" word process to open the file and exits)

*Even if you could reliably detect when word had finished using the file, the fact that you had the share open the whole time seems to contradict your requirement to lock it down in the first place

*I assume you don't have the password hard-coded like that, but if you do then it's trivial for someone to just open up your executable and find out the password.

Perhaps if you tell us why you're trying to do this, we can suggest a better way, but if all you want to do is provide read-only access to the file (which seems to be the case) then you can just grant read-only access on the share itself: no need for this complicated process at all!


text:
Q: How to prevent overloading JWT token i'm using jwt token with node.js npm jsonwebtoken in  order to manage my users authentication. above that i'm  adding to the payload the user permissions which contains the user read and write to which section.
like so:
const payload = {
  user: {
    id: user.id,
    permissions: user.account_permissions
  }
};

jwt.sign(
  payload,
  config.get('jwtSecret'),
  { expiresIn: TIME},
  (err, token) => {
    if (err) throw err;
    res.json({ token });
  }
);

The account_permissions object looks somthing like that:
 const permissions = {
    platform: 'Management',
    sections: [
      {
        sectionName: 'setup',
        read: true,
        write: true
      },
      {
        sectionName: 'chat',
        read: true,
        write: true
      },
      {
        sectionName: 'maintenence',
        read: true,
        write: true
      },
      {
        sectionName: 'classes',
        read: true,
        write: true
      },
      {
        sectionName: 'income',
        read: true,
        write: true
      },
      {
        sectionName: 'announcements',
        read: true,
        write: true
      },
      {
        sectionName: 'messages',
        read: true,
        write: true
      }
    ],
    school: shoolID
  };

My question is ; every user can have many permissions objects to different platforms which in that case makes the jwt token to be very large (sometimes to big to be even sent in the header).
I have a middleware that checks the user permissions in every route, im trying to avoid saving that data in a database in order to save database calls. how can i avoid such an overloading.


text:
Q: Arrays not getting sorted after async function On a screen on my app I have a useEffect hook that retrieves some info about a user for a notification, after that I want to get all the notifications array sorted by date, the problem is that the arrays doesn't seem to get sorted:
useEffect(() => {
  const arrayNotifications = [];
  const arrayRequests = [];

  notificationsAndRequests.forEach(async notif => {
    const senderSnapshot = await database().ref(`/users/${notif.sender}`).once('value');
    let senderImage = (senderSnapshot.val() && senderSnapshot.val().userImg);

    if (notif.sender == null) {
      const recieverSnapshot = await database().ref(`/users/${notif.sender}`).once('value');
      senderImage = (recieverSnapshot.val() && recieverSnapshot.val().userImg);
    }

    const element = {
      date: notif.date,
      id: notif.id,
      isInvitation: notif.isInvitation,
      message: notif.message,
      reciever: notif.reciever,
      sender: notif.sender,
      senderimage: senderImage,
      timestamp: notif.timestamp,
      title: notif.title,
      extraid: notif.extraid,
      requestid: notif.requestid,
      viewed: notif.viewed,
      status: notif.status || ''
    };

    if (notif.isInvitation) {
      arrayRequests.push(element);
    } else {
      arrayNotifications.push(element);
    }
  });
  const sortedNotifications = arrayNotifications.sort(
    (a, b) => Date.parse(mom(b.timestamp, 'YYYY-MM-DD HH:mm').toDate())
    - Date.parse(mom(a.timestamp, 'YYYY-MM-DD HH:mm').toDate())
  );
  const sortedRequests = arrayRequests.sort(
    (a, b) => Date.parse(mom(b.timestamp, 'YYYY-MM-DD HH:mm').toDate())
    - Date.parse(mom(a.timestamp, 'YYYY-MM-DD HH:mm').toDate())
  );

  setNotifications(sortedNotifications);
  setRequestsNotifications(sortedRequests);
}, [notificationsAndRequests]);

Both sortedRequests and sortedNotifications should be ordered by the timestamp property of the notif object (timestamp is just a string formatted as a date).
Should I sort both arrayRequests and arrayNotifications instead?

A: async on your forEach is not waiting for arrayNotifications and arrayRequests results. You need to wrap your async logic in another function and then update your states there
const sortNotificationsAndRequests = async (notificationsAndRequests) => {
  const arrayNotifications = [];
  const arrayRequests = [];

 for(const notif of notificationsAndRequests) {
   const senderSnapshot = await database().ref(`/users/${notif.sender}`).once('value');
    let senderImage = (senderSnapshot.val() && senderSnapshot.val().userImg);

    if (notif.sender == null) {
      const recieverSnapshot = await database().ref(`/users/${notif.sender}`).once('value');
      senderImage = (recieverSnapshot.val() && recieverSnapshot.val().userImg);
    }

    const element = {
      date: notif.date,
      id: notif.id,
      isInvitation: notif.isInvitation,
      message: notif.message,
      reciever: notif.reciever,
      sender: notif.sender,
      senderimage: senderImage,
      timestamp: notif.timestamp,
      title: notif.title,
      extraid: notif.extraid,
      requestid: notif.requestid,
      viewed: notif.viewed,
      status: notif.status || ''
    };

    if (notif.isInvitation) {
      arrayRequests.push(element);
    } else {
      arrayNotifications.push(element);
    }
 }

  const sortedNotifications = arrayNotifications.sort(
    (a, b) => Date.parse(mom(b.timestamp, 'YYYY-MM-DD HH:mm').toDate())
    - Date.parse(mom(a.timestamp, 'YYYY-MM-DD HH:mm').toDate())
  );
  const sortedRequests = arrayRequests.sort(
    (a, b) => Date.parse(mom(b.timestamp, 'YYYY-MM-DD HH:mm').toDate())
    - Date.parse(mom(a.timestamp, 'YYYY-MM-DD HH:mm').toDate())
  );

  setNotifications(sortedNotifications);
  setRequestsNotifications(sortedRequests);
}

useEffect(() => {
  //call the new function to update your states
  sortNotificationsAndRequests(notificationsAndRequests)
}, [notificationsAndRequests]);


text:
Q: In sqlite, how are return values chosen for columns that are not used for aggregation or grouping? Given an SQLite database with three columns (char, char, int), the following query
select column2, avg(column3) from table_name group by column2;

will return the average values of column3 aggregate for each distinct value of column2.
What will the following query return?
select column1, column2, avg(column3) from table_name group by column2;

I came across this case while playing with Codeacademy's SQL tutorial. This particular query returns a value of column1 for each distinct value of column2, but I can't figure out how these values were chosen.

A: The database will return the value from some arbitrary row in the group.
(In the current implementation, it's the value from that last row in the group that was processed, but due to indexes or other optimizations, the processing order might not be predictable.)
Since SQLite 3.7.11, using MIN() or MAX() guarantees that values from a row with the minimum/maximum value are returned.


text:
Q: The method usingChromeDriverExecutable(File) is undefined for the type ChromeDriverService in Selenium WebDriver My code is as below:
  ChromeDriverService service = new ChromeDriverService.Builder()
 .usingChromeDriverExecutable(new File("E:\\Software\\chromedriver.exe"))
 .usingAnyFreePort().build();

It gave the following error:
 The method usingChromeDriverExecutable(File) is undefined for the type
 ChromeDriverService

A: Change
usingChromeDriverExecutable

to
usingDriverExecutable


text:
Q: Why I input a string with space but can not print out it fully? I am writing a very simple program to input a string with space and then output it, my problem is, it not printed out fully as I expected.
Here is my code, as you can see, very simple
import java.util.Scanner;
public class Testjapanese {
public static void main(String[] args) {
    String x;
    Scanner keyboard = new Scanner(System.in);
    System.out.println(" Add a string");
    x = keyboard.next();
    System.out.println(x);
    }
}

For example, it print "Add a string" but when I input a string "Today is very", it gave me "Today", not "Today is very".
I search and they said to me that I should use input.nextLine(), but I do not know how to use it.
May be I must use public java.lang.String nextLine() first ?
Sorry if my question is easy to solve. Thank you for your answer.

A: import java.util.Scanner;
public class MyClass {
    public static void main(String args[]) {
      String x;
    Scanner keyboard = new Scanner(System.in);
    System.out.println(" Add a string");
    x = keyboard.nextLine();
    System.out.println(x);
    }
}

A: You should just replace next with nextLine as below
 public static void main(String[] args) {
    String x;
    Scanner keyboard = new Scanner(System.in);
    System.out.println(" Add a string");
    x = keyboard.nextLine();
    System.out.println(x);
}


text:
Q: Error on phone "unfortunately 'app name' has stopped" (OutOfMemoryError) My newly made app is giving error on phone:

"unfortunately 'app name' has stopped"

below is my logcat error
07-27 19:35:58.261 7466-7466/com.example.android.happybirthday E/AndroidRuntime: FATAL EXCEPTION: main
 Process: com.example.android.happybirthday, PID: 7466
 java.lang.OutOfMemoryError
     at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
     at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:683)
     at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:513)
     at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:889)
     at android.content.res.Resources.loadDrawable(Resources.java:3436)
     at android.content.res.TypedArray.getDrawable(TypedArray.java:602)
     at android.widget.ImageView.<init>(ImageView.java:133)
     at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:57)
     at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:53)
     at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:102)
     at android.support.v7.app.AppCompatDelegateImplV7.createView(AppCompatDelegateImplV7.java:972)
     at android.support.v7.app.AppCompatDelegateImplV7.onCreateView(AppCompatDelegateImplV7.java:1030)
     at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:44)
     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:690)
     at android.view.LayoutInflater.rInflate(LayoutInflater.java:761)
     at android.view.LayoutInflater.inflate(LayoutInflater.java:498)
     at android.view.LayoutInflater.inflate(LayoutInflater.java:398)
     at android.view.LayoutInflater.inflate(LayoutInflater.java:354)
     at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:276)
     at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:136)
     at com.example.android.happybirthday.MainActivity.onCreate(MainActivity.java:11)
     at android.app.Activity.performCreate(Activity.java:5451)
     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2377)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2471)
     at android.app.ActivityThread.access$900(ActivityThread.java:175)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
     at android.os.Handler.dispatchMessage(Handler.java:102)
     at android.os.Looper.loop(Looper.java:146)
     at android.app.ActivityThread.main(ActivityThread.java:5602)
     at java.lang.reflect.Method.invokeNative(Native Method)
     at java.lang.reflect.Method.invoke(Method.java:515)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
     at dalvik.system.NativeStart.main(Native Method)

A: try to put this into the application tag of your manifest:
android:largeHeap="true"


text:
Q: What is the best practice for declaring a global variable in an iOS app? Suppose I have a UIColor that I want to use across every view controller to tint it's title/navigation bar. I was wondering what is the best way to declare such a property. Should I declare it as a member of the application delegate? Create a model class for global properties, and declare a static function + (UIColor)getTitleColor? Pass the UIColor object to every view controller? Is there another method that I did not describe, that is viewed as being the best way to go about this?

A: There are lots of ways to do this.  I like to do it by putting a category on UIColor:
UIColor+MyAppColors.h
@interface UIColor (MyAppColors)

+ (UIColor *)MyApp_titleBarBackgroundColor;

@end

UIColor+MyAppColors.m
#import "UIColor+MyAppColors.h"

@implementation UIColor (MyAppColors)

+ (UIColor *)MyApp_titleBarBackgroundColor {
    static UIColor *color;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        color = [UIColor colorWithHue:0.2 saturation:0.6 brightness:0.7 alpha:1];
    });
    return color;
}

@end

Then I can use it by importing UIColor+MyAppColors.h in any file that needs the title bar background color, and calling it like this:
myBar.tintColor = [UIColor MyApp_titleBarBackgroundColor];

A: By what you are trying to do, I think you could do it much easier by using appearance. You can assign different colors to all of your different types of interface elements. Check the UIAppearance protocol for more information.
If this is not what you want, then I would suggest @rob mayoff answer: using a category.


text:
Q: What are the constraints on the value returned by `id()` The doc only has this to say:

Return the "identity" of an object. This is an integer which is
guaranteed to be unique and constant for this object during its
lifetime. Two objects with non-overlapping lifetimes may have the same
id() value.
CPython implementation detail: This is the address of the object in
memory.

Which doesn't bound the returned integer, not does it have anything to say about how or if it varies on different OS.
I assume some virtual memory addresses won't ever be returned, and also assume it is different on 32 vs 64 bit systems, and also on Win/Linux/OSX.
Is there an equivalent os function that is more predictable?


text:
Q: Adding rows with duplicate indexes in pandas I have a set of "unidirectional" airline data, somewhat like below (numbers are not sequential or the same for every row in actual data):
origin dest    a  b  c  d  e  f
BOS    JFK     1  2  3  4  5  6
       DCA     1  2  3  4  5  6
JFK    BOS     1  2  3  4  5  6
       DCA     1  2  3  4  5  6
DCA    BOS     1  2  3  4  5  6
       JFK     1  2  3  4  5  6

I want to get the "multidirectional" data, i.e. something like below:
air1 air2    a  b  c  d  e  f
BOS  JFK     2  4  6  8  10 12
     DCA     2  4  6  8  10 12
JFK  DCA     2  4  6  8  10 12

I've been experimenting with pivot tables but so far haven't found any remotely useful solutions.

A: is that what you want?
In [133]: df.groupby('dest').sum().reset_index()
Out[133]:
  dest  a  b  c  d   e   f
0  BOS  2  4  6  8  10  12
1  DCA  2  4  6  8  10  12
2  JFK  2  4  6  8  10  12

A: You can sort your origin and dest columns by row firstly and then do a groupby, sum since it looks like that your result doesn't care about the order of the origin and dest:
import pandas as pd

df.reset_index(["origin", "dest"])
od = df.loc[:,'origin':'dest'].as_matrix()
od.sort()
df[['air1','air2']] = pd.DataFrame(od)
df.groupby(['air1','air2']).sum()

            a   b   c   d   e   f
air1 air2
BOS  DCA    2   4   6   8   10  12
     JFK    2   4   6   8   10  12
DCA  JFK    2   4   6   8   10  12


text:
Q: How to write a protocol document I am writing a protocol for my Game, and I am not sure what software to use for that.
I been trying writing it in Microsoft Word, and Excel, but it's not always easy to read or edit it.
Is there any good practices or tools that can help me with it?

A: You can use doxygen for this. You either can implement the doc of your protocol somewhere in your source or create a stand-alone-file. Doxygen is used for source-documentation normaly but should also work well for this.
Doxygen also implements mscgen, which should become handy for your purpose.

A: The standard tool for describing protocols is message sequence chart which has been used by the telecom industry (and others) for decades.

It is a really powerful tool you most certainly should learn and use. I recommend using http://sourceforge.net/projects/msc-generator/ to edit and generate charts.


text:
Q: Vuejs: Cannot set property 'profile_picture' of undefined I'm really confused whats wrong with my code. Can someone tell me what I did wrong here.
data() {
    return {
        users: [],
    }
},
methods:{
    moveData(response){
        for(var x=0;x<response.data.data.length; x++){
            this.users[x].profile_picture = response.data.data[x].profile_picture;
            this.users[x].age = response.data.data[x].age;
            this.users[x].intro = response.data.data[x].introMessage;
            this.users[x].name = response.data.data[x].userName;
        }
        // eslint-disable-next-line
        console.log('Users',this.users);
    }
}

A: as the error suggests that this.users[x] is undefined. the simple solution would be to initialize this.users[x] with some empty object just like
for(var x=0;x<response.data.data.length; x++){
   this.users[x] = {};
   this.users[x].profile_picture = response.data.data[x].profile_picture;
   this.users[x].age = response.data.data[x].age;
   this.users[x].intro = response.data.data[x].introMessage;
   this.users[x].name = response.data.data[x].userName;
}

A: As you using this.users[x], it always undefined because your array length is 0. So here one way more you can use .map() array to modify the field name and directly assign response to your users in moveData.
By use of Map array with spread operator

const response = [{
  profile_picture: 'https://image.flaticon.com/icons/svg/149/149452.svg',
  age: 25,
  introMessage: 'Hello',
  userName: 'test105'
}, {
  profile_picture: 'https://image.flaticon.com/icons/svg/149/149452.svg',
  age: 18,
  introMessage: 'HI',
  userName: 'demo105'
}]

console.log(response.map(({age,profile_picture,...r}) => Object.create({
  age,
  profile_picture,
  name: r.userName,
  intro: r.introMessage
})));

Modification in your code, use push method of array

const response = {
  data: {
    data: [{
      profile_picture: 'https://image.flaticon.com/icons/svg/149/149452.svg',
      age: 25,
      introMessage: 'Hello',
      userName: 'test105'
    }, {
      profile_picture: 'https://image.flaticon.com/icons/svg/149/149452.svg',
      age: 18,
      introMessage: 'HI',
      userName: 'demo105'
    }]
  }
}

let users = [];
for (var x = 0; x < response.data.data.length; x++) {
  users.push({
    profile_picture: response.data.data[x].profile_picture,
    age: response.data.data[x].age,
    intro: response.data.data[x].introMessage,
    name: response.data.data[x].userName
  });
}

console.log(users)


text:
Q: Web-based *nix shell is there any solution like LogmeIn consisting on a small client to install upon a *nix machine and hence being able to use its shell from the browser bypassing proxies because it all will work on :80?
Thanks

A: My favourite solution to this is Ajaxterm which I run on an https server since port 443 is rarely blocked and the encrypted stream can't be decoded by firewalls.
http://antony.lesuisse.org/software/ajaxterm/

A: The client doesn't have to run in a browser to use port 80 or 443. Just add a line with Port 80 in /etc/ssh/sshd_config and restart sshd. This obviously requires root or sudo privileges. Then you can connect to the computer using any SSH client, while specifying port 80 (e.g. ssh -p 80 user@host.org).
This solution makes sshd listen on port 80. It will not work if the server runs a web server, of course.
If you rather want port 443, change the port number, or add another line with Port 443.

A: Try this solution "MindTerm". I used an early release years ago and it worked pretty well. I configured Apache to use http based authorization when accessing a special url, e.g. "/myshell/" for further protection.

A: If your system can connect to the outside using SSH, and you have some other system that's always online, you can create a reverse SSH tunnel.
I highly recommend using autossh for this purpose (after setting up public key authentication), eg.
autossh -M 12345 -f -R 2200:localhost:22 user@target.example.com

will set up a tunnel where connecting to the remote system's port 2200 will forward to your NAT machine's port 22

A: ShellInABox implements a web-based console that can be used for logging in to your system.  All you need is a browser.  From the project description:

Shell In A Box implements a web server that can export arbitrary command line tools to a web based terminal emulator. This emulator is accessible to any JavaScript and CSS enabled web browser and does not require any additional browser plugins.

I've run this myself and it's worked out great.  I only use it occasionally (e.g., when I'm visiting friends/relative and need to log in and don't have an ssh client handy), but it works great even with curses applications like Mutt and Pine.


text:
Q: Doctrine2 define collate and charset in yaml config file Hoy I can configure collate and charset in doctrine2 yaml config file ?
I have this config but seems that not work
Vulco\AppBundle\Entity\Garage:
    type: entity
    table: vulco_garage
    options:
        collate: utf8_general_ci
        charset: utf8
    repositoryClass: Vulco\AppBundle\Repository\GarageRepository

Thanks

Edited: It works correct!


text:
Q: Split on new line when using BufferedReader Android I am trying to read from a text file, splitting the contents when a new line character is met and displaying the result in a TextView.
This is the readfromfile method that I have:
public String readFromFile(Context context) {
        String ret = "";
        try {
            InputStream inputStream = context.openFileInput("history.txt");
            if ( inputStream != null ) {
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String receiveString = "";
                StringBuilder stringBuilder = new StringBuilder();
                while ( (receiveString = bufferedReader.readLine()) != null ) {
                    //receiveString.split("\n");
                    //String[] split = receiveString.split("\n\\s*");
                    stringBuilder.append(receiveString);
                   // if((receiveString = bufferedReader.readLine()) == "\n"){
                   // }
                }
                inputStream.close();
                //stringBuilder.
                ret = stringBuilder.toString();
            }
        }
        catch (FileNotFoundException e) {
            Log.e("login activity", "File not found: " + e.toString());
            Toast.makeText(this, "You have not sent any messages!!", Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            Log.e("login activity", "Can not read file: " + e.toString());
            Toast.makeText(this, "Cannot read from file!!", Toast.LENGTH_LONG).show();
        }
        return ret;
    }

And this is where the method is called:
String message = readFromFile(getApplicationContext()); // is this really needed? yes it is, use with readFromFile()
        TextView textView = new TextView(this);
        params2.addRule(RelativeLayout.BELOW, history.getId()); // this is very important for spacing using ids
        textView.setTextSize(14); //this might give an error or look weird on devices, horizontally and vertically
        textView.setText(message); // simplest fix is to force device to stick with horizontal, no common device is bigger than 5.5"
        //textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        textView.setId(View.generateViewId()); // This requires a minimum API 17
        textView.setGravity(Gravity.LEFT | Gravity.BOTTOM);
        layout.addView(textView, params2);

I think the issue might be the append that I am using with the string to display, i.e. I am returning a string with appended text.
This is the View output:
Output
I am trying to load from a file called history.txt, which contains all SMS's that have been sent using the app in string format.
This is the writeToFile method:
public void writeToFile(String data,Context context) {
        try {
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("history.txt", Context.MODE_APPEND));
            //format data string here to include time stamp
            BufferedWriter writer = new BufferedWriter(outputStreamWriter);

            String currentDateTime = DateFormat.getDateTimeInstance().format(new Date());

                outputStreamWriter.append("\n");
                outputStreamWriter.append(data);
                outputStreamWriter.append(" ");
                outputStreamWriter.append(currentDateTime);
                writer.newLine();

                outputStreamWriter.close();

        }
        catch (IOException e) {
            Log.e("Exception", "File write failed: " + e.toString());
        }
    }

Any ideas?

A: Check the Javadoc. readLine() removes the line terminator. If you want lines when you do the output, you have to add line terminators yourself: in this case by adding \n or \r\n to every like as you read it, as you're displaying the data in a GUI.

A: Perhaps you should use a ListView instead. Each row of the ListView can be a single TextView for a single line from the file or can be multiple TextViews if you want to break the data into nicely formatted columns.

A: This has been solved by adding and if condition. Since the amount of variables is set and will not be changed, on every 8 read lines, two lines are skipped like so:
 while ( (receiveString = bufferedReader.readLine()) != null ) {
                    //receiveString.split("\n");
                    //String[] split = receiveString.split("\n\\s*");
                    stringBuilder.append(receiveString);
                    if(i == 8) {
                        stringBuilder.append("\n");
                        i = 0;
                    }
                    stringBuilder.append("\n");
                   // if((receiveString = bufferedReader.readLine()) == "\n"){
                   i++;
                   // }
                }

Thankyou all for your input!
p.s As @Code-Apprentice pointed out, ListView should have been the way to go from the start.


text:
Q: "configuration could not be verified - is the username or password wrong?" I have enabled the two-step verification to my gmail account. I have tried for application specific password for Thunderbird, but still Thunderbird showing this error message. And the same case with outlook.com email account. How can i configure my email accounts.

A: I had the same problem before, you have to double check the configuration.
Have a look at here: http://davmail.sourceforge.net/thunderbirdimapmailsetup.html


text:
Q: Get value inside unordered list using React UseRef Hi I have the below code, in which I am trying to get the value inside list using when a person clicks on the button wrapped inside that is inside list element. I tried using UseRef but it is returning all the listed items, but In my case I only want to target the value that is associated with that button. Here is my current approach.
const tabRef = useRef();

  function addButtonHandler() {
    console.log(tabRef.current.innerText);

  }

      <button onClick={addButtonHandler}></button>
      Some context here.

      <button onClick={addButtonHandler}"></button>
      More context here.

      <button onClick={addButtonHandler}></button>
      even more context here.

A: This seems like a good candidate for event delegation. Also, you don't necessarily need a ref here just to get the value, because JavaScript event handlers provide you with the event object, which includes the target of the event! You could certainly use a ref to store it for later, but my point here is that useRef is not a necessary part of getting a value from a list in an event handler. No "Reacty" features needed at all here!

const App = () => {

  function handleClick(event) {
    event.preventDefault();
    if (event.target.tagName === 'BUTTON') {
      console.log(event.target.nextSibling);
    }
  }

  return (

      <button>Button 1</button>
      Some context here.

      <button>Button 2</button>
      More context here.

      <button>Button 3</button>
      even more context here.

)
    }
ReactDOM.render(<App />, document.getElementById("root"));

A: You may get DOM nodes of those
s by looking at tabRef.current.children[n]
But not sure if ref is the right way in React to achieve what you wanted to do.
How about to hold the text within an array?
const textArr = ['Some context here', 'More context here', 'even more context here'];
const addButtonHandler = (text) => { console.log(text) };
return (

  { textArr.map(text =>

<button onClick={() => addButtonHandler(text)} />{text}
) }

)


text:
Q: PHP not showing error when I put only single = in if condition My code as follows:
if($_POST['user_id'] = ''){
  //some statement;
}

In the above if condition I have put only single =. PHP is not showing any error but I am getting a white blank page. Does anyone has any clue?

A: if($_POST['user_id'] = '') means:
$_POST['user_id'] becomes '' .. if ('') // always false
if($_POST['user_id'] == '') means:
$_POST['user_id'] compares to  '' .. if ( comparison)

A: Not sure if trolling or real question...
you said it yourself, you're using a single =. You need 2 to check for equality.
if($_POST['user_id'] == ''){
  //some statement;
}

When you use a single equal sign, you're basically "set $_POST['user_id'] to '', then test if it's true). Since '' evaluates to false, you get nothing.

A: This:
if($_POST['user_id'] = ''){

Tries to assign an empty string to $_POST['user_id']. This:
if($_POST['user_id'] == ''){

Is a comparison. You should almost always be doing the second one - the first one over-rides the value in $_POST, and returns the value of the assignment.

A: try it
Use it
$user_id = $_POST['user_id'];

if($user_id == ''){
  //some statement;
}

inseted of
if($user_id = ''){
  //some statement;
}

Or try another one
$user_id = $_POST['user_id'];

if(isset($user_id) && !empty($user_id)){
  //some statement;
}

A: It's not triggering any error because it is a valid condition.
if($_POST['user_id'] = '')
equals to
$_POST['user_id'] = '';
if($_POST['user_id']){
    //Boolean comparison of a string. Empty = false. Not empty = true.
}

An example of use:
function division($var1, $var2){
    if($var2 > 0){
        return $var1/$var2;
    return false;
}

if($result = division(50,2)){
     //It returned 25 which is true!
}

if(!$result = division(50,0)){
    //Returned FALSE because you can't divide by zero!
}


text:
Q: Exporting a matrix in Mathematica in curly brackets format I am trying to export a matrix in a file using Mathematica.
I get the matrix and then use
Export["myfile.dat", MyMatrix, "???Format???"]

There are many formats. I want the one that prints the matrix in this way:
{{0,1,0,....},{0,0,1,...},...}

That is the classic Mathematica format....
How can I do this?
Which one is the correct format?

A: Export["file.txt",MyMatrix,"String"] works in Mathematica 6

A: In really you can do this just with Put:
a = Table[RandomInteger[], {10}, {10}];
a >> "C:\\test.txt"


text:
Q: Highstock date input, page jumps to top on ipad In highstock on the ipad if you have content before the chart and you have to scroll down the page to view the chart, clicking on the date input jumps the page to the top and you can't see the chart, see http://jsbin.com/oyicuc/35
Also, the keyboard opens by default, we're using the jquery ui datepicker in our project and so ideally we would like the keyboard not to open, is this possible? Even better would to be able to use the native iOS datepicker. Don't really want to have to write our own function with custom inputs...
Thanks

A: It's probably the same issue as https://github.com/highslide-software/highcharts.com/issues/1645, which will be fixed with the next maintenance.


text:
Q: Better way to use multiple context providers in ReactNative I am having an app in which I am using 3 Context Provider. For the app to work, I have to wrap  <App/> in all these providers. As my app grows I am expecting to have a few more providers for more types of data I have to connect with. I have already started to feel that there may be a better way to pass providers into the <App />.
My App.js Code:
import React from 'react';
import { createStackNavigator } from 'react-navigation-stack';
import { createAppContainer } from 'react-navigation';
import { Provider as BlogProvider} from './src/context/BlogContext';
import { Provider as VehicleProvider} from './src/context/VehicleContext';
import { Provider as AuthProvider} from './src/context/AuthContext';

import IndexScreen from './src/screens/IndexScreen';
import ShowScreen from './src/screens/ShowScreen';
import CreateScreen from './src/screens/CreateScreen';
import EditScreen from './src/screens/EditScreen';
import VehicleScreen from './src/screens/VehicleScreen';

const navigator = createStackNavigator(
  {
    Index: IndexScreen,
    Show: ShowScreen,
    Create: CreateScreen,
    Edit: EditScreen,
    Debug: DebugScreen,
    Vehicle: VehicleScreen,

  },
  {
    initialRouteName: 'Index',
    defaultNavigationOptions: {
      title: 'Main'
    }
  }
);

const App = createAppContainer(navigator);

export default () => {
  return (
    <BlogProvider>
      <VehicleProvider>
        <AuthProvider>
             <App />
        </AuthProvider>
      </VehicleProvider>
    </BlogProvider>
  );
};

Some of the questions I have are:

*

*Is there a better way to use multiple context providers in an App.

*Does the order in which these providers are nested have any impact on the App?

*Can we skip adding provider in <App/> and instead import them in a any screen where it's required and wrap that screen element in it?

A: I won't answer in order it's asked.
Answer 3
If a provider ONLY provides context for a specific Component, you should import and use it in that Component. DO NOT wrap App with it.
The reason is whenever provider is updated, every consumer will be re-render, you can't no use React.memo or ReactPureComponent or shouldComponentUpdate to stop it. You should not overuse context
const Root = () => {
  return (
    <AppProvider>
      <ComponentProvider>
        <App/>
      <ComponentProvider>
    </AppProvider>
  )
}

const App = () => {
  return (
    <>
      <ComponentA/>
      <ComponentB/>
    <>
  )
}

const ComponentContext = createContext()
const ComponentProvider = ({ children }) => {
  // If any value here is updated --> all consumer will be render
  // --> App re-render --> ComponentA and ComponentB re-render
  return (
    <ComponentContext.Provider value={{ value1, value2, value }}>
      {children}
    </ComponentContext.Provider>
  )
}

You should do this instead
const Root = () => {
  <AppProvider>
    <App/>
  </AppProvider>
}

const App = () => {
  return (
   <>
    <ComponentA/>
    <ComponentB/>
   <>
  )
}

const ComponentA = () => {
  return (
    <ComponentProvider>
      <OtherComponent/>
    <ComponentProvider>
   )
}

const ComponentContext = createContext()
const ComponentProvider = ({ children }) => {
  // If any value here is updated --> all consumer (ComponentA only) will be render
  return (
    <ComponentContext.Provider value={{ value1, value2, value3 }}>
      {children}
    </ComponenContext.Provider>
  )
}

Answer 1
Answer 3 can be the answer for this, use context in the right place (For the Components which consume the context only. DO NOT randomly every context at App level). If your context is frequently updated, I recommend not to use other ways so you can use React.memo or PureComponent or shouldComponentUpdate to prevent unwanted re-render to optimise performance.
Answer 2
The order doesn't impact the App.

A: Answers
Answer 1:

*

*There is no better way to add app-level provider but some provider do not have context app-level mean (we do not need context in-app everywhere). Some providers have module levels. so you can wrap outside a specific tree or component

const UserScreen = () => (
  <UserProvider>
    <UserScreen />
  <UserProvider />
)

Answer 2:

*In working there is no effect but sometimes we need to call the child function from the parent, therefore, we need to use ref. in this nested level provider we have to use forwardRef. Rest of the things work fine.

Answer 3:

*Yes we can skip provider in App.js if that provider is not app-level mean we do not need context everywhere in app. if we need context in one or two screens or one tree then we can wrap that screen or tree in provider and do not use in App.js

A: *

*I'm not sure what you mean with "better". If you just want to clean up your App component, you can abstract the Provider rendering into a separate function. This or this might help you accomplish it according to your needs

*If, like your example, you wrap your entire application with all Providers and they are independent of each other, then the order would not matter. Otherwise they behave no different than other components, only children have access to its data and the data flow is unidirectional.

*Yes, there is no need to provide all data to your entire application.

A: *

*Is there a better way to use multiple context providers in an App.

Answer: Yes

*

*you can use whatever number Context Providers to wrap around your App, but make sure that data of those Providers should not be frequently updated and they are treated as global state which means they are accessed or will be accessed from anywhere in your app. Ex: your app theme, authentication status, user's profile,...

*If data is considered as specific use-case which is only used in just few places in your App, you should not use Context Provider, because if data is updated, all its chilren are forced to re-render, no matters you use any React APIs to prevent it like React.memo. Refer to this

*Does the order in which these providers are nested have any impact on the App

Answer: Yes

*

*As I said in answer 1, if Provider has data that is updated frequently is parent of those which are having less frequently updates, it will impact all its children, so you can refactor by wrapping the most less updated outermost as parent.

*Can we skip adding provider in  and instead import them in a any screen where it's required and wrap that screen element in it?

Answer: it is up to your use case.


text:
Q: Select all users that belong to a certain group, complicated query I am working on a query that for now has worked well (I'm using input from frontend to generate the WHERE clause), but I want to be able to search on another parameter and this truly makes my mind boggle.

*

*Table groups contains id, name.

*Table persons is my table with the persons that I want to retrieve.

*Table group_memberships is my group<->person many-to-many relationship table. The columns are participant (person.id) and group (groups.id)

The retrieved result set's last column is a concatenation of group_memberships but where "1, 2, 3" has been replaced with the groups' real names via JOIN.
Here's the query today:
SELECT
  `persons`.`id`,
  CONCAT_WS(\' \', `fname`, `lname`) AS `full_name`,
  `job_title`,
  `email`,
  `phone`,
  `participant_group_memberships`.`memberships`
FROM
  `persons`
  LEFT JOIN (SELECT
               `participant`, `name`,
               GROUP_CONCAT(`groups`.`name` ORDER BY `groups`.`name`
                            SEPARATOR  \', \') AS `memberships`
             FROM
               `group_memberships` JOIN `groups`
                ON (`groups`.`id` = `group_memberships`.`group`)
             GROUP BY `participant`) AS `participant_group_memberships`
  ON (`participant_group_memberships`.`participant` = `persons`.`id`)
WHERE TRUE . $where . '
ORDER BY `full_name`

If I add WHERE name = 'search_query_group' then the concatenated list only will show that group which is not what I want. I still want to show all the groups that person belongs to.
I also want to achieve this with 1 query, and avoid having to use IN(), if possible.

As you can see, the last column (generated with GROUP_CONCAT) will only show the group I searched on, not all the groups the person is member of.

A: You could use a SUM and CASE statement in a HAVING clause in your subquery to include your search results.  You would also need to change your join to the subquery to be an INNER JOIN.  This will return all persons who are in a certain group and show all of the groups they are members of.
SELECT  `persons`.`id`,
        CONCAT_WS(\' \', `fname`, `lname`) AS `full_name`,
        `job_title`,
        `email`,
        `phone`,
        `participant_group_memberships`.`memberships`

FROM    `persons`

        JOIN `pers_department`
        ON (`pers_department`.`pers_rid` = `persons`.`id`)

        JOIN
        (SELECT `participant`, `name`,
                GROUP_CONCAT(`groups`.`name` ORDER BY `groups`.`name`
                            SEPARATOR  \', \') AS `memberships`
         FROM   `group_memberships`
                JOIN `groups` ON (`groups`.`id` = `group_memberships`.`group`)
         GROUP BY `participant`
         HAVING SUM(CASE WHEN name = 'search_query_group' THEN 1 ELSE 0 END) > 0
        ) AS `participant_group_memberships`
        ON (`participant_group_memberships`.`participant` = `persons`.`id`)

WHERE TRUE . $where . '

ORDER BY `full_name`


text:
Q: Select2 Error on unselect I am using select2 with a multiple select element to create an simpler user interface for adding many items to the select. Everything functions correctly - I can create the selector, add items, and remove items, however, when looking at my Javascript console log I am receiving two different errors when unselecting items.

*

*
Uncaught TypeError: Cannot read property 'id' of undefined

*
Uncaught TypeError: Cannot read property 'query' of null

And from what I have found, the errors are a result of these lines:
$('#eleId').on("select2:unselect", function(){
    $('#eleId').select2();
});

I have removed some code to try to pinpoint the errors, but normally this code block would update some attributes of the element, set within the select2({...}) call. The first error is given the first time removing an element after the the selection panel of options is opened and closed, so if the user clicks the selector, adds an item, then removes that item the first error is fired. The second error occurs when elements are removed not immediately following an opening and closing of the selection panel, so if the user were to add three items, removing the first would give the first error, removing the second and third would produce the second error for each item removed.
If I remove the select2() call within the function the errors go away, but the errors seem to be triggered by the unselect itself, since I have added a log statement to the end of the function and that will print before the error prints.
Working Copy:
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
        <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
    </head>
    <body>
        <select multiple id='eleId'>
            <option>1</option>
            <option>2</option>
            <option>3</option>
        </select>
    </body>
    <script>
        $(document).ready(function() {
            $('#eleId').select2();
        });
        $('#eleId').on("select2:unselect", function(){
            $('#eleId').select2();
        });
    </script>
</html>

A: After doing some more research, I found this error is caused by select2 not loading the select element in time after the unselect event, so it could not immediately find the properties listed. To combat this I needed to wrap the .select2() call in a setTimeout() as such:
$('#eleId').on("select2:unselect", function(){
    setTimeout(function(){
        $('#eleId').select2();
    });
});

This gives select2 just enough time to load the element before trying to access this properties. Though this solves the errors, it will produce a flickering effect with the selection panel when removing selections. To fix this I modify how the opening event is handled during this time:
$('#eleId').on("select2:unselect", function(){
    $(this).on('select2:opening', function(e) {
        e.preventDefault();
    });
    setTimeout(function(){
        $('#eleId').select2();
    });
    $(this).on('select2:unselect', function() {
        var sel = $(this);
        setTimeout(function() {
            sel.off('select2:opening');
        });
    });
});

A: Using the following worked for me and the errors disappeared:
$('.class').on('select2:select', function (e) {...});


text:
Q: Is there a way to backup and restore basic file / folder permissions on Ubuntu the way that there is using icacls in Windows? In Windows you can do this (backup and restore basic file permissions) can this be done in Linux?
And to clarify, by basic file permissions I don't mean ACLs in Linux, I mean the default permissions modified with chmod / chown.

A: Yes, using the stat command (See man stat, man find, man xargs), but why would it be needed? In normal Linux life, wholesale permission changes/restores are rarely needed.
sudo find / \(-type f -o -type d \) -print0 | \
    xargs -0 stat <stat parameters>

A: If you have the space, just tar up your test directory. If you need to revert things, delete the test files, and extract your archive to get back to what you started with. tar preserves ownership and permissions by default.


text:
Q: callback function for string in Codeigniter Anyone know how to design the callback function for string in Codeigniter?if use this function for int,it works.for string,the validation does not work.here is my model:
> function check_user_name($User_Name='')
>     {
>         $this -> db -> select('User_Name');
>         $this -> db -> from('login');
>         $this -> db -> where('User_Name',$User_Name);
>         $this -> db -> limit(1);
>         $query = $this -> db -> get();
>
>         if($query -> num_rows() == 1)
>         {
>             return $query->result();
>         }
>         else
>         {
>             return false;
>         }
>     }

and here is my controller:
form validation

$this->form_validation->set_rules('User_Name','User_Name','trim|required|xss_clean|callback_check_User_Name');

> function check_User_Name($User_Name)
>     {
>         //Field validation succeeded.  Validate against database
>
>         $row = $this->UserRegistration->check_user_name($User_Name);//query the
> database
>
>         if($row)
>         {
>             return TRUE;
>         }
>         else
>         {
>             $this->form_validation->set_message('check_User_Name', 'The User_Name already exist.Please use other User_Name.Thank you.');
>             return FALSE;
>         }
>     }

A: put your validation script in function.
function check_User_Name($User_Name)
         {
             //Field validation succeeded.  Validate against database
    if($this->form_validation-set_rules('User_Name','User_Name','trim|required|xss_clean|callback_check_User_Name'))
    {
         $row = $this->UserRegistration->check_user_name($User_Name);//query the
 database

         if($row)
        {
             return TRUE;
         }
        else
         {
             $this->form_validation->set_message('check_User_Name', 'The User_Name already exist.Please use other User_Name.Thank you.');
            return FALSE;
         }
       }
     }


text:
Q: How can I get input ng-model of the form to add some validators dynamically in code? I use angulardart 1.1.
I have component that contains form, something like this one
<my_component>
   <form name='"my_form">
      <input ng-model=''>
....
   </form>
</my_component>

How can I get input ng-model of the form "my_form" to add some validators dynamically in code?

A: I`ve found solution how to get form from component that contain  fields models :
var form = scope.context.form;

where form['Email'] will be NgModel of field named Email

A: You can inject the Element via the constructor and then use querySelector to retrieve the <input>.
class MyComponent implements ShadowRootAware {
  Element element;
  MyComponent(this.element);

  @override
  void onShadowRoot(_) {
    final input = element.querySelector('input');
  }
}


text:
Q: Can't select the thumbnails view in Word 2007 I lost the thumbnail view panel for Print Layout in Word 2007.
However, in the "Show/Hide" tab, it's not grey, but the check box for thumbnails just can't "hold" my selection.  The only thing can be shown is the "document map" view panel. When I click on thumbnails view, the whole side panel disappears.

A: It may be that you have hit a bug in Word 2007 (so also a chance that this will fix itself). Meanwhile you may be able to show thumbnails by calling the following code:
Sub OpenThumbnails()
ActiveWindow.Thumbnails = True
End Sub

with Developer, Macros and selecting OpenThumbnails, Run.
I am not clear whether this has affected a single document or all your documents. If the latter the code should be inserted in Normal.dotm but to begin with I suggest trying it out within just one document known to have the problem.


text:
Q: Displaying content in tabs on Onsen UI page I am building a single page app on onsen UI with various pages defined. One of the pages shows schedule for a two day event and so it's only logical to have tabs with dates and respective daily content.
How would you do this in onsen ui considering all tutorials I've seen on tabs assume your main website navigation will use tabs which is not usually the case.
Here's code I'd been tinkering with
<ons-template id="schedule.html">
<ons-page>
  <ons-toolbar>

      <ons-back-button>Back</ons-back-button>

Schedule

  </ons-toolbar>

        <ons-tabbar  position="top">
            <ons-tab page="dayone.html">

Day One

            </ons-tab>
            <ons-tab page="daytwo.html">

Day Two

            </ons-tab>
        </ons-tabbar>

        <ons-tab active="true" page="dayone.html">

Registration and viewing of exhibition stands
8.30 – 9.00AM

Welcome and Introductions
9.00 – 9.10AM

        </ons-tab>
        <ons-tab page="daytwo.html">

Registration and viewing of exhibition stands
9.30 – 9.00AM

Welcome and Introductions
9.00 – 9.10AM

        </ons-tab>

    <ons-button modifier="light" onclick="myNavigator.popPage()">
      Pop Page
    </ons-button>

</ons-page>

A: The usage of tabbar is explained here: http://onsen.io/reference/ons-tabbar.html#usage
Your pages "dayone.html" and "daytwo.html" should be templates or different pages. Something like this:
<ons-page>
    <ons-navigator var="myNavigator">
        <ons-toolbar>

Main page

        </ons-toolbar>
        <ons-button onclick="myNavigator.pushPage('schedules.html');">Go to schedules</ons-button>
    </ons-navigator>
</ons-page>

<ons-template id="schedules.html">
    <ons-page>
        <ons-tabbar>
            <ons-tab page="day1.html" active="true">
                <ons-icon icon="ion-home"></ons-icon>
                Day 1
            </ons-tab>
            <ons-tab page="day2.html">
                <ons-icon icon="ion-star"></ons-icon>
                Day 2
            </ons-tab>
        </ons-tabbar>
    </ons-page>
</ons-template>

<ons-template id="day1.html">
    <ons-page>
        <ons-toolbar>

<ons-back-button>Back</ons-back-button>

Day 1 schedule

        </ons-toolbar>

Day 1 activities here...

    </ons-page>
</ons-template>

<ons-template id="day2.html">
    <ons-page>
        <ons-toolbar>

<ons-back-button>Back</ons-back-button>

Day 2 schedule

        </ons-toolbar>

Day 2 activities here...

    </ons-page>
</ons-template>

Working example here: http://codepen.io/frankdiox/pen/bNZMPg
Hope it helps!


text:
Q: Adding formula in field calculator when new attribute is text type? I added a new text attribute to my table. I would like it to print the values "y" or 'n", for when an attribute in the table is other a specific cut off it will code Y, and then that attribute is equal to or below that specific cut off number it will code "n".

A: The following approach should get you going:


text:
Q: GridView in UpdatePanel adds extra rows when sorting another grid I'm a seeing some weird behavior that i have never seen before.
I have two grid in separate UpdatePanels. I can page and sort each without any problems.
Each grid is set for 10 per page.
If the first grid (13 records) is paged to the second page and then i go down to the second grid (14 records) and page to the next page and the first grid adds a bunch of empty rows to the grid so it is full to show 10. There is no data in the rows...just empty rows. Each grid does this on paging and sorting.
Ive stepped through the code and the the loading of the other grids never happens so it tells my AJAX is doing something to add the 'phantom' rows to the grid.
Any ideas why or ways to debug this?

A: I don't know whether you got a fix for this or not.  I had a similar problem with a gridview involving a checkbox in a templatefield.  Whenever I clicked the checkbox on a page with less than the defined page size, the gridview would redraw itself with as many rows as was defined by the page size.  So I'd end up with several empty rows after the last row of valid data.
I solved this problem by disabling the viewstate on the gridview (i.e. EnableViewState="false") and everything worked out fine.


text:
Q: Inno setup file execution in Windows Server 2012R2 not working I am trying to install SQL Server through inno setup in Windows Server 2012R2 machine which fails with exit code "Process exit code: 1".
The same setup is working fine in Windows 2008R2 and Windows 7 machines. I am not getting any error prompt for the failure. When the Executable file is called with parameters, the setup terminates. The log snippet is available below.
2015-07-15 16:47:38.734   Run as: Current user
2015-07-15 16:47:38.734   Type: Exec
2015-07-15 16:47:38.734   Filename: C:\Users\ADMINI~1\AppData\Local\Temp\1\is-4IUN9.tmp\dbs-server\DBS Server Setup.exe
2015-07-15 16:47:38.734   Parameters: /dir="D:\Install.Folder" /dbsapwd=123_Admin /MSSQLServerSetupFile="F:\setup.exe" /MSSQLServerSPSetupFile="G:\SQLServer2008R2SP3-KB123456-x64-ENU.exe" /MSSQLServerLicense="AAAAA-BBBBB-CCCCC-DDDDD-EEEEE" /dbinstancename="ABC_SYSTEMS" /MSSQLServerSelection="SQL Server 2008R2" /silent /restart=false
2015-07-15 16:47:42.609   Process exit code: 1
2015-07-15 16:47:42.609   Need to restart Windows? Yes
2015-07-15 16:47:45.344   Will not restart Windows automatically.

I believe it has something to do with how the parameters is passed. Could anyone suggest?
Thanks in Advance,
DeeJay.

A: Found the issue at last. SQL Server required .NET Framework 3.5 as a pre-requisite which is not available by default in the Windows Server 2012 R2. So after installing the same, the SQL Server was installed properly.
The following link helped!!!
https://technet.microsoft.com/en-us/library/dn482071.aspx


text:
Q: Установить картинку на фон textArea Добрый день,пишу легкий чатик, захотел сделать приятный интерфейс, и при попытке поставить картинку на фон textArea столкнулся с проблемой отсутствия таковой возможности. Для графического составляющего использую Scene Builder.
Могу взять ImageView растянуть по всей textArea и подрегулировать opacity. Но теряется резкость выводимого текста. Подскажите пожалуйста, какие есть решение данной проблемы ?

A: С помощью Scenic View можно выявить внутреннюю структуру TextArea:
TextArea styleClass="text-input text-area"
  ScrollPane styleClass="scroll-pane"
    StackPane styleClass="viewport"
      StackPane
        ContentView styleClass="content"
          Group
            Text styleClass="text"
          Path
    ScrollBar styleClass="scroll-bar"
      ...
    ScrollBar styleClass="scroll-bar"
      ...
    StackPane styleClass="corner"

Исходя из этого, можно задать фоновое изображение в .css-файле в .text-area {...}, а внутренним панелям назначить прозрачность. При этом изображение не будет прокручиваться вместе с текстом:
.text-area {
    -fx-background-image: url("bg.png");
}

.text-area .scroll-pane .scroll-bar {
    -fx-background-color: rgba(255,255,255,0.5);
}

.text-area .viewport {
    -fx-background-color: transparent;
}

.text-area .content {
    -fx-background-color: transparent;
}

.text-area .text {
    -fx-effect: dropshadow(gaussian,#fff,10,0.8,0,0);
}

Если же нужно, чтобы изображение прокручивалось, тогда следует указать его в .text-area .content {...}.
Документация по CSS:
JavaFX 9 CSS Reference Guide
JavaFX 8 CSS Reference Guide


text:
Q: Flutter Google Maps doesn't show location on first launch I'm using Google Maps (google_maps_flutter: ^2.1.3) in my Flutter app, and when I open the app on the phone for the first time, it asks for location permission. After giving this permission, my location on the Map is not shown with a blue dot and the go to my location button is not visible either. However, after that, when I close the application and open it again, both my location appears with a blue dot and the go to my location button is actively displayed on the screen.
Here is my GoogleMap widget:
GoogleMap(
                          myLocationEnabled: true,
                          myLocationButtonEnabled: true,
                          mapType: MapType.normal,
                          initialCameraPosition: const CameraPosition(
                            target: LatLng(30, 30),
                            zoom: 4,
                          ),
                          markers: markers,
                          mapToolbarEnabled: false,
                        ),

What do I need to do in order for my location to appear on Google Maps after I give location permission when I first open the application?

A: I was initially launching my app from HomePage but to fix this issue I created the transition page LandingPage. In LandingPage, I first checked if the user's location is turned on. I forced the user to turn on their location if it wasn't turned on. If it's turned on, I got the user's location and sent that location to HomePage using constructor. In HomePage, I started the map from this location. Thus, the user gave the location permission on the previous transition page and I used the location we got on that page as the map starting location.
I performed the following operations on LandingPage:
bool isLocationEnabled = false;
  bool isLocationEnabledChecked = false;
  double? latMe;
  double? longMe;
  Location _locationTracker = Location();

  Future<void> checkIsLocationEnabled() async {
    isLocationEnabled = await _locationTracker.serviceEnabled();
    setState(() {});
    if (isLocationEnabled) {
      var location = await _locationTracker.getLocation();
      latMe = location.latitude;
      longMe = location.longitude;
    }
    setState(() {
      isLocationEnabledChecked = true;
    });
  }

@override
  void initState() {
    super.initState();
    checkIsLocationEnabled();
  }

@override
  Widget build(BuildContext context) {
      if (isLocationEnabledChecked) {
        if (isLocationEnabled) {
          return HomePage(
            latitude: latMe,
            longitude: longMe,
          );
        } else {
          return EnableLocationScreen();
        }
      } else {
        return WaitingScreen();
      }
  }

I performed the following operations on HomePage:
GoogleMap(
                                onMapCreated: (GoogleMapController controller) async {
                                  _customInfoWindowController.googleMapController = controller;
                                  mapController.complete(controller);
                                },
                                onTap: (position) {
                                  _customInfoWindowController.hideInfoWindow!();
                                },
                                onCameraMove: (position) {
                                  _customInfoWindowController.onCameraMove!();
                                },
                                myLocationEnabled: true,
                                myLocationButtonEnabled: true,
                                mapType: MapType.normal,
                                initialCameraPosition: CameraPosition(
                                  target: LatLng(widget.latitude ?? 38.917001095328345, widget.longitude ?? 35.532376170158386),
                                  zoom: 15,
                                ),
                                markers: markers,
                                polygons: polygon,
                                mapToolbarEnabled: false,
                                minMaxZoomPreference: const MinMaxZoomPreference(10, 20),
                              ),

I am using location: ^4.3.0 package.

A: In IOS it works and in android it needs reboot so show permission on splash before opening map page or after getting permission reload page. Simple solution set bool isLocationEnabled=false; then when you get permission from user make
setState(() {
      isLocationEnabled=true;
    });

and set the value  as follows
GoogleMap(
                      myLocationEnabled: isLocationEnabled,
                      myLocationButtonEnabled: true,
                      mapType: MapType.normal,
                      initialCameraPosition: const CameraPosition(
                        target: LatLng(30, 30),
                        zoom: 4,
                      ),
                      markers: markers,
                      mapToolbarEnabled: false,
                    ),


text:
Q: jquery calender not working via ajax page load in php I have html page with calender select input. It is working fine when I open in localhost but I call same code in php page via ajax it is not working. Below is HTML Code

   <link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />

   <input type="text" id="datepicker" />

If I am call above code in php page and loading that page via ajax the above code not working.
I am using 2 php file delete.php, deleteDateCalender.php
code for delete.php

<title>test</title>

                        <form>
                            <input type="button" value="test" onclick="deleteCalDateAjax();" />

                        </form>

code for deleteDateCalender.php
<input type="text" id="datepicker" />

  <link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />

deleteDateCalender.php called on click of test button in delete.php
Can you see what is wrong in the above code?
Any help will be appreciated.

A: The $(function() { ... }); is triggered when the document has finished loading. If you load that code via AJAX then the document has already been loaded and will therefor never get triggered.
Your best bet would be to initiate the datepicker() script AFTER you have finished adding the HTML from AJAX into the page.
Your delete.php code would look something like this:
(I removed all that other XMLHttpRequest JavaScript as if you are using jQuery it handles everything for you and ensures it works across all browsers)

<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />

Example

<input type="button" onclick="deleteCalDateAjax();" value="Test" />

this text will be replaced with HTML from AJAX call

<input name="DateButton" type="button" id="DateButton" value="Open Calander" onclick="$('#datepicker').datepicker('show');" />

code for deleteDateCalender.php (I'm not entirely sure why you would do this but I'm sure you have a plan)
<input type="text" id="datepicker" />

Does that help?


text:
Q: How to fetch data from *.txt file to Iterable object in Flutter I would like to fetch the data from .txt file and save it in "Iterable<String'> object.
Code below is getting data from file to String, but I don't know how to go from here. I would be glad for any help.
Future<String> fetchFileData() async
  {
    String response;
    response =  await rootBundle.loadString('assets/file.txt');
  }

A: You can split the String you get from the loadString() by new lines, getting a List<String> which is an Iterable:
Future<List<String>> fetchFileData() async {
  String response;
  response = await rootBundle.loadString('assets/file.txt');
  return response.split('\n');
}

Example call:
List<String> list = await fetchFileData();


text:
Q: selecting pairs of records php array I need to create a code that will take the value of $time[1] and subtract the value of $time[2], then takes the value of $time[3] and subtracts the value of $time[4], and so on, until it runs out of $time records. It should keep a running total.
Mock data:
$time[1] = "2017-08-28 18:30:00";
$time[2] = "2017-08-28 14:00:00";
$time[3] = "2017-08-28 13:00:00";
$time[4] = "2017-08-28 12:45:00";
$time[5] = "2017-08-28 12:30:00";
$time[6] = "2017-08-28 12:00:00";

For example: [1]-[2]=4.5 hours, [3]-[4]=0.25 hours, [5]-[6]=0.5 hours; total=5.25 hours.
$hourdiff = round((strtotime($time[1]) - strtotime($time[2]))/3600, 1); //gives you the quantity of hours worked between 2 records

I need a way to select records 1 and 2, calculate the $hourdiff, add it to the running total, then select records 3 and 4, calculate the $hourdiff, add it to the running total, etc. until there are no records left to calculate.

A: It sounds like you're looking for a for loop:
for ($i = 1; $i <= count($time) - 1; $i++) {
    $hourdiff = round((strtotime($time[$i + 1]) - strtotime($time[$i]))/3600, 1);
    echo "The difference is: $hourdiff" . "<br />";
}

This will echo out the five differences in time.
Note that you need to start with the $i at 1, because you can't subtract 'nothing' from the first event! To counter this, you need to stop the index one short of the count.
This can be seen working here.
Hope this helps! :)

A: Iterate through the array, but instead of adding 1 to the iterating variable, add two (and check for an out of bounds error):
<?php
$time[0] = "2017-08-28 18:30:00";
$time[1] = "2017-08-28 14:00:00";
$time[2] = "2017-08-28 13:00:00";
$time[3] = "2017-08-28 12:45:00";
$time[4] = "2017-08-28 12:30:00";
$time[5] = "2017-08-28 12:00:00";
$total = 0;
for ($i = 0; $i < count($time); $i += 2) {
    if ($i + 1 > count($time) - 1) break; // check of out of bounds
    $total += round((strtotime($time[$i]) - strtotime($time[$i + 1]))/3600, 1); // add diff of next two numbers
}
echo $total;

Demo

A: Try with:
$time[1] = "2017-08-28 18:30:00";
$time[2] = "2017-08-28 14:00:00";
$time[3] = "2017-08-28 13:00:00";
$time[4] = "2017-08-28 12:45:00";
$time[5] = "2017-08-28 12:30:00";
$time[6] = "2017-08-28 12:00:00";

$times = array();

$total = 0;

foreach ($time as $n => $t0) {
    if ($n % 2) {
        continue;
    }
    $t1 = strtotime($time[$n - 1]);
    $t2 = strtotime($t0);
    $k = sprintf('%s-%s', $n - 1, $n);
    $diff = ($t1 - $t2) / 3600;
    $times[$k] = sprintf('%.2f hours', $diff);
    $total += $diff;
}

print_r($times);
printf('TOTAL : %s hours', $total);

Output
Array
(
    [1-2] => 4.50 hours
    [3-4] => 0.25 hours
    [5-6] => 0.50 hours
)
TOTAL : 5.25 hours

Or yo can try with DateTime::diff
$time[1] = "2017-08-28 18:30:00";
$time[2] = "2017-08-28 14:00:00";
$time[3] = "2017-08-28 13:00:00";
$time[4] = "2017-08-28 12:45:00";
$time[5] = "2017-08-28 12:30:00";
$time[6] = "2017-08-28 12:00:00";

$times = array();

$total = new DateTime;

foreach ($time as $n => $t0) {
    if ($n % 2) {
        continue;
    }
    $t1 = new DateTime($time[$n - 1]);
    $t2 = new DateTime($t0);
    $k = sprintf('%s-%s', $n - 1, $n);
    $diff = $t1->diff($t2);
    $times[$k] = $diff->format('%h hour(s) %i min(s) %s sec(s)');
    $total = $total->add($diff);
}

$total = ($total->diff(new DateTime))->format('%h hour(s) %i min(s) %s sec(s)');

print_r($times);
printf('TOTAL : %s', $total);

Output
Array
(
    [1-2] => 4 hour(s) 30 min(s) 0 sec(s)
    [3-4] => 0 hour(s) 15 min(s) 0 sec(s)
    [5-6] => 0 hour(s) 30 min(s) 0 sec(s)
)
TOTAL : 5 hour(s) 15 min(s) 0 sec(s)

A: Use array_chunk to group into pairs, then array_reduce to sum the differences:
$total = array_reduce(
    array_chunk($time, 2),
    function ($total, $pair) {
        return $total + (strtotime($pair[0]) - strtotime($pair[1]));
    },
    0
);

See it online at 3v4l.org.
The input $time is an array of time-like strings, suitable for passing to strtotime. The resulting $total will be an integer number of seconds.


text:
Q: What does the leading semicolon in a javascript file mean? I have a file jquery.flex.js which starts with

What does beginning mean?

A: The purpose of this semicolon is to avoid an error if the file is concatenated with another one.
For example suppose you have two files like this :
(function(){
    ...
})()

It's OK as long as it's in two separate files but it's a error if you concatenate them as is frequently done to reduce the number of requests. What happens is that basically you have
(A)()(B)()

and that the engine is trying to call the result of (A)() with argument B.
Adding a semicolon to delimit the statements fix the problem.

A: Since most modules start with a self-executing function (function() {/* module code */}()) the trailing semicolon is just a security issue:
Take this example: if you load two js modules on your website, and the first one ends without a semicolon:
(function firstModule (window, undefined) {
    /* whatever this module does comes here */
})()

and the second one looks the same:
(function secondModule (window, undefined) {
    /* whatever this second module does comes here */
})()

Then you got a problem. Because your first module will execute itself and the second module will try to execute the result of the first modules self-execution:
(firstModule)()(secondModule)()

This would mostly break your code, or at least lead to unexpected behaviour.
So it is a simple pattern to add a leading semicolon to your module code:
;(firstModule)();(secondModule)()

And everything is fine.

A: I don't know what you're asking for, but your title says:

What does comma mean in javascript?

It is used as a separator.


text:
Q: QTestLib - Verifying non-const reference arguments I'm currently building a unit test suite for my application, using QTestLib.  It's generally pretty straight-forward, but I'm become stuck on how to verify 'return' arguments.  For example, if I have a function:
double pointLineSegmentDistance(const QVector2D& start,
                                const QVector2D& end,
                                const QVector2D& point,
                                bool& withinBounds);

The function assigns withinBounds the bounded state of the segment distance analysis.  How can I make the QCOMPARE/QVERIFY macros analyse it's state?

A: Just pass a local variable as argument and verify/compare its value afterwards:
bool withinBounds = false;
const double distance = pointLineSegmentDistance( ..., withinBounds );
QCOMPARE(distance + 1.0, 2.0); //qFuzzyCompare doesn't work well with 0.0
QVERIFY(withinBounds);


text:
Q: PostgreSQL is not using the unique index when having variable number of values in IN clause Simplified problem
I've tried to isolate and minimize the case we have on our PostgreSQL v11 database, so here it is:
We can have this simple table:
CREATE TABLE "Table" (
    id BIGSERIAL PRIMARY KEY,
    col1_text TEXT NOT NULL,
    col2_bigint BIGINT NOT NULL,
    CONSTRAINT "table_col1_col2_unique" UNIQUE (col1_text, col2_bigint)
);

We can insert one row but the amount of data doesn't seem to have an effect in this case:
INSERT INTO "Table" VALUES (default, '1', 1);
Then we have these two queries which is the same base query but with different amount of data in the IN clause:
Example1:
SELECT * FROM "Table"
    WHERE (col1_text, col2_bigint) in (
        SELECT ids.id_text, ids.id_bigint from (
            VALUES
            ('1', 1),
            ('1', 1),
            ('1', 1),
            ('1', 1),
            ('1', 1),
            ('1', 1),
            ('1', 1),
            ('1', 1),
            ('1', 1),
            ('1', 1),
            ('1', 1),
            ('1', 1),
            ('1', 1)
        ) as ids(id_text, id_bigint)
    )

and this:
Example2:
SELECT * FROM "Table"
    WHERE (col1_text, col2_bigint) in (
        SELECT ids.id_text, ids.id_bigint from (
            VALUES
            ('1', 1),
            ('1', 1),
            ('1', 1),
            ('1', 1),
            ('1', 1)
        ) as ids(id_text, id_bigint)
    )

The explain analyze command on the first one gives the following output:
"Hash Semi Join  (cost=0.36..29.96 rows=268 width=48) (actual time=0.002..0.002 rows=0 loops=1)"
"  Hash Cond: (("Table".col1_text = "*VALUES*".column1) AND ("Table".col2_bigint = "*VALUES*".column2))"
"  ->  Seq Scan on "Table"  (cost=0.00..20.70 rows=1070 width=48) (actual time=0.002..0.002 rows=0 loops=1)"
"  ->  Hash  (cost=0.16..0.16 rows=13 width=36) (never executed)"
"        ->  Values Scan on "*VALUES*"  (cost=0.00..0.16 rows=13 width=36) (never executed)"
"Planning Time: 0.185 ms"
"Execution Time: 0.017 ms"

and for the second one we have this:
"Nested Loop  (cost=0.24..21.01 rows=268 width=48) (actual time=0.019..0.019 rows=0 loops=1)"
"  ->  HashAggregate  (cost=0.09..0.14 rows=5 width=36) (actual time=0.012..0.013 rows=1 loops=1)"
"        Group Key: "*VALUES*".column1, "*VALUES*".column2"
"        ->  Values Scan on "*VALUES*"  (cost=0.00..0.06 rows=5 width=36) (actual time=0.002..0.003 rows=5 loops=1)"
"  ->  Index Scan using table_unique_col1_col2 on "Table"  (cost=0.15..4.17 rows=1 width=48) (actual time=0.005..0.005 rows=0 loops=1)"
"        Index Cond: ((col1_text = "*VALUES*".column1) AND (col2_bigint = "*VALUES*".column2))"
"Planning Time: 0.168 ms"
"Execution Time: 0.050 ms"

(Don't mind the execution time here as the table is empty in this case, but not in the real case, see below.)
The question is why do we get this different behavior of the same query?
I would expect increase of the cost of the values scan but not to change the way it scans the original table.
What I've tried is increasing the work_mem to 32 MB (the default was 4 MB) of my instance but it didn't change the query planner.
Our real problem
Our real situation is that we have a "Table" with a unique constraint defined like in the example above and it has around 12M records and few more columns (around 10).
We also have a select query that is similar to the Example1 but in the Values section, in one scenario, it had around 58K pairs. It made our application stuck in a query timeout loop as PostgreSQL needs around 17 seconds to run the query, which was a lot more than expected.
We tried partitioning the query data (the values section) in few queries, each having around 500 pairs, and then it seems that the query planner uses the unique index, and each query runs in less than a second.
Executing the partitioned queries, cumulatively took almost half of the time (around 9s in total) compared to the runtime of the single big query (around 17s).
Can someone explain why this happens and can we expect this to be changed in some other version of postgres?
Or maybe suggest some tweak that could increase the probability of using the index?

A: PostgreSQL uses the following logic to estimate the selectivity of the IN clause (from scalararraysel in src/backend/utils/adt/selfuncs.c):
We consider three cases:

1. rightop is an Array constant: deconstruct the array, apply the
operator's selectivity function for each array element, and merge the
results in the same way that clausesel.c does for AND/OR combinations.

[...]

For generic operators, we assume the probability of success is
independent for each array element.  But for "= ANY" or "<> ALL",
if the array elements are distinct (which'd typically be the case)
then the probabilities are disjoint, and we should just sum them.

If we were being really tense we would try to confirm that the
elements are all distinct, but that would be expensive and it
doesn't seem to be worth the cycles; it would amount to penalizing
well-written queries in favor of poorly-written ones.  However, we
do protect ourselves a little bit by checking whether the
disjointness assumption leads to an impossible (out of range)
probability; if so, we fall back to the normal calculation.

Now how does that apply to your case?
We have an = ANY here (IN is translated to that), so PostgreSQL estimates the selectivity of each individual value and treats them as different, that is, it adds the results.
Assuming that the selectivity of
WHERE (col1_text, col2_bigint) = ('1', 1)

is 0.01 (it filters out 99% of the rows), the selectivity of the IN list with five elements would be 0.05, which is small enough to make an index scan look attractive.
With 13 elements, the selectivity becomes 0.13, which already warrants a sequential scan.
If there are 101 elements, PostgreSQL realizes that something is fishy, because a probability can never exceed 1. In that case, it uses 1-(1-0.01)101 (the probabilistic sum), which is about 0.64.
The problem with your test statement is that all elements of the IN list are empty, but as the comments quoted above say: If we were being really tense we would try to confirm that the
elements are all distinct, but that would be expensive and it
doesn't seem to be worth the cycles; it would amount to penalizing
well-written queries in favor of poorly-written ones.
In your real case, one of two things could be the case:

*

*you have duplicates, so PostgreSQL mis-estimates similar to above.

*each estimate is a little bit off, and the error adds in the sum.
You could try running ANALYZE on the large table with a higher value of default_statistics_target, maybe that improves the estimate sufficiently.
But my real recommendation is to change the way you go about this. I may be wrong, but this looks like some kind of "poor man's join"
SELECT id
   FROM table1
   WHERE <condition>;

SELECT *
   FROM table2
   WHERE table1_id IN (<result from the first query>);

Instead, do
SELECT table2.*
   FROM table1
      JOIN table2 ON table2.table1_id = table1.id
   WHERE <consition>;


text:
Q: Using A4SWIFT to generate SWIFT FIN MT103 results in empty multi-option SWIFT field tokens We're using BizTalk and A4SWIFT to generate SWIFT FIN MT 103 messages.
When we're outputting to fields that have multiple options (eg. 57a, 57b, 57c, 57d) we should only have a single output (I'm calling this a field token). However, all available options are output, regardless of whether they should be.
Consider field 57, which can have options 57a, 57b, 57c and 57d.
In our testing, we're limiting to 57a and 57d for now.
We have a map from our source XML document/schema, which selects which fields to use and populates the A4SWIFT schema accordingly.

(I've blanked out irrelevant detail in the image)
In the example, we're looking for a string for the BIC ("ABCDEFGHXXX") and populating the A4SWIFT-side for field 57A IF that is true.
For the Name Address (57d), we check the NameAddress/Line1 field for an arbitrary string which we know will evaluate to false.
(The BIC is fictitious)
This works fine, except we also get an empty result for 57D, even though this should have evaluated to false.
:57A:/
ABCDEFGHXXX
:57D:/

We need 57D to not be there. If the condition Functoid returns False, the Value Mapping Functoid still seems to cause a result.
So we're thinking out Functoid selection isn't right. We've tried with Logical Existence, Logical String and String Equal.
How can we suppress unselected fields from appearing in our output SWIFT?

A: Try linking through a Equal or Not Equal Functoid directly to 57D and/or 57A.  That will suppress the entire loop.


text:
Q: How can I make my form only except values that the user entered that are between 1 - 100 (e.g like for the age box) I want this to apply to the age input box and to only except the values that are between 1 - 100,in 'javascript'.

Form

<form name="form"  onsubmit="myFunction()" method="post" action="">

    <input type="text" required minlength="3" maxlength="20" placeholder="Enter your first name">

    <input type="text" minlength="3" maxlength="20" required placeholder="Enter your last name">

    <input id="age" required name="number" type="number" placeholder="Enter your age">

    <input type="text" required placeholder="Enter your email">

    <input type="submit" required value="Submit">

</form>

A: The attributes min and max is probably what you're looking for.
<input id="age" required name="number" type="number" placeholder="Enter your age" min="1" max="100">

You may need to clarify what you mean by "only except the values that are between 1 - 100,in 'javascript'." if not.


text:
Q: If the fibers of a submersion are connected, does it mean that any 2 sections are homotopic (locally on the base)? Is the following fact known? If yes - what is the reference?
Let $\phi:X\to Y$ be a submersion of smooth manifolds with connected fibers.
Let $s_0,s_1:Y\to X$ be its (smooth) sections. Then, for any $y\in Y$, there exists an open neighborhood $U$ of $y$ and a smooth homotopy $h:[0,1] \times U\to X$ such that $h|_{\{0\}\times U}=s_0$, $h|_{\{1\}\times U}=s_1$, and $h|_{\{t\}\times U}$ is a section of $\phi$ for any $t$.
We seem to have a proof, but we prefer to give a reference.