问:
Undefined variable:visiteur in Laravel
Helloo , i want to add comment into a blog with showing the name of the patient who added , with using session , so i get this error : Undefined variable: visiteur

This is the commentcontroller.php :

```<code>public function store  (blog $getid , Request $request)
{
    $visitor=patient::orderBy('created_at','desc')->get() ;
    $patient_id=$request->session()->get('patient_id');
     comment::create([
        'body' =>request('body'),
        'blog_id'=> $getid->id,
        'patient_id'=>$patient_id
    ]);

     return back()->with(['visiteur'=>$visitor]);
}
}
</code>```

This is the view : show.blade.php

```<code> <div class="card-body" >
  @foreach ($showme->comments as $comment)
    <blockquote class="blockquote mb-0">
      <p style="font-size:15px;">{{$comment->body}}</p>
        @foreach ($visiteur as $viis)
        @if ($comment->patient_id == $viis->id)
         <p> {{$comment->patient_id}}</p>
        @endif
        @endforeach
      <footer class="blockquote-footer"> {{$comment->created_at}} <cite title="Source Title"> </cite></footer>
    </blockquote>
    @endforeach
  </div>
  <!-- si le patient est connceter -->
  @if(Session::has('log_in'))
    <div class="card-block">
   <form method="POST" action="/blog/{{$showme->id}}/store" >
   @csrf
   <div class="form-group">
   <label> Commentaire </label> </br>
   <textarea name="body"  rows="3" cols="80" cols="form-control"></textarea> </br>
</div>

<div class="form-group">
<button type="submit" class="btn btn-primary"> Ajouter commentaire</button>
</div>
  </form>
</div>
@endif
</code>```

And finally this is the web.php

```<code>Route::Post('/store' , 'patientcontroller@store');
</code>```

This is the Patient controller :

```<code>public function welcome(Request $request)
    {
        $request->validate([
            'mail' => 'required|email',
            'mdp' => 'required',
        ]);

        // since email is unique. no need to grab all data
        $patient = patient::where('Login', $request->input('mail'))->first();

        // if patient exists
        if ($patient) {
            // check hashed password
            // assuming $patient->Password hashed
            if (Hash::check($request->input('mdp'), $patient->Password)) {
                //session
                $request->session()->put('patient_id', $patient->Nom);
                $request->session()->put('log_in', true);
                return redirect ('index');
            }
        }
        return back()->withErrors([
            'message' => 'Emails or password not correct!',
        ]);
    }
</code>```

i want to show the name of the user who add the comment but he show me only the ID

答:
Should be</p>

```<code>return back()->with(['visiteur', $visitor]);
</code>```

Title: Undefined variable:visiteur in Laravel

Body:
Helloo , i want to add comment into a blog with showing the name of the patient who added , with using session , so i get this error : Undefined variable: visiteur

This is the commentcontroller.php :

public function store  (blog $getid , Request $request)
{
    $visitor=patient::orderBy('created_at','desc')->get() ;
    $patient_id=$request->session()->get('patient_id');
     comment::create([
        'body' =>request('body'),
        'blog_id'=> $getid->id,
        'patient_id'=>$patient_id
    ]);

     return back()->with(['visiteur'=>$visitor]);
}
}

This is the view : show.blade.php

  @foreach ($showme->comments as $comment)

{{$comment->body}}

        @foreach ($visiteur as $viis)
        @if ($comment->patient_id == $viis->id)

 {{$comment->patient_id}}

        @endif
        @endforeach
       {{$comment->created_at}}

    @endforeach

  @if(Session::has('log_in'))

   <form method="POST" action="/blog/{{$showme->id}}/store" >
   @csrf

    Commentaire

   <textarea name="body"  rows="3" cols="80" cols="form-control"></textarea>

<button type="submit" class="btn btn-primary"> Ajouter commentaire</button>

  </form>

@endif

And finally this is the web.php

Route::Post('/store' , 'patientcontroller@store');

This is the Patient controller :

public function welcome(Request $request)
    {
        $request->validate([
            'mail' => 'required|email',
            'mdp' => 'required',
        ]);

        // since email is unique. no need to grab all data
        $patient = patient::where('Login', $request->input('mail'))->first();

        // if patient exists
        if ($patient) {
            // check hashed password
            // assuming $patient->Password hashed
            if (Hash::check($request->input('mdp'), $patient->Password)) {
                //session
                $request->session()->put('patient_id', $patient->Nom);
                $request->session()->put('log_in', true);
                return redirect ('index');
            }
        }
        return back()->withErrors([
            'message' => 'Emails or password not correct!',
        ]);
    }

i want to show the name of the user who add the comment but he show me only the ID

Body:
Should be

return back()->with(['visiteur', $visitor]);


来源: stackexchange

问:
aggregate dataframe horizontally
I have the following data:

```<code>inputdata = [[1,'long',30.2,'Win'],[1,'long',-12.4,'Loss'],
            [2,'short',-12.3,'Loss'],[1,'long',3.2,'Win'],
            [3,'short',0.0,'B/E'],[3,'short',23.2,'Win'],
            [3,'long',3.2,'Win'],[4,'short',-4.2,'Loss']]
datadf = DataFrame(columns=['AssetId','Direction','PnL','W_L'], data = inputdata)

datadf

    AssetId Direction   PnL     W_L
0   1       long        30.2    Win
1   1       long       -12.4    Loss
2   2       short      -12.3    Loss
3   1       long        3.2     Win
4   3       short       0.0     B/E
5   3       short       23.2    Win
6   3       long        3.2     Win
7   4       short      -4.2     Loss
</code>```

Now I want to aggregate this further into a new dataframe that looks like this mock up (a few sample rows added, more stats to be added:

```<code>    Stat    Long    Short   Total
0   Trades  4       4       8
1   Won     3       1       4
2   Lost    1       2       3
    (...)
</code>```

I tried this:

```<code>datadf.groupby(['Direction'])['PnL'].count()
Direction
long     4
short    4
Name: PnL, dtype: int64
</code>```

This produces the necessary data, but I would have to fill my aggregation data frame field by field, which seems cumbersome and I am not even sure how to get the exact value into each row/column. Based on this example, is there a better way to achieve this goal?

答:
You can do crosstab:

```<code>pd.crosstab(df['W_L'], df['Direction'],margins=True, margins_name='Total')
</code>```

Output:

```<code>Direction  long  short  Total
W_L
B/E           0      1      1
Loss          1      2      3
Win           3      1      4
Total         4      4      8
</code>```

ContentLicense: CC BY-SA 4.0

Title: aggregate dataframe horizontally

Body:
I have the following data:

inputdata = [[1,'long',30.2,'Win'],[1,'long',-12.4,'Loss'],
            [2,'short',-12.3,'Loss'],[1,'long',3.2,'Win'],
            [3,'short',0.0,'B/E'],[3,'short',23.2,'Win'],
            [3,'long',3.2,'Win'],[4,'short',-4.2,'Loss']]
datadf = DataFrame(columns=['AssetId','Direction','PnL','W_L'], data = inputdata)

datadf

    AssetId Direction   PnL     W_L
0   1       long        30.2    Win
1   1       long       -12.4    Loss
2   2       short      -12.3    Loss
3   1       long        3.2     Win
4   3       short       0.0     B/E
5   3       short       23.2    Win
6   3       long        3.2     Win
7   4       short      -4.2     Loss

Now I want to aggregate this further into a new dataframe that looks like this mock up (a few sample rows added, more stats to be added:

    Stat    Long    Short   Total
0   Trades  4       4       8
1   Won     3       1       4
2   Lost    1       2       3
    (...)

I tried this:

datadf.groupby(['Direction'])['PnL'].count()
Direction
long     4
short    4
Name: PnL, dtype: int64

This produces the necessary data, but I would have to fill my aggregation data frame field by field, which seems cumbersome and I am not even sure how to get the exact value into each row/column. Based on this example, is there a better way to achieve this goal?

Body:
You can do crosstab:

pd.crosstab(df['W_L'], df['Direction'],margins=True, margins_name='Total')

Output:

Direction  long  short  Total
W_L
B/E           0      1      1
Loss          1      2      3
Win           3      1      4
Total         4      4      8


问:
How to add a list with a list of lists so that each index would be a list containing a an element and a list in python
I have two lists to start with.

Say I had a list like
ls_1 = ["2", "1", "2", "1"] and a second list which contains lists ls_2 = [[2, 7], [1, 2], [4, 6], [5,2]]

how would I combine them into:

```<code>final_ls = [["2", [2, 7]], ["1", [1, 2]], ["2", [4, 6]], ["1", [5, 2]]]
</code>```

where final_ls[0][0] would be "2"?
and final_ls[1][0] would be "1"?

I've tried to append the lists but that doesn't work

答:
zip(ls_1, ls_2) does almost what you specify.

There are various expressions which would convert that into something closer to the exact format requested. To get exactly the output specified in the question, you could use something like list(map(list, zip(ls_1, ls_2))) or [list(x) for x in zip(ls_1, ls_2)].

However, for many applications the 2-tuples will be the appropriate data type if you do not need to modify (e.g. append to) them, in which case simply list(zip(ls_1, ls_2)) will be adequate.

And if also you only intend to iterate over the sequence, then simply zip(ls_1, ls_2) will be sufficient in itself.  For example a loop for i, j in zip(ls_1, ls_2): will set i=2, j=[2,7] on the first iteration, i=1, j=[1,2] on the next iteration, etc.

The advantage of just using the plain zip, for large lists, is that you are not unnecessarily duplicating the data in memory; you are simply creating an iterator pointing to the inputs, which will get the relevant elements when needed.  The same is true of map(list, zip(ls_1, ls_2)) if you do indeed require them as 2-element lists, but only accessed by iterating over them (for lst in map(list, zip(ls_1, ls_2)):).

Body:
I have two lists to start with.

Say I had a list like
ls_1 = ["2", "1", "2", "1"] and a second list which contains lists ls_2 = [[2, 7], [1, 2], [4, 6], [5,2]]

how would I combine them into:

final_ls = [["2", [2, 7]], ["1", [1, 2]], ["2", [4, 6]], ["1", [5, 2]]]

where final_ls[0][0] would be "2"?
and final_ls[1][0] would be "1"?

I've tried to append the lists but that doesn't work


问:
Python - download video using web scraping
I'm trying to write a function that downloads a video using the webpage's url as an argument for practice. I basically have two questions.

First:
I am unable to find the iframe source with the following code in order to switch to it in Python. Are there any reasons or things I'm missing:

```<code>import requests
from bs4 import BeautifulSoup

url = 'https://fmovies.wtf/film/adventures-of-rufus-the-fantastic-pet.72o71'

r = requests.get(url)
soup = BeautifulSoup(r.content,'html.parser')

soup.find_all('iframe')
</code>```

Second:
While looking through the html of the website on Google Chrome I'm also unable to find the source of the video that I would need to use to download the video with. If you could suggest what I'm missing in order to find the video url that would work code that would be a great help:

```<code>import requests

def download_file(video_url):

    local_filename = 'potatoes.mp4'

    r = requests.get(url, stream=True)
    with open(local_filename, 'wb') as f:
        for chunk in r.iter_content(chunk_size=1024):
            if chunk: # filter out keep-alive new chunks
                f.write(chunk)

    return local_filename

download_file(**THIS IS WHERE THE VIDEO_URL WOULD GO**)
</code>```

Any help would be greatly appreciated steering my in the right direction as I'm pretty new to this.

答:
If you look at the source of the page view-source:https://fmovies.wtf/film/adventures-of-rufus-the-fantastic-pet.72o71 (Copy and paste it in Chrome Address Bar), you'll see that there is no iframe in Source, so it's probably being rendered into DOM by javascript at runtime.

Using requests you only get the serve-side-rendered source (the link which I shared above) and since iframe is not being rendered by Server bs4 will not be able to find it!

What should you do? Goto Selenium-based Web Scraping or dig through the Network Panel to see if you could find any API Request that is fetching the URL of the Iframe or any piece of code that is rendering that iframe into DOM.

TLDR; You can't scrape client-side rendered elements using requests library.

Body:
I'm trying to write a function that downloads a video using the webpage's url as an argument for practice. I basically have two questions.

First:
I am unable to find the iframe source with the following code in order to switch to it in Python. Are there any reasons or things I'm missing:

import requests
from bs4 import BeautifulSoup

url = 'https://fmovies.wtf/film/adventures-of-rufus-the-fantastic-pet.72o71'

r = requests.get(url)
soup = BeautifulSoup(r.content,'html.parser')

soup.find_all('iframe')

Second:
While looking through the html of the website on Google Chrome I'm also unable to find the source of the video that I would need to use to download the video with. If you could suggest what I'm missing in order to find the video url that would work code that would be a great help:

import requests

def download_file(video_url):

    local_filename = 'potatoes.mp4'

    r = requests.get(url, stream=True)
    with open(local_filename, 'wb') as f:
        for chunk in r.iter_content(chunk_size=1024):
            if chunk: # filter out keep-alive new chunks
                f.write(chunk)

    return local_filename

download_file(**THIS IS WHERE THE VIDEO_URL WOULD GO**)

Any help would be greatly appreciated steering my in the right direction as I'm pretty new to this.


问:
SYNTAX ERROR:GROUP BY clause cannot contain aggregations or window functions
```<code>select json_extract(other_detail,'$.is_substitute_allowed') as substitute,
       count(date(order_date)) as order_date
from prescription_metrics
group by 1;
</code>```

I am unable to group by over the extracted value from other_detail(which can be 0 or 1 only) in AWS Athena. 'other_detail' is a JSON while order_date is of type date. Error:

GROUP BY clause cannot contain aggregations or window functions.

The query works fine when not using GROUP BY

答:
A simple solution is to use a nested query:

```<code>select substitute, order_date from
(select json_extract(other_detail,'$.is_substitute_allowed') as substitute,
       count(date(order_date)) as order_date
from prescription_metrics)
group by 1;
</code>```

BTW, did you mean to have count(distinct(order_date)) or any other date manipulation (day ?) on the order_date column?

Body:
select json_extract(other_detail,'$.is_substitute_allowed') as substitute,
       count(date(order_date)) as order_date
from prescription_metrics
group by 1;

I am unable to group by over the extracted value from other_detail(which can be 0 or 1 only) in AWS Athena. 'other_detail' is a JSON while order_date is of type date. Error:

GROUP BY clause cannot contain aggregations or window functions.

The query works fine when not using GROUP BY

Body:
A simple solution is to use a nested query:

select substitute, order_date from
(select json_extract(other_detail,'$.is_substitute_allowed') as substitute,
       count(date(order_date)) as order_date
from prescription_metrics)
group by 1;

BTW, did you mean to have count(distinct(order_date)) or any other date manipulation (day ?) on the order_date column?


问:
'>' symbol whenever I try to copy results of a command to a variable
Whenever I try to save the command output to a variable terminal is stuck with a '>' symbol. I tried:

```<code>n=$(awk 'END{print NR}' 1.log')
</code>```

and
also

```<code>n="$(awk 'END{print NR}' 1.log')"
</code>```

Every time I have to break the execution using ctrl+c

what am I doing wrong here?

答:
Maybe a simple typo with a stray '.

Try this:

n=$(awk 'END{print NR}' 1.log)
```

The > is a prompt and an indication that bash is waiting for you to close the (stray) ' with a matching '.  The exact value printed is held in the PS2 variable.  The following is from the bash manual:

PS2    The  value of this parameter is expanded as with PS1 and used as the secondary prompt string.  The default is '> '.

Body:
Whenever I try to save the command output to a variable terminal is stuck with a '>' symbol. I tried:

n=$(awk 'END{print NR}' 1.log')

and
also

n="$(awk 'END{print NR}' 1.log')"

Every time I have to break the execution using ctrl+c

what am I doing wrong here?

Body:
Maybe a simple typo with a stray '.

Try this:

n=$(awk 'END{print NR}' 1.log)

The > is a prompt and an indication that bash is waiting for you to close the (stray) ' with a matching '.  The exact value printed is held in the PS2 variable.  The following is from the bash manual:

PS2    The  value of this parameter is expanded as with PS1 and used as the secondary prompt string.  The default is '> '.


问:
How to disable a Textfield in Material UI when used with Formik
I have a resulable Material UI textfield that I am using with my formik form -

```<code><Fieldname="reportType"
    label="Report Type"
    disabled
    as={TextFieldOutLined}
/>
</code>```

I want to make my reportType disabled. When I am passing disabled like above to my TextFieldOutLined it is not working.

Below is my TextFieldOutLined snippet.

```<code>const TextFieldOutLined = ({ label, disabled, ...props }) => {
    const classes = useStyles();

    const [field] = useField(props);
    return (
        <TextField
            className={classes.formControl}
            {...field}
            {...disabled}
</code>```

答:
You should pass disabled={disabled} to your TextField component to disable your TextField when the value of disabled prop is truthy.

<TextField
    className={classes.formControl}
    {...field}
    disabled={disabled}```

Body:
I have a resulable Material UI textfield that I am using with my formik form -

<Fieldname="reportType"
    label="Report Type"
    disabled
    as={TextFieldOutLined}
/>

I want to make my reportType disabled. When I am passing disabled like above to my TextFieldOutLined it is not working.

Below is my TextFieldOutLined snippet.

const TextFieldOutLined = ({ label, disabled, ...props }) => {
    const classes = useStyles();

    const [field] = useField(props);
    return (
        <TextField
            className={classes.formControl}
            {...field}
            {...disabled}


问:
Is it possible to use React Hooks outside of functional component, or i have to use mobx or redux?
I am new to React, and when I was reading about the docs, I found there were two ways to implement React components, functional-based and class-based. I know before React 16.8 it's not possible to manage state in functional components, but after that there is React Hooks.

The problem is, there seems to be one restriction for React Hooks, they can only be used inside functional components. Take a server-client as an example, which needs to change an isAuthenticated state while 401 received.

```<code>//client.js
import { useUserDispatch, signOut } from "auth";

export function request(url, args) {
  var dispatch = useUserDispatch();
  return fetch(url, args).then(response => {
  if (response.status === 401) {
    logout(dispatch);
  }
}
);

//auth.js
import React from "react";

var UserStateContext = React.createContext();
var UserDispatchContext = React.createContext();

function userReducer(state, action) {
  ...
}

function UserProvider({ children }) {
  var [state, dispatch] = React.useReducer(userReducer, {
    isAuthenticated: false,
  });

  return (
    <UserStateContext.Provider value={state}>
      <UserDispatchContext.Provider value={dispatch}>
        {children}
      </UserDispatchContext.Provider>
    </UserStateContext.Provider>
  );
}

function useUserState() {
  return React.useContext(UserStateContext);
}

function useUserDispatch() {
  return React.useContext(UserDispatchContext);
}

function signOut(dispatch) {
  dispatch({});
}

export { UserProvider, useUserState, useUserDispatch, loginUser, signOut };

</code>```

The client code above will produce error "Hooks can only be called inside of the body of a function component".
So maybe I have to move line var dispatch = useUserDispatch() upward to the component where request is called, and pass dispatch as props to request.
I feel this is not right, no only request is forced to care about some meaningless(to it) dispatch, but also this dispatch will spread everywhere a component needs to request.

For class-based components, this.state doesn't solve this problem either, but at least I can use mobx.

So are there some other ideal ways to solve this problem?

答:
When you are creating a hooks you must refer to the Rules of Hooks

You can only call hooks from a react functions.
Don’t call Hooks from regular JavaScript functions. Instead, you can:

✅ Call Hooks from React function components.
✅ Call Hooks from custom Hooks (learn about them on this page).

If you want to create a reusable hooks then you can create a custom hooks for your functions.
You can call as many functions inside a hooks.

For example, here I'm refactoring the request function as a hook.

```<code>export function useRequest(url, args) {
  var userDispatch = useUserDispatch();
  const fetcher = React.useCallback(() => {
    return new Promise((resolve, reject) =>
      fetch(url, args)
        .then((response) => {
          if (response.status === 401) {
            logout();
            reject();
          }

          resolve(response);
        })
        .catch(reject)
    );
  }, [url, args]);

  return [fetcher, userDispatch];
}
</code>```

and then consumes it.

```<code>function App() {
  const [fetch, userDispatch] = useRequest("/url", {});
  React.useEffect(() => {
    fetch().then((response) => {
      userDispatch({ type: "USER_REQUEST", payload: response });
    });
  }, []);
  return <div>Hello world</div>;
}
</code>```

Body:
I am new to React, and when I was reading about the docs, I found there were two ways to implement React components, functional-based and class-based. I know before React 16.8 it's not possible to manage state in functional components, but after that there is React Hooks.

The problem is, there seems to be one restriction for React Hooks, they can only be used inside functional components. Take a server-client as an example, which needs to change an isAuthenticated state while 401 received.

//client.js
import { useUserDispatch, signOut } from "auth";

export function request(url, args) {
  var dispatch = useUserDispatch();
  return fetch(url, args).then(response => {
  if (response.status === 401) {
    logout(dispatch);
  }
}
);

//auth.js
import React from "react";

var UserStateContext = React.createContext();
var UserDispatchContext = React.createContext();

function userReducer(state, action) {
  ...
}

function UserProvider({ children }) {
  var [state, dispatch] = React.useReducer(userReducer, {
    isAuthenticated: false,
  });

  return (
    <UserStateContext.Provider value={state}>
      <UserDispatchContext.Provider value={dispatch}>
        {children}
      </UserDispatchContext.Provider>
    </UserStateContext.Provider>
  );
}

function useUserState() {
  return React.useContext(UserStateContext);
}

function useUserDispatch() {
  return React.useContext(UserDispatchContext);
}

function signOut(dispatch) {
  dispatch({});
}

export { UserProvider, useUserState, useUserDispatch, loginUser, signOut };

The client code above will produce error "Hooks can only be called inside of the body of a function component".
So maybe I have to move line var dispatch = useUserDispatch() upward to the component where request is called, and pass dispatch as props to request.
I feel this is not right, no only request is forced to care about some meaningless(to it) dispatch, but also this dispatch will spread everywhere a component needs to request.

For class-based components, this.state doesn't solve this problem either, but at least I can use mobx.

So are there some other ideal ways to solve this problem?

Body:
When you are creating a hooks you must refer to the Rules of Hooks

You can only call hooks from a react functions.
Don’t call Hooks from regular JavaScript functions. Instead, you can:

✅ Call Hooks from React function components.
✅ Call Hooks from custom Hooks (learn about them on this page).

If you want to create a reusable hooks then you can create a custom hooks for your functions.
You can call as many functions inside a hooks.

For example, here I'm refactoring the request function as a hook.

export function useRequest(url, args) {
  var userDispatch = useUserDispatch();
  const fetcher = React.useCallback(() => {
    return new Promise((resolve, reject) =>
      fetch(url, args)
        .then((response) => {
          if (response.status === 401) {
            logout();
            reject();
          }

          resolve(response);
        })
        .catch(reject)
    );
  }, [url, args]);

  return [fetcher, userDispatch];
}

and then consumes it.

function App() {
  const [fetch, userDispatch] = useRequest("/url", {});
  React.useEffect(() => {
    fetch().then((response) => {
      userDispatch({ type: "USER_REQUEST", payload: response });
    });
  }, []);
  return <div>Hello world</div>;
}


问:
.NET DateTime to SqlDateTime Conversion
While converting .NET DateTime (when is default(DateTime)) to SqlDateTime should I always check if the .NET date is between SqlDateTime.MinValue and SqlDateTime.MaxValue [or] Is there a good way to do this.</p>

答:
on my quest to do this with entitie, i stumbled over here, just hitting back to post what i've found out...

when using EF4, "a sql's" datetime column can be filled from .NET's DateTime using BitConverter.

```<code>EntitieObj.thetime = BitConverter.GetBytes(DateTime.Now.ToBinary());
</code>```

also Fakrudeen's link brought me further... thank you.

ContentLicense: CC BY-SA 2.5

Title: .NET DateTime to SqlDateTime Conversion

Body:
on my quest to do this with entitie, i stumbled over here, just hitting back to post what i've found out...

when using EF4, "a sql's" datetime column can be filled from .NET's DateTime using BitConverter.

EntitieObj.thetime = BitConverter.GetBytes(DateTime.Now.ToBinary());

also Fakrudeen's link brought me further... thank you.

ContentLicense: CC BY-SA 3.0


问:
SQL Query to get 2nd most recent results with multiple columns
I am trying to obtain the 2nd most recent results for all distinct part_id's(based off of order_date) to go into a report I am working on making to compare it to the most recent results.

The commented sections are from another approach I was trying but unsuccessful with.

Any help is greatly appreciated!

(Side note: I am new to posting on SO, and I apologize in advance if this is answered elsewhere, but I was unable to find anything that pertained to this issue)

I am using the following query:

```<code>SELECT
                              PURCHASE_ORDER.ORDER_DATE
                            , PURC_ORDER_LINE.PART_ID
                            , PURCHASE_ORDER.VENDOR_ID
                            , PURC_ORDER_LINE.LINE_STATUS
                            , PURC_ORDER_LINE.ORDER_QTY
                            , PURC_ORDER_LINE.UNIT_PRICE
                            --, ROW_NUMBER() over (ORDER BY PURCHASE_ORDER.ORDER_DATE DESC)AS ROW
                            , CAST (PURC_ORDER_LINE.ORDER_QTY * PURC_ORDER_LINE.UNIT_PRICE AS VARCHAR) AS TOTAL_COST
                    FROM
                              PURCHASE_ORDER
                              INNER JOIN
                                        PURC_ORDER_LINE
                              ON
                                        PURCHASE_ORDER.ID = PURC_ORDER_LINE.PURC_ORDER_ID

                    WHERE PURCHASE_ORDER.ORDER_DATE < (SELECT MAX(ORDER_DATE) FROM PURCHASE_ORDER) AND PURC_ORDER_LINE.PART_ID = 'XXXX'
                    ORDER BY ORDER_dATE DESC

                    --WHERE PURC_ORDER_LINE.PART_ID = 'XXXX' and PURCHASE_ORDER.ORDER_DATE = (SELECT MAX(ORDER_DATE) FROM PURCHASE_ORDER WHERE ORDER_DATE < (SELECT MAX(ORDER_DATE) FROM PURCHASE_ORDER))
</code>```

EDIT 5/28 LATE NIGHT:

Lets say below is the data set I need the 2nd result from each part_id (2nd based off of ORDER_DATE DESC)

```<code>+-------------+---------+-----------+
| ORDER_DATE  | PART_ID | VENDOR_ID |
+-------------+---------+-----------+
| 2020-05-29  | XXXX    | CVVB      |
| 2020-05-27  | XXXX    | CVVB      |
| 2020-05-28  | XXXX    | CVVA      |
| 2020-05-28  | YYYY    | GGNB      |
| 2020-04-12  | YYYY    | GGNB      |
| 2020-02-08  | YYYY    | GGNB      |
| 2020-05-28  | ZZZZ    | LLNB      |
| 2019-10-28  | ZZZZ    | LLNB      |
| 2019-05-27  | ZZZZ    | OKIJ      |
+-------------+---------+-----------+
</code>```

I am looking to receive the following output (for more than 3 different part id's):

```<code>+------------+---------+-----------+
| ORDER_DATE | PART_ID | VENDOR_ID |
+------------+---------+-----------+
| 2020-05-28 | XXXX    | CVVA      |
| 2020-04-12 | YYYY    | GGNB      |
| 2019-10-28 | ZZZZ    | LLNB      |
+------------+---------+-----------+

</code>```

There are also additional columns in the query but formatting them as a table would have taken much longer. I have left off a few of the columns on the examples.

ANOTHER EDIT

I am not sure if this information helps, but I am trying to compare the most recent results to the previous results to show pricing and vendor differences. We are compiling the data into Report Builder; My approach here was to create 2 separate datasets one with the most recent and the other with the 2nd most recent and combine the data from the datasets in Report Builder. If there is an easier approach and I am heading in the wrong direction please let me know!

Example:

```<code>+------------+---------+-----------+-------------+----------+------------+
| ORDER_DATE | PART_ID | VENDOR_ID | Porder_Date | Ppart_ID | pVendor_id |
+------------+---------+-----------+-------------+----------+------------+
| 2020-05-29 | XXXX    | CVVB      | 2020-05-28  | XXXX     | CVVA       |
| 2020-05-28 | YYYY    | GGNB      | 2020-04-12  | YYYY     | GGNB       |
| 2020-05-28 | ZZZZ    | LLNB      | 2019-10-28  | ZZZZ     | LLNB       |
+------------+---------+-----------+-------------+----------+------------+
</code>```

EDIT THE NEXT MORNING

Thanks everyone for all the help! After Harry posted his solution I went ahead and made some tiny edits to get the columns I needed added on. I swapped his union portion with the original select statement. Everything here seems to be exactly what I am looking for!

Code:

```<code>;
WITH mycte AS
          (
                    SELECT
                              PURCHASE_ORDER.ORDER_DATE
                            , PURC_ORDER_LINE.PART_ID
                            , PURCHASE_ORDER.VENDOR_ID
                            , PURC_ORDER_LINE.LINE_STATUS
                            , PURC_ORDER_LINE.ORDER_QTY
                            , PURC_ORDER_LINE.UNIT_PRICE
                            , CAST (PURC_ORDER_LINE.ORDER_QTY * PURC_ORDER_LINE.UNIT_PRICE AS VARCHAR) AS TOTAL_COST
                    FROM
                              PURCHASE_ORDER
                              INNER JOIN
                                        PURC_ORDER_LINE
                              ON
                                        PURCHASE_ORDER.ID = PURC_ORDER_LINE.PURC_ORDER_ID
          )
        , mycte2 AS
          (
                    SELECT
                              CONVERT(DATE,order_date) AS order_date
                            , part_id
                            , vendor_id
                            , order_qty
                            , unit_price
                            , total_cost
                            , ROW_NUMBER() over(
                                      PARTITION BY part_id
                                      ORDER BY
                                                CONVERT(DATE,order_date) DESC) AS row_num
                    FROM
                              mycte
          )
SELECT
          mycte2.order_date
        , mycte2.part_id
        , mycte2.vendor_id
        , mycte2.order_qty
        , mycte2.unit_price
        , mycte2.total_cost
        , previous.order_date porder_date
        , previous.part_id    ppart_id
        , previous.vendor_id  pvendor_id
        , previous.order_qty  poqrder_qty
        , previous.unit_price punit_price
        , previous.total_cost ptotal_cost
FROM
          mycte2
          LEFT JOIN
                    mycte2 previous
          ON
                    previous.row_num   = mycte2.row_num +1
                    AND mycte2.part_id = previous.part_id
WHERE
          mycte2.row_num = 1
</code>```

答:
Based on the data you have provided, you can do this with a cte and row number function.

Note - it always helps to show the whole picture rather than just ask for the part you want help with (usually).. as it is easier to answer if we can understand the entire issue!

See code below

```<code>;with mycte as (

select
 '2020-05-29' as order_date  , 'XXXX'  as part_id   , 'CVVB' as vendor_id
 union all select
 '2020-05-27'  , 'XXXX'    , 'CVVB'
  union all select
 '2020-05-28'  , 'XXXX'    , 'CVVA'
  union all select
 '2020-05-28'  , 'YYYY'    , 'GGNB'
  union all select
 '2020-04-12'  , 'YYYY'    , 'GGNB'
  union all select
 '2020-02-08'  , 'YYYY'    , 'GGNB'
  union all select
 '2020-05-28'  , 'ZZZZ'    , 'LLNB'
  union all select
 '2019-10-28' , 'ZZZZ'    , 'LLNB'
  union all select
 '2019-05-27'  , 'ZZZZ'    , 'OKIJ'
 )
 , mycte2 as (
 Select
  convert(date,order_date) as order_date
 ,part_id
 ,vendor_id
 ,ROW_NUMBER() over( partition by part_id order by convert(date,order_date) desc) as row_num
 from mycte
)

Select
mycte2.order_date
,mycte2.part_id
,mycte2.vendor_id
,previous.order_date porder_date
,previous.part_id ppart_id
,previous.vendor_id pvendor_id
from  mycte2

 left join mycte2 previous
    on previous.row_num = mycte2.row_num +1
    and mycte2.part_id = previous.part_id

where mycte2.row_num = 1
</code>```

result

Body:
I am trying to obtain the 2nd most recent results for all distinct part_id's(based off of order_date) to go into a report I am working on making to compare it to the most recent results.

The commented sections are from another approach I was trying but unsuccessful with.

Any help is greatly appreciated!

(Side note: I am new to posting on SO, and I apologize in advance if this is answered elsewhere, but I was unable to find anything that pertained to this issue)

I am using the following query:

SELECT
                              PURCHASE_ORDER.ORDER_DATE
                            , PURC_ORDER_LINE.PART_ID
                            , PURCHASE_ORDER.VENDOR_ID
                            , PURC_ORDER_LINE.LINE_STATUS
                            , PURC_ORDER_LINE.ORDER_QTY
                            , PURC_ORDER_LINE.UNIT_PRICE
                            --, ROW_NUMBER() over (ORDER BY PURCHASE_ORDER.ORDER_DATE DESC)AS ROW
                            , CAST (PURC_ORDER_LINE.ORDER_QTY * PURC_ORDER_LINE.UNIT_PRICE AS VARCHAR) AS TOTAL_COST
                    FROM
                              PURCHASE_ORDER
                              INNER JOIN
                                        PURC_ORDER_LINE
                              ON
                                        PURCHASE_ORDER.ID = PURC_ORDER_LINE.PURC_ORDER_ID

                    WHERE PURCHASE_ORDER.ORDER_DATE < (SELECT MAX(ORDER_DATE) FROM PURCHASE_ORDER) AND PURC_ORDER_LINE.PART_ID = 'XXXX'
                    ORDER BY ORDER_dATE DESC

                    --WHERE PURC_ORDER_LINE.PART_ID = 'XXXX' and PURCHASE_ORDER.ORDER_DATE = (SELECT MAX(ORDER_DATE) FROM PURCHASE_ORDER WHERE ORDER_DATE < (SELECT MAX(ORDER_DATE) FROM PURCHASE_ORDER))

EDIT 5/28 LATE NIGHT:

Lets say below is the data set I need the 2nd result from each part_id (2nd based off of ORDER_DATE DESC)

+-------------+---------+-----------+
| ORDER_DATE  | PART_ID | VENDOR_ID |
+-------------+---------+-----------+
| 2020-05-29  | XXXX    | CVVB      |
| 2020-05-27  | XXXX    | CVVB      |
| 2020-05-28  | XXXX    | CVVA      |
| 2020-05-28  | YYYY    | GGNB      |
| 2020-04-12  | YYYY    | GGNB      |
| 2020-02-08  | YYYY    | GGNB      |
| 2020-05-28  | ZZZZ    | LLNB      |
| 2019-10-28  | ZZZZ    | LLNB      |
| 2019-05-27  | ZZZZ    | OKIJ      |
+-------------+---------+-----------+

I am looking to receive the following output (for more than 3 different part id's):

+------------+---------+-----------+
| ORDER_DATE | PART_ID | VENDOR_ID |
+------------+---------+-----------+
| 2020-05-28 | XXXX    | CVVA      |
| 2020-04-12 | YYYY    | GGNB      |
| 2019-10-28 | ZZZZ    | LLNB      |
+------------+---------+-----------+

There are also additional columns in the query but formatting them as a table would have taken much longer. I have left off a few of the columns on the examples.

ANOTHER EDIT

I am not sure if this information helps, but I am trying to compare the most recent results to the previous results to show pricing and vendor differences. We are compiling the data into Report Builder; My approach here was to create 2 separate datasets one with the most recent and the other with the 2nd most recent and combine the data from the datasets in Report Builder. If there is an easier approach and I am heading in the wrong direction please let me know!

Example:

+------------+---------+-----------+-------------+----------+------------+
| ORDER_DATE | PART_ID | VENDOR_ID | Porder_Date | Ppart_ID | pVendor_id |
+------------+---------+-----------+-------------+----------+------------+
| 2020-05-29 | XXXX    | CVVB      | 2020-05-28  | XXXX     | CVVA       |
| 2020-05-28 | YYYY    | GGNB      | 2020-04-12  | YYYY     | GGNB       |
| 2020-05-28 | ZZZZ    | LLNB      | 2019-10-28  | ZZZZ     | LLNB       |
+------------+---------+-----------+-------------+----------+------------+

EDIT THE NEXT MORNING

Thanks everyone for all the help! After Harry posted his solution I went ahead and made some tiny edits to get the columns I needed added on. I swapped his union portion with the original select statement. Everything here seems to be exactly what I am looking for!

Code:

;
WITH mycte AS
          (
                    SELECT
                              PURCHASE_ORDER.ORDER_DATE
                            , PURC_ORDER_LINE.PART_ID
                            , PURCHASE_ORDER.VENDOR_ID
                            , PURC_ORDER_LINE.LINE_STATUS
                            , PURC_ORDER_LINE.ORDER_QTY
                            , PURC_ORDER_LINE.UNIT_PRICE
                            , CAST (PURC_ORDER_LINE.ORDER_QTY * PURC_ORDER_LINE.UNIT_PRICE AS VARCHAR) AS TOTAL_COST
                    FROM
                              PURCHASE_ORDER
                              INNER JOIN
                                        PURC_ORDER_LINE
                              ON
                                        PURCHASE_ORDER.ID = PURC_ORDER_LINE.PURC_ORDER_ID
          )
        , mycte2 AS
          (
                    SELECT
                              CONVERT(DATE,order_date) AS order_date
                            , part_id
                            , vendor_id
                            , order_qty
                            , unit_price
                            , total_cost
                            , ROW_NUMBER() over(
                                      PARTITION BY part_id
                                      ORDER BY
                                                CONVERT(DATE,order_date) DESC) AS row_num
                    FROM
                              mycte
          )
SELECT
          mycte2.order_date
        , mycte2.part_id
        , mycte2.vendor_id
        , mycte2.order_qty
        , mycte2.unit_price
        , mycte2.total_cost
        , previous.order_date porder_date
        , previous.part_id    ppart_id
        , previous.vendor_id  pvendor_id
        , previous.order_qty  poqrder_qty
        , previous.unit_price punit_price
        , previous.total_cost ptotal_cost
FROM
          mycte2
          LEFT JOIN
                    mycte2 previous
          ON
                    previous.row_num   = mycte2.row_num +1
                    AND mycte2.part_id = previous.part_id
WHERE
          mycte2.row_num = 1

Body:
Based on the data you have provided, you can do this with a cte and row number function.

Note - it always helps to show the whole picture rather than just ask for the part you want help with (usually).. as it is easier to answer if we can understand the entire issue!

See code below

;with mycte as (

select
 '2020-05-29' as order_date  , 'XXXX'  as part_id   , 'CVVB' as vendor_id
 union all select
 '2020-05-27'  , 'XXXX'    , 'CVVB'
  union all select
 '2020-05-28'  , 'XXXX'    , 'CVVA'
  union all select
 '2020-05-28'  , 'YYYY'    , 'GGNB'
  union all select
 '2020-04-12'  , 'YYYY'    , 'GGNB'
  union all select
 '2020-02-08'  , 'YYYY'    , 'GGNB'
  union all select
 '2020-05-28'  , 'ZZZZ'    , 'LLNB'
  union all select
 '2019-10-28' , 'ZZZZ'    , 'LLNB'
  union all select
 '2019-05-27'  , 'ZZZZ'    , 'OKIJ'
 )
 , mycte2 as (
 Select
  convert(date,order_date) as order_date
 ,part_id
 ,vendor_id
 ,ROW_NUMBER() over( partition by part_id order by convert(date,order_date) desc) as row_num
 from mycte
)

Select
mycte2.order_date
,mycte2.part_id
,mycte2.vendor_id
,previous.order_date porder_date
,previous.part_id ppart_id
,previous.vendor_id pvendor_id
from  mycte2

 left join mycte2 previous
    on previous.row_num = mycte2.row_num +1
    and mycte2.part_id = previous.part_id

where mycte2.row_num = 1

result


问:
Apply one animation to multiple views at the same time
So Id like to rotate a handful of views all at the same time, all using the same rotation specs.  The issue is that for some reason the rotation acts differently for the second element.  Apparently this has to do with the animation object actually changing state in between those two lines of code.  Obviously I could just create a seperate Animation object and apply it, but I feel like there is an easier way (I have about 15 views)

Rotates only the first view correctly:

```<code>Animation rotateAnim = AnimationUtils.loadAnimation(this, R.anim.rotationtoportrait);
target.startAnimation(rotateAnim);
lightBtn.startAnimation(rotateAnim);
</code>```

Rotates both correctly

```<code>Animation rotateAnim = AnimationUtils.loadAnimation(this, R.anim.rotationtoportrait);
Animation rotateAnim2 = AnimationUtils.loadAnimation(this, R.anim.rotationtoportrait);
target.startAnimation(rotateAnim);
lightBtn.startAnimation(rotateAnim2);
</code>```

XML:

```<code><?xml version="1.0" encoding="utf-8"?>
<rotate
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="-90"
    android:toDegrees="0"
    android:pivotX="50%"
    android:pivotY="50%"
    android:duration="500" android:fillAfter="true">
</code>```

Anyone have any ideas?

答:
I was able to do this in Kotlin by programmatically creating one AnimatorSet.

1. Create an ArrayList of the views you want to animate

```<code> var viewList = arrayListOf(view1,view2,view3)
</code>```

2. Loop through the ArrayList and create a growing AnimatorSet

```<code>var ix = 0
var anim = AnimatorSet()
var viewList = arrayListOf(view1,view2,view3)
        viewList.forEach{
        // Initiate the animator set with one ObjectAnimator
            if(ix == 0){
                anim = AnimatorSet().apply {
                    play(ObjectAnimator.ofFloat(it, "rotation", 0F, 360F))
                }
            }
        // Add one ObjectAnimator at a time to the growing AnimatorSet
            else{
                var currentAnim = ObjectAnimator.ofFloat(it,"rotation",0F,360F)
                anim = AnimatorSet().apply {
                    play(anim).with(currentAnim)
                }
            }
            ix++
        }
</code>```

3. Start the animation

```<code>button.setOnClickListener {
            AnimatorSet().apply {
                play(anim)
                start()
            }
</code>```

Body:
So Id like to rotate a handful of views all at the same time, all using the same rotation specs.  The issue is that for some reason the rotation acts differently for the second element.  Apparently this has to do with the animation object actually changing state in between those two lines of code.  Obviously I could just create a seperate Animation object and apply it, but I feel like there is an easier way (I have about 15 views)

Rotates only the first view correctly:

Animation rotateAnim = AnimationUtils.loadAnimation(this, R.anim.rotationtoportrait);
target.startAnimation(rotateAnim);
lightBtn.startAnimation(rotateAnim);

Rotates both correctly

Animation rotateAnim = AnimationUtils.loadAnimation(this, R.anim.rotationtoportrait);
Animation rotateAnim2 = AnimationUtils.loadAnimation(this, R.anim.rotationtoportrait);
target.startAnimation(rotateAnim);
lightBtn.startAnimation(rotateAnim2);

XML:

<?xml version="1.0" encoding="utf-8"?>
<rotate
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="-90"
    android:toDegrees="0"
    android:pivotX="50%"
    android:pivotY="50%"
    android:duration="500" android:fillAfter="true">

Anyone have any ideas?

Body:
I was able to do this in Kotlin by programmatically creating one AnimatorSet.

1. Create an ArrayList of the views you want to animate

 var viewList = arrayListOf(view1,view2,view3)

2. Loop through the ArrayList and create a growing AnimatorSet

var ix = 0
var anim = AnimatorSet()
var viewList = arrayListOf(view1,view2,view3)
        viewList.forEach{
        // Initiate the animator set with one ObjectAnimator
            if(ix == 0){
                anim = AnimatorSet().apply {
                    play(ObjectAnimator.ofFloat(it, "rotation", 0F, 360F))
                }
            }
        // Add one ObjectAnimator at a time to the growing AnimatorSet
            else{
                var currentAnim = ObjectAnimator.ofFloat(it,"rotation",0F,360F)
                anim = AnimatorSet().apply {
                    play(anim).with(currentAnim)
                }
            }
            ix++
        }

3. Start the animation

button.setOnClickListener {
            AnimatorSet().apply {
                play(anim)
                start()
            }


问:
Is there any R function that visualize the interaction effect of IV regression?
I'm looking for a function for interaction effects visualization which has a correspondence with ivreg or plm. My model is 2sls with fixed effects but it seems there are no packages available for calculating interaction effects in R.

I'd be pleased if someone could solve my concern.

答:
You might want to have a look at interplot(). You can use this function to visualize e.g. the estimated coefficient of regressor X on outcome Y conditional on values of instrument Z by simply plugging in the fitted values from ivreg(). (The confidence intervals are trickier, but you are probably less interested in those in the first instance.)

https://cran.r-project.org/web/packages/interplot/vignettes/interplot-vignette.html


问:
#1064 - You have an error in your SQL syntax: MAX NULL problem
I'm new to MySQL and ran into a little trouble with a learning project I'm working on.

Whenever I try to create a table

SQL query:

```<code>CREATE TABLE IF NOT EXISTS `tweeter` (
`id` INT NULL,
`conversation_id` INT NULL,
`created_at` INT NULL,
`date` VARCHAR(MAX) NULL,
`time` VARCHAR(MAX) NULL,
`timezone` VARCHAR(MAX) NULL,
`user_id` INT NULL,
`username` VARCHAR(MAX) NULL,
`name` VARCHAR(MAX) NULL,
`place` VARCHAR(MAX) NULL,
`tweet` VARCHAR(MAX) NULL,
`mentions` JSON NULL,
`urls` JSON NULL,
`photos` JSON NULL,
`replies_count` INT NULL,
`retweets_count` INT NULL,
`likes_count` INT NULL,
`hashtags` JSON NULL,
`cashtags` JSON NULL,
`link` VARCHAR(MAX) NULL,
`retweet` BOOL NULL,
`quote_url` VARCHAR(MAX) NULL,
`video` INT NULL,
`near` VARCHAR(MAX) NULL,
`geo` VARCHAR(MAX) NULL,
`source` VARCHAR(MAX) NULL,
`user_rt_id` VARCHAR(MAX) NULL,
`user_rt` VARCHAR(MAX) NULL,
`retweet_id` VARCHAR(MAX) NULL,
`reply_to` JSON NULL,
`retweet_date` VARCHAR(MAX) NULL,
`translate` VARCHAR(MAX) NULL,
`trans_src` VARCHAR(MAX) NULL,
`trans_dest` VARCHAR(MAX) NULL )
</code>```

I get the following error message:

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'MAX) NULL,

```<code>`time` VARCHAR(MAX) NULL,
`timezone` VARCHAR(MAX) NULL,
`user_id` INT' at line 5
</code>```

Here is some info on what I'm working with

WAMPServer

Server type: MySQL

Server version: 8.0.18

phpMyAdmin: 4.9.2.

I've spent a day trying to solve this and now I think its time to ask for help.I was wondering if anyone can tell me what I'm doing wrong?

答:
There is no such thing as VARCHAR(MAX) in MySQL. You do need to specify an actual value. The actual limit is not set on the column itself but on the row, that should not be more than 64 kB.

You have a lot of VARCHAR columns, so this limit will matter here. Do not blindly set a high value on all your columns; instead, you should tune each column size according to the actually value it will store.

Also, consider using the proper datatypes rather than strings everywhere. Some of your string columns seem to be dates. For those, use the relevant date-like datatype (DATE, DATETIME, TIMESTAMP or TIME).

Body:
I'm new to MySQL and ran into a little trouble with a learning project I'm working on.

Whenever I try to create a table

SQL query:

CREATE TABLE IF NOT EXISTS `tweeter` (
`id` INT NULL,
`conversation_id` INT NULL,
`created_at` INT NULL,
`date` VARCHAR(MAX) NULL,
`time` VARCHAR(MAX) NULL,
`timezone` VARCHAR(MAX) NULL,
`user_id` INT NULL,
`username` VARCHAR(MAX) NULL,
`name` VARCHAR(MAX) NULL,
`place` VARCHAR(MAX) NULL,
`tweet` VARCHAR(MAX) NULL,
`mentions` JSON NULL,
`urls` JSON NULL,
`photos` JSON NULL,
`replies_count` INT NULL,
`retweets_count` INT NULL,
`likes_count` INT NULL,
`hashtags` JSON NULL,
`cashtags` JSON NULL,
`link` VARCHAR(MAX) NULL,
`retweet` BOOL NULL,
`quote_url` VARCHAR(MAX) NULL,
`video` INT NULL,
`near` VARCHAR(MAX) NULL,
`geo` VARCHAR(MAX) NULL,
`source` VARCHAR(MAX) NULL,
`user_rt_id` VARCHAR(MAX) NULL,
`user_rt` VARCHAR(MAX) NULL,
`retweet_id` VARCHAR(MAX) NULL,
`reply_to` JSON NULL,
`retweet_date` VARCHAR(MAX) NULL,
`translate` VARCHAR(MAX) NULL,
`trans_src` VARCHAR(MAX) NULL,
`trans_dest` VARCHAR(MAX) NULL )

I get the following error message:

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'MAX) NULL,

`time` VARCHAR(MAX) NULL,
`timezone` VARCHAR(MAX) NULL,
`user_id` INT' at line 5

Here is some info on what I'm working with

WAMPServer

Server type: MySQL

Server version: 8.0.18

phpMyAdmin: 4.9.2.

I've spent a day trying to solve this and now I think its time to ask for help.I was wondering if anyone can tell me what I'm doing wrong?


问:
how to convert csv into dict format
I have a.csv file as below:

```<code> OLD,NEW
 AA,XX
 BB,YY
 CC,ZZ
</code>```

I wanna convert it to dict format,
say dict1 = {'AA':'XX','BB':'YY','CC':'ZZ'}
Should I use DictReader or join string?

答:
```<code>with open('file.csv') as f:
    f.readline() # ignore first line (header)
    mydict = dict(csv.reader(f, delimiter=','))

print mydict
</code>```

Title: how to convert csv into dict format

Body:
I have a.csv file as below:

 OLD,NEW
 AA,XX
 BB,YY
 CC,ZZ

I wanna convert it to dict format,
say dict1 = {'AA':'XX','BB':'YY','CC':'ZZ'}
Should I use DictReader or join string?


问:
How to get Imageview location in android
I want to crop picture got from FrameLayout(@+id/previewFrame) as overlapped ImageView(@+id/guide_line_view) yellow guide line boundary.

I got ImageView location and cropped image what I got from previewFrame camera along the border of ImageView.

But imageview location is different from where it is visible, so cropped image not coincide with what I expect

ImageView(@+id/guide_line_view) is rectangle border xml like this

What's wrong with my crop. I searched stackoverflow, google 7 hours, but nothing helps.

@drawable/guide_line.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <stroke
        android:width="1dp"
        android:color="#FFFF00"
        android:dashGap="8dp"
        android:dashWidth="30dp"/>
    <corners android:radius="8dp" />
</shape>
</code>```

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="2">
        <FrameLayout
            android:id="@+id/previewFrame"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
        </FrameLayout>

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <ImageView
                android:id="@+id/guide_line_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="100dp"
                android:background="@drawable/guide_line"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHorizontal_bias="0.498"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Bring Here"
                android:textColor="#FFFF00"
                android:textSize="20sp"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/guide_line_view"
                app:layout_constraintVertical_bias="0.207" />
        </androidx.constraintlayout.widget.ConstraintLayout>

    </FrameLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/take"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="takePicture"
            tools:ignore="ButtonStyle" />

        <Button
            android:id="@+id/close"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="close"
            tools:ignore="ButtonStyle" />

    </LinearLayout>
</LinearLayout>
</code>```

To get imageview location

below guide variable asserted as global int

And I calculate at onWindowFocusChanged.

```<code>guide_left = imageview.getLeft();
guide_top = imageview.getTop();
guide_width = imageview.getWidth();
guide_height = imageview.getHeight();

</code>```

I've tried this as well. And so on.

```<code>int[] guide_location = new int[2];

imageview.getLocationOnScreen(guide_location);
int guide_left = guide_location[0];
int guide_top = guide_location[1];

</code>```

crop bitmap

```<code>public void takePicture() {
        cameraView.capture(new Camera.PictureCallback(){
            public void onPictureTaken(byte[] data, Camera camera){
                try {
                    Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                    Matrix matrix = new Matrix();
                    matrix.postRotate(90);
                    Bitmap r_bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);

                    // crop the image
                    Bitmap cropped_bitmap = Bitmap.createBitmap(r_bitmap, guide_left, guide_top, guide_width, guide_height);
</code>```

I save cropped_bitmap and check it is correct, but not.

答:
Supposed you take a picture in resolution 4096×2160 , and then set in previewFrame,
but if your device only have 1920x1080 resolution, the previewFrame only measure size in 1920x1080

As post you want to crop the specified rect from the orgin picture , you need to scale the crop ratio up
from 1920x1080 to 4096x2160

--- Try below ---

```<code>Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
Matrix matrix = new Matrix();
matrix.postRotate(90);
Bitmap r_bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);

// scaled ratio
float ratio = 1f * bitmap.getWidth() / previewFrame.width;

// crop the image
Bitmap cropped_bitmap = Bitmap.createBitmap(r_bitmap,
    (int) (guide_left * ratio),
    (int) (guide_top * ratio),
    (int) (guide_width * ratio),
    (int) (guide_height * ratio));
</code>```

Body:
I want to crop picture got from FrameLayout(@+id/previewFrame) as overlapped ImageView(@+id/guide_line_view) yellow guide line boundary.

I got ImageView location and cropped image what I got from previewFrame camera along the border of ImageView.

But imageview location is different from where it is visible, so cropped image not coincide with what I expect

ImageView(@+id/guide_line_view) is rectangle border xml like this

What's wrong with my crop. I searched stackoverflow, google 7 hours, but nothing helps.

@drawable/guide_line.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <stroke
        android:width="1dp"
        android:color="#FFFF00"
        android:dashGap="8dp"
        android:dashWidth="30dp"/>
    <corners android:radius="8dp" />
</shape>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="2">
        <FrameLayout
            android:id="@+id/previewFrame"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
        </FrameLayout>

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <ImageView
                android:id="@+id/guide_line_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="100dp"
                android:background="@drawable/guide_line"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHorizontal_bias="0.498"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Bring Here"
                android:textColor="#FFFF00"
                android:textSize="20sp"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/guide_line_view"
                app:layout_constraintVertical_bias="0.207" />
        </androidx.constraintlayout.widget.ConstraintLayout>

    </FrameLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/take"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="takePicture"
            tools:ignore="ButtonStyle" />

        <Button
            android:id="@+id/close"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="close"
            tools:ignore="ButtonStyle" />

    </LinearLayout>
</LinearLayout>

To get imageview location

below guide variable asserted as global int

And I calculate at onWindowFocusChanged.

guide_left = imageview.getLeft();
guide_top = imageview.getTop();
guide_width = imageview.getWidth();
guide_height = imageview.getHeight();

I've tried this as well. And so on.

int[] guide_location = new int[2];

imageview.getLocationOnScreen(guide_location);
int guide_left = guide_location[0];
int guide_top = guide_location[1];

crop bitmap

public void takePicture() {
        cameraView.capture(new Camera.PictureCallback(){
            public void onPictureTaken(byte[] data, Camera camera){
                try {
                    Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                    Matrix matrix = new Matrix();
                    matrix.postRotate(90);
                    Bitmap r_bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);

                    // crop the image
                    Bitmap cropped_bitmap = Bitmap.createBitmap(r_bitmap, guide_left, guide_top, guide_width, guide_height);

I save cropped_bitmap and check it is correct, but not.

Body:
Supposed you take a picture in resolution 4096×2160 , and then set in previewFrame,
but if your device only have 1920x1080 resolution, the previewFrame only measure size in 1920x1080

As post you want to crop the specified rect from the orgin picture , you need to scale the crop ratio up
from 1920x1080 to 4096x2160

--- Try below ---

Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
Matrix matrix = new Matrix();
matrix.postRotate(90);
Bitmap r_bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);

// scaled ratio
float ratio = 1f * bitmap.getWidth() / previewFrame.width;

// crop the image
Bitmap cropped_bitmap = Bitmap.createBitmap(r_bitmap,
    (int) (guide_left * ratio),
    (int) (guide_top * ratio),
    (int) (guide_width * ratio),
    (int) (guide_height * ratio));


问:
How does pushState protect against potential content forgeries?
As seen in GitHub's blog, they've implemented HTML5's JavaScript pushState feature for tree browsing (for modern browsers), bringing AJAX navigation without Hash Bangs.

The code is simple:

```<code>$('#slider a').click(function() {
  history.pushState({ path: this.path }, '', this.href)
  $.get(this.href, function(data) {
    $('#slider').slideTo(data)
  })
  return false
})
</code>```

This quite elegantly allows them to:

Request the just the new content through AJAX instead of a full page

Animate the transition

And change the browsers URL (not just the #, as Twitter does — twitter.com/stackexchange → twitter.com/#!/stackexchange )

My question is, how does JavaScript prevent against the use of pushState by one website to imitate another, resulting in a convincing phishing attack?

At the very least it seems that the domain can't be changed, but what about multiple paths within a site, potentially by multiple unrelated and untrusting content providers?  Could one path (I.E. /joe) essentially imitate another (pushState /jane) and provide imitative content, with possibly malicious purposes?

答:
My understanding is that this is perfectly consistent with the Same Origin Policy that governs XMLHttpRequest, setting cookies, and various other browser functions. The assumption is that if it's on the same domain + protocol + port, it's a trusted resource. Usually, as a web developer, that's what you want (and need) in order for your AJAX scripts to work and your cookies to be readable throughout your site. If you are running a site where users can post content, it's your job, not the browser's, to make sure they can't phish or keylog each other's visitors.

Here's some more detail on what the FireFox folks are thinking about pushState - it doesn't seem like this is an issue for them. There's another discussion of a possible pushState security hole here, but it's a different concern, about being able to hide a malicious querystring on the end of someone else's URL.

Body:
As seen in GitHub's blog, they've implemented HTML5's JavaScript pushState feature for tree browsing (for modern browsers), bringing AJAX navigation without Hash Bangs.

The code is simple:

$('#slider a').click(function() {
  history.pushState({ path: this.path }, '', this.href)
  $.get(this.href, function(data) {
    $('#slider').slideTo(data)
  })
  return false
})

This quite elegantly allows them to:

Request the just the new content through AJAX instead of a full page

Animate the transition

And change the browsers URL (not just the #, as Twitter does — twitter.com/stackexchange → twitter.com/#!/stackexchange )

My question is, how does JavaScript prevent against the use of pushState by one website to imitate another, resulting in a convincing phishing attack?

At the very least it seems that the domain can't be changed, but what about multiple paths within a site, potentially by multiple unrelated and untrusting content providers?  Could one path (I.E. /joe) essentially imitate another (pushState /jane) and provide imitative content, with possibly malicious purposes?


问:
How remove "api" from route - Azure Functions v3 -- host.json routePrefix empty string doesn't work
I'm trying to remove the "api" prefix in my URL.

This is my host.json.

```<code>{
  "version": "2.0",
  "extensions":   {
    "http":     {
      "routePrefix": ""
    }
  }
}
</code>```

NOTE: if I change "routePrefix" : "foo", it works.
It seems that the string.empty is causing the problem.

This is my startup.cs code:

```<code>public class Startup : FunctionsStartup
{
    public override void Configure(IFunctionsHostBuilder builder)
    {

        var serviceProvider = builder.Services.BuildServiceProvider();
        var existingConfig = serviceProvider.GetService<IConfiguration>();

        var config = new ConfigurationBuilder()
            .AddEnvironmentVariables()
            .AddConfiguration(existingConfig)
            .Build();

        builder.Services.AddSingleton<IConfiguration>(configRoot);
        services.BuildServiceProvider(true);

    }
}
</code>```

Note that I am already adding the existing configuration to the builder, as per documentation in here:

https://github.com/Azure/azure-functions-host/issues/4363

https://github.com/Azure/azure-functions-durable-extension/issues/894

And this issue, someone else also reported the same problem as me. But the ticket is closed...

https://github.com/Azure/azure-functions-host/issues/5466

What else am I missing or doing wrong?

aside: if I comment out this line, then the URL with api also works.
            builder.Services.AddSingleton(configRoot);

答:
My problem is this line:

```<code>builder.Services.AddSingleton<IConfiguration>(configRoot);
</code>```

We had this line of code in our project because we were passing in IConfiguration directly to our classes. However, we didn't actually need it, as we are now using IOptions for passing in our typed configuration settings.

FYI: These are the nuget packages

Body:
I'm trying to remove the "api" prefix in my URL.

This is my host.json.

{
  "version": "2.0",
  "extensions":   {
    "http":     {
      "routePrefix": ""
    }
  }
}

NOTE: if I change "routePrefix" : "foo", it works.
It seems that the string.empty is causing the problem.

This is my startup.cs code:

public class Startup : FunctionsStartup
{
    public override void Configure(IFunctionsHostBuilder builder)
    {

        var serviceProvider = builder.Services.BuildServiceProvider();
        var existingConfig = serviceProvider.GetService<IConfiguration>();

        var config = new ConfigurationBuilder()
            .AddEnvironmentVariables()
            .AddConfiguration(existingConfig)
            .Build();

        builder.Services.AddSingleton<IConfiguration>(configRoot);
        services.BuildServiceProvider(true);

    }
}

Note that I am already adding the existing configuration to the builder, as per documentation in here:

https://github.com/Azure/azure-functions-host/issues/4363

https://github.com/Azure/azure-functions-durable-extension/issues/894

And this issue, someone else also reported the same problem as me. But the ticket is closed...

https://github.com/Azure/azure-functions-host/issues/5466

What else am I missing or doing wrong?

aside: if I comment out this line, then the URL with api also works.
            builder.Services.AddSingleton(configRoot);

Body:
My problem is this line:

builder.Services.AddSingleton<IConfiguration>(configRoot);

We had this line of code in our project because we were passing in IConfiguration directly to our classes. However, we didn't actually need it, as we are now using IOptions for passing in our typed configuration settings.

FYI: These are the nuget packages


问:
How to use a Laravel Collection as both object and array?
I am doing this:

$product = new \Illuminate\Database\Eloquent\Collection($product_array);

But it works as an array not as an object like $product->subscription won't work, but $product['subscription'] would work.

答:
```<code>$product = (object) $product_array;
$product->subscription;
</code>```

Example :

```<code>$product_arr = [
   'name' => 'bag',
   'qty' => 4,
];

$product = (object) $product_arr;
$product->name; // result = bag
</code>```

Body:
$product = (object) $product_array;
$product->subscription;

Example :

$product_arr = [
   'name' => 'bag',
   'qty' => 4,
];

$product = (object) $product_arr;
$product->name; // result = bag


问:
Numpy Lambda Function Not Working as Expected
market['AAPL'] is a dataframe with Apple's daily stock return

I noticed that:

```<code>market['AAPL'].apply(lambda x: np.exp(x))

market['AAPL'].apply(lambda x: np.cumprod(np.exp(x)))
</code>```

Both give the same results
Why is the np.cumprod not working?

答: Because x is a number, it's np.exp is a number, and a product of one number is itself.

Body:
market['AAPL'] is a dataframe with Apple's daily stock return

I noticed that:

market['AAPL'].apply(lambda x: np.exp(x))

market['AAPL'].apply(lambda x: np.cumprod(np.exp(x)))

Both give the same results
Why is the np.cumprod not working?


问:
Can't fill the height of the window with my navbar
I'm having this problem with the menu in my code.
I wanted to do a navbar that on the PC screen fill the height on the left side, and make it scrolleable on the top in mobile version.

The problem is that my flex container doesn't fill the height of the screen,it's getting off on the bottom..
Here's my code:

/* css */

body {
  margin: 0;
}

#main-doc {
  width: 100%;
  display: flex;
  flex-flow: row wrap;
}

#container-nav {
  position: fixed;
  height: 100%;
  width: 13.35em;
  display: flex;
  flex-direction: column;
  background-color: red;
}

#nav-header {
  flex-grow: 1;
  flex-shrink: 1;
  flex-basis: auto;
}

.nav-link {
  flex-grow: 1;
  flex-shrink: 1;
  flex-basis: auto;
  background: green;
}

#container-nav {
  padding: 1em;
  display: flex;
  flex-direction: column;
}

@media screen and (max-width: 780px) {
  #container-nav {
    position: absolute;
    width: 100%;
    padding: 0;
    overflow-y: scroll;
    height: 20%;
    border-right: none;
  }
  #main-doc {
    display: flex;
    flex-flow: column wrap;
  }
  #nav-header {
    flex: 0;
  }
  .nav-link {
    flex: 0;
    padding: 1em;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- html -->
<main id="main-doc">

  <nav id="navbar">
    <div id="container-nav">
      <header class="nav-link" id="nav-header">Flexbox Documentation</header>

      About
      Basics
      Flex Container Properties
      Flex Items Properties
      Examples

    </div>
  </nav>
</main></code>```

答:
The problem of making a column full-height is related to the 'Holy Grail' layout and has been solved by flexbox and grid for a while.

But as mentioned, top-most container should be set to min-height: 100vh for this to work. Use min-height instead of height to allow the element to extend if required.

Additionally, I've cleaned up that HTML by a) removing unnecessary elements, classes and ids, b) moving the header outside of the nav and c) putting your nav links into a ul with correct href attributes instead of src.

body {
  margin: 0;
  min-height: 100vh;
  display: flex;
  flex-direction: row;
}

a {
  color: inherit;
}

h1 {
  font-size: 1.25rem;
  margin: 1rem 0;
}

nav {
  background-color: red;
  padding: 2rem;
}
nav ul {
  list-style: none;
  padding: 0;
  display: flex;
  flex-direction: column;
}
nav li {
  margin: 0 1rem 1rem 0;
}
nav a {
  background-color: green;
}

main {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 2rem;
}
main p {
  height: 200rem;
}

@media screen and (max-width: 780px) {

  body {
    flex-direction: column;
  }
  nav ul {
    flex-direction: row;
  }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>

  <header></header>

  <nav>
    <h1>Flexbox Documentation</h1>
    <ul>
      <li>About</li>
      <li>Basics</li>
      <li>Flex Container Properties</li>
      <li>Flex Items Properties</li>
      <li>Examples</li>
    </ul>
  </nav>

  <main>
    <p>Main content</p>
  </main>

</body></code>```

Body:
I'm having this problem with the menu in my code.
I wanted to do a navbar that on the PC screen fill the height on the left side, and make it scrolleable on the top in mobile version.

The problem is that my flex container doesn't fill the height of the screen,it's getting off on the bottom..
Here's my code:

/* css */

body {
  margin: 0;
}

#main-doc {
  width: 100%;
  display: flex;
  flex-flow: row wrap;
}

#container-nav {
  position: fixed;
  height: 100%;
  width: 13.35em;
  display: flex;
  flex-direction: column;
  background-color: red;
}

#nav-header {
  flex-grow: 1;
  flex-shrink: 1;
  flex-basis: auto;
}

.nav-link {
  flex-grow: 1;
  flex-shrink: 1;
  flex-basis: auto;
  background: green;
}

#container-nav {
  padding: 1em;
  display: flex;
  flex-direction: column;
}

@media screen and (max-width: 780px) {
  #container-nav {
    position: absolute;
    width: 100%;
    padding: 0;
    overflow-y: scroll;
    height: 20%;
    border-right: none;
  }
  #main-doc {
    display: flex;
    flex-flow: column wrap;
  }
  #nav-header {
    flex: 0;
  }
  .nav-link {
    flex: 0;
    padding: 1em;
  }
}

      Flexbox Documentation

      About
      Basics
      Flex Container Properties
      Flex Items Properties
      Examples

Body:
The problem of making a column full-height is related to the 'Holy Grail' layout and has been solved by flexbox and grid for a while.

But as mentioned, top-most container should be set to min-height: 100vh for this to work. Use min-height instead of height to allow the element to extend if required.

Additionally, I've cleaned up that HTML by a) removing unnecessary elements, classes and ids, b) moving the header outside of the nav and c) putting your nav links into a ul with correct href attributes instead of src.

body {
  margin: 0;
  min-height: 100vh;
  display: flex;
  flex-direction: row;
}

a {
  color: inherit;
}

h1 {
  font-size: 1.25rem;
  margin: 1rem 0;
}

nav {
  background-color: red;
  padding: 2rem;
}
nav ul {
  list-style: none;
  padding: 0;
  display: flex;
  flex-direction: column;
}
nav li {
  margin: 0 1rem 1rem 0;
}
nav a {
  background-color: green;
}

main {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 2rem;
}
main p {
  height: 200rem;
}

@media screen and (max-width: 780px) {

  body {
    flex-direction: column;
  }
  nav ul {
    flex-direction: row;
  }

}

<body>

  <header></header>

  <nav>
    <h1>Flexbox Documentation</h1>
    <ul>
      <li><a href="#">About</a></li>
      <li><a href="#">Basics</a></li>
      <li><a href="#">Flex Container Properties</a></li>
      <li><a href="#">Flex Items Properties</a></li>
      <li><a href="#">Examples</a></li>
    </ul>
  </nav>

  <main>
    <p>Main content</p>
  </main>

</body>


问:
PHP EOF shows only one result from loop
I am using in my PHP EOF.

The problem is that it does display only one item coming from a mySQL loop.

It shows only the last result.

Is this necessary in EOF? or can I avoid this issue?

Thanks

```<code>function getYiBAdminBanner() {
global $site;
global $dir;
$queryYiBmenu = "SELECT * FROM `(YiB)_cPanel_Menu` WHERE Type = 'top'";
$resultYiBmenu=mysql_query($queryYiBmenu) or die("Errore select menu: ".mysql_error());
$countYiBmenu = mysql_num_rows($resultYiBmenu);
while($rowYiBmenu = mysql_fetch_array($resultYiBmenu)) {
$menu = "<div id=\"menu\" style=\"display:none;\"><li><a href=\"".$site['url'].$rowYiBmenu['linkHref']."\" onMouseOut=\"javascript: $('#menu').hide('9000');\"><img class=\"imgmenu\" src=\"".$site['url'].$rowYiBmenu['linkIcon']."\">".$rowYiBmenu['linkTitle']."</a></li></div>";
}
if($countYiBmenu <= 0){
$menu = "No Modules Installed";
}
$bannerCode .= <<<EOF
<div style="width:520px; background-color: #EEE; height:30px;">
{$menu}
</div>
EOF;
return $bannerCode;
}
</code>```

答:
Edit: based on your code sample: try $menu .= <your result> or $menu = $menu . <your result> rather than $menu = <your result>. But its unclear if you are expecting multiple results or not

If you are looping through the results of a mySQL query you should be doing something like this:

```<code>$query = sprintf("SELECT firstname, lastname, address, age FROM friends WHERE firstname='%s' AND lastname='%s'",
    mysql_real_escape_string($firstname),
    mysql_real_escape_string($lastname));

// Perform Query
$result = mysql_query($query);

while ($row = mysql_fetch_assoc($result)) {
    echo $row['firstname'];
    echo $row['lastname'];
    echo $row['address'];
    echo $row['age'];
}
</code>```

http://php.net/manual/en/function.mysql-query.php

If you are looping through the contents of a file you should be doing something like this:

```<code><?php
$file = fopen("welcome.txt", "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
while(!feof($file))
  {
  echo fgets($file). "<br />";
  }
fclose($file);
?>
</code>```

http://www.w3schools.com/php/php_file.asp

php manual fopen

I hope that helps but your question isn't very clear on how/where your using EOF.

Title: PHP EOF shows only one result from loop

Body:
I am using in my PHP EOF.

The problem is that it does display only one item coming from a mySQL loop.

It shows only the last result.

Is this necessary in EOF? or can I avoid this issue?

Thanks

function getYiBAdminBanner() {
global $site;
global $dir;
$queryYiBmenu = "SELECT * FROM `(YiB)_cPanel_Menu` WHERE Type = 'top'";
$resultYiBmenu=mysql_query($queryYiBmenu) or die("Errore select menu: ".mysql_error());
$countYiBmenu = mysql_num_rows($resultYiBmenu);
while($rowYiBmenu = mysql_fetch_array($resultYiBmenu)) {
$menu = "

".$rowYiBmenu['linkTitle']."

";
}
if($countYiBmenu <= 0){
$menu = "No Modules Installed";
}
$bannerCode .= <<<EOF

{$menu}

EOF;
return $bannerCode;
}

Body:
Edit: based on your code sample: try $menu .= <your result> or $menu = $menu . <your result> rather than $menu = <your result>. But its unclear if you are expecting multiple results or not

If you are looping through the results of a mySQL query you should be doing something like this:

$query = sprintf("SELECT firstname, lastname, address, age FROM friends WHERE firstname='%s' AND lastname='%s'",
    mysql_real_escape_string($firstname),
    mysql_real_escape_string($lastname));

// Perform Query
$result = mysql_query($query);

while ($row = mysql_fetch_assoc($result)) {
    echo $row['firstname'];
    echo $row['lastname'];
    echo $row['address'];
    echo $row['age'];
}

http://php.net/manual/en/function.mysql-query.php

If you are looping through the contents of a file you should be doing something like this:

<?php
$file = fopen("welcome.txt", "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
while(!feof($file))
  {
  echo fgets($file). "<br />";
  }
fclose($file);
?>

http://www.w3schools.com/php/php_file.asp

php manual fopen

I hope that helps but your question isn't very clear on how/where your using EOF.


问:
Can I replace just one string despite the existence of other strings with similar values in R
I’m learning R. I want to replace a “0” string in a column of a data frame to NA value. This column  has other strings with “0” values include in them.

I’ve used:

```<code>For(n in 1:nrow(d2)) {
  If(grepl(“0”, d2[n,10]) == TRUE)
  d2[n,10] <- NA
</code>```

And it work but it replace every strings that has a “0” (that column was a large answer question) many other strings had “0” in them with other information, but I don’t want to replace them, just the ones that have exclusively “0” in the cell.

If anyone knows how to exclusively replace the cells with “0” values, please help :(

答:
The grep/grepl is vectorized.  So, we can create a logical vector directly on the column and change it to NA

```<code>d2[,10][grepl("^0$", d2[,10])] <- NA
</code>```

Or do a fixed match

```<code>d2[,10][d2[,10] == '0'] <- NA
</code>```

Body:
I’m learning R. I want to replace a “0” string in a column of a data frame to NA value. This column  has other strings with “0” values include in them.

I’ve used:

For(n in 1:nrow(d2)) {
  If(grepl(“0”, d2[n,10]) == TRUE)
  d2[n,10] <- NA

And it work but it replace every strings that has a “0” (that column was a large answer question) many other strings had “0” in them with other information, but I don’t want to replace them, just the ones that have exclusively “0” in the cell.

If anyone knows how to exclusively replace the cells with “0” values, please help :(

Body:
The grep/grepl is vectorized.  So, we can create a logical vector directly on the column and change it to NA

d2[,10][grepl("^0$", d2[,10])] <- NA

Or do a fixed match

d2[,10][d2[,10] == '0'] <- NA


问:
With set -e, exit status of command following ! is lost in an if block
```<code>set -e
if ! some_command; then
  RET=$?
  if [[ $RET == 255 ]]; then
    ...do something handling...
  fi
fi
</code>```

guess what happened?
the RET will always be 0, regardless the some_command returns non-zero value.

Is this by design? I can not believe it.

答:
Yes, it is by design (and has nothing to do with set -e); ! negates the exit status of pipeline it precedes. However, the exit statuses of pipeline components can be found in PIPESTATUS variable, for example:

```<code>set -e
if ! some_command; then
  ret=$PIPESTATUS
  # do something with ret ...
fi
</code>```

Proof of concept:

```<code>$ ! (exit 42)
$ echo $?,$PIPESTATUS
0,42
$
</code>```

Body:
set -e
if ! some_command; then
  RET=$?
  if [[ $RET == 255 ]]; then
    ...do something handling...
  fi
fi

guess what happened?
the RET will always be 0, regardless the some_command returns non-zero value.

Is this by design? I can not believe it.

Body:
Yes, it is by design (and has nothing to do with set -e); ! negates the exit status of pipeline it precedes. However, the exit statuses of pipeline components can be found in PIPESTATUS variable, for example:

set -e
if ! some_command; then
  ret=$PIPESTATUS
  # do something with ret ...
fi

Proof of concept:

$ ! (exit 42)
$ echo $?,$PIPESTATUS
0,42
$


问:
How to fix "Unexpected end of JSON input" thrown on sending a POST request to the server using fetch?
I have a simple chatbox UI that is integrated into a chatbot developed using .netcore.

SyntaxError: Unexpected end of JSON input

  (anonymous) @ im.html:201

I'm thrown with this error after having a couple of conversations with the bot. Below is the input box I'm using to capture the text message.

```<code><form action="javascript:void(0);" class="bg-light" autocomplete="off">
  <div class="input-group">
    <input type="text" placeholder="Type a message" aria-describedby="button-addon2" class="form-control rounded-0 border-0 py-4" id="message">
    <div class="input-group-append">
      <button id="button-addon2" type="submit" class="btn btn-link" onclick="userMessage()"> <i class="fa fa-paper-plane"></i></button>
    </div>
  </div>
</form>
</code>```

When the user hits enter, I'm displaying the typed message in the UI and sending a POST request to the server to get a response.

```<code> // User message layout
function userMessage() {
    var spinner = document.getElementById('textSpinner');
    var h5 = document.getElementById("h5");
    var inputBox = document.getElementById("message");
    var p = document.createElement("p");
    var inputValue = inputBox.value;
    var text = document.createTextNode(inputValue);
    p.appendChild(text);

    if (inputValue === '' || !h5.innerText) {
        alert("Please sart the session first!");
    } else {
        var div = document.createElement("div");
        div.className = "media";

          /.../

        var chatArea = document.getElementById('chat-area')
        chatArea.scrollIntoView({ behavior: 'smooth', block: 'end' })
        spinner.style.display = "none";
        interact(h5.innerText, inputValue);
    }
    inputBox.value = "";
}
</code>```

Below is the POST request

```<code>   // POST user message
   function interact(userId, message) {
    var spinner = document.getElementById('textSpinner');
    spinner.style.display = "block";
    const payload = {
        userId: userId,
        utterance: message
    };

    fetch('Sessions/Interact', {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(payload)
    })
        .then(response => response.json())
        .then(data => botMessage(data.Message))
        .then(() => spinner.style.display = "none")
        .catch(error => console.error(error));
    }
</code>```

When I get the response from the server, I'm calling another function called botMessage() which is similar to the userMessage() that will display the bot message.
Can someone guide me as to why this error is thrown and is there any solution to fix this issue?
Thanks in advance.

Here is the response body from the server.

```<code>{
  "Message": "Hello, It's me. Let's start chatting shall we?",
  "Data": null
}
</code>```

答:
I changed the response handling as below. Is this approach I'm doing is correct? Please correct me if i'm wrong.    </p>

```<code>.then(response => {
      if (response.status === 200) {
         return response.json()
         .then(data => botMessage(data.Message))
      } else if (response.status === 204) {
         return;
      }
    })
    .then(() => spinner.style.display = "none")
    .catch(error => console.error(error));
</code>```

Body:
I have a simple chatbox UI that is integrated into a chatbot developed using .netcore.

SyntaxError: Unexpected end of JSON input

  (anonymous) @ im.html:201

I'm thrown with this error after having a couple of conversations with the bot. Below is the input box I'm using to capture the text message.

<form action="javascript:void(0);" class="bg-light" autocomplete="off">

    <input type="text" placeholder="Type a message" aria-describedby="button-addon2" class="form-control rounded-0 border-0 py-4" id="message">

      <button id="button-addon2" type="submit" class="btn btn-link" onclick="userMessage()"> </button>

</form>

When the user hits enter, I'm displaying the typed message in the UI and sending a POST request to the server to get a response.

 // User message layout
function userMessage() {
    var spinner = document.getElementById('textSpinner');
    var h5 = document.getElementById("h5");
    var inputBox = document.getElementById("message");
    var p = document.createElement("p");
    var inputValue = inputBox.value;
    var text = document.createTextNode(inputValue);
    p.appendChild(text);

    if (inputValue === '' || !h5.innerText) {
        alert("Please sart the session first!");
    } else {
        var div = document.createElement("div");
        div.className = "media";

          /.../

        var chatArea = document.getElementById('chat-area')
        chatArea.scrollIntoView({ behavior: 'smooth', block: 'end' })
        spinner.style.display = "none";
        interact(h5.innerText, inputValue);
    }
    inputBox.value = "";
}

Below is the POST request

   // POST user message
   function interact(userId, message) {
    var spinner = document.getElementById('textSpinner');
    spinner.style.display = "block";
    const payload = {
        userId: userId,
        utterance: message
    };

    fetch('Sessions/Interact', {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(payload)
    })
        .then(response => response.json())
        .then(data => botMessage(data.Message))
        .then(() => spinner.style.display = "none")
        .catch(error => console.error(error));
    }

When I get the response from the server, I'm calling another function called botMessage() which is similar to the userMessage() that will display the bot message.
Can someone guide me as to why this error is thrown and is there any solution to fix this issue?
Thanks in advance.

Here is the response body from the server.

{
  "Message": "Hello, It's me. Let's start chatting shall we?",
  "Data": null
}

Body:
I changed the response handling as below. Is this approach I'm doing is correct? Please correct me if i'm wrong.

.then(response => {
      if (response.status === 200) {
         return response.json()
         .then(data => botMessage(data.Message))
      } else if (response.status === 204) {
         return;
      }
    })
    .then(() => spinner.style.display = "none")
    .catch(error => console.error(error));


问:
nodejs package for parsing excel formula DATEDIF in months?
looking for nodejs package that can read and process formula excel
datedif in months

im currently using
handsontable/RuleJS
https://handsontable.github.io/ruleJS/

but there is no datedif in month

i need a tool because the
excel formula might be complex

from the current package i can do this in days

'IF(DAYS("6/6/2019","1/1/2019") >= 30,

now i need in months

答:
if you have access to just the fields then moment may work (npm i moment):

var moment = require('moment');

// 'IF(DAYS("6/6/2019","1/1/2019") >= 30,
var result = moment('6/6/2019').add(1, 'months').isAfter(moment('1/1/2019'));
```


问:
How to delete a Jupyter Notebook input cell programmatically, using its tag?
In our largest ML modeling pipeline notebook we need to delete a single input (code) cell (containing sensitive information which we cannot pass via other means when automating its execution).

The cell has been created (injected) by papermill.execute_notebook() executed in another notebook (controller) and has been auto-tagged with injected-parameters tag.

The solution (possibly not the only one?) is deleting the cell as soon as it gets executed.

If searching for a tag makes it extra difficult, than let's use solutions for just deleting the previous input cell (programmatically).

What did not work

Hiding the input cell is not good enough, as it would still get saved to the disk (this includes the report_only option in papermill's execute_notebook()). Also "converting" with nbconvert to HTML (which does allow to select cells for removal on the basis of their tags, as in this solution) would still preserve the original notebook with the encoded password inside.

答:
I'm assuming you want to remove the cell cause it contains sensitive information (a password).

My first advice would be not to pass sensitive information in plain text. A (slightly) better and simple option would be to store the password in a environment variable, and read it from the notebook using os.environ.

Here's how to remove the cell:

Note: I wrote this code on the fly and didn't test it, might need small edits.

import nbformat

nb = nbformat.read('/path/to/your/notebook.ipynb')

index = None

# find index for the cell with the injected params
for i, c in enumerate(nb.cells):
    cell_tags = c.metadata.get('tags')
    if cell_tags:
        if 'injected-parameters' in cell_tags:
            index = i

# remove cell
if index is not None:
    nb.cells.pop(index)

# save modified notebook
nbformat.write(nb,  '/path/to/your/notebook.ipynb')
```


问:
How to pass a value from this.state from one js file to another reactjs
I have a file and I have defined there a variable called "approve" in this.state{}

```<code>class cd extends React.Component {
  constructor() {
    super();
    this.state = {
      approve: "",

    };
    this.handleA = this.handleApprove.bind(this);

  }

  handleA(e) {
    console.log(e.target.value);

    this.setState({ approve: e.target.value });

  }
  render() {
    const { approve } = this.state;
    const {

    } = this.props;

    console.log(approveState);

    return (
     <Card>
                    <CardHeader title="Name" />
                    <CardContent>
                      <Field
                        name="Name"
                        component={RenderText}
                        label=""

                      />
                    </CardContent>
                  </Card>)
</code>```

I need to pass it to another js file....

how d oi pass the value of approve to this js file

答:
If your setup is currently:

```<code>[component A]
  -> [component B state(approve)]
  -> [component C *wants state(approve)*]
</code>```

then push the state up the component hierarchy and pass it down as a prop. If the children need to be able to change the value, then pass a callback like setApprove:

```<code>[component A state(approve) setApprove]
  -> [component B props(approve, setApprove)]
  -> [component C props(approve, setApprove)]
</code>```

Body:
I have a file and I have defined there a variable called "approve" in this.state{}

class cd extends React.Component {
  constructor() {
    super();
    this.state = {
      approve: "",

    };
    this.handleA = this.handleApprove.bind(this);

  }

  handleA(e) {
    console.log(e.target.value);

    this.setState({ approve: e.target.value });

  }
  render() {
    const { approve } = this.state;
    const {

    } = this.props;

    console.log(approveState);

    return (
     <Card>
                    <CardHeader title="Name" />
                    <CardContent>
                      <Field
                        name="Name"
                        component={RenderText}
                        label=""

                      />
                    </CardContent>
                  </Card>)

I need to pass it to another js file....

how d oi pass the value of approve to this js file

Body:
If your setup is currently:

[component A]
  -> [component B state(approve)]
  -> [component C *wants state(approve)*]

then push the state up the component hierarchy and pass it down as a prop. If the children need to be able to change the value, then pass a callback like setApprove:

[component A state(approve) setApprove]
  -> [component B props(approve, setApprove)]
  -> [component C props(approve, setApprove)]


问:
Why json hijacking can be prevented using POST method?
I came across the following ASP.NET MVC error, when returning json in a Get method:

This request has been blocked because sensitive information could be
  disclosed to third party web sites when this is used in a GET request.
  To allow GET requests, set JsonRequestBehavior to AllowGet.

Apparently this vulnerability is called json Hijacking. This article explains that a website could be exploited when returning json using Get. But returning json in a Post method is safe.

Why changing Get to Post prevents this attack?

Body:
JSON shouldn't be returned as GET because the data can be stolen with an injected <script> from an attacker (for example, if dynamic content is loaded without being HTML escaped). Scripts are requested from the server via the GET method, so anything sent from the server with POST won't be ran from an injected script. With their script being ran, the hacker can use your logged in cookie to access your JSON, which they shouldn't be allowed to get.

Read more about JSON hacking vulnerabilities in this article and this SO answer.