问:
The model item passed into the dictionary is of type , how i will pass orders_tables model with variable
Why I got this error:

The model item passed into the dictionary is of type 'AljawdahNewSite.Models.Orders_Tables',but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[AljawdahNewSite.Models.Orders_Tables]'.

This is the model Orders_Tables :

```<code>public class Orders_Tables
    {
        public List<Lab_Orders>  LabOrders { get; set; }
        public List<Lab_orders_Cash> LabOrdersCash { get; set; }
        public List<Lab_Sample_status> LabOrderStatus { get; set; }

        public List<LAB_RESULTS> LabResults { get; set; }
        public List<LabTests> labtests { get; set; }
        public List<LAB_RESULTS_CLINIC_VIEW> labViewResult { get; set; }
        public List<LAB_RESULT_CASH_VIEW> labCashView { get; set; }

        public List<LAB_PARASITOLOGY_VIEW> labparaview { get; set; }

       public List<Lab_Hematology_Samples> LabSamples { get; set; }

      public List<Patients> patients { get; set; }

        public Orders_Tables()
        {
            this.LabOrders = new List<Lab_Orders>();
            this.LabOrdersCash = new List<Lab_orders_Cash>();
            this.LabOrderStatus = new List<Lab_Sample_status>();
            this.LabResults = new List<LAB_RESULTS>();
            this.labtests = new List<LabTests>();
            this.labViewResult = new List<LAB_RESULTS_CLINIC_VIEW>();
            this.labCashView = new List<LAB_RESULT_CASH_VIEW>();
            this.labparaview = new List<LAB_PARASITOLOGY_VIEW>();
            this.LabSamples = new List<Lab_Hematology_Samples>();
            this.patients = new List<Patients>();
        }

    }
</code>```

This is the controller:

```<code>public ActionResult ordersCash1()
        {
            Orders_Tables tables = new Orders_Tables();

            var OrdersList = from o in tables.LabOrdersCash
                             join st in tables.LabOrderStatus on o.order_status equals st.status_id
                             where o.patient_no == (int)Session["UserpatientNo"]
                             select o;

            return View(OrdersList);
         }
</code>```

this is the view code:

```<code>@model IEnumerable<AljawdahNewSite.Models.Orders_Tables>
@{
    ViewBag.Title = "ordersCash1";
    Layout = "~/Views/Shared/_LayoutPatients.cshtml";
}

<h2>Orders List</h2>

<table class="table">
        <tr>
            <td> Order No. </td>
            <td> order date    </td>
            <td> MRN Patient No  </td>
            <td> Order Status   </td>

        </tr>
        @foreach (var item in Model)
        {
            <tr>
                <td>@item.LabOrdersCash.First().cash_order_id</td>
                <td>@item.LabOrdersCash.First().order_date</td>
                <td>@item.LabOrdersCash.First().patient_no</td>
                <td>@item.LabOrderStatus.First().status_name</td>
                <td>@Html.ActionLink("Result Details", "Details1", new { id = item.LabOrdersCash.First().cash_order_id })</td>
            </tr>
        }
    </table>
</code>```

how to solve this error i checked solutions in the site but its different cases ?

答:
In the action, try to select list of oreders Cach and sample Status and add them to tables object like the following code :

```<code>public ActionResult ordersCash1()
{
    Orders_Tables tables = new Orders_Tables();
    int patientId = (int)Session["UserpatientNo"];

    var result  = (from o in db.Lab_orders_Cash
                 join st in db.Lab_Sample_status on o.order_status equals st.status_id
                 where o.patient_no == patientId
                 select new {orederCach = o, sampleStatus = st}).ToList();

    tables.LabOrdersCash = result.Select(x => x.orederCach).ToList();
    tables.LabOrderStatus = result.Select(x => x.sampleStatus).ToList();

    return View(tables);
 }
</code>```

`
In the view, change the model to :

```<code>@model AljawdahNewSite.Models.Orders_Tables
</code>```

You don't need to loop, if you search just the first element for LabOrdersCash and LabOrderStatus

```<code>....
    <tr>
        <td>@Model.LabOrdersCash.First().cash_order_id</td>
        <td>@Model.LabOrdersCash.First().order_date</td>
        <td>@Model.LabOrdersCash.First().patient_no</td>
        <td>@Model.LabOrderStatus.First().status_name</td>
        <td>@Html.ActionLink("Result Details", "Details1", new { id = item.LabOrdersCash.First().cash_order_id })</td>
    </tr>
</code>```

I hope you find this helpful.

Body:
Why I got this error:

The model item passed into the dictionary is of type 'AljawdahNewSite.Models.Orders_Tables',but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[AljawdahNewSite.Models.Orders_Tables]'.

This is the model Orders_Tables :

public class Orders_Tables
    {
        public List<Lab_Orders>  LabOrders { get; set; }
        public List<Lab_orders_Cash> LabOrdersCash { get; set; }
        public List<Lab_Sample_status> LabOrderStatus { get; set; }

        public List<LAB_RESULTS> LabResults { get; set; }
        public List<LabTests> labtests { get; set; }
        public List<LAB_RESULTS_CLINIC_VIEW> labViewResult { get; set; }
        public List<LAB_RESULT_CASH_VIEW> labCashView { get; set; }

        public List<LAB_PARASITOLOGY_VIEW> labparaview { get; set; }

       public List<Lab_Hematology_Samples> LabSamples { get; set; }

      public List<Patients> patients { get; set; }

        public Orders_Tables()
        {
            this.LabOrders = new List<Lab_Orders>();
            this.LabOrdersCash = new List<Lab_orders_Cash>();
            this.LabOrderStatus = new List<Lab_Sample_status>();
            this.LabResults = new List<LAB_RESULTS>();
            this.labtests = new List<LabTests>();
            this.labViewResult = new List<LAB_RESULTS_CLINIC_VIEW>();
            this.labCashView = new List<LAB_RESULT_CASH_VIEW>();
            this.labparaview = new List<LAB_PARASITOLOGY_VIEW>();
            this.LabSamples = new List<Lab_Hematology_Samples>();
            this.patients = new List<Patients>();
        }

    }

This is the controller:

public ActionResult ordersCash1()
        {
            Orders_Tables tables = new Orders_Tables();

            var OrdersList = from o in tables.LabOrdersCash
                             join st in tables.LabOrderStatus on o.order_status equals st.status_id
                             where o.patient_no == (int)Session["UserpatientNo"]
                             select o;

            return View(OrdersList);
         }

this is the view code:

@model IEnumerable<AljawdahNewSite.Models.Orders_Tables>
@{
    ViewBag.Title = "ordersCash1";
    Layout = "~/Views/Shared/_LayoutPatients.cshtml";
}

Orders List

             Order No.
             order date
             MRN Patient No
             Order Status

        @foreach (var item in Model)
        {

                @item.LabOrdersCash.First().cash_order_id
                @item.LabOrdersCash.First().order_date
                @item.LabOrdersCash.First().patient_no
                @item.LabOrderStatus.First().status_name
                @Html.ActionLink("Result Details", "Details1", new { id = item.LabOrdersCash.First().cash_order_id })

        }

how to solve this error i checked solutions in the site but its different cases ?

Body:
In the action, try to select list of oreders Cach and sample Status and add them to tables object like the following code :

public ActionResult ordersCash1()
{
    Orders_Tables tables = new Orders_Tables();
    int patientId = (int)Session["UserpatientNo"];

    var result  = (from o in db.Lab_orders_Cash
                 join st in db.Lab_Sample_status on o.order_status equals st.status_id
                 where o.patient_no == patientId
                 select new {orederCach = o, sampleStatus = st}).ToList();

    tables.LabOrdersCash = result.Select(x => x.orederCach).ToList();
    tables.LabOrderStatus = result.Select(x => x.sampleStatus).ToList();

    return View(tables);
 }

`
In the view, change the model to :

@model AljawdahNewSite.Models.Orders_Tables

You don't need to loop, if you search just the first element for LabOrdersCash and LabOrderStatus

....
    <tr>
        <td>@Model.LabOrdersCash.First().cash_order_id</td>
        <td>@Model.LabOrdersCash.First().order_date</td>
        <td>@Model.LabOrdersCash.First().patient_no</td>
        <td>@Model.LabOrderStatus.First().status_name</td>
        <td>@Html.ActionLink("Result Details", "Details1", new { id = item.LabOrdersCash.First().cash_order_id })</td>
    </tr>

I hope you find this helpful.


来源: stackexchange

问:
phpmyadmin in xampp not working on windows 10
I'm getting below error when I type in localhost/phpMyAdmin after starting apache and mysql server in Xampp in Windows 10.

Is there a way I can fix this issue?

```<code>MySQL said: Documentation

#2002 - No connection could be made because the target machine actively refused it.

The server is not responding (or the local server's socket is not correctly configured).
Connection for controluser as defined in your configuration failed.
</code>```

答: My problem was probably because i had installed bitnami and then later installed xampp. I deleted bitnami, xampp and my temp folder C:\Users\Default\AppData\Local\Temp. It worked fine after reinstalation. thats the only way it worked for me</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm getting below error when I type in localhost/phpMyAdmin after starting apache and mysql server in Xampp in Windows 10.

Is there a way I can fix this issue?

MySQL said: Documentation

#2002 - No connection could be made because the target machine actively refused it.

The server is not responding (or the local server's socket is not correctly configured).
Connection for controluser as defined in your configuration failed.

ContentLicense: CC BY-SA 4.0


问:
ADB2C with authentication/logout not working in Blazor
When using ADB2C for authentication in a Blazor Webassembly project, the authentication/logout seems to log out and shows a page with the request to close all browsers.
Anyway if the user just uses the back button in the browser she/he is still able to access the contents and is treated as still loged-on.
So, how to get a real logout? </p>

答:
While directing the user to the end_session_endpoint will clear some of the user's single sign-on state with Azure AD B2C, it will not sign the user out of the user's social identity provider (IDP) session. If the user selects the same IDP during a subsequent sign-in, they will be reauthenticated, without entering their credentials. If a user wants to sign out of your B2C application, it does not necessarily mean they want to sign out of their Facebook account entirely. However, in the case of local accounts, the user's session will be ended properly.

To sign out the user, redirect the user to the end_session endpoint that is listed in the OpenID Connect metadata document(example) :

```<code>GET https://{tenant}.b2clogin.com/{tenant}.onmicrosoft.com/{policy}/oauth2/v2.0/logout?post_logout_redirect_uri=https%3A%2F%2Fjwt.ms%2F
</code>```

Reference: Azure Active Directory B2C: Web sign-in with OpenID Connect

Body:
While directing the user to the end_session_endpoint will clear some of the user's single sign-on state with Azure AD B2C, it will not sign the user out of the user's social identity provider (IDP) session. If the user selects the same IDP during a subsequent sign-in, they will be reauthenticated, without entering their credentials. If a user wants to sign out of your B2C application, it does not necessarily mean they want to sign out of their Facebook account entirely. However, in the case of local accounts, the user's session will be ended properly.

To sign out the user, redirect the user to the end_session endpoint that is listed in the OpenID Connect metadata document(example) :

GET https://{tenant}.b2clogin.com/{tenant}.onmicrosoft.com/{policy}/oauth2/v2.0/logout?post_logout_redirect_uri=https%3A%2F%2Fjwt.ms%2F

Reference: Azure Active Directory B2C: Web sign-in with OpenID Connect


问:
Add whitespace to string in Coldfusion
I need to add whitespace onto the end of a string.

ColdFusion seems to be automatically removing any whitespace I try to add, I'll sometimes get 1 empty space character but that's it.

I have an input field, a string, that can be up to 7 characters long. If the input is less than 7 characters, I'm to pad the end with spaces.

Does anyone know of a quick, easy, intuitive way to accomplish this using coldfusion. As little code as possible is preferred.

Some of the solutions I tried were:

```<code> #LEFT(FORM.strInput & '       ', 7)#

 #LEFT(FORM.strInput & '        0', 7)#

 #REPLACE(LEFT(FORM.strInput & 0000000, 7), '0', ' ', 'all')#

<CFLOOP FROM="1" TO="7 - LEN(FORM.strInput)">
  <CFSET FORM.strInput = FORM.strInput & ' '>
</CFLOOP>

<CFLOOP FROM="1" TO="7 - LEN(FORM.strInput)">
  <CFSET FORM.strInput = FORM.strInput & ' '>
</CFLOOP>
</code>```

答:
You can use repeatString()

```<code><cfset form.strInput = form.strInput & repeatString( ' ', max( 7-len(form.strInput), 0 ) ) />
</code>```

But, keep in mind, if you try to display multiple consecutive spaces on a web page, the browser will only 'display' the first one.

Title: Add whitespace to string in Coldfusion

Body:
I need to add whitespace onto the end of a string.

ColdFusion seems to be automatically removing any whitespace I try to add, I'll sometimes get 1 empty space character but that's it.

I have an input field, a string, that can be up to 7 characters long. If the input is less than 7 characters, I'm to pad the end with spaces.

Does anyone know of a quick, easy, intuitive way to accomplish this using coldfusion. As little code as possible is preferred.

Some of the solutions I tried were:

 #LEFT(FORM.strInput & '       ', 7)#

 #LEFT(FORM.strInput & '        0', 7)#

 #REPLACE(LEFT(FORM.strInput & 0000000, 7), '0', ' ', 'all')#

<CFLOOP FROM="1" TO="7 - LEN(FORM.strInput)">
  <CFSET FORM.strInput = FORM.strInput & ' '>
</CFLOOP>

<CFLOOP FROM="1" TO="7 - LEN(FORM.strInput)">
  <CFSET FORM.strInput = FORM.strInput & ' '>
</CFLOOP>

Body:
You can use repeatString()

<cfset form.strInput = form.strInput & repeatString( ' ', max( 7-len(form.strInput), 0 ) ) />

But, keep in mind, if you try to display multiple consecutive spaces on a web page, the browser will only 'display' the first one.


问:
Dashed line in plotly::add_segment
Is there a way to use the add_segments() function to create a dashed line?

I've tried using linetype, linetypes, line = list(...), dash = "dash" but nothing seems to work. Here is some sample code with a horizontal line. Right now it's just ignoring the linetype argument.

```<code>plot <- plot_ly() %>%
  add_segments(x = 1, xend = 10, y = 5, yend = 5, linetype = "dashed")
plot
</code>```

I have a way around this, but I like the simplicity/readability of add_segments so it would be ideal to use it as opposed to add_lines().

答:
plotly::add_segment does not have a linetype argument. You can set the line type like below;

library(plotly)

plot_ly() %>%
  add_segments(x = 1, xend = 10, y = 5, yend = 5, line = list(dash = "dash"))
```

Title: Dashed line in plotly::add_segment

Body:
Is there a way to use the add_segments() function to create a dashed line?

I've tried using linetype, linetypes, line = list(...), dash = "dash" but nothing seems to work. Here is some sample code with a horizontal line. Right now it's just ignoring the linetype argument.

plot <- plot_ly() %>%
  add_segments(x = 1, xend = 10, y = 5, yend = 5, linetype = "dashed")
plot

I have a way around this, but I like the simplicity/readability of add_segments so it would be ideal to use it as opposed to add_lines().


问:
How to create an inverse ordered variable in my sql
I have a column with running sum, but I would like to inverse the order in a new or same column

My Query is

```<code>SELECT date,
ant,
num_room,
(@csum:= @csum + num_room) as cumulative_room
from xxx_xxxx_xxxx
WHERE date BETWEEN CURDATE() - INTERVAL 30 DAY AND CURDATE()
AND(select @csum := 0) = 0
order by date
</code>```

Mi table is

```<code> date         | ant  | num_room  | cumulative_room
    28-04-2020       6       1              1
    28-04-2020       3       1              2
    28-04-2020       4       1              3
    28-04-2020       7       1              4
    28-04-2020       4       1              5
    ....
</code>```

How I can do another variable with reverse order from cumulative_room?

```<code> date         | ant  | num_room  | cumulative_room |reverse_cumulative room
28-04-2020       6       1              1                5
28-04-2020       3       1              2                4
28-04-2020       4       1              3                3
28-04-2020       7       1              4                2
28-04-2020       4       1              5                1
    ....
</code>```

答:
Your complete code is

```<code>SELECT
t1.*
, t2.max_room - `cumulative_room` 'reverse_cumulative room'
FROm (SELECT date,
                ant,
                num_room,
                (@csum:= @csum + num_room) as cumulative_room
                from xxx_xxxx_xxxx
                WHERE date BETWEEN CURDATE() - INTERVAL 30 DAY AND CURDATE()
                AND(select @csum := 0) = 0
                order by date) t1
INNER JOIN (SELECT MAX(`cumulative_room`) +1 max_room,  `date` FROM (SELECT date,
                                                                            ant,
                                                                            num_room,
                                                                            (@csum:= @csum + num_room) as cumulative_room
                                                                            from xxx_xxxx_xxxx
                                                                            WHERE date BETWEEN CURDATE() - INTERVAL 30 DAY AND CURDATE()
                                                                            AND(select @csum := 0) = 0
                                                                            order by date) t3 GROUP BY  `date`) t2
ON t1.`date` = t2.`date`;
</code>```

The idea behind this is

```<code>CREATE TABLE xxx_xxxx_xxxx (
  `date` VARCHAR(10),
  `ant` INTEGER,
  `num_room` INTEGER,
  `cumulative_room` INTEGER
);

INSERT INTO xxx_xxxx_xxxx
  (`date`, `ant`, `num_room`, `cumulative_room`)
VALUES
  ('28-04-2020', '6', '1', '1'),
  ('28-04-2020', '3', '1', '2'),
  ('28-04-2020', '4', '1', '3'),
  ('28-04-2020', '7', '1', '4'),
  ('28-04-2020', '4', '1', '5');
</code>```

```
✓

✓
```

```<code>SELECT
t1.*
,t2.max_room - `cumulative_room` 'reverse_cumulative room'
FROm xxx_xxxx_xxxx t1
INNER JOIN (SELECT MAX(`cumulative_room`) +1 max_room,  `date` FROM xxx_xxxx_xxxx GROUP BY  `date`) t2
ON t1.`date` = t2.`date`;
</code>```

```
date       | ant | num_room | cumulative_room | reverse_cumulative room
:--------- | --: | -------: | --------------: | ----------------------:
28-04-2020 |   6 |        1 |               1 |                       5
28-04-2020 |   3 |        1 |               2 |                       4
28-04-2020 |   4 |        1 |               3 |                       3
28-04-2020 |   7 |        1 |               4 |                       2
28-04-2020 |   4 |        1 |               5 |                       1
```

db<>fiddle here

Body:
I have a column with running sum, but I would like to inverse the order in a new or same column

My Query is

SELECT date,
ant,
num_room,
(@csum:= @csum + num_room) as cumulative_room
from xxx_xxxx_xxxx
WHERE date BETWEEN CURDATE() - INTERVAL 30 DAY AND CURDATE()
AND(select @csum := 0) = 0
order by date

Mi table is

 date         | ant  | num_room  | cumulative_room
    28-04-2020       6       1              1
    28-04-2020       3       1              2
    28-04-2020       4       1              3
    28-04-2020       7       1              4
    28-04-2020       4       1              5
    ....

How I can do another variable with reverse order from cumulative_room?

 date         | ant  | num_room  | cumulative_room |reverse_cumulative room
28-04-2020       6       1              1                5
28-04-2020       3       1              2                4
28-04-2020       4       1              3                3
28-04-2020       7       1              4                2
28-04-2020       4       1              5                1
    ....

Body:
Your complete code is

SELECT
t1.*
, t2.max_room - `cumulative_room` 'reverse_cumulative room'
FROm (SELECT date,
                ant,
                num_room,
                (@csum:= @csum + num_room) as cumulative_room
                from xxx_xxxx_xxxx
                WHERE date BETWEEN CURDATE() - INTERVAL 30 DAY AND CURDATE()
                AND(select @csum := 0) = 0
                order by date) t1
INNER JOIN (SELECT MAX(`cumulative_room`) +1 max_room,  `date` FROM (SELECT date,
                                                                            ant,
                                                                            num_room,
                                                                            (@csum:= @csum + num_room) as cumulative_room
                                                                            from xxx_xxxx_xxxx
                                                                            WHERE date BETWEEN CURDATE() - INTERVAL 30 DAY AND CURDATE()
                                                                            AND(select @csum := 0) = 0
                                                                            order by date) t3 GROUP BY  `date`) t2
ON t1.`date` = t2.`date`;

The idea behind this is

CREATE TABLE xxx_xxxx_xxxx (
  `date` VARCHAR(10),
  `ant` INTEGER,
  `num_room` INTEGER,
  `cumulative_room` INTEGER
);

INSERT INTO xxx_xxxx_xxxx
  (`date`, `ant`, `num_room`, `cumulative_room`)
VALUES
  ('28-04-2020', '6', '1', '1'),
  ('28-04-2020', '3', '1', '2'),
  ('28-04-2020', '4', '1', '3'),
  ('28-04-2020', '7', '1', '4'),
  ('28-04-2020', '4', '1', '5');

✓

✓

SELECT
t1.*
,t2.max_room - `cumulative_room` 'reverse_cumulative room'
FROm xxx_xxxx_xxxx t1
INNER JOIN (SELECT MAX(`cumulative_room`) +1 max_room,  `date` FROM xxx_xxxx_xxxx GROUP BY  `date`) t2
ON t1.`date` = t2.`date`;

date       | ant | num_room | cumulative_room | reverse_cumulative room
:--------- | --: | -------: | --------------: | ----------------------:
28-04-2020 |   6 |        1 |               1 |                       5
28-04-2020 |   3 |        1 |               2 |                       4
28-04-2020 |   4 |        1 |               3 |                       3
28-04-2020 |   7 |        1 |               4 |                       2
28-04-2020 |   4 |        1 |               5 |                       1

db<>fiddle here


问:
How to force error reporting from django management commands?
We are running custom management commands periodically on the server.

Is there any way to get something like error reporting via email working for the command?

答:
You could use django logging handler AdminEmailHandler:

https://docs.djangoproject.com/en/dev/topics/logging/#django.utils.log.AdminEmailHandler

As the docs say:

This handler sends an email to the site admins for each log message it receives.

So you could use this to log an error on any exception raised in the management command, and the exception would be automatically send to the admins


问:
Calculate Retention Rate for Cohort Analysis in AWS QuickSight
I have two "tables" in Spice.

Table A has all my user accounts including a created timestamp

Table B has user activity with timestamps

Trying to build a cohort chart that shows

Month created timestamp as rows

Month activity timestamp as columns

values for the respective intersections (users with activity in February that were created in January divided by all users that were created in January)

I tried countOver with pre_agg, partitioning by timestamp and a few other things but haven't been successful in getting the calculation to work.

Is this generally possible?

答: I have also been struggling with calculating retention rates in QuickSight. What I have found is that if I want to do these types of period to period comparisons, I have to do it outside of QuickSight. </p>


问:
How can I get the number of users in a voice channel?
I'm making a music bot, when the member writes "~play" the bot search a random file (.mp3) in a folder, and joines the voice channel where the user currently in. I want my bot to leave the voice channel when all the users leave the voicechannel.</p>

```<code>const fs = require('fs');

module.exports.run = async (bot, message, args) => {

let channel = message.member.voice.channel;
if(!channel) return message.reply("You're not connected to a voice channel!");

if (channel) {

    channel.join()
    .then(connection => {

        const commandFiles = fs.readdirSync('./commands/Workout/').filter(file => file.endsWith('.mp3'));
        let randomfile = commandFiles[Math.floor(Math.random() * commandFiles.length)]

        const dispatcher = connection.play(`./commands/Workout/${randomfile}`);

        dispatcher.on('start', () => {
            dispatcher.setVolume(0.70);
            message.reply(" started this song: " + ` ${randomfile}`)
          }).catch(err => console.error(err))
            //console.log("Playing music");
        })

        dispatcher.on('error', (err) => console.log(err));

        if(channel.members == 1){  //this is the problem
          channel.leave()
        }

        dispatcher.on('finish', finish => {
            message.reply(" Song ended! - " + ` ${randomfile}`)
            //console.log("Playing ended");
            channel.leave()
        })
    }).catch(err => console.error(err))
}
</code>```

答:
Um I don't know if it's already an array of not, if it is then</p>

```<code>channel.members.length == 1
</code>```

Body:
I'm making a music bot, when the member writes "~play" the bot search a random file (.mp3) in a folder, and joines the voice channel where the user currently in. I want my bot to leave the voice channel when all the users leave the voicechannel.

const fs = require('fs');

module.exports.run = async (bot, message, args) => {

let channel = message.member.voice.channel;
if(!channel) return message.reply("You're not connected to a voice channel!");

if (channel) {

    channel.join()
    .then(connection => {

        const commandFiles = fs.readdirSync('./commands/Workout/').filter(file => file.endsWith('.mp3'));
        let randomfile = commandFiles[Math.floor(Math.random() * commandFiles.length)]

        const dispatcher = connection.play(`./commands/Workout/${randomfile}`);

        dispatcher.on('start', () => {
            dispatcher.setVolume(0.70);
            message.reply(" started this song: " + ` ${randomfile}`)
          }).catch(err => console.error(err))
            //console.log("Playing music");
        })

        dispatcher.on('error', (err) => console.log(err));

        if(channel.members == 1){  //this is the problem
          channel.leave()
        }

        dispatcher.on('finish', finish => {
            message.reply(" Song ended! - " + ` ${randomfile}`)
            //console.log("Playing ended");
            channel.leave()
        })
    }).catch(err => console.error(err))
}

Body:
Um I don't know if it's already an array of not, if it is then

channel.members.length == 1


问:
How can I (in D3) make a rectangle change its size while staying fix in one point?
With one click on the canvas I am trying to create a rectangle. While holding the click, its size should be changing based on the coordinates of the pointer. The width and height changes while the upper left corner is staying still.

The rectangle changes its form from left to right, but I also want it to go from right to left as soon as the current x Value becomes smaller than the x value of the fixed point. Can somebody help me with this problem? How can I achieve this? Thanks a lot!

const margin = {top: 10, right: 30, bottom: 100, left: 60},
        chartWidth = width  - margin.left - margin.right,
        chartHeight = height - margin.top - margin.bottom;
      let shouldAppear = false;

      const svg = d3.select('svg')
        .attr("width", width)
        .attr("height", height)
        .append("g")
        .attr("transform","translate(" + left + "," + top + ")");

        svg.append('rect')
        .attr('class', 'canvas')
        .attr('width', chartWidth)
        .attr('height', chartHeight)

      svg.on('mousedown', function(){
        shouldAppear = true;
        const mouse = d3.mouse(this);
        rectangle.attr('y', mouse[1])
          .attr('x', mouse[0])

      })
      svg.on('mousemove', function(){
        const mouse = d3.mouse(this);

        if (shouldAppear){
          rectangle
              .attr('width', Math.abs(mouse[0] - rectangle.attr('x')))
              .attr('height', Math.abs(mouse[1] - rectangle.attr('y')))
          }
      })
      svg.on('mouseup', function(){
        shouldAppear = false;
        rectangle
        .attr('width', 0)
        .attr('height', 0)
      });
      let rectangle = svg
          .append('rect')
          .attr('class', 'rectangle')
          .attr('width', 0)
          .attr('height', 0)
          .style('fill','red')
    }  ```

答:
The issue is that when the pointer goes left or top of the starting point, your calculation for the width and height turns negative, and svg does not allow negative values for width or height for rect elements.

A solution is to save the mouse starting position in the mousedown function as mousestart:

```<code>let mousestart;
svg.on("mousedown", function () {
  shouldAppear = true;
  const mouse = d3.mouse(this);
  mousestart = mouse;
  rectangle.attr("y", mouse[1]).attr("x", mouse[0]);
});
</code>```

Then use the mousestart position to evaluate if the cursor is to the left, right, top or bottom of the starting position, and create specific adjustments to the rectangle as needed in each case in your mousemove function.

```<code>svg.on("mousemove", function () {
  const mouse = d3.mouse(this);
  if (shouldAppear) {
    let x = mouse[0] - mousestart[0]; //negative values indicate cursor moved left
    let y = mouse[1] - mousestart[1]; //negative values indicate cursor moved up
    if (x >= 0 && y >= 0) { // if the cursor moved right and down from starting position
      rectangle
        .attr("width", Math.abs(mouse[0] - rectangle.attr("x")))
        .attr("height", Math.abs(mouse[1] - rectangle.attr("y")));
    }
    if (x <= 0){ // if the cursor moved left
      rectangle
        .attr('x', mouse[0]) // move the rectangle to the new cursor x position
        .attr('width', mousestart[0] - mouse[0] ) // the width of the rectangle is now the difference between the starting point and current x point
        .attr("height", Math.abs(mouse[1] - rectangle.attr("y"))); // the height is calculated based on the difference between the current position and the rectangle y
    }
    if (y <= 0) { // if the cursor moved up similar calculations as above but in the y direction
      rectangle
        .attr('y', mouse[1])
        .attr('height', mousestart[1] - mouse[1] )
        .attr("width", Math.abs(mouse[0] - rectangle.attr("x")));
    }
    if (x <= 0 && y <= 0 ) { // if the cursor moved left and up similar calculations as above but in both x and y direction
      rectangle
        .attr('x', mouse[0])
        .attr('y', mouse[1])
        .attr('width', mousestart[0] - mouse[0] )
        .attr('height', mousestart[1] - mouse[1] )
    }
  }
});
</code>```

Check the full working snippet:

let width = 400,
  height = 400;

const margin = { top: 10, right: 30, bottom: 100, left: 60 },
  chartWidth = width - margin.left - margin.right,
  chartHeight = height - margin.top - margin.bottom;
let shouldAppear = false;

const svg = d3
  .select("svg")
  .attr("width", width)
  .attr("height", height)
  .append("g")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

svg
  .append("rect")
  .attr("class", "canvas")
  .attr("width", chartWidth)
  .attr("height", chartHeight - 10);

let mousestart;

svg.on("mousedown", function () {
  shouldAppear = true;
  const mouse = d3.mouse(this);
  mousestart = mouse;
  rectangle.attr("y", mouse[1]).attr("x", mouse[0]);
});
svg.on("mousemove", function () {
  const mouse = d3.mouse(this);
  if (shouldAppear) {
    let x = mouse[0] - mousestart[0]; //negative values indicate cursor moved left
    let y = mouse[1] - mousestart[1]; //negative values indicate cursor moved up
    if (x >= 0 && y >= 0) { // if the cursor moved right and down from starting position
      rectangle
        .attr("width", Math.abs(mouse[0] - rectangle.attr("x")))
        .attr("height", Math.abs(mouse[1] - rectangle.attr("y")));
    }
    if (x <= 0){ // if the cursor moved left
      rectangle
        .attr('x', mouse[0]) // move the rectangle to the new cursor x position
        .attr('width', mousestart[0] - mouse[0] ) // the width of the rectangle is now the difference between the starting point and current x point
        .attr("height", Math.abs(mouse[1] - rectangle.attr("y"))); // the height is calculated based on the difference between the current position and the rectangle y
    }
    if (y <= 0) { // if the cursor moved up similar calculations as above but in the y direction
      rectangle
        .attr('y', mouse[1])
        .attr('height', mousestart[1] - mouse[1] )
        .attr("width", Math.abs(mouse[0] - rectangle.attr("x")));
    }
    if (x <= 0 && y <= 0 ) { // if the cursor moved left and up similar calculations as above but in both x and y direction
      rectangle
        .attr('x', mouse[0])
        .attr('y', mouse[1])
        .attr('width', mousestart[0] - mouse[0] )
        .attr('height', mousestart[1] - mouse[1] )
    }
  }
});
svg.on("mouseup", function () {
  shouldAppear = false;
  rectangle.attr("width", 0).attr("height", 0);
});
let rectangle = svg
  .append("rect")
  .attr("class", "rectangle")
  .attr("width", 0)
  .attr("height", 0)
  .style("fill", "red");```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v5.min.js"></script>
<svg></svg></code>```

Update

An improvement in the mousemove function which is easier to read calculates the rect element's attributes rectx, recty, rectwidth, rectheight and use it to set the attributes. Note you will still need to capture the mousestart coordinates in the mousedown function as shown above.:

```<code>svg.on("mousemove", function () {
  const mouse = d3.mouse(this);
  if (shouldAppear) {
    let rectx, recty, rectwidth, rectheight;
    if (mouse[0] < mousestart[0]) { // if cursor moved left
      rectx = mouse[0];
      rectwidth = mousestart[0] - mouse[0];
    } else {  // if cursor moved right
      rectx = mousestart[0];
      rectwidth = mouse[0] - mousestart[0];
    }

    if (mouse[1] < mousestart[1]) { // if cursor moved up
      recty = mouse[1];
      rectheight = mousestart[1] - mouse[1];
    } else {  // if cursor moved down
      recty = mousestart[1];
      rectheight = mouse[1] - mousestart[1];
    }

    rectangle
      .attr('x', rectx)
      .attr('y', recty)
      .attr('width', rectwidth)
      .attr('height', rectheight)
  }
});
</code>```

See full snippet:

let width = 400,
  height = 400;

const margin = { top: 10, right: 30, bottom: 100, left: 60 },
  chartWidth = width - margin.left - margin.right,
  chartHeight = height - margin.top - margin.bottom;
let shouldAppear = false;

const svg = d3
  .select("svg")
  .attr("width", width)
  .attr("height", height)
  .append("g")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

svg
  .append("rect")
  .attr("class", "canvas")
  .attr("width", chartWidth)
  .attr("height", chartHeight - 10);

let mousestart;

svg.on("mousedown", function () {
  shouldAppear = true;
  const mouse = d3.mouse(this);
  mousestart = mouse;
  rectangle.attr("y", mouse[1]).attr("x", mouse[0]);
});
svg.on("mousemove", function () {
  const mouse = d3.mouse(this);
  if (shouldAppear) {
    let rectx, recty, rectwidth, rectheight;
    if (mouse[0] < mousestart[0]) { // if cursor moved left
      rectx = mouse[0];
      rectwidth = mousestart[0] - mouse[0];
    } else {  // if cursor moved right
      rectx = mousestart[0];
      rectwidth = mouse[0] - mousestart[0];
    }

    if (mouse[1] < mousestart[1]) { // if cursor moved up
      recty = mouse[1];
      rectheight = mousestart[1] - mouse[1];
    } else {  // if cursor moved down
      recty = mousestart[1];
      rectheight = mouse[1] - mousestart[1];
    }

    rectangle
      .attr('x', rectx)
      .attr('y', recty)
      .attr('width', rectwidth)
      .attr('height', rectheight)
  }
});
svg.on("mouseup", function () {
  shouldAppear = false;
  rectangle.attr("width", 0).attr("height", 0);
});

let rectangle = svg
  .append("rect")
  .attr("class", "rectangle")
  .attr("width", 0)
  .attr("height", 0)
  .style("fill", "red");```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v5.min.js"></script>
<svg></svg></code>```

Body:
The issue is that when the pointer goes left or top of the starting point, your calculation for the width and height turns negative, and svg does not allow negative values for width or height for rect elements.

A solution is to save the mouse starting position in the mousedown function as mousestart:

let mousestart;
svg.on("mousedown", function () {
  shouldAppear = true;
  const mouse = d3.mouse(this);
  mousestart = mouse;
  rectangle.attr("y", mouse[1]).attr("x", mouse[0]);
});

Then use the mousestart position to evaluate if the cursor is to the left, right, top or bottom of the starting position, and create specific adjustments to the rectangle as needed in each case in your mousemove function.

svg.on("mousemove", function () {
  const mouse = d3.mouse(this);
  if (shouldAppear) {
    let x = mouse[0] - mousestart[0]; //negative values indicate cursor moved left
    let y = mouse[1] - mousestart[1]; //negative values indicate cursor moved up
    if (x >= 0 && y >= 0) { // if the cursor moved right and down from starting position
      rectangle
        .attr("width", Math.abs(mouse[0] - rectangle.attr("x")))
        .attr("height", Math.abs(mouse[1] - rectangle.attr("y")));
    }
    if (x <= 0){ // if the cursor moved left
      rectangle
        .attr('x', mouse[0]) // move the rectangle to the new cursor x position
        .attr('width', mousestart[0] - mouse[0] ) // the width of the rectangle is now the difference between the starting point and current x point
        .attr("height", Math.abs(mouse[1] - rectangle.attr("y"))); // the height is calculated based on the difference between the current position and the rectangle y
    }
    if (y <= 0) { // if the cursor moved up similar calculations as above but in the y direction
      rectangle
        .attr('y', mouse[1])
        .attr('height', mousestart[1] - mouse[1] )
        .attr("width", Math.abs(mouse[0] - rectangle.attr("x")));
    }
    if (x <= 0 && y <= 0 ) { // if the cursor moved left and up similar calculations as above but in both x and y direction
      rectangle
        .attr('x', mouse[0])
        .attr('y', mouse[1])
        .attr('width', mousestart[0] - mouse[0] )
        .attr('height', mousestart[1] - mouse[1] )
    }
  }
});

Check the full working snippet:

let width = 400,
  height = 400;

const margin = { top: 10, right: 30, bottom: 100, left: 60 },
  chartWidth = width - margin.left - margin.right,
  chartHeight = height - margin.top - margin.bottom;
let shouldAppear = false;

const svg = d3
  .select("svg")
  .attr("width", width)
  .attr("height", height)
  .append("g")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

svg
  .append("rect")
  .attr("class", "canvas")
  .attr("width", chartWidth)
  .attr("height", chartHeight - 10);

let mousestart;

svg.on("mousedown", function () {
  shouldAppear = true;
  const mouse = d3.mouse(this);
  mousestart = mouse;
  rectangle.attr("y", mouse[1]).attr("x", mouse[0]);
});
svg.on("mousemove", function () {
  const mouse = d3.mouse(this);
  if (shouldAppear) {
    let x = mouse[0] - mousestart[0]; //negative values indicate cursor moved left
    let y = mouse[1] - mousestart[1]; //negative values indicate cursor moved up
    if (x >= 0 && y >= 0) { // if the cursor moved right and down from starting position
      rectangle
        .attr("width", Math.abs(mouse[0] - rectangle.attr("x")))
        .attr("height", Math.abs(mouse[1] - rectangle.attr("y")));
    }
    if (x <= 0){ // if the cursor moved left
      rectangle
        .attr('x', mouse[0]) // move the rectangle to the new cursor x position
        .attr('width', mousestart[0] - mouse[0] ) // the width of the rectangle is now the difference between the starting point and current x point
        .attr("height", Math.abs(mouse[1] - rectangle.attr("y"))); // the height is calculated based on the difference between the current position and the rectangle y
    }
    if (y <= 0) { // if the cursor moved up similar calculations as above but in the y direction
      rectangle
        .attr('y', mouse[1])
        .attr('height', mousestart[1] - mouse[1] )
        .attr("width", Math.abs(mouse[0] - rectangle.attr("x")));
    }
    if (x <= 0 && y <= 0 ) { // if the cursor moved left and up similar calculations as above but in both x and y direction
      rectangle
        .attr('x', mouse[0])
        .attr('y', mouse[1])
        .attr('width', mousestart[0] - mouse[0] )
        .attr('height', mousestart[1] - mouse[1] )
    }
  }
});
svg.on("mouseup", function () {
  shouldAppear = false;
  rectangle.attr("width", 0).attr("height", 0);
});
let rectangle = svg
  .append("rect")
  .attr("class", "rectangle")
  .attr("width", 0)
  .attr("height", 0)
  .style("fill", "red");

<script src="https://d3js.org/d3.v5.min.js"></script>
<svg></svg>

Update

An improvement in the mousemove function which is easier to read calculates the rect element's attributes rectx, recty, rectwidth, rectheight and use it to set the attributes. Note you will still need to capture the mousestart coordinates in the mousedown function as shown above.:

svg.on("mousemove", function () {
  const mouse = d3.mouse(this);
  if (shouldAppear) {
    let rectx, recty, rectwidth, rectheight;
    if (mouse[0] < mousestart[0]) { // if cursor moved left
      rectx = mouse[0];
      rectwidth = mousestart[0] - mouse[0];
    } else {  // if cursor moved right
      rectx = mousestart[0];
      rectwidth = mouse[0] - mousestart[0];
    }

    if (mouse[1] < mousestart[1]) { // if cursor moved up
      recty = mouse[1];
      rectheight = mousestart[1] - mouse[1];
    } else {  // if cursor moved down
      recty = mousestart[1];
      rectheight = mouse[1] - mousestart[1];
    }

    rectangle
      .attr('x', rectx)
      .attr('y', recty)
      .attr('width', rectwidth)
      .attr('height', rectheight)
  }
});

See full snippet:

let width = 400,
  height = 400;

const margin = { top: 10, right: 30, bottom: 100, left: 60 },
  chartWidth = width - margin.left - margin.right,
  chartHeight = height - margin.top - margin.bottom;
let shouldAppear = false;

const svg = d3
  .select("svg")
  .attr("width", width)
  .attr("height", height)
  .append("g")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

svg
  .append("rect")
  .attr("class", "canvas")
  .attr("width", chartWidth)
  .attr("height", chartHeight - 10);

let mousestart;

svg.on("mousedown", function () {
  shouldAppear = true;
  const mouse = d3.mouse(this);
  mousestart = mouse;
  rectangle.attr("y", mouse[1]).attr("x", mouse[0]);
});
svg.on("mousemove", function () {
  const mouse = d3.mouse(this);
  if (shouldAppear) {
    let rectx, recty, rectwidth, rectheight;
    if (mouse[0] < mousestart[0]) { // if cursor moved left
      rectx = mouse[0];
      rectwidth = mousestart[0] - mouse[0];
    } else {  // if cursor moved right
      rectx = mousestart[0];
      rectwidth = mouse[0] - mousestart[0];
    }

    if (mouse[1] < mousestart[1]) { // if cursor moved up
      recty = mouse[1];
      rectheight = mousestart[1] - mouse[1];
    } else {  // if cursor moved down
      recty = mousestart[1];
      rectheight = mouse[1] - mousestart[1];
    }

    rectangle
      .attr('x', rectx)
      .attr('y', recty)
      .attr('width', rectwidth)
      .attr('height', rectheight)
  }
});
svg.on("mouseup", function () {
  shouldAppear = false;
  rectangle.attr("width", 0).attr("height", 0);
});

let rectangle = svg
  .append("rect")
  .attr("class", "rectangle")
  .attr("width", 0)
  .attr("height", 0)
  .style("fill", "red");

<script src="https://d3js.org/d3.v5.min.js"></script>
<svg></svg>


问:
Why is my ondragstart operation being undone immediately after executing?
I'm making a drag-and-drop form builder with three levels of grouping: Sections, which contain Questions, which contain Options. Options can be dragged within and between Questions, and Questions can be dragged within and between Sections, and Sections can be ordered amongst each other.

I'm using Bootstrap's collapse/show classes to hide the majority of Questions as they begin being dragged, since some can have a dozen plus options, and leaving it open while dragging wouldn't let you see any questions beneath it.

However, as soon as the ondragstart executes and removes the show class from the body of the Question, collapsing it, it seems to be undone immediately.

I tried stepping through each and every line that gets called after ondragstart in the debugger, and couldn't find anything that would re-add the show Bootstrap class.

Fiddle: https://jsfiddle.net/robertgreenstreet/jrdmvasw/4/

答:
It turns out all I needed was to add a condition to the ondragenter function for Questions to check whether the item being dragged A) Had the preventCollapse class AND B) Was NOT also the item being dragged over:

function addQuestionEventListeners(item) {
    /* Checking to see if the item being dragged is an option for a question so that
    the question won't collapse if it is */
    item.ondragstart = function(e) {
        if (!e.target.classList.contains('questionOption')) {
            fullForm.style.height = (fullForm.offsetHeight) + 'px';
            this.classList.add('dragging');
            this.querySelector('.collapse').classList.remove('show');
        };
    }
    item.ondragend = function(e) {
        this.classList.remove('dragging');
        this.querySelector('.collapse').classList.add('show');
        fullForm.style.height='';
    }
    item.ondragenter = function(e) {
        var dragging = document.querySelector('.dragging')
        if(dragging.classList.contains('preventCollapse') && dragging !== this) {
            this.querySelector('.collapse').classList.add('show');
        }
    }
}
```

Can anyone explain like I'm five why an element would call its own ondragenter function? It doesn't make sense to me.

Body:
It turns out all I needed was to add a condition to the ondragenter function for Questions to check whether the item being dragged A) Had the preventCollapse class AND B) Was NOT also the item being dragged over:

function addQuestionEventListeners(item) {
    /* Checking to see if the item being dragged is an option for a question so that
    the question won't collapse if it is */
    item.ondragstart = function(e) {
        if (!e.target.classList.contains('questionOption')) {
            fullForm.style.height = (fullForm.offsetHeight) + 'px';
            this.classList.add('dragging');
            this.querySelector('.collapse').classList.remove('show');
        };
    }
    item.ondragend = function(e) {
        this.classList.remove('dragging');
        this.querySelector('.collapse').classList.add('show');
        fullForm.style.height='';
    }
    item.ondragenter = function(e) {
        var dragging = document.querySelector('.dragging')
        if(dragging.classList.contains('preventCollapse') && dragging !== this) {
            this.querySelector('.collapse').classList.add('show');
        }
    }
}

Can anyone explain like I'm five why an element would call its own ondragenter function? It doesn't make sense to me.


问:
Extract words from dataframe formatted text column
I need to create a new column from another one.
The dataset is created by this code (I extracted only a few rows):

```<code>import pandas as pd

new_dataframe = pd.DataFrame({
    "Name": ['John', 'Lukas', 'Bridget', 'Carol','Madison'],
    "Notes": ["__ years old. NA", "__ years old. NA",
        "__ years old. NA", "__ years old. Old account.",
        "__ years old. New VIP account."],
    "Status": [True, False, True, True, True]})
</code>```

which generates the following

```<code>Name        Notes                           Status
John     23 years old. NA                    True
Lukas    52 years old. NA                    False
Bridget  64 years old. NA                    True
Carol    31 years old. Old account           True
Madison  54 years old. New VIP account.      True
</code>```

I need to create two new columns that contain age information in the format:

__ years old (three words): e.g. 23 years old;

__ (only numbers): e.g. 23

At the end I should have

```<code>Name        Notes                           Status          L_Age           S_Age
    John     23 years old. NA                    True      23 years old       23
    Lukas    52 years old. NA                    False     52 years old       52
    Bridget  64 years old. NA                    True      64 years old       64
    Carol    31 years old. Old account           True      31 years old       31
    Madison  54 years old. New VIP account.      True      54 years old       54
</code>```

I do not know how to extract the first three words, then only the first, to create new columns. I have tried with

```<code>new_dataframe.loc[new_dataframe.Notes == '', 'L_Age'] = new_dataframe.Notes.str.split()[:3]
new_dataframe.loc[new_dataframe.Notes == '', 'S_Age'] = new_dataframe.Notes.str.split()[0]
</code>```

but it is wrong (ValueError: Must have equal len keys and value when setting with an iterable).

Help will be appreciated.

答:
IIUC:</p>

```<code>def get_first_n_words(txt, n):
    l = txt.split(' ')
    assert(len(l)>=n)
    return ' '.join(l[:n])

new_dataframe['L_Age'] = new_dataframe['Notes'].apply(lambda x: get_first_n_words(x, 3))
new_dataframe['S_Age'] = new_dataframe['Notes'].apply(lambda x: get_first_n_words(x, 1))
</code>```

Body:
I need to create a new column from another one.
The dataset is created by this code (I extracted only a few rows):

import pandas as pd

new_dataframe = pd.DataFrame({
    "Name": ['John', 'Lukas', 'Bridget', 'Carol','Madison'],
    "Notes": ["__ years old. NA", "__ years old. NA",
        "__ years old. NA", "__ years old. Old account.",
        "__ years old. New VIP account."],
    "Status": [True, False, True, True, True]})

which generates the following

Name        Notes                           Status
John     23 years old. NA                    True
Lukas    52 years old. NA                    False
Bridget  64 years old. NA                    True
Carol    31 years old. Old account           True
Madison  54 years old. New VIP account.      True

I need to create two new columns that contain age information in the format:

__ years old (three words): e.g. 23 years old;

__ (only numbers): e.g. 23

At the end I should have

Name        Notes                           Status          L_Age           S_Age
    John     23 years old. NA                    True      23 years old       23
    Lukas    52 years old. NA                    False     52 years old       52
    Bridget  64 years old. NA                    True      64 years old       64
    Carol    31 years old. Old account           True      31 years old       31
    Madison  54 years old. New VIP account.      True      54 years old       54

I do not know how to extract the first three words, then only the first, to create new columns. I have tried with

new_dataframe.loc[new_dataframe.Notes == '', 'L_Age'] = new_dataframe.Notes.str.split()[:3]
new_dataframe.loc[new_dataframe.Notes == '', 'S_Age'] = new_dataframe.Notes.str.split()[0]

but it is wrong (ValueError: Must have equal len keys and value when setting with an iterable).

Help will be appreciated.

Body:
IIUC:

def get_first_n_words(txt, n):
    l = txt.split(' ')
    assert(len(l)>=n)
    return ' '.join(l[:n])

new_dataframe['L_Age'] = new_dataframe['Notes'].apply(lambda x: get_first_n_words(x, 3))
new_dataframe['S_Age'] = new_dataframe['Notes'].apply(lambda x: get_first_n_words(x, 1))


问:
Can I set up HTML/Email Templates with ASP.NET?
I'm working on a site that will send out a significant number of emails. I want to set up both header and footer text, or maybe even templates to allow the users to easily edit these emails if they need to.

If I embed the HTML inside C# string literals, it's ugly and they would have to worry about escaping.  Including flat files for the header and footer might work, but something about it just doesn't feel right.

What would be ideal what be to use a .ASPX page as a template somehow, then just tell my code to serve that page, and use the HTML returned for the email.

Is there a nice and easy way to do this? Is there a better way to go about solving this problem?

Updated:

I added an answer that enables you to use a standard .aspx page as the email template.  Just replace all the variables like you normally would, use databinding, etc.  Then just capture the output of the page, and voila!  You have your HTML email!

UPDATED WITH CAVEAT!!!:

I was using the MailDefinition class on some aspx pages just fine, but when trying to use this class during a server process that was running, it failed.  I believe it was because the MailDefinition.CreateMailMessage() method requires a valid control to reference, even though it doesn't always do something.  Because of this, I would recommend my approach using an aspx page, or Mun's approach using an ascx page, which seems a little better.

答:
Set the set the Email Message IsBodyHtml = true

Take your object that contains your email contents Serialize the object
and use xml/xslt to generate the html content.

If you want to do AlternateViews do the same thing that jmein only use a different xslt template to create the plain text content.

one of the major advantages to this is if you want to change your layout all you have to do update the xslt template.

OwnerDisplayName: SkippyFire

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: SkippyFire

OwnerDisplayName: Bob The Janitor


问:
Index or Unique? What is better MySql
So i have a question.

Say you have a table requests, which represent a graph.  There are 3 columns in the request table, A, B, time.  A -> B At time.  So what each row represents is a directed connection from A (the requestor) to B (the requestee) at Time T (time is just for organizing data, not really for anything else).

So what is faster if say requests were 1,000,000 rows.

  Index(A, B)
  Index(A) and Index(B)
  Unique(A, B)?

Thanks guys!  And A, B are VARCHAR(32) (MD5's)

Sorry, i forgot a typical query.

I need to be able to see if User A (who logged on) has any requests!

I also will need to search to verify that a user has accepted a correct request, A Accepts B.

So the statements will look like.

Any new requests?

```<code>SELECT B, time
FROM requests
WHERE A='$id';
</code>```

Does A have a request from B?

```<code>SELECT time
FROM requests
WHERE A='$A' and B='$B';
</code>```

答:
Index and unique are two completely different concepts.

Indexes

An index is a hidden extra column holding the same data sorted with a pointer to your real data. Using an index you can

Quickly find a particular item

Quickly find a range of items (between x and y)

Save time when using order by because the items are presorted

Save time when using group by because group by needs to match identical items

This is a normal index, it doesn't mind duplicate values, except for the primary key which is always unique.

Unique (Index)

If you want to avoid duplicate values you can put a unique index on it. This will do all of the above, but add an extra check on every update and insert to check whether that values is not already in the database. If you try to insert a duplicate row on a unique column, MySQL will give an error and refuse your insert.

(you cannot make a row unique without using an index)

Use of indexes slows inserts and updates down.

Use of unique indexes slows then even more down.

However indexes speed up select a lot, a whole lot.

Unique doesn't speed up anything it makes sure you don't accidentally insert a duplicate row.

When to use indexes and when not

Don't put an index on every field. As stated above it will slow you inserts and updates down.

Always put an index on join criteria. And seriously consider putting an index on column you use in where clauses a lot.

MySQL will refuse to use an index if 50% of your rows have the same value in a field, so forget about indexes on boolean (Y/N) fields, 99% of the time they will not work.

(Indexes in low cardinality fields are not useful)

Always assign a primary key

Always assign a primary key on your table though. Preferably of type integer autoincrement. If you don't assign a primary key, MySQL will assign a 'hidden' primary key for you (of type integer autoincrement), but you cannot use the hidden PK to speed up quotes or identify your rows and there are a host of other slowness problems with hidden PK's which make them suck very badly.

Hope this helps.

Links:

How MySQL uses indexes: http://dev.mysql.com/doc/refman/5.5/en/mysql-indexes.html

When to use indexes: http://www.howtoforge.com/when-to-use-indexes-in-mysql-databases

More of that stuff: http://www.databasejournal.com/features/mysql/article.php/1382791/Optimizing-MySQL-Queries-and-Indexes.htm

Finally lurk here if you want to know more about MySQL: http://planet.mysql.com/

Title: Index or Unique? What is better MySql

Body:
So i have a question.

Say you have a table requests, which represent a graph.  There are 3 columns in the request table, A, B, time.  A -> B At time.  So what each row represents is a directed connection from A (the requestor) to B (the requestee) at Time T (time is just for organizing data, not really for anything else).

So what is faster if say requests were 1,000,000 rows.

  Index(A, B)
  Index(A) and Index(B)
  Unique(A, B)?

Thanks guys!  And A, B are VARCHAR(32) (MD5's)

Sorry, i forgot a typical query.

I need to be able to see if User A (who logged on) has any requests!

I also will need to search to verify that a user has accepted a correct request, A Accepts B.

So the statements will look like.

Any new requests?

SELECT B, time
FROM requests
WHERE A='$id';

Does A have a request from B?

SELECT time
FROM requests
WHERE A='$A' and B='$B';


问:
How to place featured image below post title
I found this solution to getting the featured image to default below the post title.
wordpress add featured image below post title

Where do I place this php?

Will it work for all posts?

答:
Please have a look at the wordpress template hierarchy in themes:

https://developer.wordpress.org/themes/basics/template-hierarchy/

You can edit the look of single post views inside the single.php, if using a custom post type single-{post-type}.php. If you are using a theme that is not made by yourself and might get updated, make sure to use a child theme, so your changes will not be overwritten when the parent theme is getting updated.

This is a nice tutorial for creating child themes in wordpress:
https://www.smashingmagazine.com/2016/01/create-customize-wordpress-child-theme/

In the template file you get the featured image with get_the_post_thumbnail() function and the post title with get_the_title() function.

Search for the lines in the code, where you can find the functions and change the location to your desired place. Or if there is no featured image, you can add the code you already found.

Where do I place this in php?

Inside of the single page template of your theme.

Will it work for all posts?

If you use the single.php file, yes. All posts use this template. But you can only apply the changes to specific post types as described above - if you like to. You can also make it work for some specific category terms with category-{term}.php or maybe you want to change the post listing in your archive.php. Please check the link above, Wordpress Template Hierarchy will make this clear, very easy to understand.

Hope this helps!


问:
Removing gap between footer & content
i am learning HTML, CSS. I have built a local website on my PC. But there is huge space between my footer and content. Can you guys please look at the code and suggest what should i do? Where am i committing mistake. I have tried margin-top instead of bottom in the side-content but that too didn't work.

* {
  margin: 0;
  padding: 0;
}

body {
  background-color: skyblue;
  height: 100%;
}

#container {
  width: 100%;
}

#main {
  overflow: auto;
}

#nav {
  overflow: hidden;
  background: darkblue;
  position: relative;
  top: 0;
  width: 150% height: 80px;
  line-height: 70px;
}

#nav ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  text-align: center;
}

#nav li {
  display: inline;
  vertical-align: middle;
  padding: 100px;
  vertical-align: middle;
}

#nav a {
  text-decoration: none;
  font-size: 150%;
  padding-top: 50%;
  padding: 105px;
  color: white;
  vertical-align: middle;
}

#nav a:hover {
  background-color: white;
  color: red;
}

#logo {
  max-width: 5.7%;
  height: auto;
  float: left;
}

#mainimage {
  display: block;
  margin-left: auto;
  margin-right: auto;
  padding-top: 0px;
}

.caption {
  display: block;
  text-align: center;
  font-size: 150%;
  font-weight: bold;
}

h1 {
  text-align: center;
  padding-top: 20px;
  padding-bottom: 0px;
}

h2 {
  font-family: "Georgia";
}

#side-content {
  height: 100%;
  width: 350px;
  float: right;
  clear: both;
  position: relative;
  bottom: 880px;
  overflow: hidden;
}

#mf {
  width: 1000px;
}

#imag {
  float: right;
  position: relative;
  top: 7px;
  height: 300px;
  width: 270px;
  right: 18px;
  padding-bottom: 20px;
}

.info {
  position: relative;
  bottom: 2em;
  font-size: 90%;
  text-align: center;
}

.th,
.info td {
  vertical-align: top;
  border: 0;
  border-bottom: 1px solid #dddddd;
  padding-bottom: 8 px;
}

#nutshell {
  font-family: 'Lato'. sans-serif;
  font-weight: bold;
  font-size: 25px;
  text-align: center;
}

footer {
  left: 0;
  bottom: 0;
  text-align: center;
  clear: both;
  position: relative;
  height: 100%;
}

#quote {
  font-family: 'Pacifico', cursive;
  text-align: center;
  font-size: 25px;
  background-color: #ececec;
}

.balance {
  text-align: center;
  float: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">

<head>
  <meta charset="utf-8" />
  <title>Tribute To Swami Vivekanada</title>
  <link rel="stylesheet" type="text/css" href="style.css">
</head>

<body>

  <div id="container">
    <div id="main">
      <div id="nav">
        <ul>
          <li><img id="logo" src="logo.jpg" alt="WebLogo" /></li>
          <li>Tribute Page</li>
          <li>Info</li>
        </ul>
      </div>
      <br>
      <br>
      <br>
      <br>
      <br>
      <br>
      <br>
      <h1> Swami Vivekananda</h1>
      <figure class="item">
        <img id="mainimage" src="swamiji.jpg">
        <figcaption class="caption">(1863-1902)</figcaption>
      </figure>

      <h2>Here are some facts about Swami Vivekananda</h2>
      <br>
      <br>
      <div id="mf">

        <p class="firstd">1) Vivekananda was born Narendranath Datta (shortened to Narendra or Naren) in a Bengali family at his ancestral home at 3 Gourmohan Mukherjee Street in Calcutta, the capital of British India, on 12 January 1863 during the Makar Sankranti festival.</p>
        <br>
        <p class="general">2) He belonged to a traditional family and was one of nine siblings.His father, Vishwanath Datta, was an attorney at the Calcutta High Court.</p>
        <br>
        <p class="general">3) Narendranath was interested in spirituality from a young age and used to meditate before the images of deities such as Shiva, Rama, Sita, and Mahavir Hanuman.</p>
        <br>
        <p class="general">4) In 1871, at the age of eight, Narendranath enrolled at Ishwar Chandra Vidyasagar's Metropolitan Institution, where he went to school until his family moved to Raipur in 1877.</p>
        <br>
        <p class="general">5) He was an avid reader in a wide range of subjects, including philosophy, religion, history, social science, art and literature.He was also interested in Hindu scriptures, including the Vedas, the Upanishads, the Bhagavad Gita, the Ramayana,
          the Mahabharata and the Puranas.</p>
        <br>
        <p class="general">6) Narendra studied the works of David Hume, Immanuel Kant, Johann Gottlieb Fichte, Baruch Spinoza, Georg W. F. Hegel, Arthur Schopenhauer, Auguste Comte, John Stuart Mill and Charles Darwin.</p>
        <br>
        <p class="general">7) In 1880 Narendra joined Keshab Chandra Sen's Nava Vidhan, which was established by Sen after meeting Ramakrishna and reconverting from Christianity to Hinduism.Narendra became a member of a Freemasonry lodge "at some point before 1884"</p>
        <br>
        <p class="general">8) In 1888, Narendra left the monastery as a Parivrâjaka— the Hindu religious life of a wandering monk, "without fixed abode, without ties, independent and strangers wherever they go".</p>
        <br>
        <p class="general">9) Narendra left Bombay for Chicago on 31 May 1893 with the name "Vivekananda", as suggested by Ajit Singh of Khetri, which means "the bliss of discerning wisdom," from Sanskrit viveka and ānanda.</p>
        <br>
        <p class="general">10) On 4 July 1902, According to his disciples, Vivekananda attained mahasamadhi, the rupture of a blood vessel in his brain was reported as a possible cause of death.</p>

      </div>

      <br>
      <br>
      <br>
      <br>
      <br>

      <div class="Balance">
        <h2>More Facts</h2>

        <p>1) In 1880 Narendra joined Keshab Chandra Sen's Nava Vidhan, which was established by Sen after meeting Ramakrishna and reconverting from Christianity to Hinduism.</p>
        <br>
        <p>2) His initial beliefs were shaped by Brahmo concepts, which included belief in a formless God and the deprecation of idolatry,[24][46] and a "streamlined, rationalized,<br> monotheistic theology strongly coloured by a selective and modernistic
          reading of the Upanisads and of the Vedanta.</p>
        <br>
        <p>3) Vivekananda attracted followers and admirers in the US and Europe, including Josephine MacLeod, William James, Josiah Royce, Robert G. Ingersoll, Nikola Tesla, Lord Kelvin,<br> Harriet Monroe, Ella Wheeler Wilcox, Sarah Bernhardt, Emma Calvé
          and Hermann Ludwig Ferdinand von Helmholtz.</p>
        <br>
        <p>4) He initiated several followers : Marie Louise (a French woman) became Swami Abhayananda, and Leon Landsberg became Swami Kripananda, so that they could continue the work<br> of the mission of the Vedanta Society.</p>

      </div>

      <div id="side-content">

        <table class="info">

          <tbody>

            <tr>
              <th colspan="2" id="nutshell">IN A NUTSHELL
                <img id="imag" src="second.jpeg" alt="Swami Vivekananda">
              </th>
            </tr>

            <tr>
              <th>
                Born
              </th>
              <td>Narendranath Dutta<br>12 January 1863</td>
            </tr>

            <tr>
              <th>
                Died
              </th>
              <td>July 4,1902 </td>
            </tr>

            <tr>
              <th>
                Education
              </th>
              <td>Presidency College</td>
            </tr>

            <tr>
              <th>
                Joined Nava Vidhan
              </th>
              <td>1882</td>
            </tr>

            <tr>
              <th>
                Spiritual Guru
              </th>
              <td>Ramakrishna Paramhans</td>
            </tr>

            <tr>
              <th>
                1887
              </th>
              <td>Complilation of Sangeet Kalpataru</td>
            </tr>

            <tr>
              <th>
                Member of Freemasonry Lodge
              </th>
              <td>1884</td>
            </tr>

            <tr>
              <th>
                Visit to Chicago
              </th>
              <td>31st May 1893</td>
            </tr>

            <tr>
              <th>
                Parliament Of Religions
              </th>
              <td>September 1893</td>
            </tr>
        </table>
      </div>

    </div>

    <footer>
      <div id="quote">
        <ul>
          <li>
            <p>"Arise,Awake and Donot stop until the goal is reached."<br>-Swami Vivekananda</p>
          </li>
          <li>
            <p>Do read more about this impeccable personality here.</p>
          </li>
        </ul>
      </div>
    </footer>
  </div>
</body>

</html></code>```

答:
welcome to the world of front-end. The basic HTML structure looks fine. Lets get it.

1) The following need correction #nav missing semicolon after width: 150%, typo on #nutshell, font-family after Lato is a comma (,) not period (.)
Below is corrected CSS

```<code>#nav {
  overflow: hidden;
  background: darkblue;
  position: relative;
  top: 0;
  width: 150%;
  height: 80px;
  line-height: 70px;
}

#nutshell {
  font-family: "Lato", sans-serif;
  font-weight: bold;
  font-size: 25px;
  text-align: center;
}
</code>```

2) If you uncomment the following your hieght problem is sorted, but one thing that is off is your responsiveness.

```<code>#side-content {
  /* height: 100%; */
  width: 350px;
  float: right;
  clear: both;
  position: relative;
  /* bottom: 880px; */
  /* overflow: hidden; */
}

</code>```

3) First and foremost I suggest switching your entire HTML to HTML structure. Please visit W3schools https://www.w3schools.com/html/

For good responsiveness, which is not bloated I suggest you checkout skeleton
http://getskeleton.com/

For responsive tables checkout https://codepen.io/HikwaMehluli/pen/JeYypV

HTML of Table:

```<code><table>
  <thead>
    <tr>
      <th>Artist</th>
      <th>Style</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td data-column="Artist">Mehluli Hikwa</td>
      <td data-column="Style">Digital Design</td>
    </tr>
      <tr>
      <td data-column="Artist">Pablo Picasso</td>
      <td data-column="Style">Cubisim</td>
    </tr>
      <tr>
      <td data-column="Artist">Henri Matisse</td>
      <td data-column="Style">Draughtsmanship</td>
    </tr>
      <tr>
      <td data-column="Artist">Jean-Antoine Watteau</td>
      <td data-column="Style">Baroque</td>
    </tr>
  </tbody>
</table>
</code>```

And the CSS

```<code>table {
    width: 900px;
    border-collapse: collapse;
    margin: 50px auto;
}

/* Different Color Strips */
tr:nth-of-type(odd) {
    background: #f6f6f6;
}

/* Top Color of Table */
th {
    background: #fdc20e;
    color: black;
    font-weight: bold;
}

td, th {
    padding: 10px;
    border: 1px solid #ccc;
    text-align: left;
    font-size: 18px;
}

/* Max width before table looks bad on smaller screens ~ 760px ~ specifically on iPads and below */
@media only screen and (max-width: 760px),
(min-device-width: 768px) and (max-device-width: 1024px)  {

    table {
        width: 100%;
    }

    /* Force table to not be like tables anymore */
    table, thead, tbody, th, td, tr {
        display: block;
    }

    /* Hides table headers (but not display: none;, for accessibility) */
    thead tr {
        position: absolute;
        top: -9999px;
        left: -9999px;
    }

    tr { border: 1px solid #ccc; }

    td {
        /* Single row behaviour */
        border: none;
        border-bottom: 1px solid #eee;
        position: relative;
        padding-left: 50%;
    }

    td:before {
        /* give a table header effect */
        position: absolute;
        /* Top/left values mimic padding */
        top: 6px;
        left: 6px;
        width: 45%;
        padding-right: 10px;
        white-space: nowrap;

        /* Label the data */
        content: attr(data-column);
        color: #000;
        font-weight: bold;
    }
}
</code>```

GOOD LUCK!!!

Title: Removing gap between footer & content

Body:
i am learning HTML, CSS. I have built a local website on my PC. But there is huge space between my footer and content. Can you guys please look at the code and suggest what should i do? Where am i committing mistake. I have tried margin-top instead of bottom in the side-content but that too didn't work.

* {
  margin: 0;
  padding: 0;
}

body {
  background-color: skyblue;
  height: 100%;
}

#container {
  width: 100%;
}

#main {
  overflow: auto;
}

#nav {
  overflow: hidden;
  background: darkblue;
  position: relative;
  top: 0;
  width: 150% height: 80px;
  line-height: 70px;
}

#nav ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  text-align: center;
}

#nav li {
  display: inline;
  vertical-align: middle;
  padding: 100px;
  vertical-align: middle;
}

#nav a {
  text-decoration: none;
  font-size: 150%;
  padding-top: 50%;
  padding: 105px;
  color: white;
  vertical-align: middle;
}

#nav a:hover {
  background-color: white;
  color: red;
}

#logo {
  max-width: 5.7%;
  height: auto;
  float: left;
}

#mainimage {
  display: block;
  margin-left: auto;
  margin-right: auto;
  padding-top: 0px;
}

.caption {
  display: block;
  text-align: center;
  font-size: 150%;
  font-weight: bold;
}

h1 {
  text-align: center;
  padding-top: 20px;
  padding-bottom: 0px;
}

h2 {
  font-family: "Georgia";
}

#side-content {
  height: 100%;
  width: 350px;
  float: right;
  clear: both;
  position: relative;
  bottom: 880px;
  overflow: hidden;
}

#mf {
  width: 1000px;
}

#imag {
  float: right;
  position: relative;
  top: 7px;
  height: 300px;
  width: 270px;
  right: 18px;
  padding-bottom: 20px;
}

.info {
  position: relative;
  bottom: 2em;
  font-size: 90%;
  text-align: center;
}

.th,
.info td {
  vertical-align: top;
  border: 0;
  border-bottom: 1px solid #dddddd;
  padding-bottom: 8 px;
}

#nutshell {
  font-family: 'Lato'. sans-serif;
  font-weight: bold;
  font-size: 25px;
  text-align: center;
}

footer {
  left: 0;
  bottom: 0;
  text-align: center;
  clear: both;
  position: relative;
  height: 100%;
}

#quote {
  font-family: 'Pacifico', cursive;
  text-align: center;
  font-size: 25px;
  background-color: #ececec;
}

.balance {
  text-align: center;
  float: left;
}

<!DOCTYPE html>

  <meta charset="utf-8" />
  <title>Tribute To Swami Vivekanada</title>
  <link rel="stylesheet" type="text/css" href="style.css">

Tribute Page

Info

 Swami Vivekananda

(1863-1902)

Here are some facts about Swami Vivekananda

1) Vivekananda was born Narendranath Datta (shortened to Narendra or Naren) in a Bengali family at his ancestral home at 3 Gourmohan Mukherjee Street in Calcutta, the capital of British India, on 12 January 1863 during the Makar Sankranti festival.

2) He belonged to a traditional family and was one of nine siblings.His father, Vishwanath Datta, was an attorney at the Calcutta High Court.

3) Narendranath was interested in spirituality from a young age and used to meditate before the images of deities such as Shiva, Rama, Sita, and Mahavir Hanuman.

4) In 1871, at the age of eight, Narendranath enrolled at Ishwar Chandra Vidyasagar's Metropolitan Institution, where he went to school until his family moved to Raipur in 1877.

5) He was an avid reader in a wide range of subjects, including philosophy, religion, history, social science, art and literature.He was also interested in Hindu scriptures, including the Vedas, the Upanishads, the Bhagavad Gita, the Ramayana,
          the Mahabharata and the Puranas.

6) Narendra studied the works of David Hume, Immanuel Kant, Johann Gottlieb Fichte, Baruch Spinoza, Georg W. F. Hegel, Arthur Schopenhauer, Auguste Comte, John Stuart Mill and Charles Darwin.

7) In 1880 Narendra joined Keshab Chandra Sen's Nava Vidhan, which was established by Sen after meeting Ramakrishna and reconverting from Christianity to Hinduism.Narendra became a member of a Freemasonry lodge "at some point before 1884"

8) In 1888, Narendra left the monastery as a Parivrâjaka— the Hindu religious life of a wandering monk, "without fixed abode, without ties, independent and strangers wherever they go".

9) Narendra left Bombay for Chicago on 31 May 1893 with the name "Vivekananda", as suggested by Ajit Singh of Khetri, which means "the bliss of discerning wisdom," from Sanskrit viveka and ānanda.

10) On 4 July 1902, According to his disciples, Vivekananda attained mahasamadhi, the rupture of a blood vessel in his brain was reported as a possible cause of death.

More Facts

1) In 1880 Narendra joined Keshab Chandra Sen's Nava Vidhan, which was established by Sen after meeting Ramakrishna and reconverting from Christianity to Hinduism.

2) His initial beliefs were shaped by Brahmo concepts, which included belief in a formless God and the deprecation of idolatry,[24][46] and a "streamlined, rationalized,
 monotheistic theology strongly coloured by a selective and modernistic
          reading of the Upanisads and of the Vedanta.

3) Vivekananda attracted followers and admirers in the US and Europe, including Josephine MacLeod, William James, Josiah Royce, Robert G. Ingersoll, Nikola Tesla, Lord Kelvin,
 Harriet Monroe, Ella Wheeler Wilcox, Sarah Bernhardt, Emma Calvé
          and Hermann Ludwig Ferdinand von Helmholtz.

4) He initiated several followers : Marie Louise (a French woman) became Swami Abhayananda, and Leon Landsberg became Swami Kripananda, so that they could continue the work
 of the mission of the Vedanta Society.

              IN A NUTSHELL

                Born

              Narendranath Dutta
12 January 1863

                Died

              July 4,1902

                Education

              Presidency College

                Joined Nava Vidhan

              1882

                Spiritual Guru

              Ramakrishna Paramhans

                1887

              Complilation of Sangeet Kalpataru

                Member of Freemasonry Lodge

              1884

                Visit to Chicago

              31st May 1893

                Parliament Of Religions

              September 1893

"Arise,Awake and Donot stop until the goal is reached."
-Swami Vivekananda

Do read more about this impeccable personality here.

Body:
welcome to the world of front-end. The basic HTML structure looks fine. Lets get it.

1) The following need correction #nav missing semicolon after width: 150%, typo on #nutshell, font-family after Lato is a comma (,) not period (.)
Below is corrected CSS

#nav {
  overflow: hidden;
  background: darkblue;
  position: relative;
  top: 0;
  width: 150%;
  height: 80px;
  line-height: 70px;
}

#nutshell {
  font-family: "Lato", sans-serif;
  font-weight: bold;
  font-size: 25px;
  text-align: center;
}

2) If you uncomment the following your hieght problem is sorted, but one thing that is off is your responsiveness.

#side-content {
  /* height: 100%; */
  width: 350px;
  float: right;
  clear: both;
  position: relative;
  /* bottom: 880px; */
  /* overflow: hidden; */
}

3) First and foremost I suggest switching your entire HTML to HTML structure. Please visit W3schools https://www.w3schools.com/html/

For good responsiveness, which is not bloated I suggest you checkout skeleton
http://getskeleton.com/

For responsive tables checkout https://codepen.io/HikwaMehluli/pen/JeYypV

HTML of Table:

<table>
  <thead>
    <tr>
      <th>Artist</th>
      <th>Style</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td data-column="Artist">Mehluli Hikwa</td>
      <td data-column="Style">Digital Design</td>
    </tr>
      <tr>
      <td data-column="Artist">Pablo Picasso</td>
      <td data-column="Style">Cubisim</td>
    </tr>
      <tr>
      <td data-column="Artist">Henri Matisse</td>
      <td data-column="Style">Draughtsmanship</td>
    </tr>
      <tr>
      <td data-column="Artist">Jean-Antoine Watteau</td>
      <td data-column="Style">Baroque</td>
    </tr>
  </tbody>
</table>

And the CSS

table {
    width: 900px;
    border-collapse: collapse;
    margin: 50px auto;
}

/* Different Color Strips */
tr:nth-of-type(odd) {
    background: #f6f6f6;
}

/* Top Color of Table */
th {
    background: #fdc20e;
    color: black;
    font-weight: bold;
}

td, th {
    padding: 10px;
    border: 1px solid #ccc;
    text-align: left;
    font-size: 18px;
}

/* Max width before table looks bad on smaller screens ~ 760px ~ specifically on iPads and below */
@media only screen and (max-width: 760px),
(min-device-width: 768px) and (max-device-width: 1024px)  {

    table {
        width: 100%;
    }

    /* Force table to not be like tables anymore */
    table, thead, tbody, th, td, tr {
        display: block;
    }

    /* Hides table headers (but not display: none;, for accessibility) */
    thead tr {
        position: absolute;
        top: -9999px;
        left: -9999px;
    }

    tr { border: 1px solid #ccc; }

    td {
        /* Single row behaviour */
        border: none;
        border-bottom: 1px solid #eee;
        position: relative;
        padding-left: 50%;
    }

    td:before {
        /* give a table header effect */
        position: absolute;
        /* Top/left values mimic padding */
        top: 6px;
        left: 6px;
        width: 45%;
        padding-right: 10px;
        white-space: nowrap;

        /* Label the data */
        content: attr(data-column);
        color: #000;
        font-weight: bold;
    }
}

GOOD LUCK!!!


问:
When I try to use the read() function on a file in Python, the output is blank
This is the code that I've tried:

```<code>test = open('test.txt', 'w+')
test.write('test')
print(test.read())
</code>```

I'm using version 3.8.2 of Python on Visual Studio Code.
I'm getting no errors when I run it, but the output is empty.
Is there something I'm doing wrong?

答:
You need to use the format 'r+', and seek:

```<code>with open('test.txt', 'r+') as test:
    test.write('test')
    test.seek(0) # seek lets us from which index we want to start reading
    print(test.read())
</code>```

Body:
This is the code that I've tried:

test = open('test.txt', 'w+')
test.write('test')
print(test.read())

I'm using version 3.8.2 of Python on Visual Studio Code.
I'm getting no errors when I run it, but the output is empty.
Is there something I'm doing wrong?

Body:
You need to use the format 'r+', and seek:

with open('test.txt', 'r+') as test:
    test.write('test')
    test.seek(0) # seek lets us from which index we want to start reading
    print(test.read())


问:
SQL query results are duplicating
Using below query

SELECT *
            FROM Customer, Orders, Orderline, Product

Results with 6500 rows as a result instead of 30 rows. I'm using SQL Server Management Studio

```<code>Customer

----------------------------------------
CustomerNo CustomerName CustomerAddress
----------------------------------------

1          Harry        19 mousemat

2          Potter       98a speakers

Orders
-------------------------------
OrderID CustomerNo OrderDate
-------------------------------

 1       1         12/3/1992

 2       2         13/5/1997

OrderLine
-----------------------------
OrderID ProductID ProductQty
-----------------------------
1       100       27

2       101       30

Products
-----------------------------------
ProductID ProductDesc ProductPrice
-----------------------------------

100       Blue        0.13

101       Yellow      1.21
</code>```

答:
You should use JOINS to link the tables on the right keys.

e.g.

```<code>SELECT *
FROM Orderline OL
JOIN Orders O
    ON OL.OrderId = O.OrderId
JOIN Product P
    ON OL.ProductId = P.ProductId
JOIN Customer C
    ON O.CustomerNo = C.CustomerNo;
</code>```

Title: SQL query results are duplicating

Body:
Using below query

SELECT *
            FROM Customer, Orders, Orderline, Product

Results with 6500 rows as a result instead of 30 rows. I'm using SQL Server Management Studio

Customer

----------------------------------------
CustomerNo CustomerName CustomerAddress
----------------------------------------

1          Harry        19 mousemat

2          Potter       98a speakers

Orders
-------------------------------
OrderID CustomerNo OrderDate
-------------------------------

 1       1         12/3/1992

 2       2         13/5/1997

OrderLine
-----------------------------
OrderID ProductID ProductQty
-----------------------------
1       100       27

2       101       30

Products
-----------------------------------
ProductID ProductDesc ProductPrice
-----------------------------------

100       Blue        0.13

101       Yellow      1.21

Body:
You should use JOINS to link the tables on the right keys.

e.g.

SELECT *
FROM Orderline OL
JOIN Orders O
    ON OL.OrderId = O.OrderId
JOIN Product P
    ON OL.ProductId = P.ProductId
JOIN Customer C
    ON O.CustomerNo = C.CustomerNo;


答:
You can use this pattern to extract the information and join:

```<code>pattern = '^(?P<L_Age>(?P<S_Age>\d+) years? old)'

new_dataframe = new_dataframe.join(new_dataframe.Notes.str.extract(pattern))
</code>```

Output:

```<code>      Name                           Notes  Status         L_Age S_Age
0     John                23 years old. NA    True  23 years old    23
1    Lukas                52 years old. NA   False  52 years old    52
2  Bridget                64 years old. NA    True  64 years old    64
3    Carol       31 years old. Old account    True  31 years old    31
4  Madison  54 years old. New VIP account.    True  54 years old    54
</code>```

Title: Extract words from dataframe formatted text column

Body:
You can use this pattern to extract the information and join:

pattern = '^(?P<L_Age>(?P<S_Age>\d+) years? old)'

new_dataframe = new_dataframe.join(new_dataframe.Notes.str.extract(pattern))

Output:

      Name                           Notes  Status         L_Age S_Age
0     John                23 years old. NA    True  23 years old    23
1    Lukas                52 years old. NA   False  52 years old    52
2  Bridget                64 years old. NA    True  64 years old    64
3    Carol       31 years old. Old account    True  31 years old    31
4  Madison  54 years old. New VIP account.    True  54 years old    54


答:
You need to have a JOIN statement between the tables. If there are still duplicates use the distinct keyword after the select keyword as well:

```<code>select distinct *
from a
    join b on b.id = a.id
    join c on c.id = b.id
</code>```

Here is what it would look like in your case:

```<code>select *
from Customer C
    join Orders O on (O.CustomerNo = C.CustomerNo)
    join OrderLine OL on (OL.OrderID = O.OrderID)
    join Products P on (P.ProductID = OL.ProductID);
</code>```

The join statement is an inner/natural join by default. You want to link up the tables by what they have in common as a primary/secondary key.

When you don't have joins between multiple tables in sql, sql will make combinations between them. This is why you end up with 6500 rows instead of 30.

Title: SQL query results are duplicating

Body:
You need to have a JOIN statement between the tables. If there are still duplicates use the distinct keyword after the select keyword as well:

select distinct *
from a
    join b on b.id = a.id
    join c on c.id = b.id

Here is what it would look like in your case:

select *
from Customer C
    join Orders O on (O.CustomerNo = C.CustomerNo)
    join OrderLine OL on (OL.OrderID = O.OrderID)
    join Products P on (P.ProductID = OL.ProductID);

The join statement is an inner/natural join by default. You want to link up the tables by what they have in common as a primary/secondary key.

When you don't have joins between multiple tables in sql, sql will make combinations between them. This is why you end up with 6500 rows instead of 30.


问:
Is there any way around this conditional hook workaround?
I'm using NextJS's useRouter to access the router like so:

const router = useRouter();
```

<p>but however, when my component renders, I tend to notice that <code>router</code> can be <code>null</code> until it actually instantiates. My workaround would be doing something like this:</p>

<pre class="lang-js prettyprint-override"><code>const router = useRouter();

if (!router) return null;

return (
  // ... jsx
);
</code>```

However, I have a custom hook that I'm using and it's dependent on the router's queries:

const router = useRouter();

if (!router) return null;

const {data} = useCustomHook(router.query.id);

return ( //.... )
```

<p>But I get an eslint error like so:</p>

```React Hook "useCustomHook" is called conditionally. React Hooks must be called in the exact same order in every component render. Did you accidentally call a React Hook after an early return?
```

<p>My workaround is to make two separate components to handle this conditional:</p>

<pre class="lang-js prettyprint-override"><code>const HookComponent = ({ id }) => {
  const { data } = useCustomHook(id);
  return ( // ....)
}

const HookComponentWrapper = () => {
  const router = useRouter();
  if (!router) return null;

  return <HookComponent id={router.query.id}/>
}
</code>```

My question is: is it possible to avoid having to add that wrapper just for a conditional?

答:
Since router can sometimes be null you can use guard clauses to access up to the id passed to the hook. useCustomHook still needs to handle null input gracefully.

```<code>const {data} = useCustomHook(router && router.query && router.query.id);
</code>```

Or use optional chaining if your build allows it

```<code>const {data} = useCustomHook(router?.query?.id);
</code>```

At this point I'd suggest just passing the router object and handle extracting what you need from it in any custom hook.

Body:
I'm using NextJS's useRouter to access the router like so:

const router = useRouter();

but however, when my component renders, I tend to notice that router can be null until it actually instantiates. My workaround would be doing something like this:

const router = useRouter();

if (!router) return null;

return (
  // ... jsx
);

However, I have a custom hook that I'm using and it's dependent on the router's queries:

const router = useRouter();

if (!router) return null;

const {data} = useCustomHook(router.query.id);

return ( //.... )

But I get an eslint error like so:

React Hook "useCustomHook" is called conditionally. React Hooks must be called in the exact same order in every component render. Did you accidentally call a React Hook after an early return?

My workaround is to make two separate components to handle this conditional:

const HookComponent = ({ id }) => {
  const { data } = useCustomHook(id);
  return ( // ....)
}

const HookComponentWrapper = () => {
  const router = useRouter();
  if (!router) return null;

  return <HookComponent id={router.query.id}/>
}

My question is: is it possible to avoid having to add that wrapper just for a conditional?

Body:
Since router can sometimes be null you can use guard clauses to access up to the id passed to the hook. useCustomHook still needs to handle null input gracefully.

const {data} = useCustomHook(router && router.query && router.query.id);

Or use optional chaining if your build allows it

const {data} = useCustomHook(router?.query?.id);

At this point I'd suggest just passing the router object and handle extracting what you need from it in any custom hook.


问:
interceptor delete headers from request
```<code>    @Injectable()
export class TokenInterceptorService implements HttpInterceptor {

  constructor(private injector: Injector) {
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const authReq = req.clone({
      headers: req.headers.set('Authorization', "dassda")
    });
    console.log(authReq);
    return next.handle(authReq);
  }
}
</code>```

any tutorials on Internet use this code to add Authorization header in a request, in my situation if I set header, all other headers are deleted.

Error : "Access to XMLHttpRequest at '' from origin '' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource".

but if I delete line  headers: req.headers.set('Authorization', "dassda") always is ok

console.log(req.headers) returns map(0)

I'm trying:

hardcode all headers- error anywhere

trying to use all methods in req.headers like append, setHeaders, Headers

append headers like "Access-Control-Allow-Origin/headers/methods" and etc
  -create new headers,

download google plugin Moesif Origin & CORS Changer that program add all needed headers to all requests- then write error "has been blocked
  by CORS policy: Response to preflight request doesn't pass access
  control check: It does not have HTTP ok status."

答:
problem was on my Backend(Java), i pasted this code into my config method and everything worked fine.</p>

```<code>@Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "DELETE", "PUT"));
        configuration.setAllowedHeaders(Collections.singletonList("*"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
</code>```

Title: interceptor delete headers from request

Body:
    @Injectable()
export class TokenInterceptorService implements HttpInterceptor {

  constructor(private injector: Injector) {
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const authReq = req.clone({
      headers: req.headers.set('Authorization', "dassda")
    });
    console.log(authReq);
    return next.handle(authReq);
  }
}

any tutorials on Internet use this code to add Authorization header in a request, in my situation if I set header, all other headers are deleted.

Error : "Access to XMLHttpRequest at '' from origin '' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource".

but if I delete line  headers: req.headers.set('Authorization', "dassda") always is ok

console.log(req.headers) returns map(0)

I'm trying:

hardcode all headers- error anywhere

trying to use all methods in req.headers like append, setHeaders, Headers

append headers like "Access-Control-Allow-Origin/headers/methods" and etc
  -create new headers,

download google plugin Moesif Origin & CORS Changer that program add all needed headers to all requests- then write error "has been blocked
  by CORS policy: Response to preflight request doesn't pass access
  control check: It does not have HTTP ok status."

Body:
problem was on my Backend(Java), i pasted this code into my config method and everything worked fine.

@Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "DELETE", "PUT"));
        configuration.setAllowedHeaders(Collections.singletonList("*"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }