问:
Does the set.seed() function in combination with the sample() function provides always the same sample independent of the used hardware?
I ran the sample() command in combination with the set.seed() command to obtain always the same sample and everything worked fine. However, applying the same commands on a different laptop gave back a different sample. Does anyone have any idea what has happened?

I tried also the combination set.seed() and rnorm(), surprisingly I got then exactly the same random numbers on both laptops.

```<code>set.seed(123)
sample(LETTERS,6)

set.seed(123)
rnorm(6,1,1)
</code>```

I expected that on both laptops the result "H" "T" "J" "U" "W" "A" is displayed. However, one laptop displayed the result "O" "S" "N" "C" "J" "R".

```<code>set.seed(123)
rnorm(6,1,1)
</code>```

produced

```<code>0.4395244 0.7698225 2.5587083 1.0705084 1.1292877 2.7150650
</code>```

on both laptops.

答:
This is not due to cross-hardware reproducibility issues, but a difference introduced in R 3.6.0 -- you must have one machine on R 3.6.0 and the other on an earlier version. From help("set.seed") (from R 3.6.0):

Usage

...

  set.seed(seed, kind = NULL, normal.kind = NULL, sample.kind = NULL)

  ...

Details

sample.kind can be "Rounding" or "Rejection", or partial matches to
  these. The former was the default in versions prior to 3.6.0: it made
  sample noticeably non-uniform on large populations, and should only be
  used for reproduction of old results. See PR#17494 for a discussion.

Observe the following to see the difference within machine (i.e., this shows it is not a cross-hardware issue, because I'm doing this on only one machine):

```<code>set.seed(123, sample.kind = "Rejection") # Default in R 3.6.0
sample(LETTERS, 6)
# [1] "O" "S" "N" "C" "J" "R"

set.seed(123, sample.kind = "Rounding") # Default in R < 3.6.0
sample(LETTERS, 6)
# [Warning omitted]
# [1] "H" "T" "J" "U" "W" "A"
</code>```

Body:
I ran the sample() command in combination with the set.seed() command to obtain always the same sample and everything worked fine. However, applying the same commands on a different laptop gave back a different sample. Does anyone have any idea what has happened?

I tried also the combination set.seed() and rnorm(), surprisingly I got then exactly the same random numbers on both laptops.

set.seed(123)
sample(LETTERS,6)

set.seed(123)
rnorm(6,1,1)

I expected that on both laptops the result "H" "T" "J" "U" "W" "A" is displayed. However, one laptop displayed the result "O" "S" "N" "C" "J" "R".

set.seed(123)
rnorm(6,1,1)

produced

0.4395244 0.7698225 2.5587083 1.0705084 1.1292877 2.7150650

on both laptops.

Body:
This is not due to cross-hardware reproducibility issues, but a difference introduced in R 3.6.0 -- you must have one machine on R 3.6.0 and the other on an earlier version. From help("set.seed") (from R 3.6.0):

Usage

...

  set.seed(seed, kind = NULL, normal.kind = NULL, sample.kind = NULL)

  ...

Details

sample.kind can be "Rounding" or "Rejection", or partial matches to
  these. The former was the default in versions prior to 3.6.0: it made
  sample noticeably non-uniform on large populations, and should only be
  used for reproduction of old results. See PR#17494 for a discussion.

Observe the following to see the difference within machine (i.e., this shows it is not a cross-hardware issue, because I'm doing this on only one machine):

set.seed(123, sample.kind = "Rejection") # Default in R 3.6.0
sample(LETTERS, 6)
# [1] "O" "S" "N" "C" "J" "R"

set.seed(123, sample.kind = "Rounding") # Default in R < 3.6.0
sample(LETTERS, 6)
# [Warning omitted]
# [1] "H" "T" "J" "U" "W" "A"


来源: stackexchange

问:
Query Performance Optimization
I have this mysql query :

```<code>SELECT tbl.userid, tbl.name, tbl.courseid, tbl.fullname, IFNULL(tbl.instance, '-') instance, IFNULL(tbl.activityname, '-') activityname,
    IFNULL(tbl.module, '-') module, IFNULL(tbl.attempt, '-') attempt, IFNULL(tbl.score, '-') score,
    CASE tbl.module WHEN 'quiz' THEN (
        CASE WHEN (tbl.attempt IS NULL AND tbl.score IS NULL) THEN 'NOT YET'
        WHEN (tbl.attempt IS NOT NULL AND tbl.score IS NULL) THEN 'ATTEMPT'
        WHEN (tbl.attempt IS NOT NULL AND tbl.score IS NOT NULL) THEN 'FINISH'
        END)
    WHEN 'scorm' THEN (
        CASE WHEN tbl.attempt IS NULL THEN 'NOT YET'
        ELSE (SELECT `status` FROM mdl_scorm_logs WHERE scormid = tbl.instance AND userid = tbl.userid)
        END)
    ELSE '-'
    END `status`
FROM (
    SELECT tbl1.userid, tbl1.name, tbl1.courseid, tbl1.fullname, tbl2.instance,
        CASE tbl2.module WHEN 'quiz' THEN (SELECT `name` FROM mdl_quiz WHERE id = tbl2.instance AND course = tbl1.courseid)
        WHEN 'scorm' THEN (SELECT `name` FROM mdl_scorm WHERE id = tbl2.instance AND course = tbl1.courseid)
        END activityname
        , tbl2.module,
        CASE tbl2.module WHEN 'quiz' THEN (SELECT MAX(attempt) FROM mdl_quiz_attempts WHERE quiz = tbl2.instance AND userid = tbl1.userid)
        WHEN 'scorm' THEN (SELECT MAX(attempt) FROM mdl_scorm_scoes_track WHERE scormid = tbl2.instance AND userid = tbl1.userid )
        END attempt,
        (SELECT CONCAT(TRUNCATE(ROUND(gg.finalgrade / gi.grademax * 100, 2), 2), ' %')
        FROM mdl_grade_grades gg
        JOIN mdl_grade_items gi ON gg.itemid = gi.id
        WHERE gg.userid = tbl1.userid AND gi.courseid = tbl1.courseid AND gi.itemname = activityname AND gi.itemtype = 'mod'
            AND gi.itemmodule = tbl2.module AND gi.iteminstance = tbl2.instance) score
    FROM (
        SELECT u.id userid, CONCAT(u.firstname, ' ', u.lastname) `name`, c.id courseid, c.fullname
        FROM mdl_user u
        JOIN mdl_role_assignments ra ON u.id = ra.userid
        JOIN mdl_context co ON ra.contextid = co.id
        JOIN mdl_role r ON ra.roleid = r.id
        JOIN mdl_course c ON co.instanceid = c.id
        JOIN mdl_enrol e ON c.id = e.courseid
        JOIN mdl_user_enrolments ue ON e.id = ue.enrolid AND u.id = ue.userid
        WHERE r.archetype = 'student') tbl1
    LEFT JOIN (
        SELECT cm.course, m.name module, cm.instance FROM mdl_course_modules cm
        JOIN mdl_modules m ON cm.module = m.id
        WHERE m.name IN ('quiz', 'scorm')
        ) tbl2
    ON tbl1.courseid = tbl2.course) tbl
WHERE tbl.userid = '4' AND tbl.courseid = '8'
GROUP BY tbl.courseid, tbl.instance
ORDER BY tbl.name, tbl.fullname, tbl.activityname
</code>```

Result after I use EXPLAIN :

```<code>id  select_type table   type    possible_keys   key key_len ref rows    Extra
1   PRIMARY <derived3>  ALL                 122 Using where; Using temporary; Using filesort
3   DERIVED <derived9>  ALL                 42
3   DERIVED <derived10> ALL                 23
10  DERIVED m   range   PRIMARY,mdl_modu_nam_ix mdl_modu_nam_ix 62      2   Using where; Using index
10  DERIVED cm  ref mdl_courmodu_mod_ix mdl_courmodu_mod_ix 8   moodle.m.id 4
9   DERIVED r   ref PRIMARY,mdl_role_arc_ix mdl_role_arc_ix 92      1   Using where; Using index
9   DERIVED ra  ref mdl_roleassi_rol_ix,mdl_roleassi_con_ix,mdl_roleassi_use_ix mdl_roleassi_rol_ix 8   moodle.r.id 5
9   DERIVED u   eq_ref  PRIMARY PRIMARY 8   moodle.ra.userid    1
9   DERIVED co  eq_ref  PRIMARY,mdl_cont_ins_ix PRIMARY 8   moodle.ra.contextid 1
9   DERIVED e   ref PRIMARY,mdl_enro_cou_ix mdl_enro_cou_ix 8   moodle.co.instanceid    1   Using index
9   DERIVED c   eq_ref  PRIMARY PRIMARY 8   moodle.co.instanceid    1
9   DERIVED ue  eq_ref  mdl_userenro_enruse_uix,mdl_userenro_enr_ix,mdl_userenro_use_ix mdl_userenro_enruse_uix 16  moodle.e.id,moodle.ra.userid    1   Using index
8   DEPENDENT SUBQUERY  gi  ref PRIMARY,mdl_graditem_itenee_ix,mdl_graditem_cou_ix  mdl_graditem_cou_ix 9   tbl1.courseid   1   Using where
8   DEPENDENT SUBQUERY  gg  eq_ref  mdl_gradgrad_useite_uix,mdl_gradgrad_ite_ix,mdl_gradgrad_use_ix mdl_gradgrad_useite_uix 16  tbl1.userid,moodle.gi.id    1   Using where
7   DEPENDENT SUBQUERY  mdl_scorm_scoes_track   ref mdl_scorscoetrac_usescosco_uix,mdl_scorscoetrac_use_ix,mdl_scorscoetrac_sco_ix  mdl_scorscoetrac_usescosco_uix  16  tbl1.userid,tbl2.instance   6   Using where; Using index
6   DEPENDENT SUBQUERY  mdl_quiz_attempts   ref mdl_quizatte_use_ix,mdl_quizatte_qui_ix mdl_quizatte_qui_ix 8   tbl2.instance   2   Using where
5   DEPENDENT SUBQUERY  mdl_scorm   eq_ref  PRIMARY,mdl_scor_cou_ix PRIMARY 8   tbl2.instance   1   Using where
4   DEPENDENT SUBQUERY  mdl_quiz    eq_ref  PRIMARY,mdl_quiz_cou_ix PRIMARY 8   tbl2.instance   1   Using where
2   DEPENDENT SUBQUERY  mdl_scorm_logs  eq_ref  PRIMARY PRIMARY 16  func,func   1   Using where
</code>```

Any idea to optimize it?
Thank You.

答:
Yes. Convert the correllated subqueries to outer joins. You should probably be able to get a good start by querying those terms on this site and google.

Same for the "derived tables", I imagine.

The syntax

SELECT ... FROM (SELECT FROM ... ) can be problematic.

I may not understand the context, but denormalization seems to me to be a wildly premature choice.

ContentLicense: CC BY-SA 3.0

Title: Query Performance Optimization

Body:
I have this mysql query :

SELECT tbl.userid, tbl.name, tbl.courseid, tbl.fullname, IFNULL(tbl.instance, '-') instance, IFNULL(tbl.activityname, '-') activityname,
    IFNULL(tbl.module, '-') module, IFNULL(tbl.attempt, '-') attempt, IFNULL(tbl.score, '-') score,
    CASE tbl.module WHEN 'quiz' THEN (
        CASE WHEN (tbl.attempt IS NULL AND tbl.score IS NULL) THEN 'NOT YET'
        WHEN (tbl.attempt IS NOT NULL AND tbl.score IS NULL) THEN 'ATTEMPT'
        WHEN (tbl.attempt IS NOT NULL AND tbl.score IS NOT NULL) THEN 'FINISH'
        END)
    WHEN 'scorm' THEN (
        CASE WHEN tbl.attempt IS NULL THEN 'NOT YET'
        ELSE (SELECT `status` FROM mdl_scorm_logs WHERE scormid = tbl.instance AND userid = tbl.userid)
        END)
    ELSE '-'
    END `status`
FROM (
    SELECT tbl1.userid, tbl1.name, tbl1.courseid, tbl1.fullname, tbl2.instance,
        CASE tbl2.module WHEN 'quiz' THEN (SELECT `name` FROM mdl_quiz WHERE id = tbl2.instance AND course = tbl1.courseid)
        WHEN 'scorm' THEN (SELECT `name` FROM mdl_scorm WHERE id = tbl2.instance AND course = tbl1.courseid)
        END activityname
        , tbl2.module,
        CASE tbl2.module WHEN 'quiz' THEN (SELECT MAX(attempt) FROM mdl_quiz_attempts WHERE quiz = tbl2.instance AND userid = tbl1.userid)
        WHEN 'scorm' THEN (SELECT MAX(attempt) FROM mdl_scorm_scoes_track WHERE scormid = tbl2.instance AND userid = tbl1.userid )
        END attempt,
        (SELECT CONCAT(TRUNCATE(ROUND(gg.finalgrade / gi.grademax * 100, 2), 2), ' %')
        FROM mdl_grade_grades gg
        JOIN mdl_grade_items gi ON gg.itemid = gi.id
        WHERE gg.userid = tbl1.userid AND gi.courseid = tbl1.courseid AND gi.itemname = activityname AND gi.itemtype = 'mod'
            AND gi.itemmodule = tbl2.module AND gi.iteminstance = tbl2.instance) score
    FROM (
        SELECT u.id userid, CONCAT(u.firstname, ' ', u.lastname) `name`, c.id courseid, c.fullname
        FROM mdl_user u
        JOIN mdl_role_assignments ra ON u.id = ra.userid
        JOIN mdl_context co ON ra.contextid = co.id
        JOIN mdl_role r ON ra.roleid = r.id
        JOIN mdl_course c ON co.instanceid = c.id
        JOIN mdl_enrol e ON c.id = e.courseid
        JOIN mdl_user_enrolments ue ON e.id = ue.enrolid AND u.id = ue.userid
        WHERE r.archetype = 'student') tbl1
    LEFT JOIN (
        SELECT cm.course, m.name module, cm.instance FROM mdl_course_modules cm
        JOIN mdl_modules m ON cm.module = m.id
        WHERE m.name IN ('quiz', 'scorm')
        ) tbl2
    ON tbl1.courseid = tbl2.course) tbl
WHERE tbl.userid = '4' AND tbl.courseid = '8'
GROUP BY tbl.courseid, tbl.instance
ORDER BY tbl.name, tbl.fullname, tbl.activityname

Result after I use EXPLAIN :

id  select_type table   type    possible_keys   key key_len ref rows    Extra
1   PRIMARY <derived3>  ALL                 122 Using where; Using temporary; Using filesort
3   DERIVED <derived9>  ALL                 42
3   DERIVED <derived10> ALL                 23
10  DERIVED m   range   PRIMARY,mdl_modu_nam_ix mdl_modu_nam_ix 62      2   Using where; Using index
10  DERIVED cm  ref mdl_courmodu_mod_ix mdl_courmodu_mod_ix 8   moodle.m.id 4
9   DERIVED r   ref PRIMARY,mdl_role_arc_ix mdl_role_arc_ix 92      1   Using where; Using index
9   DERIVED ra  ref mdl_roleassi_rol_ix,mdl_roleassi_con_ix,mdl_roleassi_use_ix mdl_roleassi_rol_ix 8   moodle.r.id 5
9   DERIVED u   eq_ref  PRIMARY PRIMARY 8   moodle.ra.userid    1
9   DERIVED co  eq_ref  PRIMARY,mdl_cont_ins_ix PRIMARY 8   moodle.ra.contextid 1
9   DERIVED e   ref PRIMARY,mdl_enro_cou_ix mdl_enro_cou_ix 8   moodle.co.instanceid    1   Using index
9   DERIVED c   eq_ref  PRIMARY PRIMARY 8   moodle.co.instanceid    1
9   DERIVED ue  eq_ref  mdl_userenro_enruse_uix,mdl_userenro_enr_ix,mdl_userenro_use_ix mdl_userenro_enruse_uix 16  moodle.e.id,moodle.ra.userid    1   Using index
8   DEPENDENT SUBQUERY  gi  ref PRIMARY,mdl_graditem_itenee_ix,mdl_graditem_cou_ix  mdl_graditem_cou_ix 9   tbl1.courseid   1   Using where
8   DEPENDENT SUBQUERY  gg  eq_ref  mdl_gradgrad_useite_uix,mdl_gradgrad_ite_ix,mdl_gradgrad_use_ix mdl_gradgrad_useite_uix 16  tbl1.userid,moodle.gi.id    1   Using where
7   DEPENDENT SUBQUERY  mdl_scorm_scoes_track   ref mdl_scorscoetrac_usescosco_uix,mdl_scorscoetrac_use_ix,mdl_scorscoetrac_sco_ix  mdl_scorscoetrac_usescosco_uix  16  tbl1.userid,tbl2.instance   6   Using where; Using index
6   DEPENDENT SUBQUERY  mdl_quiz_attempts   ref mdl_quizatte_use_ix,mdl_quizatte_qui_ix mdl_quizatte_qui_ix 8   tbl2.instance   2   Using where
5   DEPENDENT SUBQUERY  mdl_scorm   eq_ref  PRIMARY,mdl_scor_cou_ix PRIMARY 8   tbl2.instance   1   Using where
4   DEPENDENT SUBQUERY  mdl_quiz    eq_ref  PRIMARY,mdl_quiz_cou_ix PRIMARY 8   tbl2.instance   1   Using where
2   DEPENDENT SUBQUERY  mdl_scorm_logs  eq_ref  PRIMARY PRIMARY 16  func,func   1   Using where

Any idea to optimize it?
Thank You.


问:
KSVM (in r) giving - Error in indexes[[j]] : subscript out of bounds
I have been running into this error every time I try to implement ksvm.
My code:

```<code>Train11<- read.csv('Train.csv', head=TRUE)
Train11 <- (sapply(Train11, as.numeric)) #convert all data to numeric
Train11 <- as.data.frame(Train11)
ModelV2<-ksvm(CityAssessment~., data=Train11, type= "C-svc", kernel="vanilladot", C=0.1,prob.model=TRUE)
 Setting default kernel parameters
Error in indexes[[j]] : subscript out of bounds
</code>```

I am not sure where I am going wrong. the dimensions of the dataset are 686 x 72. there aren't any NA values in the dataset (I've checked it!) and no infinite values either.

Many thanks!

答: I had the same problem, turned out I had only one class in my target vector. </p>

Body:
I have been running into this error every time I try to implement ksvm.
My code:

Train11<- read.csv('Train.csv', head=TRUE)
Train11 <- (sapply(Train11, as.numeric)) #convert all data to numeric
Train11 <- as.data.frame(Train11)
ModelV2<-ksvm(CityAssessment~., data=Train11, type= "C-svc", kernel="vanilladot", C=0.1,prob.model=TRUE)
 Setting default kernel parameters
Error in indexes[[j]] : subscript out of bounds

I am not sure where I am going wrong. the dimensions of the dataset are 686 x 72. there aren't any NA values in the dataset (I've checked it!) and no infinite values either.

Many thanks!

ContentLicense: CC BY-SA 4.0


问:
Index out of bounds problem with easyimap
I'm sorry if this has already been answered but I am getting an IndexError: list index out of range with this line:

```<code>print(unread[item].body)
</code>```

IndexError: list index out of range with this line:

```<code>print(unread[item].body)
</code>```

I have the following code:

```<code>import ConfigParser
import easyimap

config = ConfigParser.ConfigParser()

path = "settings.ini"

config.read(path)

hostname = config.get("mailserver", "host")
username = config.get("mailserver", "user")
password = config.get("mailserver", "pass")
mailbox  = config.get("mailserver", "mbox")

imapper = easyimap.connect(hostname, username, password, mailbox)

emails = 4
unread = imapper.unseen(emails)

for item in range(emails):
    print(unread[item].body)
</code>```

I've tried rewriteing the for loop to subtract 1 from item then to add 1 to it

答:
When you call unseen(emails), then emails states the limit
how many at most mails should be read.

But the number of mails that have just been read may be smaller.
You have no guarantee that just as many mails have been read.
The actual number is the length of the unread (list).

So the loop should be:

```<code>for item in range(len(unread)):
    print(unread[item].body)
</code>```

Body:
I'm sorry if this has already been answered but I am getting an IndexError: list index out of range with this line:

print(unread[item].body)

IndexError: list index out of range with this line:

print(unread[item].body)

I have the following code:

import ConfigParser
import easyimap

config = ConfigParser.ConfigParser()

path = "settings.ini"

config.read(path)

hostname = config.get("mailserver", "host")
username = config.get("mailserver", "user")
password = config.get("mailserver", "pass")
mailbox  = config.get("mailserver", "mbox")

imapper = easyimap.connect(hostname, username, password, mailbox)

emails = 4
unread = imapper.unseen(emails)

for item in range(emails):
    print(unread[item].body)

I've tried rewriteing the for loop to subtract 1 from item then to add 1 to it

Body:
When you call unseen(emails), then emails states the limit
how many at most mails should be read.

But the number of mails that have just been read may be smaller.
You have no guarantee that just as many mails have been read.
The actual number is the length of the unread (list).

So the loop should be:

for item in range(len(unread)):
    print(unread[item].body)


问:
How to put a horizontal frame containing a couple of widgets into a default vertical frame?
I have a layout that is vertical, with some horizontal rows containing a few widgets. When I add the first row it goes fine, but the second row goes at the end of the first row and not back in the vertical frame

I've tried everything I can find with no luck.

```<code>import tkinter
win = tkinter.Tk()

frame2 = tkinter.Frame()
frame3 = tkinter.Frame()

frame2.pack()
frame3.pack()

lv1 = tkinter.Label(win, text = "Vertical lab 1")
lv1.pack()
lv2 = tkinter.Label(win, text = "Vertical lab 2")
lv2.pack()

v = tkinter.IntVar()

rb1 = tkinter.Radiobutton(frame2, padx = 10, variable=v,value=1)
rb1.pack()
lh1 = tkinter.Label(frame2, text = "Horizontal lab1")
lh1.pack()
frame2 = tkinter.Frame(win).pack()

rb2 = tkinter.Radiobutton(frame3, padx = 10, variable=v, value=2)
rb2.pack()
lh2 = tkinter.Label(frame3, text = "Horizontal lab2")
lh2.pack()
frame3 = tkinter.Frame(win).pack()

lv3 = tkinter.Label(win, text = "Vertical lab 3")
lv3.pack(anchor="w")

win.mainloop()
</code>```

What I want is something that looks like: One widget on line 1, one widget on line 2, 2 widgets on line 3, 2 widgets on line 4, 1 widget on line 5

答:
For positioning use tkinter grid option:</p>

```<code>from tkinter import *

window = Tk()
window.geometry('600x400')

# set widget object
label = Label(window, text="Vertical lab 1")
# set position of widget into grid
label.grid(column=0, row=0)

label = Label(window, text="Vertical lab 2")
label.grid(column=0, row=1)
label = Radiobutton(window, text="Horizontal lab 1", value=0)
label.grid(column=0, row=2)
label = Radiobutton(window, text="Horizontal lab 2", value=1)
label.grid(column=1, row=2)
label = Radiobutton(window, text="Horizontal lab 3", value=0)
label.grid(column=0, row=3)
label = Radiobutton(window, text="Horizontal lab 4", value=1)
label.grid(column=1, row=3)
label = Label(window, text="Vertical lab 3")
label.grid(column=0, row=4)

window.mainloop()
</code>```

Body:
I have a layout that is vertical, with some horizontal rows containing a few widgets. When I add the first row it goes fine, but the second row goes at the end of the first row and not back in the vertical frame

I've tried everything I can find with no luck.

import tkinter
win = tkinter.Tk()

frame2 = tkinter.Frame()
frame3 = tkinter.Frame()

frame2.pack()
frame3.pack()

lv1 = tkinter.Label(win, text = "Vertical lab 1")
lv1.pack()
lv2 = tkinter.Label(win, text = "Vertical lab 2")
lv2.pack()

v = tkinter.IntVar()

rb1 = tkinter.Radiobutton(frame2, padx = 10, variable=v,value=1)
rb1.pack()
lh1 = tkinter.Label(frame2, text = "Horizontal lab1")
lh1.pack()
frame2 = tkinter.Frame(win).pack()

rb2 = tkinter.Radiobutton(frame3, padx = 10, variable=v, value=2)
rb2.pack()
lh2 = tkinter.Label(frame3, text = "Horizontal lab2")
lh2.pack()
frame3 = tkinter.Frame(win).pack()

lv3 = tkinter.Label(win, text = "Vertical lab 3")
lv3.pack(anchor="w")

win.mainloop()

What I want is something that looks like: One widget on line 1, one widget on line 2, 2 widgets on line 3, 2 widgets on line 4, 1 widget on line 5

Body:
For positioning use tkinter grid option:

from tkinter import *

window = Tk()
window.geometry('600x400')

# set widget object
label = Label(window, text="Vertical lab 1")
# set position of widget into grid
label.grid(column=0, row=0)

label = Label(window, text="Vertical lab 2")
label.grid(column=0, row=1)
label = Radiobutton(window, text="Horizontal lab 1", value=0)
label.grid(column=0, row=2)
label = Radiobutton(window, text="Horizontal lab 2", value=1)
label.grid(column=1, row=2)
label = Radiobutton(window, text="Horizontal lab 3", value=0)
label.grid(column=0, row=3)
label = Radiobutton(window, text="Horizontal lab 4", value=1)
label.grid(column=1, row=3)
label = Label(window, text="Vertical lab 3")
label.grid(column=0, row=4)

window.mainloop()


问:
Filter Google Map markers with a checkbox
I'm trying to show certain markers when a user selects a checkbox and clicks "show on map". It should show 2 markers when the "Gaudi Tour" is selected and two different markers when the "Gothic Tour" is selected. However, it isn't filtering the results in the createMarkers() function and is instead showing all the markers when the button is clicked.

I can't figure out why it's not filtering the results and I'm not getting any errors.

Choose your tour:

                        <input type="checkbox" class="form-check-input" id="one">Gaudi Tour

                        <input type="checkbox" class="form-check-input" id="two">Gothic Tour

                <button onclick="updateMarkers();">Show on Map</button>

```

```
var map;

var markers = [];

//---------------------Data of Locations-----------------

let locations = [{
        name: 'one',
        tour: 'gaudi',
        coords: { lat: 41.403706, lng: 2.173504 },
        content: 'google',
    },
    {
        name: 'one',
        tour: 'gaudi',
        coords: { lat: 41.4145, lng: 2.1527 },
        content: 'maps',
    },
    {
        name: 'two',
        tour: 'gothic',
        coords: { lat: 41.3839, lng: 2.1821 },
        content: 'are'
    },
    {
        name: 'two',
        tour: 'gothic',
        coords: { lat: 41.3840, lng: 2.1762 },
        content: 'annoying'
    }
];

//---------------------Initializing Map-----------------

function initMap() {
    var mapOptions = {
        center: new google.maps.LatLng(41.3851, 2.1734),
        zoom: 12
    };

    map = new google.maps.Map(document.getElementById("map"), mapOptions);

}
//---------------------Markers-----------------

function addMarker(props) {
    var marker = new google.maps.Marker({
        position: props.coords,
        map: map,
        icon: props.iconImage
    });

    //checking for icon
    if (props.iconImage) {
        marker.setIcon(props.iconImage);
    }

    //checking for infowindow
    if (props.content) {
        var infoWindow = new google.maps.InfoWindow({
            content: props.content
        });

        marker.addListener('click', function() {
            infoWindow.open(map, marker);
        });
    }
}

function updateMarkers() {
    createMarkers();
    for (var i = 0; i < locations.length; i++) {
       addMarker(locations[i]);
    }
}

//---------------------Select Tour-----------------

function createMarkers() {
    let selectedLocations = locations.filter(function(obj) {
        var selectedTour = document.getElementById("selectTour").value;
        return obj.tour === selectedTour;
    });

    let resultlist = [];

    if (document.getElementById("one").checked) {
        let one = selectedLocations.filter(function(obj) {
            return obj.name === 'one';
        });
        resultlist = resultlist.concat(one);
    }

    if (document.getElementById("two").checked) {
        let two = selectedLocations.filter(function(obj) {
            return obj.name === 'two';
        });
        resultlist = resultlist.concat(two);
    }

    for (var i = 0; i < resultlist.length;) {
        markers.push({
            coords: {
                lat: resultlist[i].lat,
                lng: resultlist[i].lng
            },
            content: resultlist[i].name
        });
    }
}

```

Any advice would be a massive help.

答:
Based upon your original code but modified - I hope this will help you towards finding google maps a little less "annoying" '-)</p>

```<code><!doctype html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title>Google Maps: </title>
        <style>
            #map{
                width:100%;
                height:80vh;
                float:none;
                margin:auto;
            }
        </style>
        <script>
            let map;
            let markers=[];
            let infoWindow;

            let locations = [
                {
                    name: 'one',
                    tour: 'gaudi',
                    latlng: { lat: 41.403706, lng: 2.173504 },
                    content: 'google',
                },
                {
                    name: 'one',
                    tour: 'gaudi',
                    latlng: { lat: 41.4145, lng: 2.1527 },
                    content: 'maps',
                },
                {
                    name: 'two',
                    tour: 'gothic',
                    latlng: { lat: 41.3839, lng: 2.1821 },
                    content: 'are'
                },
                {
                    name: 'two',
                    tour: 'gothic',
                    latlng: { lat: 41.3840, lng: 2.1762 },
                    content: 'annoying'
                }
            ];

            function initMap(){
                let options = {
                    center: new google.maps.LatLng(41.3851, 2.1734),
                    zoom: 12
                };
                map = new google.maps.Map( document.getElementById('map'), options );
                infoWindow = new google.maps.InfoWindow();

                const addmarker=function(args){
                    let mkr=new google.maps.Marker({
                        position: args.latlng,
                        map: map
                    });
                    if( args.hasOwnProperty('icon') ) mkr.setIcon( args.icon );
                    if( args.hasOwnProperty('name') ) mkr.name=args.name;
                    if( args.hasOwnProperty('content') ) mkr.content=args.content;

                    google.maps.event.addListener( mkr, 'click', clickhandler );
                    return mkr;
                };
                const clickhandler=function(e){
                    infoWindow.open( map, this );
                    infoWindow.setContent( this.content );
                };
                const clearmarkers=function(){
                    markers.forEach( mkr=>{
                        mkr.setMap( null );
                    });
                };

                Array.prototype.slice.call( document.querySelectorAll('input[type="radio"][name="tour"]') ).forEach(function(input){
                    input.addEventListener('click', function(e){
                        if( this.value ){
                            /* clear any markers added to the map already */
                            clearmarkers();

                            /* only show those that qualify based upon selected tour */
                            locations.forEach( obj=>{
                                if( obj.tour==this.value ) markers.push( addmarker.call( this, obj ) );
                            });
                        }
                    });
                });
            }
        </script>
        <script async defer src='//maps.googleapis.com/maps/api/js?key=APIKEY&callback=initMap'></script>
    </head>
    <body>
        <form>
            <!--

                if you use `radio` buttons instead of checkboxes then you ensure
                that only 1 tour type can be selected at once.

                You may note that there is also a hidden field with the same
                name before the radio buttons - not strictly necessary in this
                case but is a useful trick in some circumstances.

            -->

            <section>
                <div class='container'>
                    <h2>Choose your tour:</h2>

                    <input type='hidden' name='tour' value=false />

                    <div class='container'>

                        <div class='form-check-inline'>
                            <label class='form-check-label'>
                                <input name='tour' value='gaudi' type='radio' class='form-check-input' />Gaudi Tour
                            </label>
                        </div>

                        <div class='form-check-inline'>
                            <label class='form-check-label'>
                                <input name='tour' value='gothic' type='radio' class='form-check-input' />Gothic Tour
                            </label>
                        </div>
                    </div>

                    <!--The Map-->
                    <div class='container'>
                        <div id='map'></div>
                    </div>
                </div>
            </section>

        </form>
    </body>
</html>
</code>```

Body:
I'm trying to show certain markers when a user selects a checkbox and clicks "show on map". It should show 2 markers when the "Gaudi Tour" is selected and two different markers when the "Gothic Tour" is selected. However, it isn't filtering the results in the createMarkers() function and is instead showing all the markers when the button is clicked.

I can't figure out why it's not filtering the results and I'm not getting any errors.

Choose your tour:

                        <input type="checkbox" class="form-check-input" id="one">Gaudi Tour

                        <input type="checkbox" class="form-check-input" id="two">Gothic Tour

                <button onclick="updateMarkers();">Show on Map</button>

var map;

var markers = [];

//---------------------Data of Locations-----------------

let locations = [{
        name: 'one',
        tour: 'gaudi',
        coords: { lat: 41.403706, lng: 2.173504 },
        content: 'google',
    },
    {
        name: 'one',
        tour: 'gaudi',
        coords: { lat: 41.4145, lng: 2.1527 },
        content: 'maps',
    },
    {
        name: 'two',
        tour: 'gothic',
        coords: { lat: 41.3839, lng: 2.1821 },
        content: 'are'
    },
    {
        name: 'two',
        tour: 'gothic',
        coords: { lat: 41.3840, lng: 2.1762 },
        content: 'annoying'
    }
];

//---------------------Initializing Map-----------------

function initMap() {
    var mapOptions = {
        center: new google.maps.LatLng(41.3851, 2.1734),
        zoom: 12
    };

    map = new google.maps.Map(document.getElementById("map"), mapOptions);

}
//---------------------Markers-----------------

function addMarker(props) {
    var marker = new google.maps.Marker({
        position: props.coords,
        map: map,
        icon: props.iconImage
    });

    //checking for icon
    if (props.iconImage) {
        marker.setIcon(props.iconImage);
    }

    //checking for infowindow
    if (props.content) {
        var infoWindow = new google.maps.InfoWindow({
            content: props.content
        });

        marker.addListener('click', function() {
            infoWindow.open(map, marker);
        });
    }
}

function updateMarkers() {
    createMarkers();
    for (var i = 0; i < locations.length; i++) {
       addMarker(locations[i]);
    }
}

//---------------------Select Tour-----------------

function createMarkers() {
    let selectedLocations = locations.filter(function(obj) {
        var selectedTour = document.getElementById("selectTour").value;
        return obj.tour === selectedTour;
    });

    let resultlist = [];

    if (document.getElementById("one").checked) {
        let one = selectedLocations.filter(function(obj) {
            return obj.name === 'one';
        });
        resultlist = resultlist.concat(one);
    }

    if (document.getElementById("two").checked) {
        let two = selectedLocations.filter(function(obj) {
            return obj.name === 'two';
        });
        resultlist = resultlist.concat(two);
    }

    for (var i = 0; i < resultlist.length;) {
        markers.push({
            coords: {
                lat: resultlist[i].lat,
                lng: resultlist[i].lng
            },
            content: resultlist[i].name
        });
    }
}

Any advice would be a massive help.

Body:
Based upon your original code but modified - I hope this will help you towards finding google maps a little less "annoying" '-)

<!doctype html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title>Google Maps: </title>
        <style>
            #map{
                width:100%;
                height:80vh;
                float:none;
                margin:auto;
            }
        </style>
        <script>
            let map;
            let markers=[];
            let infoWindow;

            let locations = [
                {
                    name: 'one',
                    tour: 'gaudi',
                    latlng: { lat: 41.403706, lng: 2.173504 },
                    content: 'google',
                },
                {
                    name: 'one',
                    tour: 'gaudi',
                    latlng: { lat: 41.4145, lng: 2.1527 },
                    content: 'maps',
                },
                {
                    name: 'two',
                    tour: 'gothic',
                    latlng: { lat: 41.3839, lng: 2.1821 },
                    content: 'are'
                },
                {
                    name: 'two',
                    tour: 'gothic',
                    latlng: { lat: 41.3840, lng: 2.1762 },
                    content: 'annoying'
                }
            ];

            function initMap(){
                let options = {
                    center: new google.maps.LatLng(41.3851, 2.1734),
                    zoom: 12
                };
                map = new google.maps.Map( document.getElementById('map'), options );
                infoWindow = new google.maps.InfoWindow();

                const addmarker=function(args){
                    let mkr=new google.maps.Marker({
                        position: args.latlng,
                        map: map
                    });
                    if( args.hasOwnProperty('icon') ) mkr.setIcon( args.icon );
                    if( args.hasOwnProperty('name') ) mkr.name=args.name;
                    if( args.hasOwnProperty('content') ) mkr.content=args.content;

                    google.maps.event.addListener( mkr, 'click', clickhandler );
                    return mkr;
                };
                const clickhandler=function(e){
                    infoWindow.open( map, this );
                    infoWindow.setContent( this.content );
                };
                const clearmarkers=function(){
                    markers.forEach( mkr=>{
                        mkr.setMap( null );
                    });
                };

                Array.prototype.slice.call( document.querySelectorAll('input[type="radio"][name="tour"]') ).forEach(function(input){
                    input.addEventListener('click', function(e){
                        if( this.value ){
                            /* clear any markers added to the map already */
                            clearmarkers();

                            /* only show those that qualify based upon selected tour */
                            locations.forEach( obj=>{
                                if( obj.tour==this.value ) markers.push( addmarker.call( this, obj ) );
                            });
                        }
                    });
                });
            }
        </script>
        <script async defer src='//maps.googleapis.com/maps/api/js?key=APIKEY&callback=initMap'></script>
    </head>
    <body>
        <form>
            <!--

                if you use `radio` buttons instead of checkboxes then you ensure
                that only 1 tour type can be selected at once.

                You may note that there is also a hidden field with the same
                name before the radio buttons - not strictly necessary in this
                case but is a useful trick in some circumstances.

            -->

            <section>
                <div class='container'>
                    <h2>Choose your tour:</h2>

                    <input type='hidden' name='tour' value=false />

                    <div class='container'>

                        <div class='form-check-inline'>
                            <label class='form-check-label'>
                                <input name='tour' value='gaudi' type='radio' class='form-check-input' />Gaudi Tour
                            </label>
                        </div>

                        <div class='form-check-inline'>
                            <label class='form-check-label'>
                                <input name='tour' value='gothic' type='radio' class='form-check-input' />Gothic Tour
                            </label>
                        </div>
                    </div>

                    <!--The Map-->
                    <div class='container'>
                        <div id='map'></div>
                    </div>
                </div>
            </section>

        </form>
    </body>
</html>


问:
Need to display the max price and company that has it
So, i just started working with python and i need to display the maximum price and the company that has it. I got the data from an CSV file that has multiple columns that describes some cars. I'm only interested in two of them: price and company.

I need to display the maximum price and the company that has it. Some advice?
This is what i tried and I don't know how to get the company too, not only the maximum price.

import pandas as pd
df = pd.read_csv("Automobile_data.csv")
for x in df['price']:
    if x == df['price'].max():
       print(x)
```

答:
In addition to the complete answer of Jezrael, I would suggest using groupby as follows:

```<code>df = pd.DataFrame({
        'company':list('abcdef'),
         'price':[7,8,9,4,2,3],

})

sorted_df = df.groupby(['price']).max().reset_index()

desired_row = sorted_df.loc[sorted_df.index[-1]]

price = desired_row[0]
company = desired_row[1]

print('Maximum price is: ', price)
print('The company is: ', company)
</code>```

The above code prints:

```<code>Maximum price is:  9
The company is:  c
</code>```

Body:
In addition to the complete answer of Jezrael, I would suggest using groupby as follows:

df = pd.DataFrame({
        'company':list('abcdef'),
         'price':[7,8,9,4,2,3],

})

sorted_df = df.groupby(['price']).max().reset_index()

desired_row = sorted_df.loc[sorted_df.index[-1]]

price = desired_row[0]
company = desired_row[1]

print('Maximum price is: ', price)
print('The company is: ', company)

The above code prints:

Maximum price is:  9
The company is:  c


问:
Width transtion not working with flex display
I have a flex element that I want to expand whenever i hover on it.

Here is my code:

HTML

```<code>    <div class="fixed-header">
        <div id="header"><h1>Physi_cs</h1></div>

        <div id="nav-list">
            <ul>
                <li><a href="#">Shop</a></li>
                <li><a href="#">Learn Physics</a></li>
                <li><a href="#">Articles</a></li>
                <li><a href="LoginPage.html">Log In</a></li>
                <li><a href="SignUpPage.html">Sign Up</a></li>
            </ul>
        </div>
    </div>
</code>```

CSS

```<code>.fixed-header {
    background-color: rgba(237, 241, 242, 0.8);
    height: 25vh;
    padding: 20px 0px;

    display: flex;
    flex-direction: row;
    align-items: center;

    box-shadow:0px -1px 2px rgba(23, 37, 58, 0.8) inset;
}

.fixed-header #header {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-grow: 1;

    height: 80%;
    box-shadow: 3px 0px 0px rgba(40, 40, 40, 0.8); /* ACTS AS A BORDER */

    cursor: pointer;
    transition: all ease 1s;
}

.fixed-header #header:hover {
    width: 50vw; // HERE I AM TRYING TO CHANGE THE WIDTH
}
</code>```

I want my #header to expand over 1 second and not instantly.

Thanks for your help in advance!

答:
A few things here. It looks like the property you actually want to adjust is flex-basis, not width. You also will need to remove the flex-grow property from the header:

https://jsfiddle.net/dtyxmpza/

Body:
I have a flex element that I want to expand whenever i hover on it.

Here is my code:

HTML

Physi_cs

Shop

Learn Physics

Articles

Log In

Sign Up

CSS

.fixed-header {
    background-color: rgba(237, 241, 242, 0.8);
    height: 25vh;
    padding: 20px 0px;

    display: flex;
    flex-direction: row;
    align-items: center;

    box-shadow:0px -1px 2px rgba(23, 37, 58, 0.8) inset;
}

.fixed-header #header {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-grow: 1;

    height: 80%;
    box-shadow: 3px 0px 0px rgba(40, 40, 40, 0.8); /* ACTS AS A BORDER */

    cursor: pointer;
    transition: all ease 1s;
}

.fixed-header #header:hover {
    width: 50vw; // HERE I AM TRYING TO CHANGE THE WIDTH
}

I want my #header to expand over 1 second and not instantly.

Thanks for your help in advance!


问:
Adjacency List Model for User Types
I have a fairly large number of user types that I need in my database and so far the only good option that does not involve lots and lots of tables is to use Adjacency List Model. Basically, my users are first split between the following types: Business, Individual and Administrator. From there it goes like this:

Note: I currently have 3 Levels of user types but this might change over time depending on business needs.

All my users share a common users table which holds details such as email, password, first name, last name, etc. All my business users have a separate businesses table which stores business specific data. The businesses users don't all share the same fields, but since I only need a few fields for each different type of user I thought it might be the best approach to have all the fields into one table and store NULL for the fields I don't use.

Now, I have this simple scenario. All my users have an user profile page. My business users have a business profile page as well. My Business-Technicians must have another page specific to them.
Imagine a Computer Technician logs in. I want to be able to display a link for a Profile Page, Business Profile Page, and a Technician Dashboard.

To get a user type I have my model setup so that I can retrieve a "child" or "parent". If I say:

```<code>$user = new User::find(11);
$userType = $user->userType; //(relation set in the UserType & User Models)
while($userType != NULL) {
   dump($userType->name);
   $userType = $userType->parent; //(relation set in UserType Model)

}
// dump result:
// 11 - Computer Technician
// 5 - Technicians
// 1 - Business
</code>```

How can I easily implement a way to check for Technicians (to provide the link for the Technician Dashboard) and to also check for Businesses (to provide the Business profile page link)?

答:
I've created a package that uses common table expressions (CTE) to implement recursive relationships: https://github.com/staudenmeir/laravel-adjacency-list

You can use the ancestorsAndSelf relationship to check for specific user types:

class UserType extends Model
{
    use \Staudenmeir\LaravelAdjacencyList\Eloquent\HasRecursiveRelationships;
}

$user = User::find(11);

$userTypes = $user->userType->ancestorsAndSelf;

if ($userTypes->where('name', 'Technicians')->isNotEmpty()) {
    //
}

if ($userTypes->where('name', 'Business')->isNotEmpty()) {
    //
}
```

Title: Adjacency List Model for User Types

Body:
I have a fairly large number of user types that I need in my database and so far the only good option that does not involve lots and lots of tables is to use Adjacency List Model. Basically, my users are first split between the following types: Business, Individual and Administrator. From there it goes like this:

Note: I currently have 3 Levels of user types but this might change over time depending on business needs.

All my users share a common users table which holds details such as email, password, first name, last name, etc. All my business users have a separate businesses table which stores business specific data. The businesses users don't all share the same fields, but since I only need a few fields for each different type of user I thought it might be the best approach to have all the fields into one table and store NULL for the fields I don't use.

Now, I have this simple scenario. All my users have an user profile page. My business users have a business profile page as well. My Business-Technicians must have another page specific to them.
Imagine a Computer Technician logs in. I want to be able to display a link for a Profile Page, Business Profile Page, and a Technician Dashboard.

To get a user type I have my model setup so that I can retrieve a "child" or "parent". If I say:

$user = new User::find(11);
$userType = $user->userType; //(relation set in the UserType & User Models)
while($userType != NULL) {
   dump($userType->name);
   $userType = $userType->parent; //(relation set in UserType Model)

}
// dump result:
// 11 - Computer Technician
// 5 - Technicians
// 1 - Business

How can I easily implement a way to check for Technicians (to provide the link for the Technician Dashboard) and to also check for Businesses (to provide the Business profile page link)?


问:
React input - no default value
I am so confused, I have no idea what is wrong. the default value does only sometimes show up, and sometimes when the default value shows up, if I press enter or click submit it results in being an empty string.

My Desired Outcome is: I want the input to show the default value, which is dueDateObject.dueDate. And then I want to be able to submit the input with the default value and have it being saved.

Problem::: Now when I save the default value, it sometimes saves it as an empty string.

Thanks in advance :)

```<code>state = {
    editDueDateText: ''
}
</code>```

```<code>onChangeEditDueDate = (event) => {
    this.setState({
      editDueDateText: event.target.value
    })
  }
</code>```

```<code>editDueDate = (e, keyName, dueDateObject) => {
    dueDateObject.showEditDate = false;
    this.props.editDueDate({ keyName, dueDateObject, editText: this.state.editDueDateText })
  }
</code>```

```<code> <input className="form-control"
              onKeyDown={(e) => this.editDueDatekeypress(e, keyName, dueDateObject)}
              onChange={this.onChangeEditDueDate}
              value={this.state.editDueDateText}
              defaultValue={dueDateObject.dueDate}
              type="text"
              placeholder="By 28th May, I will have" />
            <div className="input-group-append">
              <button className="btn btn-outline-primary"
                type="button"
                onClick={(e) => this.editDueDate(e, keyName, dueDateObject)}>Submit</button>
            </div>
</code>```

答:
I solved it by:
Deleting this code snippet: value={this.state.editDueDateText} and adjusting with some conditional statements along the way in the function below.</p>

```<code>editDueDate = (e, keyName, dueDateObject) => {
    dueDateObject.showEditDate = false;

    if (this.state.editDueDateText) {
      this.props.editDueDate({ keyName, dueDateObject, editText: this.state.editDueDateText })
      this.setState({
        editDueDateText: ''
      })
    } else {
      this.props.editDueDate({ keyName, dueDateObject, editText: dueDateObject.dueDate })
      this.setState({
      editDueDateText:''
    })
    }
</code>```

Title: React input - no default value

Body:
I am so confused, I have no idea what is wrong. the default value does only sometimes show up, and sometimes when the default value shows up, if I press enter or click submit it results in being an empty string.

My Desired Outcome is: I want the input to show the default value, which is dueDateObject.dueDate. And then I want to be able to submit the input with the default value and have it being saved.

Problem::: Now when I save the default value, it sometimes saves it as an empty string.

Thanks in advance :)

state = {
    editDueDateText: ''
}

onChangeEditDueDate = (event) => {
    this.setState({
      editDueDateText: event.target.value
    })
  }

editDueDate = (e, keyName, dueDateObject) => {
    dueDateObject.showEditDate = false;
    this.props.editDueDate({ keyName, dueDateObject, editText: this.state.editDueDateText })
  }

 <input className="form-control"
              onKeyDown={(e) => this.editDueDatekeypress(e, keyName, dueDateObject)}
              onChange={this.onChangeEditDueDate}
              value={this.state.editDueDateText}
              defaultValue={dueDateObject.dueDate}
              type="text"
              placeholder="By 28th May, I will have" />

              <button className="btn btn-outline-primary"
                type="button"
                onClick={(e) => this.editDueDate(e, keyName, dueDateObject)}>Submit</button>

Body:
I solved it by:
Deleting this code snippet: value={this.state.editDueDateText} and adjusting with some conditional statements along the way in the function below.

editDueDate = (e, keyName, dueDateObject) => {
    dueDateObject.showEditDate = false;

    if (this.state.editDueDateText) {
      this.props.editDueDate({ keyName, dueDateObject, editText: this.state.editDueDateText })
      this.setState({
        editDueDateText: ''
      })
    } else {
      this.props.editDueDate({ keyName, dueDateObject, editText: dueDateObject.dueDate })
      this.setState({
      editDueDateText:''
    })
    }


问:
How much memory to multiply int by a double?
How much memory does multiplying 16 bit unsigned integer by a double and assigning it to another unsigned 16 bit integer take in C?  Would it temporarily load the double result in a register before assigning it to int?  I'm doing some programming for embedded systems that's why I'm asking.</p>

```<code>u16int_t a = 3;
u16int_t b = a * .4;
</code>```

答:
The computation itself uses very little memory, if any at all since in this particular piece of code, the result can be computed at compile time.

More generally, if the code fragment is the only place in your software where you use floating point arithmetics, depending on the actual embedded system characteristics, the code fragment might cause runtime library code to be linked for floating point support, which may amount to several kilobytes of code added to your binary file.

To avoid this, you could use use integer arithmetics:

```<code>u16int_t a = 3;
u16int_t b = a * 4 / 10;
</code>```

Body:
How much memory does multiplying 16 bit unsigned integer by a double and assigning it to another unsigned 16 bit integer take in C?  Would it temporarily load the double result in a register before assigning it to int?  I'm doing some programming for embedded systems that's why I'm asking.

u16int_t a = 3;
u16int_t b = a * .4;

Body:
The computation itself uses very little memory, if any at all since in this particular piece of code, the result can be computed at compile time.

More generally, if the code fragment is the only place in your software where you use floating point arithmetics, depending on the actual embedded system characteristics, the code fragment might cause runtime library code to be linked for floating point support, which may amount to several kilobytes of code added to your binary file.

To avoid this, you could use use integer arithmetics:

u16int_t a = 3;
u16int_t b = a * 4 / 10;


问:
How read the next value in the same line?
I want to read the value "-2.5" in variable "x1", and the value "0.4" in other variable called "y1". And the same for the line below: read "12.1" in a variable "x2" and read "7.3" in a variable "y2"

```<code>var lines = [
    "-2.5 0.4",
    "12.1 7.3"
];
</code>```

```<code>var x1 = parseFloat(lines[0]);
var y1 = jQuery(x1).next();
var x2 = parseFloat(lines[1]);
var y2 = jQuery(x2).next();

console.log(x1);
console.log(y1);
console.log(x2);
console.log(y2);
</code>```

this is the problem i'm solving
and the code i've made so far, but not accepting "Wrong Answer 85%"

Uncaught ReferenceError: jQuery is not defined

答:
I think you can have a look over this solution for your reference, hope this help

var lines = [
  "-2.5 0.4",
  "12.1 7.3"
];

// This will convert a string into an array seperated by space (" ")
const generatePosition = string => string.split(" ");

// This will map all our initial values and change them into a full array
const pos = lines.map(string => generatePosition(string));
console.log(pos);

// From now you can freely access the variable the way you want, this is just for sample demo
const a = pos[0][0];
const b = pos[0][1];
console.log(a);
console.log(b);```

Body:
I want to read the value "-2.5" in variable "x1", and the value "0.4" in other variable called "y1". And the same for the line below: read "12.1" in a variable "x2" and read "7.3" in a variable "y2"

var lines = [
    "-2.5 0.4",
    "12.1 7.3"
];

var x1 = parseFloat(lines[0]);
var y1 = jQuery(x1).next();
var x2 = parseFloat(lines[1]);
var y2 = jQuery(x2).next();

console.log(x1);
console.log(y1);
console.log(x2);
console.log(y2);

this is the problem i'm solving
and the code i've made so far, but not accepting "Wrong Answer 85%"

Uncaught ReferenceError: jQuery is not defined


答:
Your error can be solved by investigating whether Jquery is loaded or not, but it won't give you the correct result with your current code.

You can do this:

var lines = [
    "-2.5 0.4",
    "12.1 7.3"
];
var lineParts = lines[0].split(" ");
var x1 = parseFloat(lineParts[0]);
var y1 = parseFloat(lineParts[1]);

lineParts = lines[1].split(" ");
var x2 = parseFloat(lineParts[0]);
var y2 = parseFloat(lineParts[1]);

console.log(x1, y1, x2, y2);```

Title: How read the next value in the same line?


问:
how to get the same size like navigation bar using custom view?
I need to recreate navigation bar using custom view, since it will be easier to make than inserting view to the actual navigation bar from apple.
I need to insert search bar and some buttons.

but I have problem to set the size of that custom navigation bar view, in some iOS device it seems little bit bigger than the navigation bar from apple, I set the autolayout like the picture below. constraint to leading, trailing and top to the superview and then set the aspect ration to 375:80

the custom view is the red one. the navigation bar in orangeVC is from apple using navigation controller

and here is the result, for iPhone XR, XSMax, it seems great, the size seems the same.

but for iPhone 8 it seems the custom view is slightly bigger

how to properly make custom view that has the same size like navigation bar from apple?

答:
The best approach I found so far, without having to create a navigation controller instance:</p>

```<code>[self.navigationBar sizeThatFits:CGSizeZero].height;
</code>```

Body:
The best approach I found so far, without having to create a navigation controller instance:

[self.navigationBar sizeThatFits:CGSizeZero].height;


问:
I want to get the last 6 objects from an array
I have an array list of objects, and I only want to return the last 7 objects in the array. help pls

I have tried to use, filter, map and find, but I could not get the output I was expecting

var welcomeMessage = [{
    from: "Clement",
    text: "Welcome to Freeborn chat system!",
    id: 0
  },
  {
    from: "mark",
    text: "Hello",
    id: 1
  },
  {
    from: "clement",
    text: "welcome",
    id: 2
  },
  {
    from: "mark",
    text: "long time",
    id: 3
  },
  {
    from: "clement",
    text: "yeah, indeed",
    id: 4
  },
  {
    from: "mark",
    text: "real good to be hear",
    id: 5
  },
  {
    from: "clement",
    text: "you looking good",
    id: 7
  },
  {
    from: "mark",
    text: "Hello",
    id: 8
  },
  {
    from: "clement",
    text: "welcome",
    id: 9
  }
]

const messages = [welcomeMessage]

function latestMessage(messages, search) {
  let search = rquest.body;
  let messages = messages.length - 7
  const messages.filter(message => {
    return message
  })
}
```

答:
The above answers are correct and the best solution but if you need to use filter you can do something like this:</p>

```<code>const items = welcomeMessage.filter((obj, index) => {
    const arrayLength = welcomeMessage.length;
    const wantedItems = 6;
    return arrayLength - index <= wantedItems;
});
</code>```

Body:
The above answers are correct and the best solution but if you need to use filter you can do something like this:

const items = welcomeMessage.filter((obj, index) => {
    const arrayLength = welcomeMessage.length;
    const wantedItems = 6;
    return arrayLength - index <= wantedItems;
});


问:
Can I change the passed value inside function?
I want to transfer variable using function(), but I am not sure if I am able to put variable inside of variable

I tried to put variable inside variable like this var toStore = myVariable

```<code>var myText = "Hi";

changeMyText(myText);

function changeMyText(variableToUse) {
    variableToUse = "Hello World";
    console.log(myText);
}
</code>```

It does not change the content of variable myText

答:
Actually the argument you pass to function is pass by value this means that even when you change the argument value it doesn't reflect to actual value...

Here, from w3Schools - JavaScript Function Parameters

Arguments are Passed by Value

The parameters, in a function call, are the function's arguments.

JavaScript arguments are passed by value: The function only gets to
know the values, not the argument's locations.

If a function changes an argument's value, it does not change the
parameter's original value.

Changes to arguments are not visible (reflected) outside the function.

Objects are Passed by Reference

In JavaScript, object references are values.

Because of this, objects will behave like they are passed by
reference:

If a function changes an object property, it changes the original
value.

Changes to object properties are visible (reflected) outside the
function

This from mdn - function deceleration | Thanks @Ivar

Primitive parameters (such as a number) are passed to functions by value; the value is >passed to the function, but if the function changes the value of the parameter, this change is not reflected globally or in the calling function.

If you pass an object (i.e. a non-primitive value, such as Array or a user-defined object) as >a parameter and the function changes the object's properties, that change is visible outside the function

Body:
I want to transfer variable using function(), but I am not sure if I am able to put variable inside of variable

I tried to put variable inside variable like this var toStore = myVariable

var myText = "Hi";

changeMyText(myText);

function changeMyText(variableToUse) {
    variableToUse = "Hello World";
    console.log(myText);
}

It does not change the content of variable myText


问:
Delete na columns through several dataframe
I would like to delete columns full of na values in several data frame
I tried to use a function and loop through a list of dataframes but it doesn't work properly

I would like to obtain as output each dataframe in the list without na columns

答:
We can place the datasets in a list and then remove it

```<code>lst1 <- lapply(lst, function(dat) Filter(function(x) !all(is.na(x)), dat))
lst1
#[[1]]
#  col2 col3
#1   NA   12
#2   24   22

#[[2]]
#  col2 col3
#1   NA   12
#2   24   22
</code>```

In the OP's code,

```<code>data_frame_list <- paste0('df_',unique(df3$DATE))
</code>```

is just a string, we can get the values with mget

```<code>lst2 <- mget(paste0('df_',unique(df3$DATE)))
</code>```

data

```<code>df1 <- data.frame(col1 = NA, col2 = c(NA, 24), col3 = c(12, 22))
df2 <- df1
lst <- mget(paste0("df", 1:2))
</code>```

Body:
We can place the datasets in a list and then remove it

lst1 <- lapply(lst, function(dat) Filter(function(x) !all(is.na(x)), dat))
lst1
#[[1]]
#  col2 col3
#1   NA   12
#2   24   22

#[[2]]
#  col2 col3
#1   NA   12
#2   24   22

In the OP's code,

data_frame_list <- paste0('df_',unique(df3$DATE))

is just a string, we can get the values with mget

lst2 <- mget(paste0('df_',unique(df3$DATE)))

data

df1 <- data.frame(col1 = NA, col2 = c(NA, 24), col3 = c(12, 22))
df2 <- df1
lst <- mget(paste0("df", 1:2))


问:
React/WordPress PWA does not respond with a 200 when offline
I am currently trying to build a WordPress theme using React/Redux. Everything is working as expected except for responding with 200 when offline.

The build folder of CRA (Create React App) is located at /wp-content/themes/pwa/build.

When online, WordPress loads the index.php for all routes. This registers the .css and .js from the build folder. Here everything is working as expected.

Im trying to understand how to configure CRA / WorkBox to register the service worker at / and serve all pages using the index.html in the build folder whilst offline.

Full url of index.html: https://example.com/wp-content/themes/pwa/build/index.html

I can provide a link to the demo if required.

答:
I finally solved the problem with some help from W3C.

Pass scope option in /src/serviceWorker.js of the react app.

```<code>// navigator.serviceWorker.register(swUrl)
navigator.serviceWorker.register(swUrl, {scope: "/"})
</code>```

Configure Apache to serve the Service-Worker-Allowed header for the deployed service worker.

```<code><Files "service-worker.js">
    Header Set Service-Worker-Allowed "/"
</Files>
</code>```

Body:
I finally solved the problem with some help from W3C.

Pass scope option in /src/serviceWorker.js of the react app.

// navigator.serviceWorker.register(swUrl)
navigator.serviceWorker.register(swUrl, {scope: "/"})

Configure Apache to serve the Service-Worker-Allowed header for the deployed service worker.

<Files "service-worker.js">
    Header Set Service-Worker-Allowed "/"
</Files>


答:
Can you reformat your lines array so that each value is in its own element? That would make it easier to access each element. Like this:

```<code>var lines = [
    Array("-2.5","0.4"),
    Array("12.1","7.3")
];
</code>```

Then you could access the values this way:

```<code>var x1 = parseFloat(lines[0][0]);
var y1 = parseFloat(lines[0][1]);
var x2 = parseFloat(lines[1][0]);
var y2 = parseFloat(lines[1][1]);
</code>```

Body:
Can you reformat your lines array so that each value is in its own element? That would make it easier to access each element. Like this:

var lines = [
    Array("-2.5","0.4"),
    Array("12.1","7.3")
];

Then you could access the values this way:

var x1 = parseFloat(lines[0][0]);
var y1 = parseFloat(lines[0][1]);
var x2 = parseFloat(lines[1][0]);
var y2 = parseFloat(lines[1][1]);


问:
Unable to solve the XOR problem with just two hidden neurons in Python
I have a small, 3 layer, neural network with two input neurons, two hidden neurons and one output neuron. I am trying to stick to the below format of using only 2 hidden neurons.

I am trying to show how this can be used to behave as the XOR logic gate, however with just two hidden neurons I get the following poor output after 1,000,000 iterations!

```<code>Input: 0 0   Output:  [0.01039096]
Input: 1 0   Output:  [0.93708829]
Input: 0 1   Output:  [0.93599738]
Input: 1 1   Output:  [0.51917667]
</code>```

If I use three hidden neurons I get a much better output with 100,000 iterations:

```<code>Input: 0 0   Output:  [0.01831612]
Input: 1 0   Output:  [0.98558057]
Input: 0 1   Output:  [0.98567602]
Input: 1 1   Output:  [0.02007876]
</code>```

I am getting a decent output with 3 neurons in the hidden layer but not with two neurons in the hidden layer. Why?

As per a comment below, this repo contains code of high to solve the XOR problem using two hidden neurons.

I can't figure out what I am doing wrong. Any suggestions are appreciated!
Attached is my code:

```<code>import numpy as np
import matplotlib
from matplotlib import pyplot as plt

# Sigmoid function
def sigmoid(x, deriv=False):
    if deriv:
        return x * (1 - x)
    return 1 / (1 + np.exp(-x))

alpha = [0.7]

# Input dataset
X = np.array([[0, 0],
              [0, 1],
              [1, 0],
              [1, 1]])

# Output dataset
y = np.array([[0, 1, 1, 0]]).T

# seed random numbers to make calculation deterministic
np.random.seed(1)

# initialise weights randomly with mean 0
syn0 = 2 * np.random.random((2, 3)) - 1  # 1st layer of weights synapse 0 connecting L0 to L1
syn1 = 2 * np.random.random((3, 1)) - 1  # 2nd layer of weights synapse 0 connecting L1 to L2

# Randomize inputs for stochastic gradient descent
data = np.hstack((X, y))    # append Input and output dataset
np.random.shuffle(data)     # shuffle
x, y = np.array_split(data, 2, 1)    # Split along vertical(1) axis

for iter in range(100000):
    for i in range(4):
        # forward prop
        layer0 = x[i]  # Input layer
        layer1 = sigmoid(np.dot(layer0, syn0))  # Prediction step for layer 1
        layer2 = sigmoid(np.dot(layer1, syn1))  # Prediction step for layer 2

        layer2_error = y[i] - layer2  # Compare how well layer2's guess was with input

        layer2_delta = layer2_error * sigmoid(layer2, deriv=True)  # Error weighted derivative step

        if iter % 10000 == 0:
            print("Error: ", str(np.mean(np.abs(layer2_error))))
            plt.plot(iter, layer2_error, 'ro')

        # Uses "confidence weighted error" from l2 to establish an error for l1
        layer1_error = layer2_delta.dot(syn1.T)

        layer1_delta = layer1_error * sigmoid(layer1, deriv=True)  # Error weighted derivative step

        # Since SGD we need to dot product two 1D arrays. This is how.
        syn1 += (alpha * np.dot(layer1[:, None], layer2_delta[None, :]))  # Update weights
        syn0 += (alpha * np.dot(layer0[:, None], layer1_delta[None, :]))

    # Training was done above, below we re run to test algorithm

    layer0 = X  # Input layer
    layer1 = sigmoid(np.dot(layer0, syn0))  # Prediction step for layer 1
    layer2 = sigmoid(np.dot(layer1, syn1))  # Prediction step for layer 2

plt.show()
print("output after training: \n")
print("Input: 0 0 \t Output: ", layer2[0])
print("Input: 1 0 \t Output: ", layer2[1])
print("Input: 0 1 \t Output: ", layer2[2])
print("Input: 1 1 \t Output: ", layer2[3])
</code>```

答:
It is an unsolvable equation system, that is why NN can not solve it either.
While it may be an oversimplification, if we say the transfer function is linear, the expression becomes something like

```<code>z = (w1*x+w2*y)*w3 + (w4*x+w5*y)*w6
</code>```

Then there are the 4 cases:

```<code>xy=00, z=0 = 0
xy=10, z=1 = w1*w3+w4*w6
xy=01, z=1 = w2*w3+w5*w6
xy=11, z=0 = (w1+w2)*w3 + (w4+w5)*w6
</code>```

The problem is that

```<code>0 = (w1+w2)*w3 + (w4+w5)*w6 = w1*w3+w2*w3 + w4*w6+w5*w6            <-- xy=11 line
                            = w1*w3+w4*w6 + w2*w3+w5*w6 = 1+1 = 2  <-- xy=10 and xy=01 lines
</code>```

So the seemingly 6 degrees of freedom are just not enough here, that is why you experience the need for adding something extra.

Body:
I have a small, 3 layer, neural network with two input neurons, two hidden neurons and one output neuron. I am trying to stick to the below format of using only 2 hidden neurons.

I am trying to show how this can be used to behave as the XOR logic gate, however with just two hidden neurons I get the following poor output after 1,000,000 iterations!

Input: 0 0   Output:  [0.01039096]
Input: 1 0   Output:  [0.93708829]
Input: 0 1   Output:  [0.93599738]
Input: 1 1   Output:  [0.51917667]

If I use three hidden neurons I get a much better output with 100,000 iterations:

Input: 0 0   Output:  [0.01831612]
Input: 1 0   Output:  [0.98558057]
Input: 0 1   Output:  [0.98567602]
Input: 1 1   Output:  [0.02007876]

I am getting a decent output with 3 neurons in the hidden layer but not with two neurons in the hidden layer. Why?

As per a comment below, this repo contains code of high to solve the XOR problem using two hidden neurons.

I can't figure out what I am doing wrong. Any suggestions are appreciated!
Attached is my code:

import numpy as np
import matplotlib
from matplotlib import pyplot as plt

# Sigmoid function
def sigmoid(x, deriv=False):
    if deriv:
        return x * (1 - x)
    return 1 / (1 + np.exp(-x))

alpha = [0.7]

# Input dataset
X = np.array([[0, 0],
              [0, 1],
              [1, 0],
              [1, 1]])

# Output dataset
y = np.array([[0, 1, 1, 0]]).T

# seed random numbers to make calculation deterministic
np.random.seed(1)

# initialise weights randomly with mean 0
syn0 = 2 * np.random.random((2, 3)) - 1  # 1st layer of weights synapse 0 connecting L0 to L1
syn1 = 2 * np.random.random((3, 1)) - 1  # 2nd layer of weights synapse 0 connecting L1 to L2

# Randomize inputs for stochastic gradient descent
data = np.hstack((X, y))    # append Input and output dataset
np.random.shuffle(data)     # shuffle
x, y = np.array_split(data, 2, 1)    # Split along vertical(1) axis

for iter in range(100000):
    for i in range(4):
        # forward prop
        layer0 = x[i]  # Input layer
        layer1 = sigmoid(np.dot(layer0, syn0))  # Prediction step for layer 1
        layer2 = sigmoid(np.dot(layer1, syn1))  # Prediction step for layer 2

        layer2_error = y[i] - layer2  # Compare how well layer2's guess was with input

        layer2_delta = layer2_error * sigmoid(layer2, deriv=True)  # Error weighted derivative step

        if iter % 10000 == 0:
            print("Error: ", str(np.mean(np.abs(layer2_error))))
            plt.plot(iter, layer2_error, 'ro')

        # Uses "confidence weighted error" from l2 to establish an error for l1
        layer1_error = layer2_delta.dot(syn1.T)

        layer1_delta = layer1_error * sigmoid(layer1, deriv=True)  # Error weighted derivative step

        # Since SGD we need to dot product two 1D arrays. This is how.
        syn1 += (alpha * np.dot(layer1[:, None], layer2_delta[None, :]))  # Update weights
        syn0 += (alpha * np.dot(layer0[:, None], layer1_delta[None, :]))

    # Training was done above, below we re run to test algorithm

    layer0 = X  # Input layer
    layer1 = sigmoid(np.dot(layer0, syn0))  # Prediction step for layer 1
    layer2 = sigmoid(np.dot(layer1, syn1))  # Prediction step for layer 2

plt.show()
print("output after training: \n")
print("Input: 0 0 \t Output: ", layer2[0])
print("Input: 1 0 \t Output: ", layer2[1])
print("Input: 0 1 \t Output: ", layer2[2])
print("Input: 1 1 \t Output: ", layer2[3])

Body:
It is an unsolvable equation system, that is why NN can not solve it either.
While it may be an oversimplification, if we say the transfer function is linear, the expression becomes something like

z = (w1*x+w2*y)*w3 + (w4*x+w5*y)*w6

Then there are the 4 cases:

xy=00, z=0 = 0
xy=10, z=1 = w1*w3+w4*w6
xy=01, z=1 = w2*w3+w5*w6
xy=11, z=0 = (w1+w2)*w3 + (w4+w5)*w6

The problem is that

0 = (w1+w2)*w3 + (w4+w5)*w6 = w1*w3+w2*w3 + w4*w6+w5*w6            <-- xy=11 line
                            = w1*w3+w4*w6 + w2*w3+w5*w6 = 1+1 = 2  <-- xy=10 and xy=01 lines

So the seemingly 6 degrees of freedom are just not enough here, that is why you experience the need for adding something extra.


问:
Spark SQL performance difference in spark-sql vs spark-shell REPL
Spark newb question: I'm making exactly the same Spark SQL query in spark-sql and in spark-shell.  The spark-shell version takes about 10 seconds, while the spark-sql version takes about 20.

The spark-sql REPL gets the query directly:

```<code>spark-sql> SELECT .... FROM .... LIMIT 20
</code>```

The spark-shell REPL commands are like this:

```<code>scala> val df = sqlContext.sql("SELECT ... FROM ... LIMIT 20 ")
scala> df.show()
</code>```

In both cases, it's exactly the same query.  Also, the query returns only a few rows because of the explicit LIMIT 20.

What's different about how the same query is executed from the different CLIs?

I'm running on Hortonworks sandbox VM (Linux CentOS) if that helps.

答:
I think it is more about two parts,

First, it could be related the order. If you run the spark-sql first spark will be able to build the explain plan from scratch. But if you run the same query again. It could take less than the first one either from shell or sql because the explain plan will be easy to be retrieved

Second, it could be related to the spark-sql conversion to the ordering the resources. It happened multiple times. Spark-shell get the resources and start the process faster than spark-sql. You can check this from the UI or from top you will find the actual start for the spark-shell is faster than spark-sql.

Body:
Spark newb question: I'm making exactly the same Spark SQL query in spark-sql and in spark-shell.  The spark-shell version takes about 10 seconds, while the spark-sql version takes about 20.

The spark-sql REPL gets the query directly:

spark-sql> SELECT .... FROM .... LIMIT 20

The spark-shell REPL commands are like this:

scala> val df = sqlContext.sql("SELECT ... FROM ... LIMIT 20 ")
scala> df.show()

In both cases, it's exactly the same query.  Also, the query returns only a few rows because of the explicit LIMIT 20.

What's different about how the same query is executed from the different CLIs?

I'm running on Hortonworks sandbox VM (Linux CentOS) if that helps.


问:
Whats forcing the menu to go to the left?
I am using the menu from

https://www.w3schools.com/howto/howto_css_dropdown_navbar.asp

but whenever I use it in my code, the menu is always on the left of the screen rather than in the page section.

I am using a div with the following css :-

```<code>    .page {
        max-width: 1000px;
        margin: 0 auto;
    }
</code>```

Instead of the menu being in the 1000px, its just displays on the left.

答:
You are just setting a max-width, which is more of an assertion than a property - the width will never exceed 1000px. You never actually set the width, though.

```<code>.page {
    width: 1000px;
    margin: 0 auto;
}
</code>```

Unless you need max-width for something else, it's safe to ommit it if you're not using relative sizing (percents or vw/vh).

Body:
I am using the menu from

https://www.w3schools.com/howto/howto_css_dropdown_navbar.asp

but whenever I use it in my code, the menu is always on the left of the screen rather than in the page section.

I am using a div with the following css :-

    .page {
        max-width: 1000px;
        margin: 0 auto;
    }

Instead of the menu being in the 1000px, its just displays on the left.

Body:
You are just setting a max-width, which is more of an assertion than a property - the width will never exceed 1000px. You never actually set the width, though.

.page {
    width: 1000px;
    margin: 0 auto;
}

Unless you need max-width for something else, it's safe to ommit it if you're not using relative sizing (percents or vw/vh).


问:
does (SQL) JOINING on TABLES ALWAYS create Cartesian products of those tables?
does JOINING on TABLES ALWAYS create Cartesian products of those tables ?

if a problem can be solved by sub-query and Joining which should i prefer ?

which one is fast and memory saving ?

All the questions are tightly coupled, so please dont tell to open another thread :(

MySQL 5

答:
does JOINING on TABLES ALWAYS create Cartesian products of those tables ?

Yes, but normall that is then filtered down and the query optimizer is smart enough to take a more efficient approach. Anyhow, all joins without conditions ARE cartesian products ni the start.

if a problem can be solved by sub-query and Joining which should i prefer ?

Depends a lot on the query optimizer and the data in question. As in: Try it out. Prettym uch the only way.

which one is fast and memory saving ?

Again - try it out.

This stuff really depends no the table sizes involved AND THE FILTER CONDITIONS. Basically a materialized cartesian product in most cases is bad programming (ups, forgot the fitler conditions) or a very bad query plan. In most cases the cartesian product iwll never materialize and the query optimizer will use a different approach.


问:
RegEx for matching MongoDB strings
I'm using mongoose and have a large quantity of objects like this:

```<code>{
"_id" : ObjectId("5bfeb4aa0a49bf3d84d885b5"),
"category" : [
    "Cult",
    "Space Opera"
],
"actors" : [
    "David Prowse in the role of Darth Vader",
    "Mark Hamill as Luke Skywalker",
    "Carrie Fisher as Leia Organa",
    ...
],
"title" : "Star Wars",
"description" : ".....",
"rating" : 4.65,
"__v" : 0
</code>```

}

I need to find all the films that matches with my array of actors

for example: ["David Prowse", "Mark Hamill", "Carrie Fisher"]

Using this array one of films should be Star Wars but in the film object there aren't clean actor names so probably need to match with regex or something like that to match by substring (case insensitive).

My actual query return always empty array of documents   ----------

```<code>let arrayOfqueries = [];

    for (let i = 0; i < arrayOfActors.length; i++) {
        arrayOfqueries.push({$regex: ".*" + arrayOfActors[i] + ".*", $options: "i"});
    }

    Utils.searchFilms({
        "actors": {
            "$all": arrayOfqueries
        }
    }).then((docs) => {
        console.log(docs)
    }).catch((err) => {
        console.log(err);
    });
</code>```

答:
I'm guessing that a simple capturing group might suffice here. Then, based on Fanpark solution, your code might look like:

```<code>for (let i = 0; i < arrayOfActors.length; i++) {
  arrayOfqueries.push(new RegExpr("(" + arrayOfActors[i] + ")"))
}
</code>```

If that did not work, we can try other expressions such as:

```<code>(?:[\s\S]*)(David Prowse)(?:[\s\S]*)
</code>```

and our code might look like:

```<code>arrayOfqueries.push(new RegExpr("(?:[\s\S]*)(" + arrayOfActors[i] + ")(?:[\s\S]*)"))
</code>```

Also, metachars should be escaped.

DEMO

Title: RegEx for matching MongoDB strings

Body:
I'm using mongoose and have a large quantity of objects like this:

{
"_id" : ObjectId("5bfeb4aa0a49bf3d84d885b5"),
"category" : [
    "Cult",
    "Space Opera"
],
"actors" : [
    "David Prowse in the role of Darth Vader",
    "Mark Hamill as Luke Skywalker",
    "Carrie Fisher as Leia Organa",
    ...
],
"title" : "Star Wars",
"description" : ".....",
"rating" : 4.65,
"__v" : 0

}

I need to find all the films that matches with my array of actors

for example: ["David Prowse", "Mark Hamill", "Carrie Fisher"]

Using this array one of films should be Star Wars but in the film object there aren't clean actor names so probably need to match with regex or something like that to match by substring (case insensitive).

My actual query return always empty array of documents   ----------

let arrayOfqueries = [];

    for (let i = 0; i < arrayOfActors.length; i++) {
        arrayOfqueries.push({$regex: ".*" + arrayOfActors[i] + ".*", $options: "i"});
    }

    Utils.searchFilms({
        "actors": {
            "$all": arrayOfqueries
        }
    }).then((docs) => {
        console.log(docs)
    }).catch((err) => {
        console.log(err);
    });

Body:
I'm guessing that a simple capturing group might suffice here. Then, based on Fanpark solution, your code might look like:

for (let i = 0; i < arrayOfActors.length; i++) {
  arrayOfqueries.push(new RegExpr("(" + arrayOfActors[i] + ")"))
}

If that did not work, we can try other expressions such as:

(?:[\s\S]*)(David Prowse)(?:[\s\S]*)

and our code might look like:

arrayOfqueries.push(new RegExpr("(?:[\s\S]*)(" + arrayOfActors[i] + ")(?:[\s\S]*)"))

Also, metachars should be escaped.

DEMO


问:
Data annotation is working on editing only
```<code>Here is my controller codes

//
        // GET: /Department/Create

        public ActionResult Create()
        {
            return View(new department());
        }

        //
        // POST: /Department/Create

        [HttpPost]
        public ActionResult Create(department dept)
        {
            try
            {
                dbContext.AddTodepartments(dept);
                dbContext.SaveChanges();
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Department/Edit/5

        public ActionResult Edit(int id)
        {
            return View(dbContext.departments.Single(d => d.DeptID == id));
        }

        //
        // POST: /Department/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            var dept = dbContext.departments.Single(d => d.DeptID == id);
            try
            {
                UpdateModel(dept);
                dbContext.SaveChanges();
                return RedirectToAction("Index");
            }
            catch
            {
                return View(dept);
            }
        }

Here is the partial class

    [MetadataType(typeof(DepartmentMetaData))]
    public partial class department
    {
    }
    public class DepartmentMetaData
    {
        [Required(AllowEmptyStrings = false, ErrorMessage = "Department name required.")]
        public string DeptName { get; set; }
    }

    The required field validation is happening on the editing only. I can insert a null 'Department name' but on eding the values, it is not allowing to enter a null value.
</code>```

答: You Should do ModelState.IsValid check when creating record. More on ModelState here</p>


问:
What's the difference between a "pull request" and a "branch"?
What's the difference between a "pull request" and a "branch"?

pull request
  branch

答: A pull request is not a git concept. It's something that sites like github or bitbucket use to refer to changes that are being developed on a branch to be carried into another. A branch in git is a pointer to a revision.</p>


问:
Get script's url by handle (in wordpress)
Is it possible to get a script url from one of my working scripts, by handle?

So for example if i have a plugin's JS file registered with the handle wp-js-plugin and i want to get this JS file's url. how can i do that?

答:
For more info dump $wp_scripts

```<code>function get_script_src_by_handle($handle) {
    global $wp_scripts;
    if(in_array($handle, $wp_scripts->queue)) {
        return $wp_scripts->registered[$handle]->src;
    }
}
</code>```

Body:
For more info dump $wp_scripts

function get_script_src_by_handle($handle) {
    global $wp_scripts;
    if(in_array($handle, $wp_scripts->queue)) {
        return $wp_scripts->registered[$handle]->src;
    }
}


问:
PHP - html_simple_dom, crawlers encodes innerhtml?
Im using PHP html_simple_dom.

The targeted site is using UTF-8. My php as well as the stream context are set to use UTF 8.

An element (which i inspect by browser) has an innerHTML of "AAA ' BBB", at least as far as when its rendering using my firefox and chrome browsers.

However, my PHP script always fetches this string as "AAA ' BBB".
I can fix this using htmlspecialchars_decode($string, 1), but i really want to know why the PHP script, or rather the website is ("wrongly) encoding the string in the first place when visiting it using my PHP, which is explicitly set to UTF

```<code>header('Content-Type: text/html; charset=utf-8');
define("CONTEXT", stream_context_create(
    array(
        "http" =>
            array(
                "header" => 'Content-Type: text/html; charset=utf-8'
               // also tried 'header' => 'Accept-Charset: UTF-8'
            )
        )
)
);
</code>```

targetsite reads UTF-8 - http://mtggoldfish.com.cutercounter.com/

$html = file_get_html($url, false, CONTEXT);

```<code>// do things, blurts out every "'" as encoded &#039
</code>```

答:
Browser inspectors do a bit of transformation to have something human-readable.

Create a simple HTML with only  AAA ' BBB in the body, you will see AAA ' BBB in the inspectors.

If you really want to see the content of the page, look at the source code (which is what file_get_html gets)

Body:
Im using PHP html_simple_dom.

The targeted site is using UTF-8. My php as well as the stream context are set to use UTF 8.

An element (which i inspect by browser) has an innerHTML of "AAA ' BBB", at least as far as when its rendering using my firefox and chrome browsers.

However, my PHP script always fetches this string as "AAA ' BBB".
I can fix this using htmlspecialchars_decode($string, 1), but i really want to know why the PHP script, or rather the website is ("wrongly) encoding the string in the first place when visiting it using my PHP, which is explicitly set to UTF

header('Content-Type: text/html; charset=utf-8');
define("CONTEXT", stream_context_create(
    array(
        "http" =>
            array(
                "header" => 'Content-Type: text/html; charset=utf-8'
               // also tried 'header' => 'Accept-Charset: UTF-8'
            )
        )
)
);

targetsite reads UTF-8 - http://mtggoldfish.com.cutercounter.com/

$html = file_get_html($url, false, CONTEXT);

// do things, blurts out every "'" as encoded &#039

Body:
Browser inspectors do a bit of transformation to have something human-readable.

Create a simple HTML with only  AAA &#039; BBB in the body, you will see AAA ' BBB in the inspectors.

If you really want to see the content of the page, look at the source code (which is what file_get_html gets)


问:
How to prevent SIGINT signal kills sub processes in Java
I'm using Java exec to run bash script, but when I enter CTRL+C, the Java process will exit and also the sub processes, how can I keep child processes running after JVM is shut down?

```<code>String command = "ffmpeg -re -strict -2 -i video.mp4 -c:v copy -an -f rtp rtp://127.0.0.1:1234";
Utils.writeToFile("sub.sh", command);

new ProcessBuilder("parent.sh", "sub.sh").inheritIO()
        .start().waitFor();
</code>```

parent.sh:

```<code>#!/bin/bash
trap '' SIGINT SIGTERM SIGQUIT SIGHUP SIGTSTP
nohup "$@" &
</code>```

I have read answers to similar questions here and here, e.g, start a  parent bash script in that script run command using nohup, or using trap command to prevent signals,
on my research, it works for example "tail -f somefile", but not for my use case
"ffmpeg -params", please help, thank you.

答:
TL;DR

Use setsid instead of nohup in your parent.sh:

#!/bin/bash
setsid $@ &
```

The first problem is while your Java programm receives a SIGTERM signal (after CTRL + C), the JVM sends a SIGKILL signal to the child processes, which cannot be caught, blocked or ignored. So, once your parent.sh process receives SIGKILL, it's then passed to its child process sub.sh which stops the process.

The second problem is with nohup "$@" & you let your sub.sh child program run in background, but it is not completely detached from the current terminal. What nohup does is basically to ignore the SIGHUP signal. It executes the process normally (in the background) and doesn't actually provide daemonization.

Instead of nohup, you can use setsid, which detaches the child process sub.sh by creating a new session, which will then have no controlling terminal, and thus will no receive the SIGKILL signal.

One other way to do this might be using disown, like source $@ & disown, but in this case, it won't block the current terminal in which parent.sh is running. The problem is, you won't be able to know, when the child process is completed. So you would have more work to do, in order to monitor the child process id.

Further notes:

SIGTERM vs. SIGKILL

Difference between nohup, disown and &

Body:
I'm using Java exec to run bash script, but when I enter CTRL+C, the Java process will exit and also the sub processes, how can I keep child processes running after JVM is shut down?

String command = "ffmpeg -re -strict -2 -i video.mp4 -c:v copy -an -f rtp rtp://127.0.0.1:1234";
Utils.writeToFile("sub.sh", command);

new ProcessBuilder("parent.sh", "sub.sh").inheritIO()
        .start().waitFor();

parent.sh:

#!/bin/bash
trap '' SIGINT SIGTERM SIGQUIT SIGHUP SIGTSTP
nohup "$@" &

I have read answers to similar questions here and here, e.g, start a  parent bash script in that script run command using nohup, or using trap command to prevent signals,
on my research, it works for example "tail -f somefile", but not for my use case
"ffmpeg -params", please help, thank you.

Body:
TL;DR

Use setsid instead of nohup in your parent.sh:

#!/bin/bash
setsid $@ &

The first problem is while your Java programm receives a SIGTERM signal (after CTRL + C), the JVM sends a SIGKILL signal to the child processes, which cannot be caught, blocked or ignored. So, once your parent.sh process receives SIGKILL, it's then passed to its child process sub.sh which stops the process.

The second problem is with nohup "$@" & you let your sub.sh child program run in background, but it is not completely detached from the current terminal. What nohup does is basically to ignore the SIGHUP signal. It executes the process normally (in the background) and doesn't actually provide daemonization.

Instead of nohup, you can use setsid, which detaches the child process sub.sh by creating a new session, which will then have no controlling terminal, and thus will no receive the SIGKILL signal.

One other way to do this might be using disown, like source $@ & disown, but in this case, it won't block the current terminal in which parent.sh is running. The problem is, you won't be able to know, when the child process is completed. So you would have more work to do, in order to monitor the child process id.

Further notes:

SIGTERM vs. SIGKILL

Difference between nohup, disown and &