问:
Displaying alert many times
I wrote a java script for alerting message when form submitted. I am using same form at many place. Bellow are my js code,

```<code> <script type="text/javascript">
  var form = document.getElementById("form_demo-form");
    jQuery("#form_demo-form").submit(function(e){
    email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|
            (".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]
            {1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

mb = /^((\+\d{1,3}(-|.| )?\(?\d\)?(-| |.)?\d{1,5})|(\(?
         \d{2,6}\)?))(-|.| )?(\d{3,4})(-|.| )?(\d{4})(( x|
         ext)\d{1,5}){0,1}$/;

   if( ((form.field_qh4icy4.value !="") &&
        (form.field_269dk2.value != "") &&
        (form.field_1bgl12.value != "") &&
        (email.test(form.field_29yf4d4.value)) &&
        (mb.test(form.field_6dask2.value)) &&
        (form.field_t6rya2.value != "") &&
        (form.field_9jv0r14.value != "")))
     {
        alert("Thank you for contacting us. We have received your
        enquiry. One of our representatives will respond to you
        within 24 hours");
        window.location.assign("/blog/thankyou");
    }
  else{
    e.preventDefault();
      }
   });
</script>
</code>```

But alert message displayed two times rather than once.I need a help.Thanks in advanced.

答:
Use e.preventDefault(); on submit click, I have corrected the code and paste it below. try this one.</p>

```<code><script type="text/javascript">
  var form = document.getElementById("form_demo-form");
    jQuery("#form_demo-form").submit(function(e){
    e.preventDefault();
    email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|
            (".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]
            {1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

mb = /^((\+\d{1,3}(-|.| )?\(?\d\)?(-| |.)?\d{1,5})|(\(?
         \d{2,6}\)?))(-|.| )?(\d{3,4})(-|.| )?(\d{4})(( x|
         ext)\d{1,5}){0,1}$/;

   if( ((form.field_qh4icy4.value !="") &&
        (form.field_269dk2.value != "") &&
        (form.field_1bgl12.value != "") &&
        (email.test(form.field_29yf4d4.value)) &&
        (mb.test(form.field_6dask2.value)) &&
        (form.field_t6rya2.value != "") &&
        (form.field_9jv0r14.value != "")))
     {
        alert("Thank you for contacting us. We have received your
        enquiry. One of our representatives will respond to you
        within 24 hours");
        window.location.assign("/blog/thankyou");
    }
  else{
    e.preventDefault();
      }
   });
</script>
</code>```

Title: Displaying alert many times

Body:
I wrote a java script for alerting message when form submitted. I am using same form at many place. Bellow are my js code,

But alert message displayed two times rather than once.I need a help.Thanks in advanced.

Body:
Use e.preventDefault(); on submit click, I have corrected the code and paste it below. try this one.

<script type="text/javascript">
  var form = document.getElementById("form_demo-form");
    jQuery("#form_demo-form").submit(function(e){
    e.preventDefault();
    email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|
            (".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]
            {1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

mb = /^((\+\d{1,3}(-|.| )?\(?\d\)?(-| |.)?\d{1,5})|(\(?
         \d{2,6}\)?))(-|.| )?(\d{3,4})(-|.| )?(\d{4})(( x|
         ext)\d{1,5}){0,1}$/;

   if( ((form.field_qh4icy4.value !="") &&
        (form.field_269dk2.value != "") &&
        (form.field_1bgl12.value != "") &&
        (email.test(form.field_29yf4d4.value)) &&
        (mb.test(form.field_6dask2.value)) &&
        (form.field_t6rya2.value != "") &&
        (form.field_9jv0r14.value != "")))
     {
        alert("Thank you for contacting us. We have received your
        enquiry. One of our representatives will respond to you
        within 24 hours");
        window.location.assign("/blog/thankyou");
    }
  else{
    e.preventDefault();
      }
   });
</script>


来源: stackexchange

问:
useImperativeHandle hook does not update the value
I am using useImperativeHandle hook in my app to give access of value to the parent component:

```<code>const [phone,setPhone]=useState("");
 useImperativeHandle(
    ref,
    () => ({
      type: "text",
      name: "phone",
      value: phone
    }),
    [phone]
  );
</code>```

When I update phone using setPhone, value not going to be updated. What is the problem with my implementation?

答:
useImperativeHandle needs to have the component use forwardRef, Once you do that, you will be able to access the updated ref in the parent since you are providing phone as a dependency to it.

```<code>import React, {
  useEffect,
  useState,
  useImperativeHandle,
  forwardRef,
  useRef
} from "react";
import ReactDOM from "react-dom";

import "./styles.css";

const App = forwardRef((props, ref) => {
  const [phone, setPhone] = useState("");
  useImperativeHandle(
    ref,
    () => ({
      type: "text",
      name: "phone",
      value: phone
    }),
    [phone]
  );
  useEffect(() => {
    setTimeout(() => {
      setPhone("9898098909");
    }, 3000);
  }, []);
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
});

const Parent = () => {
  const appRef = useRef(null);
  const handleClick = () => {
    console.log(appRef.current.value);
  };
  return (
    <>
      <App ref={appRef} />
      <button onClick={handleClick}>Click</button>
    </>
  );
};
const rootElement = document.getElementById("root");
ReactDOM.render(<Parent />, rootElement);
</code>```

Working demo

ContentLicense: CC BY-SA 4.0

Body:
I am using useImperativeHandle hook in my app to give access of value to the parent component:

const [phone,setPhone]=useState("");
 useImperativeHandle(
    ref,
    () => ({
      type: "text",
      name: "phone",
      value: phone
    }),
    [phone]
  );

When I update phone using setPhone, value not going to be updated. What is the problem with my implementation?

Body:
useImperativeHandle needs to have the component use forwardRef, Once you do that, you will be able to access the updated ref in the parent since you are providing phone as a dependency to it.

import React, {
  useEffect,
  useState,
  useImperativeHandle,
  forwardRef,
  useRef
} from "react";
import ReactDOM from "react-dom";

import "./styles.css";

const App = forwardRef((props, ref) => {
  const [phone, setPhone] = useState("");
  useImperativeHandle(
    ref,
    () => ({
      type: "text",
      name: "phone",
      value: phone
    }),
    [phone]
  );
  useEffect(() => {
    setTimeout(() => {
      setPhone("9898098909");
    }, 3000);
  }, []);
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
});

const Parent = () => {
  const appRef = useRef(null);
  const handleClick = () => {
    console.log(appRef.current.value);
  };
  return (
    <>
      <App ref={appRef} />
      <button onClick={handleClick}>Click</button>
    </>
  );
};
const rootElement = document.getElementById("root");
ReactDOM.render(<Parent />, rootElement);

Working demo


问:
I want to print html to the browser before any process in Laravel
I want to print some html to the browser while process is running so user can not see the blank page in laravel.

I tried following code but this is rendering output to the browser after process completes.

```<code>        $v = view('users.account_varification',compact('AccessToken'));
        $content = $v->render();
        echo $content;
</code>```

Please help me.

答:
I have used following code to show loading while process is going on.
PHP output buffer has limit of 4KB so we can show limited amount of content to the browser while process is going on.</p>

```<code>        //STARTs - show loading
            // Turn off output buffering
            ini_set('output_buffering', 'off');
            // Turn off PHP output compression
            ini_set('zlib.output_compression', false);

            //Flush (send) the output buffer and turn off output buffering
            //ob_end_flush();
            while (@ob_end_flush());

            // Implicitly flush the buffer(s)
            ini_set('implicit_flush', true);
            ob_implicit_flush(true);

            ob_start(null, 4096);
            $v = view('users.loading');
            echo $content = $v->render();
            ob_end_flush();
        //ENDs - show loading
</code>```

Body:
I want to print some html to the browser while process is running so user can not see the blank page in laravel.

I tried following code but this is rendering output to the browser after process completes.

        $v = view('users.account_varification',compact('AccessToken'));
        $content = $v->render();
        echo $content;

Please help me.

Body:
I have used following code to show loading while process is going on.
PHP output buffer has limit of 4KB so we can show limited amount of content to the browser while process is going on.

        //STARTs - show loading
            // Turn off output buffering
            ini_set('output_buffering', 'off');
            // Turn off PHP output compression
            ini_set('zlib.output_compression', false);

            //Flush (send) the output buffer and turn off output buffering
            //ob_end_flush();
            while (@ob_end_flush());

            // Implicitly flush the buffer(s)
            ini_set('implicit_flush', true);
            ob_implicit_flush(true);

            ob_start(null, 4096);
            $v = view('users.loading');
            echo $content = $v->render();
            ob_end_flush();
        //ENDs - show loading


问:
How to put exception for .isalnum()?
I'm trying to remove the unwanted special symbols from my string in a list by using .isalnum() function in looping through each character in the words and I use the condition for putting exception for apostrophe symbol for cases, like "can't", "didn't", "won't". But it also keeps this symbol for the cases I don't need like " ' ", " 'cant", " 'hello' ". Is there a way to keep just for when the symbol is in the middle of the words?

data_set = "Hello WOrld &()*hello world ////dog /// cat world hello can't "

split_it = data_set.lower().split()
new_word = ''
new_list = list()
for word in split_it:
    new_word = ''.join([x for x in word if x.isalnum() or x == " ' "])
    new_list.append(new_word)

print(new_list)
```

['hello', 'world', 'hello', 'world', 'dog', '', 'cat', 'world', 'hello', "can't"]

答:
You could use a regular expression that matches any character that isn't either a lowercase letter or number, and either doesn't have such a character before it (start of word) or after it (end of word):

```<code>import re

phrase = "Hello WOrld &()*hello world ////dog /// cat world hello can't "

regex = re.compile(r'(?<![a-z0-9])([^a-z0-9])|([^a-z0-9])(?![a-z0-9])')

print([re.sub(regex, '', word) for word in phrase.lower().split()])
</code>```

Output:

```<code>['hello', 'world', 'hello', 'world', 'dog', '', 'cat', 'world', 'hello', "can't"]
</code>```

Title: How to put exception for .isalnum()?

Body:
I'm trying to remove the unwanted special symbols from my string in a list by using .isalnum() function in looping through each character in the words and I use the condition for putting exception for apostrophe symbol for cases, like "can't", "didn't", "won't". But it also keeps this symbol for the cases I don't need like " ' ", " 'cant", " 'hello' ". Is there a way to keep just for when the symbol is in the middle of the words?

data_set = "Hello WOrld &()*hello world ////dog /// cat world hello can't "

split_it = data_set.lower().split()
new_word = ''
new_list = list()
for word in split_it:
    new_word = ''.join([x for x in word if x.isalnum() or x == " ' "])
    new_list.append(new_word)

print(new_list)

['hello', 'world', 'hello', 'world', 'dog', '', 'cat', 'world', 'hello', "can't"]

Body:
You could use a regular expression that matches any character that isn't either a lowercase letter or number, and either doesn't have such a character before it (start of word) or after it (end of word):

import re

phrase = "Hello WOrld &()*hello world ////dog /// cat world hello can't "

regex = re.compile(r'(?<![a-z0-9])([^a-z0-9])|([^a-z0-9])(?![a-z0-9])')

print([re.sub(regex, '', word) for word in phrase.lower().split()])

Output:

['hello', 'world', 'hello', 'world', 'dog', '', 'cat', 'world', 'hello', "can't"]


问:
Binding a gridview's itemSource to the ViewModel with INotifyPropertyChanged
I want my ViewModel to loop through all the inner elements of my gridView with the Test() function. My "gridVariable" (see code) returns null for some reason. When getting and setting values to the TextBox, I encounter no problems. Why is the GridView returning null, and how can I fix it?

MainViewModel.cs

```<code>    public class MainViewModel : Observable, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public MainViewModel(){}

        private GetGridView _myGridView = new GetGridView();
        public GetGridView MyGridView
        {
            get { return _myGridView; }
        }

        public void Test()
        {
            var gridVariable = MyGridView.AnswersGrid;
            foreach (var i in gridVariable.Items) MyText.Text += "x";
        }

        private GetText _myText = new GetText();
        public GetText MyText
        {
            get { return _myText; }
            set
            {
                _myText = value;
            }
        }
    }
</code>```

GetGridView.cs

```<code>    public class GetGridView : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private GridView _grid;
        public GridView AnswersGrid
        {
            get { return _grid; }
        }
    }
</code>```

MainPage.xaml.cs

```<code>    public MainViewModel ViewModel { get; } = new MainViewModel();
    public MainPage()
    {
        InitializeComponent();
        this.DataContext = ViewModel;
    }
</code>```

MainPage.xaml

```<code>    <RelativePanel>
        <GridView
            x:Name="GridView"
            ItemsSource="{Binding MyGridView.AnswersGrid, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}">
            <TextBox Text="{Binding MyText.Text, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"  />
            <TextBox/>
        </GridView>
        <Button RelativePanel.Below="GridView" Content="butn" Click="{x:Bind ViewModel.Test}"></Button>
    </RelativePanel>
</code>```

答:
Binding a gridview's itemSource to the ViewModel with INotifyPropertyChanged

I checked your requirement, if you want use MVVM pattern, you need split View and Model. I have rewrite your code. please check the following.

ViewModel

```<code>public class MainPageViewModel : INotifyPropertyChanged
{
    public MainPageViewModel()
    {
        items = new ObservableCollection<Item>();
        items.Add(new Item { Info = "01" });
        items.Add(new Item { Info = "02" });
        items.Add(new Item { Info = "03" });
        items.Add(new Item { Info = "04" });
        items.Add(new Item { Info = "05" });
    }
    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    public ObservableCollection<Item> items;
    public void Test()
    {
        foreach (var item in items)
        {
            item.Info += "X";
        }
    }

}

public class Item : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    private string _info;
    public string Info
    {
        get
        {
            return _info;
        }
        set
        {
            _info = value;
            OnPropertyChanged();
        }
    }
}
</code>```

Usage

```<code><GridView
    x:Name="GridView"
    ItemsSource="{x:Bind ViewModel.items}">
    <GridView.ItemTemplate>
        <DataTemplate>
            <TextBox Text="{Binding Info}"/>
        </DataTemplate>
    </GridView.ItemTemplate>

</GridView>
<Button RelativePanel.Below="GridView" Content="butn" Click="{x:Bind ViewModel.Test}"></Button>
</code>```

For more detail info, please refer Data binding and MVVM

Body:
I want my ViewModel to loop through all the inner elements of my gridView with the Test() function. My "gridVariable" (see code) returns null for some reason. When getting and setting values to the TextBox, I encounter no problems. Why is the GridView returning null, and how can I fix it?

MainViewModel.cs

    public class MainViewModel : Observable, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public MainViewModel(){}

        private GetGridView _myGridView = new GetGridView();
        public GetGridView MyGridView
        {
            get { return _myGridView; }
        }

        public void Test()
        {
            var gridVariable = MyGridView.AnswersGrid;
            foreach (var i in gridVariable.Items) MyText.Text += "x";
        }

        private GetText _myText = new GetText();
        public GetText MyText
        {
            get { return _myText; }
            set
            {
                _myText = value;
            }
        }
    }

GetGridView.cs

    public class GetGridView : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private GridView _grid;
        public GridView AnswersGrid
        {
            get { return _grid; }
        }
    }

MainPage.xaml.cs

    public MainViewModel ViewModel { get; } = new MainViewModel();
    public MainPage()
    {
        InitializeComponent();
        this.DataContext = ViewModel;
    }

MainPage.xaml

    <RelativePanel>
        <GridView
            x:Name="GridView"
            ItemsSource="{Binding MyGridView.AnswersGrid, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}">
            <TextBox Text="{Binding MyText.Text, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"  />
            <TextBox/>
        </GridView>
        <Button RelativePanel.Below="GridView" Content="butn" Click="{x:Bind ViewModel.Test}"></Button>
    </RelativePanel>

Body:
Binding a gridview's itemSource to the ViewModel with INotifyPropertyChanged

I checked your requirement, if you want use MVVM pattern, you need split View and Model. I have rewrite your code. please check the following.

ViewModel

public class MainPageViewModel : INotifyPropertyChanged
{
    public MainPageViewModel()
    {
        items = new ObservableCollection<Item>();
        items.Add(new Item { Info = "01" });
        items.Add(new Item { Info = "02" });
        items.Add(new Item { Info = "03" });
        items.Add(new Item { Info = "04" });
        items.Add(new Item { Info = "05" });
    }
    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    public ObservableCollection<Item> items;
    public void Test()
    {
        foreach (var item in items)
        {
            item.Info += "X";
        }
    }

}

public class Item : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    private string _info;
    public string Info
    {
        get
        {
            return _info;
        }
        set
        {
            _info = value;
            OnPropertyChanged();
        }
    }
}

Usage

<GridView
    x:Name="GridView"
    ItemsSource="{x:Bind ViewModel.items}">
    <GridView.ItemTemplate>
        <DataTemplate>
            <TextBox Text="{Binding Info}"/>
        </DataTemplate>
    </GridView.ItemTemplate>

</GridView>
<Button RelativePanel.Below="GridView" Content="butn" Click="{x:Bind ViewModel.Test}"></Button>

For more detail info, please refer Data binding and MVVM


问:
AWS Lambda with request-promise
I'm trying to write a Lambda function that uses the request-promise library to make an external https request. This is what I have:

```<code>exports.handler = async (event, context, callback) => {
    console.log("Starting call: " + event.queryStringParameters.filter);
    console.log("Decoded param: " + decodeURIComponent(event.queryStringParameters.filter));
    var filter = JSON.parse(decodeURIComponent(event.queryStringParameters.filter));
    console.log("Filter: " + filter);
    var ingredients = filter.ingredients;
    var options = {
        uri: 'https://api.*****.com/search',
        qs: {
            app_id: '****',
            app_key: '*****',
            q: ingredients.join(' ')
        },
        json: true
    };
    console.log("Done calling stuff");

    rp(options)
        .then(function(recipes) {
            console.log('Response: ' + recipes);
            var recipesToReturn = [];

            recipes.hits.forEach(function(recipeHit) {
                recipesToReturn.push(objectMapper(recipeHit.recipe, recipeMap));
            });
            console.log('Recipes:', recipesToReturn);
            const response = {
                statusCode: 200,
                body: JSON.stringify(recipesToReturn),
            };
            return JSON.stringify(response);
        })
        .catch(function(err) {
            console.log('Error:', err)
            const response = {
            statusCode: 400,
            body: err,
            };
            return JSON.stringify(response);
        });
};
</code>```

When I test out the API Gateway request, I see this:

Sun May 26 16:59:21 UTC 2019 : Execution failed due to configuration error: Malformed Lambda proxy response

I've been trying to read up on how the Lambda Proxy Responses should be formatted, and I'm assuming that I'm missing something with regards to the callback or the context, but I have not been able to figure out how to make it work with the request-promise library.

答:
In proxy integration API Gateway simply passes entire request and response between frontend and the backend.

It is the problem with the response lambda function sent to the API Gateway.

Response to the lambda should have the following key-values

```<code>{
    "isBase64Encoded": true|false,
    "statusCode": httpStatusCode,
    "headers": { "headerName": "headerValue", ... },
    "body": "..."
}
</code>```

isBase64Encoded : If you are not working with binary data set it to false.

statusCode : Is the HTTP response that is interpreted by API Gateway.

body : if you are sending JSON it must be converted to a string. In node.js you can use JSON.stringify() method.

The following could be the proper response to API Gateway

```<code>const response = {
                statusCode: 200,
                isBase64Encoded: false
                headers:""
                body: JSON.stringify(recipesToReturn),
            };
</code>```

Title: AWS Lambda with request-promise

Body:
I'm trying to write a Lambda function that uses the request-promise library to make an external https request. This is what I have:

exports.handler = async (event, context, callback) => {
    console.log("Starting call: " + event.queryStringParameters.filter);
    console.log("Decoded param: " + decodeURIComponent(event.queryStringParameters.filter));
    var filter = JSON.parse(decodeURIComponent(event.queryStringParameters.filter));
    console.log("Filter: " + filter);
    var ingredients = filter.ingredients;
    var options = {
        uri: 'https://api.*****.com/search',
        qs: {
            app_id: '****',
            app_key: '*****',
            q: ingredients.join(' ')
        },
        json: true
    };
    console.log("Done calling stuff");

    rp(options)
        .then(function(recipes) {
            console.log('Response: ' + recipes);
            var recipesToReturn = [];

            recipes.hits.forEach(function(recipeHit) {
                recipesToReturn.push(objectMapper(recipeHit.recipe, recipeMap));
            });
            console.log('Recipes:', recipesToReturn);
            const response = {
                statusCode: 200,
                body: JSON.stringify(recipesToReturn),
            };
            return JSON.stringify(response);
        })
        .catch(function(err) {
            console.log('Error:', err)
            const response = {
            statusCode: 400,
            body: err,
            };
            return JSON.stringify(response);
        });
};

When I test out the API Gateway request, I see this:

Sun May 26 16:59:21 UTC 2019 : Execution failed due to configuration error: Malformed Lambda proxy response

I've been trying to read up on how the Lambda Proxy Responses should be formatted, and I'm assuming that I'm missing something with regards to the callback or the context, but I have not been able to figure out how to make it work with the request-promise library.

Body:
In proxy integration API Gateway simply passes entire request and response between frontend and the backend.

It is the problem with the response lambda function sent to the API Gateway.

Response to the lambda should have the following key-values

{
    "isBase64Encoded": true|false,
    "statusCode": httpStatusCode,
    "headers": { "headerName": "headerValue", ... },
    "body": "..."
}

isBase64Encoded : If you are not working with binary data set it to false.

statusCode : Is the HTTP response that is interpreted by API Gateway.

body : if you are sending JSON it must be converted to a string. In node.js you can use JSON.stringify() method.

The following could be the proper response to API Gateway

const response = {
                statusCode: 200,
                isBase64Encoded: false
                headers:""
                body: JSON.stringify(recipesToReturn),
            };


问:
What is the fastest way to draw an array of lines?
I need to draw an array of lines in overlay. Currently, I use canvas and bitmap and draw about 500 lines. The drawing time is very high - around 200 ms which is bad, but acceptable.

Now I need to add 500 lines more and the time grows significantly. What is the fastest way to do this? Do I need to use OpenGL? and How? What is the best approach?

答: Turning off anti-aliasing will speed things up a lot.  Be sure to profile your code to make sure rendering is the place where the time is actually going.  Once you have optimized things and the majority of time is spent in rendering and you have made the rendering as simple as possible, the next step you'll have to take is to move to OpenGL.</p>

ContentLicense: CC BY-SA 3.0


问:
unserialize function in php ads extra slashes to the result string
this is a serialized form:

```<code> [featureimg520_624] => a:2:{s:9:"image_url";s:47:"2019/05/2019-05-27-06-07-02keerthy-suresh2.jpeg"
</code>```

after unserialize I get

```<code> "image_url":"2019\/05\/2019-05-27-06-07-02keerthy-suresh2.jpeg"
</code>```

with extra backslashes

I tried stripcslashes, stripslashes, str_replace

but nothing worked.

答:
It's json_encode which is adding those backslashes. You can avoid them by using the JSON_UNESCAPED_SLASHES option to that function:

```<code>$string = 'a:1:{s:9:"image_url";s:47:"2019/05/2019-05-27-06-07-02keerthy-suresh2.jpeg";}';
$array = unserialize($string);
echo json_encode($array, JSON_UNESCAPED_SLASHES);
</code>```

Output:

```<code>{"image_url":"2019/05/2019-05-27-06-07-02keerthy-suresh2.jpeg"}
</code>```

Body:
this is a serialized form:

 [featureimg520_624] => a:2:{s:9:"image_url";s:47:"2019/05/2019-05-27-06-07-02keerthy-suresh2.jpeg"

after unserialize I get

 "image_url":"2019\/05\/2019-05-27-06-07-02keerthy-suresh2.jpeg"

with extra backslashes

I tried stripcslashes, stripslashes, str_replace

but nothing worked.

Body:
It's json_encode which is adding those backslashes. You can avoid them by using the JSON_UNESCAPED_SLASHES option to that function:

$string = 'a:1:{s:9:"image_url";s:47:"2019/05/2019-05-27-06-07-02keerthy-suresh2.jpeg";}';
$array = unserialize($string);
echo json_encode($array, JSON_UNESCAPED_SLASHES);

Output:

{"image_url":"2019/05/2019-05-27-06-07-02keerthy-suresh2.jpeg"}


问:
vue cli - Uncaught SyntaxError: Unexpected token <
I create my project with vue-cli 3.0. Initially it runs ok. But after I <ctrl>-c then npm run serve again, it keep throwing error:

Uncaught SyntaxError: Unexpected token <

it indicate that the error happened at the first line of app.js, but I check in console the < is actually from index.html. Which means somewhere along the process, the webpack thought index.html should be transpile as app.js.

Below are the packages I am using:

vue 3.0.0-rc.3
@vue/cli-plugin-babel ^3.0.0-beta.15
@vue/cli-plugin-eslint ^3.0.0-beta.15
@vue/cli-service ^3.0.0-beta.15

How can I resolve this?

Update01
I delete the whole node-modules folder and npm install again, then everything seems to work fine again. But if anyone have any idea why this happen, please share it.

答: Try by adding <base href="/" /> into the  of your index.html. Hope it will work.

Body: Try by adding <base href="/" /> into the <head> of your index.html. Hope it will work.


问:
jquery row.siblings not working correctly
I have hide and show siblings js function, Here mainly I have 3 Teams

Malabar

Pazhassi

Travancore

Here when click on Malabar div Pazhassi and Travancore will disappear (ie: I need only Malabar div details with a show button.)

And when I click show button it will back to its first view, means I need all div's

my jquery

```<code>function clickInline(id)
 {

 $('#row'+id).siblings().show('');
 }
</code>```

But bad luck it's not working. here is my js fiddle
fiddle

Any help would be really appreciated

答:
Your code is good but a simple mistake, when you click a show button then show target elements but it's again hidden because of your button parent element trigger a click event where you talk the hide them. You must needed to pass show button with event and id then the target function use preventDefault and stopPropagation you can learn about more https://codeplanet.io/preventdefault-vs-stoppropagation-vs-stopimmediatepropagation/

 function cc(event, id) {

     event.preventDefault();
     event.stopPropagation();

     $('#row' + id).siblings().hide('slow');
     $(".btn-dis").css("display", "block")

 }

 function clickInline(event, id) {
     event.preventDefault();
     event.stopPropagation();

     $('#row' + id).siblings('.row').css('display', 'flex');
     $(".btn-dis").css("display", "none")

 }

 function Expandcollapse(event, id) {

 }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.row {
    display: -webkit-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    display: flex;
    flex-wrap: wrap;
}

.row>[class*='col-'] {
    display: flex;
    flex-direction: column;
}

.DC {
    border: 1px solid #bf7708;
    padding: 15px;
    margin: 4px;
    color: #575757;
    background-color: #e88d00;
    border-radius: 8px;
    width: 120px;
}

.table-hed {
    border: 1px solid #008cf3;
    background-color: #008cf3;
    color: #fff;
    padding: 10px;
    width: 147px
}

.bord-lin {
    border: 1px solid black;
}

.h-styl {
    padding-bottom: 10px;
    border-bottom: 1px solid #ccc;
    margin-bottom: 10px;
    text-align: center;
}

.teams {
    border-top: 1px solid #060606;
    padding: 10px;
    text-align: center;
    min-height: 180px;
    width: 150px
}

a {
    color: #fff;
    text-decoration: none;
}

.btn-dis {
    display: none
}</code>```

    <button onclick="cc(event,2)">dddd</button>

PI board

PI board

new features

                        <form name="registration1_form" id="registration1_form" method="POST" action="http://localhost/manage/products/deleteaboutsusall" enctype="multipart/form-data">

Tasks

Teams

                                                     sprint2

                                                        asas

                                                        <button type="button" id="pop-7" onClick="popfeatureEdit(7)" class="btn btn-primary btn-xs"> </button>

                                                        Malabar

                                                    <button type="button" class="btn btn-primary btn-xs btn-dis" onclick="clickInline(event,1)">Show
                                                    </button>

                                                            asas

                                                            <button type="button" id="pop-7" onclick="popfeatureEdit(7)" class="btn btn-primary btn-xs"> </button>

                                                        Pazhassi

                                                    <button type="button" id="mybutton" class="btn btn-primary btn-xs btn-dis" onclick="clickInline(event,2)">Show
                                                    </button>

                                                            zxz

                                                            <button type="button" class="btn btn-primary btn-xs" id="pop-6" onClick="popfeatureEdit(6)"> </button>
                                                            <button type="button" class="btn btn-primary btn-xs pull-right"> </button>

                                                            shanua

                                                            <button type="button" class="btn btn-primary btn-xs" id="pop-8" onClick="popfeatureEdit(8)"> </button>
                                                            <button type="button" class="btn btn-primary btn-xs pull-right"> </button>

                                                        Travancore

                                                    <button type="button" id="show" class="btn btn-primary btn-xs btn-dis" onclick="clickInline(event,3)">Show
                                                    </button>e

                                                            shanu testing

                                                            <button type="button" class="btn btn-primary btn-xs" id="pop-11" onClick="popfeatureEdit(11)"> </button>
                                                            <button type="button" class="btn btn-primary btn-xs pull-right"> </button>

```

-- Thanks --

Body:
I have hide and show siblings js function, Here mainly I have 3 Teams

Malabar

Pazhassi

Travancore

Here when click on Malabar div Pazhassi and Travancore will disappear (ie: I need only Malabar div details with a show button.)

And when I click show button it will back to its first view, means I need all div's

my jquery

function clickInline(id)
 {

 $('#row'+id).siblings().show('');
 }

But bad luck it's not working. here is my js fiddle
fiddle

Any help would be really appreciated

Body:
Your code is good but a simple mistake, when you click a show button then show target elements but it's again hidden because of your button parent element trigger a click event where you talk the hide them. You must needed to pass show button with event and id then the target function use preventDefault and stopPropagation you can learn about more https://codeplanet.io/preventdefault-vs-stoppropagation-vs-stopimmediatepropagation/

 function cc(event, id) {

     event.preventDefault();
     event.stopPropagation();

     $('#row' + id).siblings().hide('slow');
     $(".btn-dis").css("display", "block")

 }

 function clickInline(event, id) {
     event.preventDefault();
     event.stopPropagation();

     $('#row' + id).siblings('.row').css('display', 'flex');
     $(".btn-dis").css("display", "none")

 }

 function Expandcollapse(event, id) {

 }

.row {
    display: -webkit-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    display: flex;
    flex-wrap: wrap;
}

.row>[class*='col-'] {
    display: flex;
    flex-direction: column;
}

.DC {
    border: 1px solid #bf7708;
    padding: 15px;
    margin: 4px;
    color: #575757;
    background-color: #e88d00;
    border-radius: 8px;
    width: 120px;
}

.table-hed {
    border: 1px solid #008cf3;
    background-color: #008cf3;
    color: #fff;
    padding: 10px;
    width: 147px
}

.bord-lin {
    border: 1px solid black;
}

.h-styl {
    padding-bottom: 10px;
    border-bottom: 1px solid #ccc;
    margin-bottom: 10px;
    text-align: center;
}

.teams {
    border-top: 1px solid #060606;
    padding: 10px;
    text-align: center;
    min-height: 180px;
    width: 150px
}

a {
    color: #fff;
    text-decoration: none;
}

.btn-dis {
    display: none
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="">
    <button onclick="cc(event,2)">dddd</button>

    <div class="col-md-9">

        <div class="row">
            <div class="bread">
                <div id="bc1" class="btn-group btn-breadcrumb">
                    <a href="http://localhost/manage/manage/" class="btn btn-default">
                        <i class="fa fa-home"></i></a>
                    <a href="" class="btn btn-default">
                        <div>PI board</div>
                    </a>

                </div>
            </div>
            <div class="row">
                <div class="reg-form">
                    <div class="bulk">
                        <div class="col-md-4">
                            <h3 style="padding-left:1.2%">PI board</h3>
                        </div>
                        <div class="col-md-6" style="
                                 margin-left: -13%;
                                 margin-top: 2%;
                                 ">

                        </div>
                        <div class="col-md-2   enq-btn"><a href="#" data-toggle="modal" data-target="#myModal"><i class="fa fa-envelope"></i>new features</a></div>

                        <div class="clearfix"></div>
                    </div>
                    <div class="form clearfix">

                        <form name="registration1_form" id="registration1_form" method="POST" action="http://localhost/manage/products/deleteaboutsusall" enctype="multipart/form-data">

                            <div>

                                <div class="container" style="padding-bottom:70px">

                                    <div class="row ">
                                        <div class="col-sm-3 table-hed">Tasks
                                        </div>
                                        <div class="col-sm-9">
                                            <div class="row">
                                                <div class="col-sm-2 table-hed">Teams
                                                </div>

                                                <div class="col-sm-5 table-hed">
                                                    <a href="http://localhost/manage/scrum/TeamscrumBorad/2" /> sprint2 </a>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="row">

                                        <div class="col-sm-3 bord-lin formContainerBoxT1">
                                            <div class="row ">
                                                <div class="col-md-12 col-sm-6 col-xs-12 mb-3 text-ellipsis prop-win-label-cls draggableCompClassT1 DC" data-story_id="7" data-team-id="0" data-sprint-id="0">
                                                    <div class="col-sm-12 h-styl">
                                                        <b class="" id="content-7">asas</b>
                                                    </div>
                                                    <div class="col-md-12">
                                                        <button type="button" id="pop-7" onClick="popfeatureEdit(7)" class="btn btn-primary btn-xs"><span class="fa fa-edit"></span> </button>
                                                        <p class="blog-post-bottom pull-right">
                                                            <a class="delete btn btn-primary btn-xs" href="http://localhost/manage/scrum/deletefeature/7_1" style="float:right"> <span class="fa fa-trash"></span> </a>
                                                        </p>
                                                    </div>
                                                </div>

                                            </div>
                                        </div>
                                        <div class="col-sm-9">
                                            <div class="row" id="row1" onclick="cc(event,1)">

                                                <div class="col-md-2 teams bord-lin" id="team1">
                                                    <div style="height:140px">
                                                        Malabar
                                                    </div>
                                                    <button type="button" class="btn btn-primary btn-xs btn-dis" onclick="clickInline(event,1)">Show
                                                    </button>
                                                </div>
                                                <div id="teamz1" class="col-md-5 teams bord-lin formContainerBoxT1" data-team-id="1" data-sprint-id="2">
                                                    <div class="col-md-12 col-sm-6 col-xs-12 mb-3 text-ellipsis prop-win-label-cls draggableCompClassT1 DC ui-draggable ui-draggable-handle" data-story_id="7" data-team-id="0" data-sprint-id="0">
                                                        <div class="col-sm-12 h-styl">
                                                            <b class="" id="content-7">asas</b>
                                                        </div>
                                                        <div class="col-md-12">
                                                            <button type="button" id="pop-7" onclick="popfeatureEdit(7)" class="btn btn-primary btn-xs"><span class="fa fa-edit"></span> </button>
                                                            <p class="blog-post-bottom pull-right">
                                                                <a class="delete btn btn-primary btn-xs" href="http://localhost/manage/scrum/deletefeature/7_1" style="float:right"> <span class="fa fa-trash"></span> </a>
                                                            </p>
                                                        </div>
                                                    </div>
                                                </div>

                                            </div>
                                            <div class="row" id="row2" onclick="cc(event,2)">

                                                <div class="col-md-2 teams bord-lin" id="team2" onclick="Expandcollapse(2)">
                                                    <div style="height:140px">
                                                        Pazhassi
                                                    </div>
                                                    <button type="button" id="mybutton" class="btn btn-primary btn-xs btn-dis" onclick="clickInline(event,2)">Show
                                                    </button>
                                                </div>
                                                <div id="teamz2" class="col-md-5 teams bord-lin formContainerBoxT1" data-team-id="2" data-sprint-id="2">
                                                    <div class="col-md-12 col-sm-6 col-xs-12 mb-3 text-ellipsis prop-win-label-cls draggableCompClassT1 DC ui-draggable ui-draggable-handle" data-story_id="6" data-team-id="2" data-sprint-id="2">
                                                        <div class="col-sm-12 h-styl">
                                                            <b class="" id="content-6">zxz</b>
                                                        </div>
                                                        <div class="col-md-12">
                                                            <button type="button" class="btn btn-primary btn-xs" id="pop-6" onClick="popfeatureEdit(6)"><span class="fa fa-edit"></span> </button>
                                                            <button type="button" class="btn btn-primary btn-xs pull-right"><span class="fa fa-trash"></span> </button>
                                                        </div>
                                                    </div>

                                                    <div class="col-md-12 col-sm-6 col-xs-12 mb-3 text-ellipsis prop-win-label-cls draggableCompClassT1 DC ui-draggable ui-draggable-handle" data-story_id="8" data-team-id="2" data-sprint-id="2">
                                                        <div class="col-sm-12 h-styl">
                                                            <b class="" id="content-8">shanua</b>
                                                        </div>
                                                        <div class="col-md-12">
                                                            <button type="button" class="btn btn-primary btn-xs" id="pop-8" onClick="popfeatureEdit(8)"><span class="fa fa-edit"></span> </button>
                                                            <button type="button" class="btn btn-primary btn-xs pull-right"><span class="fa fa-trash"></span> </button>
                                                        </div>
                                                    </div>

                                                </div>

                                            </div>
                                            <div class="row" id="row3" onclick="cc(event,3)">

                                                <div class="col-md-2 teams bord-lin" id="team3" onclick="Expandcollapse(3)">
                                                    <div style="height:140px">
                                                        Travancore
                                                    </div>
                                                    <button type="button" id="show" class="btn btn-primary btn-xs btn-dis" onclick="clickInline(event,3)">Show
                                                    </button>e </div>
                                                <div id="teamz3" class="col-md-5 teams bord-lin formContainerBoxT1" data-team-id="3" data-sprint-id="2">
                                                    <div class="col-md-12 col-sm-6 col-xs-12 mb-3 text-ellipsis prop-win-label-cls draggableCompClassT1 DC ui-draggable ui-draggable-handle" data-story_id="11" data-team-id="3" data-sprint-id="2">
                                                        <div class="col-sm-12 h-styl">
                                                            <b class="" id="content-11">shanu testing</b>
                                                        </div>
                                                        <div class="col-md-12">
                                                            <button type="button" class="btn btn-primary btn-xs" id="pop-11" onClick="popfeatureEdit(11)"><span class="fa fa-edit"></span> </button>
                                                            <button type="button" class="btn btn-primary btn-xs pull-right"><span class="fa fa-trash"></span> </button>
                                                        </div>
                                                    </div>

                                                </div>

                                            </div>

-- Thanks --


问:
How to handle page refresh request for any URL of an SPA built using agularjs and hosted using S3 + Cloudfront?
I have an SPA built using angularjs (version 1.5). I've hosted this application on S3 bucket. And have setup CloudFront in front of S3 bucket.

In order to make my application SEO friendly, I had to remove # from the URLs. I did this by enabling HTML5 mode. So, now my URLs don't have hash and everything works correctly through my hosted environment.

But, the moment I hit refresh (F5) for any url (except index.html), I see

```<code>404 Not Found
Code: NoSuchKey
Message: The specified key does not exist.
</code>```

Can someone please suggest how to handle page refresh, with my current setup?

With Cloudfront, I know, I can redirect 404 to say index.html. But, then any page refresh would redirect the user to index.html. This is not desired.

What I want to do is, when a user hits refresh, I want to re-render the same page, with refreshed contents.

Do I need to do URL Rewrite on S3, to achieve this? If yes, what should be my URL re-write rule?

Or, is there any better way with CloudFront to achieve this?

答:
You need to define that all the urls in the app should render the index.html that runs your SPA.

I'm not sure how to do it with amazon, but with express it's just specifying an handler with * as a url (it sometimes calls "catch-all")

Body:
I have an SPA built using angularjs (version 1.5). I've hosted this application on S3 bucket. And have setup CloudFront in front of S3 bucket.

In order to make my application SEO friendly, I had to remove # from the URLs. I did this by enabling HTML5 mode. So, now my URLs don't have hash and everything works correctly through my hosted environment.

But, the moment I hit refresh (F5) for any url (except index.html), I see

404 Not Found
Code: NoSuchKey
Message: The specified key does not exist.

Can someone please suggest how to handle page refresh, with my current setup?

With Cloudfront, I know, I can redirect 404 to say index.html. But, then any page refresh would redirect the user to index.html. This is not desired.

What I want to do is, when a user hits refresh, I want to re-render the same page, with refreshed contents.

Do I need to do URL Rewrite on S3, to achieve this? If yes, what should be my URL re-write rule?

Or, is there any better way with CloudFront to achieve this?


问:
I have created modules for different components but loadChildren is nor=t working for modules
I am using the below code to use loadChildren for login-module, but it is showing error "ERROR Error:

"Uncaught (in promise): Error: Cannot find module
  './login/login.module'"

```<code> {
      path: 'login',
      loadChildren: './login/login.module#LoginModule'

     },
</code>```

And component module for login is:

```<code>import { ModuleWithProviders, NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';

import { LoginComponent } from './login.component';
import { LoginRoutingModule } from './login-routing.module';

@NgModule({
  imports: [
    LoginRoutingModule
  ],
  declarations: [
    LoginComponent
  ]
})
export class LoginModule {}
</code>```

login-routing.module.ts

```<code>import { RouterModule, Routes } from '@angular/router';
import { LoginComponent } from './login.component';

const routes: Routes = [
  {
    path: '',
    component: LoginComponent,
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class LoginRoutingModule {}
</code>```

-

答:
The path to your module should be absolute from src. </p>

```<code>  loadChildren: 'src/app/login/login.module#LoginModule'
</code>```

Body:
I am using the below code to use loadChildren for login-module, but it is showing error "ERROR Error:

"Uncaught (in promise): Error: Cannot find module
  './login/login.module'"

 {
      path: 'login',
      loadChildren: './login/login.module#LoginModule'

     },

And component module for login is:

import { ModuleWithProviders, NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';

import { LoginComponent } from './login.component';
import { LoginRoutingModule } from './login-routing.module';

@NgModule({
  imports: [
    LoginRoutingModule
  ],
  declarations: [
    LoginComponent
  ]
})
export class LoginModule {}

login-routing.module.ts

import { RouterModule, Routes } from '@angular/router';
import { LoginComponent } from './login.component';

const routes: Routes = [
  {
    path: '',
    component: LoginComponent,
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class LoginRoutingModule {}

-

Body:
The path to your module should be absolute from src.

  loadChildren: 'src/app/login/login.module#LoginModule'


问:
How to get the result by define divide function using pandas?
```<code>def set_div(a,b):
    if a==0:
        if b==0:
            return 0
        else:
            return 10**6
    else:
        return b/a
</code>```

df:

```<code>    a       b
0   0.0     0.0
1   30000.0 0.0
2   0.0     0.0
3   32700.0 10000.0
4   51700.0 0.0
</code>```

dtypes of col a and b are float64.

```<code>df['c'] = df[['a','b']].apply(lambda x:set_div(x[0],x[1]))
</code>```

but it returns KeyError: (0, 'occurred at index a').

I don't understand the error, please explain and how to get my result.

答:
If want to use custom function working for each row need DataFrame.apply with axis=1:

```<code>df['c'] = df.apply(lambda x :set_div(x['a'],x['b']), axis=1)
</code>```

Another solution with numpy.select is vectorized, so better performance in large DataFrame:

```<code>m1 = df['a'] == 0
m2 = df['b'] == 0
df['c'] = np.select([m1 & ~m2, m1 & m2], [10**6, 0], df['b'] / df['a'])
print (df)
         a        b        c
0      0.0      0.0  0.00000
1  30000.0      0.0  0.00000
2      0.0      0.0  0.00000
3  32700.0  10000.0  0.30581
4  51700.0      0.0  0.00000
</code>```

Performance:

```<code>#[50000 rows x 2 columns]
df = pd.concat([df] * 10000, ignore_index=True)

In [113]: %timeit df['c'] = np.select([m1 & ~m2, m1 & m2], [10**6, 0], df['b'] / df['a'])
1.85 ms ± 32.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [114]: %timeit df['c1'] = df.apply(lambda x :set_div(x['a'],x['b']), axis=1)
1.01 s ± 17.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
</code>```

Body:
def set_div(a,b):
    if a==0:
        if b==0:
            return 0
        else:
            return 10**6
    else:
        return b/a

df:

    a       b
0   0.0     0.0
1   30000.0 0.0
2   0.0     0.0
3   32700.0 10000.0
4   51700.0 0.0

dtypes of col a and b are float64.

df['c'] = df[['a','b']].apply(lambda x:set_div(x[0],x[1]))

but it returns KeyError: (0, 'occurred at index a').

I don't understand the error, please explain and how to get my result.

Body:
If want to use custom function working for each row need DataFrame.apply with axis=1:

df['c'] = df.apply(lambda x :set_div(x['a'],x['b']), axis=1)

Another solution with numpy.select is vectorized, so better performance in large DataFrame:

m1 = df['a'] == 0
m2 = df['b'] == 0
df['c'] = np.select([m1 & ~m2, m1 & m2], [10**6, 0], df['b'] / df['a'])
print (df)
         a        b        c
0      0.0      0.0  0.00000
1  30000.0      0.0  0.00000
2      0.0      0.0  0.00000
3  32700.0  10000.0  0.30581
4  51700.0      0.0  0.00000

Performance:

#[50000 rows x 2 columns]
df = pd.concat([df] * 10000, ignore_index=True)

In [113]: %timeit df['c'] = np.select([m1 & ~m2, m1 & m2], [10**6, 0], df['b'] / df['a'])
1.85 ms ± 32.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [114]: %timeit df['c1'] = df.apply(lambda x :set_div(x['a'],x['b']), axis=1)
1.01 s ± 17.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)


问:
How to insert stock quantity and update into another table?
I'm trying to update the quantity of stock when a new stock is added. I'm using array because I want to add more than one product in the page. But the data is not insert into the db and no update on the quantity of stock too. What do I miss on this code?</p>

```<code> <?php
include 'db_connection.php';

    if(isset($_POST["submit4"])){

        foreach($_POST['fk_product'] as $index => $searchid){

            $sql="INSERT INTO supplier (supplier_name, date_in, fk_product, quantity_in) VALUES ('".$_POST['supplier_name']."','".$_POST['date_in']."','".$_POST['fk_product'][$index]."', '".$_POST["quantity_in"][$index]."')";

            $quantity_bal=$_POST['quantity_bal'];

            if($quantity_bal==0){
            $sql="UPDATE product set quantity_bal= quantity_ori + '".$_POST["quantity_in"][$index]."' WHERE id_produk = '".$_GET['id']."'";
            }else if($quantity_bal!=0){
            $sql="UPDATE product set quantity_bal= quantity_bal + '".$_POST["quantity_in"][$index]."' WHERE id_produk = '".$_GET['id']."'";

            }

            $query = mysqli_multi_query($conn,$sql);
    if($query){
        header("location:product.php");
    }

    }
        }
?>
</code>```

答:
What you're missing is that you need to concatenate the queries, with the use of = assignment operator, you've just overridden the former string, so it should be like this

```<code>foreach($_POST['fk_product'] as $index => $searchid){

        $sql = "INSERT INTO supplier (supplier_name, date_in, fk_product, quantity_in) VALUES ('".$_POST['supplier_name']."','".$_POST['date_in']."','".$_POST['fk_product'][$index]."', '".$_POST["quantity_in"][$index]."')";

        $quantity_bal = $_POST['quantity_bal'];

        if($quantity_bal == 0){
            //I'm presuming that the quantity_ori is a variable here 'coz you're trying to sum up with the original to the latest one
            $sql .= "UPDATE product set quantity_bal= $quantity_ori + '".$_POST["quantity_in"][$index]."' WHERE id_produk = '".$_GET['id']."'";
        }else if($quantity_bal != 0){
            $sql .= "UPDATE product set quantity_bal= $quantity_bal + '".$_POST["quantity_in"][$index]."' WHERE id_produk = '".$_GET['id']."'";
        }

}
</code>```

We changed the = symbol in your update queries into .= and then your quantity_ori earlier doesn't have the $ symbol, since we're presuming it's a variable, don't forget the $

Body:
I'm trying to update the quantity of stock when a new stock is added. I'm using array because I want to add more than one product in the page. But the data is not insert into the db and no update on the quantity of stock too. What do I miss on this code?

 <?php
include 'db_connection.php';

    if(isset($_POST["submit4"])){

        foreach($_POST['fk_product'] as $index => $searchid){

            $sql="INSERT INTO supplier (supplier_name, date_in, fk_product, quantity_in) VALUES ('".$_POST['supplier_name']."','".$_POST['date_in']."','".$_POST['fk_product'][$index]."', '".$_POST["quantity_in"][$index]."')";

            $quantity_bal=$_POST['quantity_bal'];

            if($quantity_bal==0){
            $sql="UPDATE product set quantity_bal= quantity_ori + '".$_POST["quantity_in"][$index]."' WHERE id_produk = '".$_GET['id']."'";
            }else if($quantity_bal!=0){
            $sql="UPDATE product set quantity_bal= quantity_bal + '".$_POST["quantity_in"][$index]."' WHERE id_produk = '".$_GET['id']."'";

            }

            $query = mysqli_multi_query($conn,$sql);
    if($query){
        header("location:product.php");
    }

    }
        }
?>

Body:
What you're missing is that you need to concatenate the queries, with the use of = assignment operator, you've just overridden the former string, so it should be like this

foreach($_POST['fk_product'] as $index => $searchid){

        $sql = "INSERT INTO supplier (supplier_name, date_in, fk_product, quantity_in) VALUES ('".$_POST['supplier_name']."','".$_POST['date_in']."','".$_POST['fk_product'][$index]."', '".$_POST["quantity_in"][$index]."')";

        $quantity_bal = $_POST['quantity_bal'];

        if($quantity_bal == 0){
            //I'm presuming that the quantity_ori is a variable here 'coz you're trying to sum up with the original to the latest one
            $sql .= "UPDATE product set quantity_bal= $quantity_ori + '".$_POST["quantity_in"][$index]."' WHERE id_produk = '".$_GET['id']."'";
        }else if($quantity_bal != 0){
            $sql .= "UPDATE product set quantity_bal= $quantity_bal + '".$_POST["quantity_in"][$index]."' WHERE id_produk = '".$_GET['id']."'";
        }

}

We changed the = symbol in your update queries into .= and then your quantity_ori earlier doesn't have the $ symbol, since we're presuming it's a variable, don't forget the $


问:
array is returning null and crashing
I have an array of objects in a class and trying to reference that array to a UIPickerView, but when the UITextField is tapped it crashes and comes back nil. When tapped on the countryInput text field it should show a pickerview with "Monaco, Japan" and so on...Any ideas on what I'm doing wrong? thank you in advance.

```<code>class SelectionViewController: UIViewController {

var lifeArr : [LifeClass] = []

let picker = UIPickerView()

    override func viewDidLoad() {
    super.viewDidLoad()

    let Monaco = LifeClass()
    Monaco.country = "Monaco"
    Monaco.male = 85.6
    Monaco.female = 93.5

    let Japan = LifeClass()
    Japan.country = "Japan"
    Japan.male = 81.9
    Japan.female = 88.8

    lifeArr = [Monaco, Japan]
  }

}

class SetupViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {

@IBOutlet weak var birthDayInput: UITextField!
@IBOutlet weak var countryInput: UITextField!

var selectionData : SelectionViewController!
var picker = UIPickerView()

    override func viewDidLoad() {
    super.viewDidLoad()

        picker.dataSource = self
        picker.delegate = self

func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return selectionData.lifeArr.count
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return selectionData.lifeArr[row].country
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    countryInput.text = selectionData.lifeArr[row].country
}

}
</code>```

答:
I don't think there is even a need to use a whole instance of SelectionViewController as a dataSource to UIPickerView.

Instead, you could've simply created the [LifeClass] array in SetupViewController and used it there itself.

```<code> class SetupViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
    private var lifeArr = [LifeClass]()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.populateArray()
        picker.dataSource = self
        picker.delegate = self
    }

    private func populateArray() {
        let monaco = LifeClass()
        monaco.country = "Monaco"
        monaco.male = 85.6
        monaco.female = 93.5
        lifeArr.append(monaco)

        let japan = LifeClass()
        japan.country = "Japan"
        japan.male = 81.9
        japan.female = 88.8
        lifeArr.append(japan)
    }

    //Rest of the code...
}
</code>```

In UIPickerViewDataSource and UIPickerViewDelegate methods, use

```<code>self.lifeArr
</code>```

instead of

```<code>selectionData.lifeArr
</code>```

Title: array is returning null and crashing

Body:
I have an array of objects in a class and trying to reference that array to a UIPickerView, but when the UITextField is tapped it crashes and comes back nil. When tapped on the countryInput text field it should show a pickerview with "Monaco, Japan" and so on...Any ideas on what I'm doing wrong? thank you in advance.

class SelectionViewController: UIViewController {

var lifeArr : [LifeClass] = []

let picker = UIPickerView()

    override func viewDidLoad() {
    super.viewDidLoad()

    let Monaco = LifeClass()
    Monaco.country = "Monaco"
    Monaco.male = 85.6
    Monaco.female = 93.5

    let Japan = LifeClass()
    Japan.country = "Japan"
    Japan.male = 81.9
    Japan.female = 88.8

    lifeArr = [Monaco, Japan]
  }

}

class SetupViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {

@IBOutlet weak var birthDayInput: UITextField!
@IBOutlet weak var countryInput: UITextField!

var selectionData : SelectionViewController!
var picker = UIPickerView()

    override func viewDidLoad() {
    super.viewDidLoad()

        picker.dataSource = self
        picker.delegate = self

func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return selectionData.lifeArr.count
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return selectionData.lifeArr[row].country
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    countryInput.text = selectionData.lifeArr[row].country
}

}

Body:
I don't think there is even a need to use a whole instance of SelectionViewController as a dataSource to UIPickerView.

Instead, you could've simply created the [LifeClass] array in SetupViewController and used it there itself.

 class SetupViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
    private var lifeArr = [LifeClass]()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.populateArray()
        picker.dataSource = self
        picker.delegate = self
    }

    private func populateArray() {
        let monaco = LifeClass()
        monaco.country = "Monaco"
        monaco.male = 85.6
        monaco.female = 93.5
        lifeArr.append(monaco)

        let japan = LifeClass()
        japan.country = "Japan"
        japan.male = 81.9
        japan.female = 88.8
        lifeArr.append(japan)
    }

    //Rest of the code...
}

In UIPickerViewDataSource and UIPickerViewDelegate methods, use

self.lifeArr

instead of

selectionData.lifeArr


问:
Do we need .NET framework for installing windows app in Client Machine?
Can any one help me regarding this ? Is it mandatory?</p>

答:
Depending on which OS you have installed, you need to install a standalone of the .NET Framework.
At the moment there isn't an OS with the .NET Framework 4.0 installed, so you need to do it via the Windows Update or manual.
You can check out which .NET Framework is installed on this site: http://www.msigeek.com/2390/what-version-of-the-net-framework-is-included-in-which-version-of-the-os
The picture:

This means you need to install it on your OS.


问:
Gem 5 IOError: Can't find a path to system files. Full System X86 simulation setup
I've already got Gem5 installed.
I'm trying to do a full system simulation.
I added M5_PATH

```<code>echo "export M5_PATH==/home/sam/security/gem5/full/" >> ~/.bashrc
</code>```

I put all the system image and config files under following directory:

```<code>  :~/security/gem5/full$ ls
binaries  configs  config-x86.tar.bz2  disks  x86-system.tar.bz2  x86-system.tar.bz2.1
</code>```

I changed the path in the SysPaths.py file to following:

```<code>                paths = [ '/dist/m5/system', 'full' ]
</code>```

And updated the following line in  Benchmark.py

```<code>            return env.get('LINUX_IMAGE', disk('linux-x86.img'))
</code>```

Gem5 is compiled successfully and I'm running the following:

```<code> ./build/X86/gem5.opt configs/example/fs.py  --disk-image=/home/sam/security/gem5/full/disks/linux-x86.img
</code>```

But I get an error that it can't find a path to system files.

```<code>Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "build/X86/python/m5/main.py", line 438, in main
    exec(filecode, scope)
  File "configs/example/fs.py", line 335, in <module>
    test_sys = build_test_system(np)
  File "configs/example/fs.py", line 93, in build_test_system
    cmdline=cmdline)
  File "/home/sam/security/gem5/configs/common/FSConfig.py", line 614, in makeLinuxX86System
    makeX86System(mem_mode, numCPUs, mdesc, self, Ruby)
  File "/home/sam/security/gem5/configs/common/FSConfig.py", line 539, in makeX86System
    disk0.childImage(mdesc.disk())
  File "/home/sam/security/gem5/configs/common/Benchmarks.py", line 59, in disk
    return disk(self.diskname)
  File "/home/sam/security/gem5/configs/common/SysPaths.py", line 63, in __call__
    raise IOError("Can't find a path to system files.")
IOError: Can't find a path to system files.
</code>```

答:
Update 2020-01

As of 82f6d6e90f36e400db1f38eef5fe17430313458e reviewed at https://gem5-review.googlesource.com/c/public/gem5/+/23672/7 the CLI insanity has reduced substantially:

M5_PATH is not required anymore on X86 if you point to all required files explicitly:

```<code>fs.py --kernel path/to/vmlinux --disk-image path/to/rootfs.ext2
</code>```

The second disk named linux-bigswap2.img and x86_64-vmlinux-2.6.22.9 are not needed anymore, and you can pass multiple disks at will with multiple --disk-image options, see: How to attach multiple disk images in a simulation with gem5 fs.py?

on ARM, M5_PATH can also be dispensed, but you also need to point the bootloader with:

```<code>fs.py --bootloader ./system/arm/bootloader/arm64/boot.arm64
</code>```

If you miss any of those files, M5_PATH gets used.

Note that just like the PATH search algorithm, paths without / are only searched under M5_PATH, so if you want to point to a file in the current directory you need to add ./ as in:

```<code>fs.py --kernel ./vmlinux
</code>```

see also: Why do you need ./ (dot-slash) before executable or script name to run it in bash?

Old answer

gem5 is picky about some path names, but you don't need to patch it to achieve a decent image setup.

For example, this working setup with gem5 e2656006df442a995bf80ee03fa9700d6ec14537 essentially runs:

```<code>M5_PATH=/full/path/to/system \
  build/X86/gem5.opt \
  configs/example/fs.py \
  --disk-image /any/path/to/rootfs.ext2 \
  --kernel /any/path/to/vmlinux
</code>```

and /full/path/to/system contains:

```<code>./disks/linux-bigswap2.img
./binaries/x86_64-vmlinux-2.6.22.9
</code>```

Both of those files are dummies which I generated from here with:

```<code>dd if=/dev/zero of=./binaries/linux-bigswap2.img count=1 bs=16k
touch disks/x86_64-vmlinux-2.6.22.9
</code>```

Yes, this is a horrible workaround to gem5's opinionated image searching... someone should really patch gem5 to not look for those images if you pass --disk-image and --kernel yourself...

As always, have a try at debugging it with prints and PDB: it should then be simple to figure out why something didn't work for you.

Body:
I've already got Gem5 installed.
I'm trying to do a full system simulation.
I added M5_PATH

echo "export M5_PATH==/home/sam/security/gem5/full/" >> ~/.bashrc

I put all the system image and config files under following directory:

  :~/security/gem5/full$ ls
binaries  configs  config-x86.tar.bz2  disks  x86-system.tar.bz2  x86-system.tar.bz2.1

I changed the path in the SysPaths.py file to following:

                paths = [ '/dist/m5/system', 'full' ]

And updated the following line in  Benchmark.py

            return env.get('LINUX_IMAGE', disk('linux-x86.img'))

Gem5 is compiled successfully and I'm running the following:

 ./build/X86/gem5.opt configs/example/fs.py  --disk-image=/home/sam/security/gem5/full/disks/linux-x86.img

But I get an error that it can't find a path to system files.

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "build/X86/python/m5/main.py", line 438, in main
    exec(filecode, scope)
  File "configs/example/fs.py", line 335, in <module>
    test_sys = build_test_system(np)
  File "configs/example/fs.py", line 93, in build_test_system
    cmdline=cmdline)
  File "/home/sam/security/gem5/configs/common/FSConfig.py", line 614, in makeLinuxX86System
    makeX86System(mem_mode, numCPUs, mdesc, self, Ruby)
  File "/home/sam/security/gem5/configs/common/FSConfig.py", line 539, in makeX86System
    disk0.childImage(mdesc.disk())
  File "/home/sam/security/gem5/configs/common/Benchmarks.py", line 59, in disk
    return disk(self.diskname)
  File "/home/sam/security/gem5/configs/common/SysPaths.py", line 63, in __call__
    raise IOError("Can't find a path to system files.")
IOError: Can't find a path to system files.

Body:
Update 2020-01

As of 82f6d6e90f36e400db1f38eef5fe17430313458e reviewed at https://gem5-review.googlesource.com/c/public/gem5/+/23672/7 the CLI insanity has reduced substantially:

M5_PATH is not required anymore on X86 if you point to all required files explicitly:

fs.py --kernel path/to/vmlinux --disk-image path/to/rootfs.ext2

The second disk named linux-bigswap2.img and x86_64-vmlinux-2.6.22.9 are not needed anymore, and you can pass multiple disks at will with multiple --disk-image options, see: How to attach multiple disk images in a simulation with gem5 fs.py?

on ARM, M5_PATH can also be dispensed, but you also need to point the bootloader with:

fs.py --bootloader ./system/arm/bootloader/arm64/boot.arm64

If you miss any of those files, M5_PATH gets used.

Note that just like the PATH search algorithm, paths without / are only searched under M5_PATH, so if you want to point to a file in the current directory you need to add ./ as in:

fs.py --kernel ./vmlinux

see also: Why do you need ./ (dot-slash) before executable or script name to run it in bash?

Old answer

gem5 is picky about some path names, but you don't need to patch it to achieve a decent image setup.

For example, this working setup with gem5 e2656006df442a995bf80ee03fa9700d6ec14537 essentially runs:

M5_PATH=/full/path/to/system \
  build/X86/gem5.opt \
  configs/example/fs.py \
  --disk-image /any/path/to/rootfs.ext2 \
  --kernel /any/path/to/vmlinux

and /full/path/to/system contains:

./disks/linux-bigswap2.img
./binaries/x86_64-vmlinux-2.6.22.9

Both of those files are dummies which I generated from here with:

dd if=/dev/zero of=./binaries/linux-bigswap2.img count=1 bs=16k
touch disks/x86_64-vmlinux-2.6.22.9

Yes, this is a horrible workaround to gem5's opinionated image searching... someone should really patch gem5 to not look for those images if you pass --disk-image and --kernel yourself...

As always, have a try at debugging it with prints and PDB: it should then be simple to figure out why something didn't work for you.


问:
Angular 6 CSV download
I'm new to angular, currently i'm working in a project which needs an csv export. Here i'm using Angular 6 as frontend and laravel as backend

This is how i wrote laravel function using mattwebsite/excel

```<code>// Lead export to csv
public function downloadExcel(Request $request)
{
    $credentials = $request->only('token');
    $token = $credentials['token'];
    $userid = $this->getUseridFromToken($token);
    $type = "xls";
    $data = DB::table('user_mailbox AS A')
                    ->select('A.id', 'A.name', 'A.email', 'A.phone', DB::raw('DATE_FORMAT(A.send_on, "%d / %b / %Y") as send_on'), 'B.listing_heading','B.listing_id','B.listing_heading', 'C.name')
                    ->leftjoin('broker_listing AS B', 'B.listing_id', '=', 'A.listing_id')
                    ->leftjoin('users AS C', 'C.id', '=', 'A.sent_by')
                    ->where('A.sent_to', $userid)
                    ->where('A.user_type', '1')
                    ->orderBy('A.id', 'desc')->get()->toArray();
    Excel::create('Lead_Export', function($excel) use ($data) {
        $excel->sheet('Lead_Export', function($sheet) use ($data)
        {
            $sheet->fromArray($data);
        });
    })->download($type);
}
</code>```

This is how i wrote function in angular component

```<code>    // Download leads as excel
download_excel(){
  const fd = new FormData();
  fd.append('token',this.token);
  this.brokerleads.downloadLeads(fd).subscribe(
    data => this.handleResponsedwnload(data),
    error => this.handleErrordwnload(error)
  );
}
handleResponsedwnload(data){ console.log('test');
  const blob = new Blob([data], { type: 'text/xls' });
  const url= window.URL.createObjectURL(blob);
  window.open(url);
}
handleErrordwnload(data){

}
</code>```

service is like this

```<code>  // Download as excel
  downloadLeads(data):Observable<any>{
    return this.http.post(`${this.baseUrl}downloadExcel`, data);
  }
</code>```

view

```<code>    <a class="export-leads" href="javascript:void(0);" (click)="download_excel()" >EXPORT LEADS</a>
</code>```

while doing this i'm getting response like this but file is not downloading

答:
This can also be done using file-saver:

import * as FileSaver from 'file-saver';

```<code>this.http.post(`${this.baseUrl}downloadExcel`, data, { responseType: 'blob' })
 .subscribe((resp: any) => {
    saveAs(resp, `filename.csv`)
 });
</code>```

Title: Angular 6 CSV download

Body:
I'm new to angular, currently i'm working in a project which needs an csv export. Here i'm using Angular 6 as frontend and laravel as backend

This is how i wrote laravel function using mattwebsite/excel

// Lead export to csv
public function downloadExcel(Request $request)
{
    $credentials = $request->only('token');
    $token = $credentials['token'];
    $userid = $this->getUseridFromToken($token);
    $type = "xls";
    $data = DB::table('user_mailbox AS A')
                    ->select('A.id', 'A.name', 'A.email', 'A.phone', DB::raw('DATE_FORMAT(A.send_on, "%d / %b / %Y") as send_on'), 'B.listing_heading','B.listing_id','B.listing_heading', 'C.name')
                    ->leftjoin('broker_listing AS B', 'B.listing_id', '=', 'A.listing_id')
                    ->leftjoin('users AS C', 'C.id', '=', 'A.sent_by')
                    ->where('A.sent_to', $userid)
                    ->where('A.user_type', '1')
                    ->orderBy('A.id', 'desc')->get()->toArray();
    Excel::create('Lead_Export', function($excel) use ($data) {
        $excel->sheet('Lead_Export', function($sheet) use ($data)
        {
            $sheet->fromArray($data);
        });
    })->download($type);
}

This is how i wrote function in angular component

    // Download leads as excel
download_excel(){
  const fd = new FormData();
  fd.append('token',this.token);
  this.brokerleads.downloadLeads(fd).subscribe(
    data => this.handleResponsedwnload(data),
    error => this.handleErrordwnload(error)
  );
}
handleResponsedwnload(data){ console.log('test');
  const blob = new Blob([data], { type: 'text/xls' });
  const url= window.URL.createObjectURL(blob);
  window.open(url);
}
handleErrordwnload(data){

}

service is like this

  // Download as excel
  downloadLeads(data):Observable<any>{
    return this.http.post(`${this.baseUrl}downloadExcel`, data);
  }

view

    EXPORT LEADS

while doing this i'm getting response like this but file is not downloading

Body:
This can also be done using file-saver:

import * as FileSaver from 'file-saver';

this.http.post(`${this.baseUrl}downloadExcel`, data, { responseType: 'blob' })
 .subscribe((resp: any) => {
    saveAs(resp, `filename.csv`)
 });


问:
Appsync missing resolver
I'm using AWS appsync + DynamoDB.

The problem: I created the new field 'rating' in my 'Users' schema:

```<code>type Users {
    id: ID!
    first: String!
    last: String!
    rating: String #<----The new field
}
</code>```

AppSync created all the resources and I can create new records with Mutations and that works like a charm.

```<code>mutation createUsers{
   createUsers(input:{
     first:"John"
     last:"Smith"
     rating:"B" #<---Writing new field without problem
   }){
     id
     first
     last
     rating #<---Confirming that is recorded in DynamoDB
   }
 }
</code>```

The problem is that I can't figure out how to write the resolver to make the following query work.

```<code>query{
  queryUsersByRating(rating: "B"){
    items{
      id
      username
      rating
    }
  }
}
</code>```

The result is this:

```<code>{
  "data": {
    "queryUsersByRating": null
  }
}
</code>```

The problem is clearly identified here under "Missing Resolver", but there's no clear solution.

I tried attaching the following Resolver directly in AppSync interface but is not working:

```<code>{
    "version" : "2017-02-28",
    "operation" : "Query",
    "query" : {
        "expression": "rating = :rating",
        "expressionValues" : {
            ":rating" : $util.dynamodb.toDynamoDBJson($ctx.args.rating)
        }
    }
}
</code>```

Any help would be appreciated, THANKS!

答:
You don't have to write your own resolver for querying by rating, Appsync wrapped all the fields inside filter.

```<code>query{
  queryUsersByRating(filter: {rating: "B"}){
    items{
      id
      username
      rating
    }
  }
}
</code>```

Title: Appsync missing resolver

Body:
I'm using AWS appsync + DynamoDB.

The problem: I created the new field 'rating' in my 'Users' schema:

type Users {
    id: ID!
    first: String!
    last: String!
    rating: String #<----The new field
}

AppSync created all the resources and I can create new records with Mutations and that works like a charm.

mutation createUsers{
   createUsers(input:{
     first:"John"
     last:"Smith"
     rating:"B" #<---Writing new field without problem
   }){
     id
     first
     last
     rating #<---Confirming that is recorded in DynamoDB
   }
 }

The problem is that I can't figure out how to write the resolver to make the following query work.

query{
  queryUsersByRating(rating: "B"){
    items{
      id
      username
      rating
    }
  }
}

The result is this:

{
  "data": {
    "queryUsersByRating": null
  }
}

The problem is clearly identified here under "Missing Resolver", but there's no clear solution.

I tried attaching the following Resolver directly in AppSync interface but is not working:

{
    "version" : "2017-02-28",
    "operation" : "Query",
    "query" : {
        "expression": "rating = :rating",
        "expressionValues" : {
            ":rating" : $util.dynamodb.toDynamoDBJson($ctx.args.rating)
        }
    }
}

Any help would be appreciated, THANKS!

Body:
You don't have to write your own resolver for querying by rating, Appsync wrapped all the fields inside filter.

query{
  queryUsersByRating(filter: {rating: "B"}){
    items{
      id
      username
      rating
    }
  }
}


问:
"TypeError: Cannot read property 'email' of undefined" in nodejs authentication system
I'm trying to run an authentication module using express-session and passport.

server.js

```<code>var express = require("express");
var session = require('express-session');
var connection = require('./config');
var bodyParser = require('body-parser');
var passport = require('passport');
const redis = require('redis');
const redisStore = require('connect-redis')(session);
const client  = redis.createClient();
var app = express();
var router = express.Router();
var authController=require('./controllers/auth-controller');
var regController=require('./controllers/reg-controller');

app.use(session({secret: 'secret', store: new redisStore({ host: 'localhost', port: 8000, client: client,ttl : 260}), saveUninitialized: true, resave: true}));
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

router.get('/',(req,res) => {
    let sess = req.session;
    if(sess.email){
        return res.redirect('/admin');
    }
    res.sendFile( __dirname + '/' + 'index.html' );
})

router.post('/login',(req,res) => {
    sess = req.session;
    sess.email = req.body.email;
    res.end('done');
});

router.get('/admin',(req,res) => {
    sess = req.session;
    if(sess.email) {
        res.write(`<h1>Hello ${sess.email} </h1><br>`);
        res.end('<a href='+'/logout'+'>Logout</a>');
    }
    else {
        res.write('<h1>Please login first.</h1>');
        res.end('<a href='+'/'+'>Login</a>');
    }
});

router.get('/logout',(req,res) => {
    req.session.destroy((err) => {
        if(err) {
            return console.log(err);
        }
        res.redirect('/');
    });

});

app.use('/', router);

app.post('/api/register',regController.register);
app.post('/api/authenticate',authController.authenticate);

console.log(authController);
app.post('/controllers/register-controller', regController.register);
app.post('/controllers/authenticate-controller', authController.authenticate);
app.listen(8000);
</code>```

config.js

```<code>var mysql      = require('mysql');
const localAuth = require('./controllers/timeoutcontroller');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : 'password',
  database : 'dbname'
});
connection.connect(function(err){
if(!err) {
    console.log("Database is connected");
} else {
    console.log("Error while connecting with database");
}
});

function ensureAuthenticated(req, res, next) {
  if (!(req.headers && req.headers.authorization)) {
    return res.status(400).json({
      status: 'Please log in'
    });
  }
  // decode the token
  var header = req.headers.authorization.split(' ');
  var token = header[1];
  localAuth.decodeToken(token, (err, payload) => {
    if (err) {
      return res.status(401).json({
        status: 'Token has expired'
      });
    } else {
      return knex('users').where({id: parseInt(payload.sub)}).first()
      .then((user) => {
        next();
      })
      .catch((err) => {
        res.status(500).json({
          status: 'error'
        });
      });
    }
  });
}

module.exports = connection;
</code>```

Here I am able to connect to the mysql database and the connection is set but I'm getting the error

TypeError: Cannot read property 'email' of undefined

If someone could explain why this happens, it'd be great.
Thanks.

答:
This means that your variable sess is undefined. Your req.session variable does not have any value inside it. You need to check why is that happening.

Try this:

```<code>let sess = req.session;
sess.user = req.user;
req.mysess=sess.user //pass like this

router.get('/', function(req, res, next) {
    let sess = req.mysess;
    console.log(sess);
});
</code>```

Body:
I'm trying to run an authentication module using express-session and passport.

server.js

var express = require("express");
var session = require('express-session');
var connection = require('./config');
var bodyParser = require('body-parser');
var passport = require('passport');
const redis = require('redis');
const redisStore = require('connect-redis')(session);
const client  = redis.createClient();
var app = express();
var router = express.Router();
var authController=require('./controllers/auth-controller');
var regController=require('./controllers/reg-controller');

app.use(session({secret: 'secret', store: new redisStore({ host: 'localhost', port: 8000, client: client,ttl : 260}), saveUninitialized: true, resave: true}));
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

router.get('/',(req,res) => {
    let sess = req.session;
    if(sess.email){
        return res.redirect('/admin');
    }
    res.sendFile( __dirname + '/' + 'index.html' );
})

router.post('/login',(req,res) => {
    sess = req.session;
    sess.email = req.body.email;
    res.end('done');
});

router.get('/admin',(req,res) => {
    sess = req.session;
    if(sess.email) {
        res.write(`<h1>Hello ${sess.email} </h1><br>`);
        res.end('Logout');
    }
    else {
        res.write('
Please login first.
');
        res.end('Login');
    }
});

router.get('/logout',(req,res) => {
    req.session.destroy((err) => {
        if(err) {
            return console.log(err);
        }
        res.redirect('/');
    });

});

app.use('/', router);

app.post('/api/register',regController.register);
app.post('/api/authenticate',authController.authenticate);

console.log(authController);
app.post('/controllers/register-controller', regController.register);
app.post('/controllers/authenticate-controller', authController.authenticate);
app.listen(8000);

config.js

var mysql      = require('mysql');
const localAuth = require('./controllers/timeoutcontroller');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : 'password',
  database : 'dbname'
});
connection.connect(function(err){
if(!err) {
    console.log("Database is connected");
} else {
    console.log("Error while connecting with database");
}
});

function ensureAuthenticated(req, res, next) {
  if (!(req.headers && req.headers.authorization)) {
    return res.status(400).json({
      status: 'Please log in'
    });
  }
  // decode the token
  var header = req.headers.authorization.split(' ');
  var token = header[1];
  localAuth.decodeToken(token, (err, payload) => {
    if (err) {
      return res.status(401).json({
        status: 'Token has expired'
      });
    } else {
      return knex('users').where({id: parseInt(payload.sub)}).first()
      .then((user) => {
        next();
      })
      .catch((err) => {
        res.status(500).json({
          status: 'error'
        });
      });
    }
  });
}

module.exports = connection;

Here I am able to connect to the mysql database and the connection is set but I'm getting the error

TypeError: Cannot read property 'email' of undefined

If someone could explain why this happens, it'd be great.
Thanks.

Body:
This means that your variable sess is undefined. Your req.session variable does not have any value inside it. You need to check why is that happening.

Try this:

let sess = req.session;
sess.user = req.user;
req.mysess=sess.user //pass like this

router.get('/', function(req, res, next) {
    let sess = req.mysess;
    console.log(sess);
});


问:
Customizing the Login Control in ASP.NET
I'm making a Library Management System using ASP.NET using C#. I have a problem creating a custom login page in my website. I've tried using the ASP.NET Web Configuration but my boss doesnt allow me to install the Aspnet_regsql.exe in the main database. </p>

<p>I have two tables, one table for the username and password and the other one is for the username status (in case the username is deleted or not used anymore). So is there any alternatives or workaround? </p>

答: You could use a separate database for the aspnet login part. This way your boss doesn't have to worry about .NET adding procedures and tables to an existing database. I wouldn't recommend writing your own from scratch as there is always a danger of creating security vulnerabilities that hackers could later exploit.</p>

Body:
I'm making a Library Management System using ASP.NET using C#. I have a problem creating a custom login page in my website. I've tried using the ASP.NET Web Configuration but my boss doesnt allow me to install the Aspnet_regsql.exe in the main database.

I have two tables, one table for the username and password and the other one is for the username status (in case the username is deleted or not used anymore). So is there any alternatives or workaround?


问:
angular 7 + angular cli 7+ ng test not working
angular 7 + angular cli 7.1.0

upgraded project from angular 5 to 7
and when run
    ng test

and tsConfig added in angular.json file

```<code>` "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "test.js",
            "karmaConfig": "./karma.conf.js",
            "polyfills": "apps/app/src/polyfills.ts",
            "tsConfig": "tsconfig.spec.json",`
</code>```

I get the output
 Schema validation failed with the following errors:
  Data path "" should have required property 'tsConfig'.

What am I doing wrong?
Thanks in advance.

答:
In my angular 7 project ng test is working. below is my agular.json file test configuration.</p>

```<code>   "test": {
      "builder": "@angular-devkit/build-angular:karma",
      "options": {
        "main": "src/test.ts",
        "karmaConfig": "./karma.conf.js",
        "polyfills": "src/polyfills.ts",
        "tsConfig": "src/tsconfig.spec.json",
        "scripts": [
          "src/assets/jquery-3.2.1.min.js",
          "src/assets/vendor/bootstrap/js/bootstrap.min.js",
        ],
        "styles": [
          "src/assets/vendor/bootstrap/css/bootstrap.css",
        ],
        "assets": [
          "src/assets",
          "src/favicon.ico"
        ]
      }
    },
</code>```

Body:
angular 7 + angular cli 7.1.0

upgraded project from angular 5 to 7
and when run
    ng test

and tsConfig added in angular.json file

` "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "test.js",
            "karmaConfig": "./karma.conf.js",
            "polyfills": "apps/app/src/polyfills.ts",
            "tsConfig": "tsconfig.spec.json",`

I get the output
 Schema validation failed with the following errors:
  Data path "" should have required property 'tsConfig'.

What am I doing wrong?
Thanks in advance.

Body:
In my angular 7 project ng test is working. below is my agular.json file test configuration.

   "test": {
      "builder": "@angular-devkit/build-angular:karma",
      "options": {
        "main": "src/test.ts",
        "karmaConfig": "./karma.conf.js",
        "polyfills": "src/polyfills.ts",
        "tsConfig": "src/tsconfig.spec.json",
        "scripts": [
          "src/assets/jquery-3.2.1.min.js",
          "src/assets/vendor/bootstrap/js/bootstrap.min.js",
        ],
        "styles": [
          "src/assets/vendor/bootstrap/css/bootstrap.css",
        ],
        "assets": [
          "src/assets",
          "src/favicon.ico"
        ]
      }
    },


问:
How to pass List<int> from C# to C++ CLi?
I am beginner in C language family...

So, problem is - in my solution I have a repo (wrote in C#) that store List<int>, also I have an engine that (wrote in C++). So, I need pass List from C# implementation to C++ CLI for executing...

As far as I understood problem is C++ know how to work with std::vector and C# know how to work with List and I need somehow convert List to vector...

How to do it?

Any assumption appropriate.

EDIT

Sorry for misunderstanding, but my CLI works as a mapper for pure C++ implementation. So, as far as I understood from C# I need to pass my List to C++ CLI , C++ CLI will convert a List to vector and invoke another C++ file with pure C++ implementation.

This is my solution

h file
    using namespace System;
    using namespace System::Collections::Generic;

```<code>//forward declaration
class MathCore;

namespace MathCore_CLI_namespace
{
public ref class MathCore_CLI
{
public:
    MathCore_CLI();
    ~MathCore_CLI();

    int computeMulPlusVals(List<int>^ list_first, List<int>^ list_second);
    //int computeMulPlusVals(std::vector<int> vect_first, std::vector<int> vect_second);

private:
    MathCore * m_pMathCore;
};
}
</code>```

cpp file

```<code>#include "stdafx.h"
#include "MathCore_CLI.h"
#include "..\Engine\MathCore.h"
#include <iostream>
#include <array>
using namespace System;
using namespace System::Collections::Generic;

namespace MathCore_CLI_namespace
{
const int size = 5;
int count = 0;
int arrayVal[size];

MathCore_CLI::MathCore_CLI()
{
    m_pMathCore = new MathCore();
}

MathCore_CLI::~MathCore_CLI()
{
    delete m_pMathCore;
}

int computeMulPlusVals(List<int>^ list_first, List<int>^ list_second)
{
    return 0;
}
}
</code>```

Error

What am I doind wrong?

答:
C++ CLI directly supports List and you don't need a conversion. Here is a typical signature.

```<code>private: System::Void FooMethod( System::Collections::Generic::List<Int32>^ list )
</code>```

Besides, In your updated question, you have a linker error.

Open C++ project properties, Find Linker and then Input. Add the location to your (EngineLib_Cli.dll) Library there

Body:
I am beginner in C language family...

So, problem is - in my solution I have a repo (wrote in C#) that store List<int>, also I have an engine that (wrote in C++). So, I need pass List from C# implementation to C++ CLI for executing...

As far as I understood problem is C++ know how to work with std::vector and C# know how to work with List and I need somehow convert List to vector...

How to do it?

Any assumption appropriate.

EDIT

Sorry for misunderstanding, but my CLI works as a mapper for pure C++ implementation. So, as far as I understood from C# I need to pass my List to C++ CLI , C++ CLI will convert a List to vector and invoke another C++ file with pure C++ implementation.

This is my solution

h file
    using namespace System;
    using namespace System::Collections::Generic;

//forward declaration
class MathCore;

namespace MathCore_CLI_namespace
{
public ref class MathCore_CLI
{
public:
    MathCore_CLI();
    ~MathCore_CLI();

    int computeMulPlusVals(List<int>^ list_first, List<int>^ list_second);
    //int computeMulPlusVals(std::vector<int> vect_first, std::vector<int> vect_second);

private:
    MathCore * m_pMathCore;
};
}

cpp file

#include "stdafx.h"
#include "MathCore_CLI.h"
#include "..\Engine\MathCore.h"
#include <iostream>
#include <array>
using namespace System;
using namespace System::Collections::Generic;

namespace MathCore_CLI_namespace
{
const int size = 5;
int count = 0;
int arrayVal[size];

MathCore_CLI::MathCore_CLI()
{
    m_pMathCore = new MathCore();
}

MathCore_CLI::~MathCore_CLI()
{
    delete m_pMathCore;
}

int computeMulPlusVals(List<int>^ list_first, List<int>^ list_second)
{
    return 0;
}
}

Error

What am I doind wrong?

Body:
C++ CLI directly supports List and you don't need a conversion. Here is a typical signature.

private: System::Void FooMethod( System::Collections::Generic::List<Int32>^ list )

Besides, In your updated question, you have a linker error.

Open C++ project properties, Find Linker and then Input. Add the location to your (EngineLib_Cli.dll) Library there


问:
How do you detect where two line segments intersect?
How do I determine whether or not two lines intersect, and if they do, at what x,y point?</p>

答: If each side of the rectangle is a line segment, and the user drawn portion is a line segment, then you need to just check the user drawn segment for intersection with the four side line segments. This should be a fairly simple exercise given the start and end points of each segment.</p>

OwnerDisplayName: KingNestor

OwnerDisplayName: Harper Shelby

ContentLicense: CC BY-SA 2.5