问:
nodemon not working: -bash: nodemon: command not found
I'm on a Mac running El Capitan. I have node v5.6.0 and npm v3.6.0.
When I try to run nodemon, I get:

```<code>-bash: nodemon: command not found
</code>```

I thought this may mean that I didn't have nodemon installed, so when I tried to install it using...

```<code>sudo npm install -g nodemon
</code>```

...I get this:

```<code>npm ERR! Darwin 15.2.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "-g"     "nodemon"
npm ERR! node v5.6.0
npm ERR! npm  v3.6.0
npm ERR! path /usr/local/bin/nodemon
npm ERR! code EEXIST

npm ERR! Refusing to delete /usr/local/bin/nodemon: ../lib/node_modules/nodemon/nodemon.js symlink target is not controlled by         npm /usr/local
npm ERR! File exists: /usr/local/bin/nodemon
npm ERR! Move it away, and try again.

npm ERR! Please include the following file with any support request:
npm ERR!     /Users/brianeoneill/npm-debug.log
</code>```

If it makes a difference, I'm trying to run nodemon on a project that uses Express v4.13.1

Thanks for any help you can offer!

答:
For nodemon: not found command
I tried with many links but was not working then i tried with the below steps it worked fine.

Follow this step it worked for me.

step1 : sudo su

step2 : npm install -g nodemon --save-dev

It is working fine.

Body:
I'm on a Mac running El Capitan. I have node v5.6.0 and npm v3.6.0.
When I try to run nodemon, I get:

-bash: nodemon: command not found

I thought this may mean that I didn't have nodemon installed, so when I tried to install it using...

sudo npm install -g nodemon

...I get this:

npm ERR! Darwin 15.2.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "-g"     "nodemon"
npm ERR! node v5.6.0
npm ERR! npm  v3.6.0
npm ERR! path /usr/local/bin/nodemon
npm ERR! code EEXIST

npm ERR! Refusing to delete /usr/local/bin/nodemon: ../lib/node_modules/nodemon/nodemon.js symlink target is not controlled by         npm /usr/local
npm ERR! File exists: /usr/local/bin/nodemon
npm ERR! Move it away, and try again.

npm ERR! Please include the following file with any support request:
npm ERR!     /Users/brianeoneill/npm-debug.log

If it makes a difference, I'm trying to run nodemon on a project that uses Express v4.13.1

Thanks for any help you can offer!


来源: stackexchange

问:
SwiftUI how to call or notify scenedelegate from a view
I have some code (bluetooth manager) that I want to implement as a singleton for the application.

I read many tutorials online about passing environment variable & using observed object to share states, which is useful to pass data from scene delegate to views, like a list of found BT devices. However, how can views talk back to scene delegate?

For example, when the user click I a device, I would like to connect to it which requires the button click calling some method back into scene delegate where the singleton bluetooth manager resides?

答:
Potential solution:

Create a class conforming to ObservableObject with state variables and methods. Initiate it in scene delegate as a singleton object and then pass it to views as environment object.

Within each view, we will have access to methods & state within that shared singleton.

ContentLicense: CC BY-SA 4.0


问:
Handling value of DateTimePicker in React Native with Formik
I am using Formik to create a reminder form that store some information, including date and time. And I've encountered a problem while using DateTimePicker from react-native-modal-datetime-picker in my form.

My main goal is when a user press a Date or Time input, DateTimePicker will be shown. After user choose the time,  DateTimePicker will pass that value to the input and display that input onto screen. And when user press 'Submit' button, log console will print out the values props of Formik

Here is my code:

import React from 'react'
import {View, TouchableOpacity} from 'react-native'
import {Button, Input} from 'react-native-elements'
import ModalDropdown from 'react-native-modal-dropdown'
import DateTimePicker from 'react-native-modal-datetime-picker'
import {Formik} from 'formik'
import * as yup from 'yup'

export default class ReminderForm extends React.Component{
    constructor(props){
        super(props);
        this.state = {
           isDatePickerVisible: false,
           isTimePickerVisible: false,
           reminder: {
               date: '',
               time: '',
               //...more properties go here
           }
        }
    }
    showDatePicker = () => {//show the picker for Date input
        this.setState({ isDatePickerVisible: true });
    };

    hideDatePicker = () => {
        this.setState({ isDatePickerVisible: false });
    };
    handleDatePicked = date => {
        let newDate = new Date(date).toLocaleDateString();
        this.setState(prevState=> ({
            ...prevState,
            isDatePickerVisible: !prevState.isDatePickerVisible,
            reminder: {
                ...prevState.reminder,
                date: newDate
            }
        }));
        console.log(this.state);
    };
    showTimePicker = () => {//show the picker for time input
        this.setState({ isTimePickerVisible: true });
    };

    hideTimePicker = () => {
        this.setState({ isTimePickerVisible: false });
    };
    handleTimePicked = time => {
        let newTime = new Date(time).toLocaleTimeString();
        this.setState(prevState=> ({
            ...prevState,
            isTimePickerVisible: !prevState.isTimePickerVisible,
            reminder: {
                ...prevState.reminder,
                time: newTime
            }
        }))
        console.log(this.state)
    };
    render(){
        return(
            <View style = {{flex:1}}>
                 <Formik initialValues = {this.state.reminder}
                        onSubmit={()=> console.log('Submitted')}
                       >
                     {
                         ({values,handleChange,errors,setFieldTouched,touched,isValid,handleSubmit})=>(
                            <View style ={{flex:1, justifyContent:'space-around'}}>
                                <TouchableOpacity style ={{flex:1, marginTop: 10, marginBottom:10, backgroundColor:null}}
                                                  onPress={this.showDatePicker}>
                                    <Input value = {values.date}  inputContainerStyle={{height: '60%'}} onChangeText={handleChange('date')}
                                           onBlur={()=>setFieldTouched('date')} label = "Date" labelStyle = {{fontSize: 15}}/>
                                </TouchableOpacity>
                                <DateTimePicker mode="date" isVisible={this.state.isDatePickerVisible}
                                                 onConfirm={this.handleDatePicked} onCancel={this.hideDatePicker}/>
                                <TouchableOpacity style ={{flex:1, marginTop: 10, marginBottom:10, backgroundColor:null}}
                                                  onPress={this.showTimePicker}>
                                    <Input value = {values.time}
                                           onChangeText={handleChange('time')} inputContainerStyle={{height: '60%'}}
                                           onBlur={()=>setFieldTouched('time')} label = "Time" labelStyle = {{fontSize: 15}}/>
                                </TouchableOpacity>
                                <DateTimePicker mode="time" isVisible={this.state.isTimePickerVisible}
                                                 onConfirm={this.handleTimePicked} onCancel={this.hideTimePicker}/>

                             //..more inputs go here
                                 <Button containerStyle = {{flex:1, marginTop: 10, marginBottom:0}} TouchableComponent={TouchableOpacity}
                                        onPress={()=> console.log(values)}  title = "Submit" titleStyle = {{fontSize: 15}}/>

                            </View>
                         )
                     }
                 </Formik>
            </View>
         )
    }

}
```

<p>When I ran this code, date and time input did not show the value I chose in <code>DateTimePikcker</code> before, and when I submit form <code>date</code> and <code>time</code> property in <code>values</code> props got null. Then I tried to fix the input's attribute:</p>

<pre class="lang-js prettyprint-override"><code> <TouchableOpacity style ={{flex:1, marginTop: 10, marginBottom:10, backgroundColor:null}}
                                                  onPress={this.showDatePicker}>
                                    <Input value = {this.state.reminder.date}  inputContainerStyle={{height: '60%'}} onChangeText={handleChange('date')}
                                           onBlur={()=>setFieldTouched('date')} label = "Date" labelStyle = {{fontSize: 15}}/>
                                </TouchableOpacity>
</code>```

In this time the input did show value I chose from DateTimePicker but when I submit form the date property still return to null. The problem is that I don't know how to change the property in the values props of Formik when user chooses date in DateTimePicker. Can you guy help me to figure it out?

And one more problem is that handleSubmit props does not work in here. I try to put the console.log() in onSubmit attribute (you can see in my code above) but it's not working.

答:
Below is an example.  Notice the use of Formik's setFieldValue.</p>

```<code>import React, { useState } from 'react';
import { Button, Text, View } from 'react-native';
import { Formik } from 'formik';
import DateTimePickerModal from 'react-native-modal-datetime-picker';
import moment from 'moment';

export default function Example() {
  return (
    <Formik initialValues={{ myDate: moment().format('YYYY-MM-DD') }} onSubmit={values => console.log(values)}>
      {({ handleSubmit, values, setFieldValue }) => (
        <MyForm values={values} setFieldValue={setFieldValue} handleSubmit={handleSubmit} />
      )}
    </Formik>
  );
}

export const MyForm = props => {
  const { handleSubmit, values, setFieldValue } = props;
  const [isDatePickerVisible, setDatePickerVisibility] = useState(false);

  const showDatePicker = () => {
    setDatePickerVisibility(true);
  };

  const hideDatePicker = () => {
    setDatePickerVisibility(false);
  };

  const handleConfirm = date => {
    setFieldValue('myDate', moment(date).format('YYYY-MM-DD'))
    hideDatePicker();
  };

  return (
    <View>
      <Text onPress={showDatePicker}>{moment(values.myDate).format('YYYY-MM-DD')}</Text>
      <DateTimePickerModal
        isVisible={isDatePickerVisible}
        mode="date"
        onConfirm={handleConfirm}
        onCancel={hideDatePicker}
        date={moment(values.myDate).toDate()}
      />
      <Button title="Submit" onPress={handleSubmit} />
    </View>
  );
}
</code>```

Body:
I am using Formik to create a reminder form that store some information, including date and time. And I've encountered a problem while using DateTimePicker from react-native-modal-datetime-picker in my form.

My main goal is when a user press a Date or Time input, DateTimePicker will be shown. After user choose the time,  DateTimePicker will pass that value to the input and display that input onto screen. And when user press 'Submit' button, log console will print out the values props of Formik

Here is my code:

import React from 'react'
import {View, TouchableOpacity} from 'react-native'
import {Button, Input} from 'react-native-elements'
import ModalDropdown from 'react-native-modal-dropdown'
import DateTimePicker from 'react-native-modal-datetime-picker'
import {Formik} from 'formik'
import * as yup from 'yup'

export default class ReminderForm extends React.Component{
    constructor(props){
        super(props);
        this.state = {
           isDatePickerVisible: false,
           isTimePickerVisible: false,
           reminder: {
               date: '',
               time: '',
               //...more properties go here
           }
        }
    }
    showDatePicker = () => {//show the picker for Date input
        this.setState({ isDatePickerVisible: true });
    };

    hideDatePicker = () => {
        this.setState({ isDatePickerVisible: false });
    };
    handleDatePicked = date => {
        let newDate = new Date(date).toLocaleDateString();
        this.setState(prevState=> ({
            ...prevState,
            isDatePickerVisible: !prevState.isDatePickerVisible,
            reminder: {
                ...prevState.reminder,
                date: newDate
            }
        }));
        console.log(this.state);
    };
    showTimePicker = () => {//show the picker for time input
        this.setState({ isTimePickerVisible: true });
    };

    hideTimePicker = () => {
        this.setState({ isTimePickerVisible: false });
    };
    handleTimePicked = time => {
        let newTime = new Date(time).toLocaleTimeString();
        this.setState(prevState=> ({
            ...prevState,
            isTimePickerVisible: !prevState.isTimePickerVisible,
            reminder: {
                ...prevState.reminder,
                time: newTime
            }
        }))
        console.log(this.state)
    };
    render(){
        return(
            <View style = {{flex:1}}>
                 <Formik initialValues = {this.state.reminder}
                        onSubmit={()=> console.log('Submitted')}
                       >
                     {
                         ({values,handleChange,errors,setFieldTouched,touched,isValid,handleSubmit})=>(
                            <View style ={{flex:1, justifyContent:'space-around'}}>
                                <TouchableOpacity style ={{flex:1, marginTop: 10, marginBottom:10, backgroundColor:null}}
                                                  onPress={this.showDatePicker}>
                                    <Input value = {values.date}  inputContainerStyle={{height: '60%'}} onChangeText={handleChange('date')}
                                           onBlur={()=>setFieldTouched('date')} label = "Date" labelStyle = {{fontSize: 15}}/>
                                </TouchableOpacity>
                                <DateTimePicker mode="date" isVisible={this.state.isDatePickerVisible}
                                                 onConfirm={this.handleDatePicked} onCancel={this.hideDatePicker}/>
                                <TouchableOpacity style ={{flex:1, marginTop: 10, marginBottom:10, backgroundColor:null}}
                                                  onPress={this.showTimePicker}>
                                    <Input value = {values.time}
                                           onChangeText={handleChange('time')} inputContainerStyle={{height: '60%'}}
                                           onBlur={()=>setFieldTouched('time')} label = "Time" labelStyle = {{fontSize: 15}}/>
                                </TouchableOpacity>
                                <DateTimePicker mode="time" isVisible={this.state.isTimePickerVisible}
                                                 onConfirm={this.handleTimePicked} onCancel={this.hideTimePicker}/>

                             //..more inputs go here
                                 <Button containerStyle = {{flex:1, marginTop: 10, marginBottom:0}} TouchableComponent={TouchableOpacity}
                                        onPress={()=> console.log(values)}  title = "Submit" titleStyle = {{fontSize: 15}}/>

                            </View>
                         )
                     }
                 </Formik>
            </View>
         )
    }

}

When I ran this code, date and time input did not show the value I chose in DateTimePikcker before, and when I submit form date and time property in values props got null. Then I tried to fix the input's attribute:

 <TouchableOpacity style ={{flex:1, marginTop: 10, marginBottom:10, backgroundColor:null}}
                                                  onPress={this.showDatePicker}>
                                    <Input value = {this.state.reminder.date}  inputContainerStyle={{height: '60%'}} onChangeText={handleChange('date')}
                                           onBlur={()=>setFieldTouched('date')} label = "Date" labelStyle = {{fontSize: 15}}/>
                                </TouchableOpacity>

In this time the input did show value I chose from DateTimePicker but when I submit form the date property still return to null. The problem is that I don't know how to change the property in the values props of Formik when user chooses date in DateTimePicker. Can you guy help me to figure it out?

And one more problem is that handleSubmit props does not work in here. I try to put the console.log() in onSubmit attribute (you can see in my code above) but it's not working.

Body:
Below is an example.  Notice the use of Formik's setFieldValue.

import React, { useState } from 'react';
import { Button, Text, View } from 'react-native';
import { Formik } from 'formik';
import DateTimePickerModal from 'react-native-modal-datetime-picker';
import moment from 'moment';

export default function Example() {
  return (
    <Formik initialValues={{ myDate: moment().format('YYYY-MM-DD') }} onSubmit={values => console.log(values)}>
      {({ handleSubmit, values, setFieldValue }) => (
        <MyForm values={values} setFieldValue={setFieldValue} handleSubmit={handleSubmit} />
      )}
    </Formik>
  );
}

export const MyForm = props => {
  const { handleSubmit, values, setFieldValue } = props;
  const [isDatePickerVisible, setDatePickerVisibility] = useState(false);

  const showDatePicker = () => {
    setDatePickerVisibility(true);
  };

  const hideDatePicker = () => {
    setDatePickerVisibility(false);
  };

  const handleConfirm = date => {
    setFieldValue('myDate', moment(date).format('YYYY-MM-DD'))
    hideDatePicker();
  };

  return (
    <View>
      <Text onPress={showDatePicker}>{moment(values.myDate).format('YYYY-MM-DD')}</Text>
      <DateTimePickerModal
        isVisible={isDatePickerVisible}
        mode="date"
        onConfirm={handleConfirm}
        onCancel={hideDatePicker}
        date={moment(values.myDate).toDate()}
      />
      <Button title="Submit" onPress={handleSubmit} />
    </View>
  );
}


问:
Using CURL to call WebRequest
Good day,

Been trying to call an API using CURL. The CURL is below. How can i pass the {BVN} inside?

```<code>curl --location --request GET 'https://api.paystack.co/bank/resolve_bvn/{BVN}' \
--header 'Authorization: Bearer SECRET_KEY'
</code>```

The conversion of the CURL is as given below but i have issues passing the BVN parameter inside.

```<code>using (var httpClient = new HttpClient())
{ using (var request = new HttpRequestMessage(new HttpMethod("GET"),
"https://api.paystack.co/bank/resolve_bvn/{BVN}"))
{
    request.Headers.TryAddWithoutValidation("Authorization", "Bearer SECRET_KEY");

    var response = await httpClient.SendAsync(request);
}
}
</code>```

答:
I am not sure where the input is coming from, but you can do

```<code>string.format ("https://api.paystack.co/bank/resolve_bvn/{0}", BVN);
</code>```

and the code for the string BVN will go into {0}

Title: Using CURL to call WebRequest

Body:
Good day,

Been trying to call an API using CURL. The CURL is below. How can i pass the {BVN} inside?

curl --location --request GET 'https://api.paystack.co/bank/resolve_bvn/{BVN}' \
--header 'Authorization: Bearer SECRET_KEY'

The conversion of the CURL is as given below but i have issues passing the BVN parameter inside.

using (var httpClient = new HttpClient())
{ using (var request = new HttpRequestMessage(new HttpMethod("GET"),
"https://api.paystack.co/bank/resolve_bvn/{BVN}"))
{
    request.Headers.TryAddWithoutValidation("Authorization", "Bearer SECRET_KEY");

    var response = await httpClient.SendAsync(request);
}
}

Body:
I am not sure where the input is coming from, but you can do

string.format ("https://api.paystack.co/bank/resolve_bvn/{0}", BVN);

and the code for the string BVN will go into {0}


问:
How to build up a JSX component tree from an array of renderable components?
Imagine we have the following simple react components:

```<code>const A = function() { return "I'm an instance of A!" }
const B = function() { return "I'm an instance of B!" }
const C = function() { return "I'm an instance of C!" }
</code>```

Assuming the types are formed into an array, as follows:

```<code>const toRender = [A, B, C]
</code>```

...how can I render each type into a nested hierarchy such that each subsequent index denotes a new child? i.e. B is the child of A, and C is the child of B?

Something equivalent to this:

```<code>function render()
{
  return <A><B><C/></B></A>
}
</code>```

答:
Years after, but here's a nifty way to do that using reduce. And if we don't care about the order of the components, we can remove the reverse() call.

```<code>toRender.reverse().reduce((ChildrenTree, Current) => (
    <Current>{ChildrenTree}</Current>
), null)
</code>```

Body:
Imagine we have the following simple react components:

const A = function() { return "I'm an instance of A!" }
const B = function() { return "I'm an instance of B!" }
const C = function() { return "I'm an instance of C!" }

Assuming the types are formed into an array, as follows:

const toRender = [A, B, C]

...how can I render each type into a nested hierarchy such that each subsequent index denotes a new child? i.e. B is the child of A, and C is the child of B?

Something equivalent to this:

function render()
{
  return <C/>
}

Body:
Years after, but here's a nifty way to do that using reduce. And if we don't care about the order of the components, we can remove the reverse() call.

toRender.reverse().reduce((ChildrenTree, Current) => (
    <Current>{ChildrenTree}</Current>
), null)


问:
How is the space complexity O(m+n) here?
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

```<code>class Solution:
    def mergeTwoLists(self, l1, l2):
        if l1 is None:
            return l2
        elif l2 is None:
            return l1
        elif l1.val < l2.val:
            l1.next = self.mergeTwoLists(l1.next, l2)
            return l1
        else:
            l2.next = self.mergeTwoLists(l1, l2.next)
            return l2
</code>```

I know it has something to do with the stack. Can someone make this clear for me? I'm new to this thanks.

答:
The fundamental thing about the algorithm is that each recursive call is picking one element off either l1 or l2.  Since that can only happen M + N times, the time complexity is going to be O(M + N).

The space complexity is another matter.

I know it has something to do with the stack.

Yes.  In Python, recursive calls require a stack frame for each level of recursion.  The stack frame holds the call arguments and local variables, and the information needed to allow the call return to the correct place in the code that called it.

In your example, there are M + N levels so the space complexity of the stack space is O(M + N).

Assuming that your linked list nodes are implemented in an obvious fashion, your merge method is mutating the l1 and l2 objects, and is not consuming any more space.

Many languages / compilers support something called tail call optimization for many cases where a method that recursively calls itself.  When possible, the recursive call is optimized to a jump to the start of the method rather than using a call instruction.  Thus a stack frame is not required.

In your example, the space complexity for stack usage would be O(1).

However Python does not support this; see Does Python optimize tail recursion?

Body:
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

class Solution:
    def mergeTwoLists(self, l1, l2):
        if l1 is None:
            return l2
        elif l2 is None:
            return l1
        elif l1.val < l2.val:
            l1.next = self.mergeTwoLists(l1.next, l2)
            return l1
        else:
            l2.next = self.mergeTwoLists(l1, l2.next)
            return l2

I know it has something to do with the stack. Can someone make this clear for me? I'm new to this thanks.


问:
Difficult to understand Naive Bayes Predict() method
The below method is implementation of predict function in EMail Spam Detection project.

Predict the class for a given row(mail)

```<code>def predict(summaries, inputVector):
    probabilities = calculateClassProbabilities(summaries, inputVector)
    bestLabel, bestProb = None, -1
    for classValue, probability in probabilities.items():
        #print(classValue,'->',probability)
        if bestLabel is None or probability > bestProb:
            bestProb = probability
            bestLabel = classValue
    return bestLabel
</code>```

I am unable to understand how a particular data item is being classified as spam or ham by using above function

答: The calculateClassProbabilities function is doing all the real work (probably has a spam-or-not score for every word in the dictionary, and sums the scores for the emails vocabulary).  That function returns a list of possible categories ("spam", "legit", "mass email you did sign up for but dpn't actually want to read") and associated probabilities.  The loop here just finds the category with the highest probability and returns it.

Body:
The below method is implementation of predict function in EMail Spam Detection project.

Predict the class for a given row(mail)

def predict(summaries, inputVector):
    probabilities = calculateClassProbabilities(summaries, inputVector)
    bestLabel, bestProb = None, -1
    for classValue, probability in probabilities.items():
        #print(classValue,'->',probability)
        if bestLabel is None or probability > bestProb:
            bestProb = probability
            bestLabel = classValue
    return bestLabel

I am unable to understand how a particular data item is being classified as spam or ham by using above function


问:
How do I extract the information from the website?
I am trying to gather information of all the vessels from this website:
https://www.marinetraffic.com/en/data/?asset_type=vessels&columns=flag,shipname,photo,recognized_next_port,reported_eta,reported_destination,current_port,imo,ship_type,show_on_live_map,time_of_latest_position,lat_of_latest_position,lon_of_latest_position&ship_type_in|in|Cargo%20Vessels|ship_type_in=7

This is my code right now:

```<code>import selenium.webdriver as webdriver

url = "https://www.marinetraffic.com/en/data/?asset_type=vessels&columns=flag,shipname,photo,recognized_next_port,reported_eta,reported_destination,current_port,imo,ship_type,show_on_live_map,time_of_latest_position,lat_of_latest_position,lon_of_latest_position&ship_type_in|in|Cargo%20Vessels|ship_type_in=7"

browser = webdriver.Chrome(executable_path=r"C:\Users\CSA\OneDrive - College Sainte-Anne\Programming\PYTHON\Learning\WS\chromedriver_win32 (1)\chromedriver.exe")
browser.get(url)

browser.implicitly_wait(100)
Vessel_link = browser.find_element_by_class_name("ag-cell-content-link")
Vessel_link.click()

browser.implicitly_wait(30)
imo = browser.find_element_by_xpath('//*[@id="imo"]')
print(imo)
</code>```

My output

I am using selenium, which isn't going to work because. I have several thousands of ships to extract data from and it just isn't going to be efficient. (Also, I only need to extract information from Cargo Vessels (U can find that using the filter or by looking at green signs on the vessel type column.) and I need to extract the country name(flag), the Imo and the Vessels name.

What should I use? Selenium or Bs4 + requests or other libraries? And How? I just started web scraping...

I can't get the Imo nor anything! The HTML structure is very weird.

I would appreciate any help. Thank You! :)

答: I like to work with bs4 but I think this info will help to.</p>

Body:
I am trying to gather information of all the vessels from this website:
https://www.marinetraffic.com/en/data/?asset_type=vessels&columns=flag,shipname,photo,recognized_next_port,reported_eta,reported_destination,current_port,imo,ship_type,show_on_live_map,time_of_latest_position,lat_of_latest_position,lon_of_latest_position&ship_type_in|in|Cargo%20Vessels|ship_type_in=7

This is my code right now:

import selenium.webdriver as webdriver

url = "https://www.marinetraffic.com/en/data/?asset_type=vessels&columns=flag,shipname,photo,recognized_next_port,reported_eta,reported_destination,current_port,imo,ship_type,show_on_live_map,time_of_latest_position,lat_of_latest_position,lon_of_latest_position&ship_type_in|in|Cargo%20Vessels|ship_type_in=7"

browser = webdriver.Chrome(executable_path=r"C:\Users\CSA\OneDrive - College Sainte-Anne\Programming\PYTHON\Learning\WS\chromedriver_win32 (1)\chromedriver.exe")
browser.get(url)

browser.implicitly_wait(100)
Vessel_link = browser.find_element_by_class_name("ag-cell-content-link")
Vessel_link.click()

browser.implicitly_wait(30)
imo = browser.find_element_by_xpath('//*[@id="imo"]')
print(imo)

My output

I am using selenium, which isn't going to work because. I have several thousands of ships to extract data from and it just isn't going to be efficient. (Also, I only need to extract information from Cargo Vessels (U can find that using the filter or by looking at green signs on the vessel type column.) and I need to extract the country name(flag), the Imo and the Vessels name.

What should I use? Selenium or Bs4 + requests or other libraries? And How? I just started web scraping...

I can't get the Imo nor anything! The HTML structure is very weird.

I would appreciate any help. Thank You! :)


问:
How can i use a base address to get a dynamic?
So, I've been trying to get the value from a dynamic address for a while now and the results are this https://gyazo.com/82ef5920d01c4452840764111c60e046 When infact my Health value is 100,

This is what I've tried to do so far, I tried to read the Base address store it in a temp then read the temp+HealthOffset into temp again, then i would read the temp into an integer and try to print it. It doesn't work when i try to write to write to it either

```<code>#include <Windows.h>
#include <iostream >
#define base 0x0050f4f4

using namespace std;

int main()
{
    DWORD healthoffset[] = { 0xF8 };
    HWND hWnd = FindWindow(NULL, "AssaultCube");
    DWORD iProc = GetWindowThreadProcessId(hWnd, 0);
    HANDLE hProc = OpenProcess(PROCESS_ALL_ACCESS, 0, iProc);
    DWORD temp;
    int storage;
    ReadProcessMemory(hProc, (LPCVOID)base, &temp, sizeof(temp), 0);
    ReadProcessMemory(hProc, (LPCVOID)(temp + healthoffset[1]),     &temp,   sizeof(temp), 0);
    ReadProcessMemory(hProc, (LPCVOID)temp, &storage, sizeof(int), 0);
    cout << storage;
    system("PAUSE");
    return 0;
 }
</code>```

答:
The correct code is:

#include <Windows.h>
#include <iostream >
#define base 0x0050f4f4

using namespace std;

int main()
{
    DWORD healthoffset[] = { 0xF8 };
    HWND hWnd = FindWindow(NULL, "AssaultCube");
    DWORD iProc = GetWindowThreadProcessId(hWnd, 0);
    HANDLE hProc = OpenProcess(PROCESS_ALL_ACCESS, 0, iProc);

    DWORD temp;
    int storage;

    ReadProcessMemory(hProc, (LPCVOID)base, &temp, sizeof(temp), 0);
    ReadProcessMemory(hProc, (LPCVOID)(temp + healthoffset), &storage, sizeof(storage), 0);
    cout << storage;
    system("PAUSE");
    return 0;
 }
```

ContentLicense: CC BY-SA 3.0

Body:
So, I've been trying to get the value from a dynamic address for a while now and the results are this https://gyazo.com/82ef5920d01c4452840764111c60e046 When infact my Health value is 100,

This is what I've tried to do so far, I tried to read the Base address store it in a temp then read the temp+HealthOffset into temp again, then i would read the temp into an integer and try to print it. It doesn't work when i try to write to write to it either

#include <Windows.h>
#include <iostream >
#define base 0x0050f4f4

using namespace std;

int main()
{
    DWORD healthoffset[] = { 0xF8 };
    HWND hWnd = FindWindow(NULL, "AssaultCube");
    DWORD iProc = GetWindowThreadProcessId(hWnd, 0);
    HANDLE hProc = OpenProcess(PROCESS_ALL_ACCESS, 0, iProc);
    DWORD temp;
    int storage;
    ReadProcessMemory(hProc, (LPCVOID)base, &temp, sizeof(temp), 0);
    ReadProcessMemory(hProc, (LPCVOID)(temp + healthoffset[1]),     &temp,   sizeof(temp), 0);
    ReadProcessMemory(hProc, (LPCVOID)temp, &storage, sizeof(int), 0);
    cout << storage;
    system("PAUSE");
    return 0;
 }


问:
Module "django.template.context_processors" does not define a "custom_proc" attribute/class
```<code>def custom_proc(request):
"A context processor that provides 'app', 'user' and 'ip_address'."
return {
    'app': 'My app',
    'user': request.user,
    'ip_address': request.META['REMOTE_ADDR']
}
</code>```

above code is my code. a request Context. i write this code in a file context_processors.py.
and follow code is in settings.py file:
'context_processors': [
                'django.template.context_processors.custom_proc',
how to use the context processor in the view.py file?

```<code>        return render(request,'template1.html',
        {'message': 'I am view 1.'})```
    enter code here
```

答:
The path 'django.template.context_processors.custom_proc' to your context processor is not correct.

If you have created the file context_processors.py in an app directory called my_app, then your settings.py should have something like:

```<code>TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'my_app.context_processors.custom_proc',
            ],
        },
    },
]
</code>```

Body:
def custom_proc(request):
"A context processor that provides 'app', 'user' and 'ip_address'."
return {
    'app': 'My app',
    'user': request.user,
    'ip_address': request.META['REMOTE_ADDR']
}

above code is my code. a request Context. i write this code in a file context_processors.py.
and follow code is in settings.py file:
'context_processors': [
                'django.template.context_processors.custom_proc',
how to use the context processor in the view.py file?

        return render(request,'template1.html',
        {'message': 'I am view 1.'})```
    enter code here

Body:
The path 'django.template.context_processors.custom_proc' to your context processor is not correct.

If you have created the file context_processors.py in an app directory called my_app, then your settings.py should have something like:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'my_app.context_processors.custom_proc',
            ],
        },
    },
]


问:
Bizarre directory delete behaviour on SSD drive
Directory c:\test has 50 or so files in it, no subdirectories.

```<code>    If IO.Directory.Exists("C:\test") Then
        IO.Directory.Delete("C:\test", True)
    End If

    IO.Directory.CreateDirectory("C:\test")
</code>```

Drive C is Intel's X25-M80 SSD drive, OS is Windows 7 64 bit with TRIM support, Visual Studio is 2008 with target framework 3.5. When above code is executed, CreateDirectory breaks code execution without an (visible) exception. After much headache I found that Delete is not yet done by the time code execution gets to CreateDirectory. If I modify my code like this:

```<code>    If IO.Directory.Exists("C:\test") Then
        IO.Directory.Delete("C:\test", True)
    End If
    Threading.Thread.Sleep(2000)
    IO.Directory.CreateDirectory("C:\test")
</code>```

then everything works as expected.

My questions beside the obvious WTF here are:

shouldn't IO.Directory.Delete be a blocking function call no matter what the drive is

is SSD "cheating" on delete due to enabled TRIM support?

答:
After exploring System.IO.Directory with reflector, it looks like .Delete is just a wrapper around the FindFirstFile, FindNextFile, and RemoveDirectory Win API calls. There's nothing threaded or asynchronous about the .Net runtime's invokation of those API calls, or the API implementation themselves.

Now, supposing its somehow a TRIM issue, you can disable TRIM by opening an elevated command prompt and using fsutil:

```<code>fsutil behavior set disabledeletenotify 1
</code>```

To enable, run the same command with 0 as parameter.

To query, use query as the command argument:

```<code>fsutil behavior query disabledeletenotify
</code>```

Body:
Directory c:\test has 50 or so files in it, no subdirectories.

    If IO.Directory.Exists("C:\test") Then
        IO.Directory.Delete("C:\test", True)
    End If

    IO.Directory.CreateDirectory("C:\test")

Drive C is Intel's X25-M80 SSD drive, OS is Windows 7 64 bit with TRIM support, Visual Studio is 2008 with target framework 3.5. When above code is executed, CreateDirectory breaks code execution without an (visible) exception. After much headache I found that Delete is not yet done by the time code execution gets to CreateDirectory. If I modify my code like this:

    If IO.Directory.Exists("C:\test") Then
        IO.Directory.Delete("C:\test", True)
    End If
    Threading.Thread.Sleep(2000)
    IO.Directory.CreateDirectory("C:\test")

then everything works as expected.

My questions beside the obvious WTF here are:

shouldn't IO.Directory.Delete be a blocking function call no matter what the drive is

is SSD "cheating" on delete due to enabled TRIM support?

Body:
After exploring System.IO.Directory with reflector, it looks like .Delete is just a wrapper around the FindFirstFile, FindNextFile, and RemoveDirectory Win API calls. There's nothing threaded or asynchronous about the .Net runtime's invokation of those API calls, or the API implementation themselves.

Now, supposing its somehow a TRIM issue, you can disable TRIM by opening an elevated command prompt and using fsutil:

fsutil behavior set disabledeletenotify 1

To enable, run the same command with 0 as parameter.

To query, use query as the command argument:

fsutil behavior query disabledeletenotify


问:
Recursion problems in C
I am working on an anagram solver in C. Hit a problem where the solver will return the first few anagrams correctly, however on ones that extend past 2 words, it begins to enter an infinite loop.

Example:

I enter "team sale rest" into the anagram solver, it responds with teamster ale, and a few others. Then when it arrives at releases, it enters an infinite loop where it prints "releases am matt" "releases am am matt" etc.

Here is the code base:

```<code>//recursively find matches for each sub-word
int findMatches(char string[], char found_so_far[])
{
    printf("String entering function: %s\n", string);
    int string_length = strlen(string);
    int_char_ptr *results = getPowerSet(string, string_length);
    if(!results)
        return 2;
    // selects length of subset, starting with the largest
    for (int i = string_length - 1; i > 0; i--)
    {
        // iterates through all the subsets of a particular length
        for(int j = 0; j < results->count[i]; j++)
        {
            word_array *matches = NULL;
            // check words against dictionary
            matches = dictionary_check(results->table[i][j]);
            if (matches)
            {
                // iterate through matches
                for(size_t k = 0; k < matches->size; k++)
                {
                    int found_length;
                    // find out length of string needed for found
                    if (strcmp(found_so_far, "") == 0)
                        found_length = strlen(matches->arr[k]) + 1;
                    else
                        found_length = strlen(found_so_far) + strlen(matches->arr[k]) + 2;
                    char found[found_length];

                    // on first passthrough, copy directly from matches
                    if (strcmp(found_so_far, "") == 0)
                        strcpy(found, matches->arr[k]);
                    else
                        sprintf(found, "%s %s", found_so_far, matches->arr[k]);
                    char tempstr[string_length];
                    strcpy(tempstr, string);
                    char *remain = get_remaining_letters(tempstr, results->table[i][j]);
                    // if there are no letters remaining
                    if (strcmp(remain, "") == 0)
                    {
                        printf("MATCH FOUND: %s \n", found);
                        // alternatively, could store strings to array
                    }
                    else
                    {
                        findMatches(remain, found);
                    }
                }
            }
        }
        free(results->table[i][results->count[i] - 1]);
        free(results->table[i]);
    }
    return 0;
}
</code>```

How I read it (I am obviously missing something) is that it should try to match all matches, and if it can't , it should move to the next subset of letters found.

I have tries going through with a debugger, and cant make rhyme or reason of it.

答:
As mentioned above in the commment:

get_remaining_letters used the original results->table[i][j] and removed the letters. This would leave an empty string for the next iteration and cause it to not perform as expected. Fixed by copying the string to a temporary one inside that function.

Title: Recursion problems in C

Body:
I am working on an anagram solver in C. Hit a problem where the solver will return the first few anagrams correctly, however on ones that extend past 2 words, it begins to enter an infinite loop.

Example:

I enter "team sale rest" into the anagram solver, it responds with teamster ale, and a few others. Then when it arrives at releases, it enters an infinite loop where it prints "releases am matt" "releases am am matt" etc.

Here is the code base:

//recursively find matches for each sub-word
int findMatches(char string[], char found_so_far[])
{
    printf("String entering function: %s\n", string);
    int string_length = strlen(string);
    int_char_ptr *results = getPowerSet(string, string_length);
    if(!results)
        return 2;
    // selects length of subset, starting with the largest
    for (int i = string_length - 1; i > 0; i--)
    {
        // iterates through all the subsets of a particular length
        for(int j = 0; j < results->count[i]; j++)
        {
            word_array *matches = NULL;
            // check words against dictionary
            matches = dictionary_check(results->table[i][j]);
            if (matches)
            {
                // iterate through matches
                for(size_t k = 0; k < matches->size; k++)
                {
                    int found_length;
                    // find out length of string needed for found
                    if (strcmp(found_so_far, "") == 0)
                        found_length = strlen(matches->arr[k]) + 1;
                    else
                        found_length = strlen(found_so_far) + strlen(matches->arr[k]) + 2;
                    char found[found_length];

                    // on first passthrough, copy directly from matches
                    if (strcmp(found_so_far, "") == 0)
                        strcpy(found, matches->arr[k]);
                    else
                        sprintf(found, "%s %s", found_so_far, matches->arr[k]);
                    char tempstr[string_length];
                    strcpy(tempstr, string);
                    char *remain = get_remaining_letters(tempstr, results->table[i][j]);
                    // if there are no letters remaining
                    if (strcmp(remain, "") == 0)
                    {
                        printf("MATCH FOUND: %s \n", found);
                        // alternatively, could store strings to array
                    }
                    else
                    {
                        findMatches(remain, found);
                    }
                }
            }
        }
        free(results->table[i][results->count[i] - 1]);
        free(results->table[i]);
    }
    return 0;
}

How I read it (I am obviously missing something) is that it should try to match all matches, and if it can't , it should move to the next subset of letters found.

I have tries going through with a debugger, and cant make rhyme or reason of it.


问:
Add property to React Typescript High Order Component including implementation
I'm trying to build a React HOC that I want to do the following:

Take a passed in component, add (or override) the hidden property, and return the modified component

Render the component such that when 'hidden' is true, nothing is rendered

I have this working for specific components as follows in Typescript

```<code>import React from 'react';
import { FabProps, Fab } from '@material-ui/core';
import ButtonWithText, { ButtonWithTextProps } from '../UserInterface/ButtonWithText';

interface IFabWithHiddenProps {
    hidden?: boolean;
}

export class ButtonWithTextWithHidden extends React.Component<ButtonWithTextProps & IFabWithHiddenProps> {
    render(){
        const {
            hidden,
            ...buttonProps
        } = this.props;

        if (hidden === undefined || hidden) {
            return <></>;
        }
        else {
            return <ButtonWithText {...buttonProps} />;
        }
    }
}

export class FabWithHidden extends React.Component<FabProps & IFabWithHiddenProps> {
    render(){
        const {
            hidden,
            ...buttonProps
        } = this.props;

        if (hidden === undefined || hidden) {
            return <></>;
        }
        else {
            return <Fab {...buttonProps} />;
        }
    }
}
</code>```

However, I would like to turn these two classes into one HOC. Any suggestions?

EDIT: I'd like the something that is generic enough to handle ALL component types going forward, not just these two cases so I can easily use the HOC on components other than Fab and ButtonWithText.

答:
i think you nee to merge your two interfaces and handle your problem like so : </p>

```<code>interface IFabWithHiddenProps extends ButtonWithTextProps , FabProps  {
  hidden?:boolean;
  type : string; // this can be fab | button
}

</code>```

<p>and use it like so : </p>

```<code>export default class FabOrButtonWithHidden extends React.Component<IFabWithHiddenProps> {
    render(){
        const {
            hidden,
            type
            ...rest
        } = this.props;

        if (hidden === undefined || hidden) {
            return <></>;
        } else if(type === "button") {
           return (
            <ButtonWithText {...rest} />
           )

        }
        else {
            return <Fab {...rest} />;
        }
    }
}

</code>```

Body:
I'm trying to build a React HOC that I want to do the following:

Take a passed in component, add (or override) the hidden property, and return the modified component

Render the component such that when 'hidden' is true, nothing is rendered

I have this working for specific components as follows in Typescript

import React from 'react';
import { FabProps, Fab } from '@material-ui/core';
import ButtonWithText, { ButtonWithTextProps } from '../UserInterface/ButtonWithText';

interface IFabWithHiddenProps {
    hidden?: boolean;
}

export class ButtonWithTextWithHidden extends React.Component<ButtonWithTextProps & IFabWithHiddenProps> {
    render(){
        const {
            hidden,
            ...buttonProps
        } = this.props;

        if (hidden === undefined || hidden) {
            return <></>;
        }
        else {
            return <ButtonWithText {...buttonProps} />;
        }
    }
}

export class FabWithHidden extends React.Component<FabProps & IFabWithHiddenProps> {
    render(){
        const {
            hidden,
            ...buttonProps
        } = this.props;

        if (hidden === undefined || hidden) {
            return <></>;
        }
        else {
            return <Fab {...buttonProps} />;
        }
    }
}

However, I would like to turn these two classes into one HOC. Any suggestions?

EDIT: I'd like the something that is generic enough to handle ALL component types going forward, not just these two cases so I can easily use the HOC on components other than Fab and ButtonWithText.

Body:
i think you nee to merge your two interfaces and handle your problem like so :

interface IFabWithHiddenProps extends ButtonWithTextProps , FabProps  {
  hidden?:boolean;
  type : string; // this can be fab | button
}

and use it like so :

export default class FabOrButtonWithHidden extends React.Component<IFabWithHiddenProps> {
    render(){
        const {
            hidden,
            type
            ...rest
        } = this.props;

        if (hidden === undefined || hidden) {
            return <></>;
        } else if(type === "button") {
           return (
            <ButtonWithText {...rest} />
           )

        }
        else {
            return <Fab {...rest} />;
        }
    }
}


问:
How do I attach a debugger to native code of a release build in a react-native Android app?
I have a react-native app that's crashing in native code but only on Android release mode builds. I know it's possible to debug native code in Android Studio in debug mode. How do I attach a debugger to native code with Android Studio in release mode?</p>

答:
This is the library i use to report production bugs and crashes : bugsnag- .Its pretty good , you get a report of all the errors which your users face and also along with devices id and mobile type.Its integrtaion is pretty simple.

Hope it helps. feel free for doubts.


问:
How do I get the empty value in JSON response?
consider the code below:

```<code>fetch(`http://localhost:9000/api/item/list?searchText=${search}`,)
  .then((resp)=>{
   resp.json().then((res)=>{
   if(res.data === 0){
      alert("Sorry, your item cannot be found")
    }else{
      console.log(res.data);
      this.setState({data: res.data});}
 }

</code>```

Here is my response from console log:

So when data is empty, the alert message will show out. I have try for null but also same. The alert message cannot be show. is it anything I'm wrong?

答:
Instead of res.data === 0

Try !res.data.length or res.data.length === 0

Body:
consider the code below:

fetch(`http://localhost:9000/api/item/list?searchText=${search}`,)
  .then((resp)=>{
   resp.json().then((res)=>{
   if(res.data === 0){
      alert("Sorry, your item cannot be found")
    }else{
      console.log(res.data);
      this.setState({data: res.data});}
 }

Here is my response from console log:

So when data is empty, the alert message will show out. I have try for null but also same. The alert message cannot be show. is it anything I'm wrong?


问:
"AttributeError: 'DataFrame' object has no attribute 'dtype'" using pandas to_datetime
I have been using Python 2.7.13 on a windows machine to write my code.  But I am now trying to run my code on a Unix cluster using Python 2.7.12-goolf-2015a. When I run my code on the cluster with 2.7.12, I encounter an error in the pandas function to_datetime which does not occur using 2.7.13.

The error occurs when I try to convert a date entries in a dataframe to datetime.

df = pd.DataFrame({'year': [2015, 2016],
                       'month': [2, 3],
                       'day': [4, 5]})
pd.to_datetime(df)
```
<p>Here is an example ot the error I get with the <code>to_datetime</code> command</p>
```Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/easybuild/software/Python/2.7.12-goolf-
2015a/lib/python2.7/site-packages/pandas-0.16.1-py2.7-linux-
x86_64.egg/pandas/tseries/tools.py", line 343, in to_datetime
return _convert_listlike(arg, box, format)
File "/usr/local/easybuild/software/Python/2.7.12-goolf-
2015a/lib/python2.7/site-packages/pandas-0.16.1-py2.7-linux-
x86_64.egg/pandas/tseries/tools.py", line 266, in _convert_listlike
if com.is_datetime64_ns_dtype(arg):
File "/usr/local/easybuild/software/Python/2.7.12-goolf-
2015a/lib/python2.7/site-packages/pandas-0.16.1-py2.7-linux-
x86_64.egg/pandas/core/common.py", line 2513, in is_datetime64_ns_dtype
tipo = _get_dtype(arr_or_dtype)
File "/usr/local/easybuild/software/Python/2.7.12-goolf-
2015a/lib/python2.7/site-packages/pandas-0.16.1-py2.7-linux-
x86_64.egg/pandas/core/common.py", line 2458, in _get_dtype
return arr_or_dtype.dtype
File "/usr/local/easybuild/software/Python/2.7.12-goolf-
2015a/lib/python2.7/site-packages/pandas-0.16.1-py2.7-linux-
x86_64.egg/pandas/core/generic.py", line 2083, in __getattr__
(type(self).__name__, name))
AttributeError: 'DataFrame' object has no attribute 'dtype'
```

The to_datetime works when I load Python/3.5.2-intel-2016.u3, but that causes other problems. I am inexperienced with Unix operating systems and as I don’t have admin rights to software on the cluster, I am pretty tied to using 2.7.12

答:
DataFrame.dtypes is an attribute to list data types, for series it's a dtype.

reference: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.dtypes.html

Body:
I have been using Python 2.7.13 on a windows machine to write my code.  But I am now trying to run my code on a Unix cluster using Python 2.7.12-goolf-2015a. When I run my code on the cluster with 2.7.12, I encounter an error in the pandas function to_datetime which does not occur using 2.7.13.

The error occurs when I try to convert a date entries in a dataframe to datetime.

df = pd.DataFrame({'year': [2015, 2016],
                       'month': [2, 3],
                       'day': [4, 5]})
pd.to_datetime(df)

Here is an example ot the error I get with the to_datetime command

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/easybuild/software/Python/2.7.12-goolf-
2015a/lib/python2.7/site-packages/pandas-0.16.1-py2.7-linux-
x86_64.egg/pandas/tseries/tools.py", line 343, in to_datetime
return _convert_listlike(arg, box, format)
File "/usr/local/easybuild/software/Python/2.7.12-goolf-
2015a/lib/python2.7/site-packages/pandas-0.16.1-py2.7-linux-
x86_64.egg/pandas/tseries/tools.py", line 266, in _convert_listlike
if com.is_datetime64_ns_dtype(arg):
File "/usr/local/easybuild/software/Python/2.7.12-goolf-
2015a/lib/python2.7/site-packages/pandas-0.16.1-py2.7-linux-
x86_64.egg/pandas/core/common.py", line 2513, in is_datetime64_ns_dtype
tipo = _get_dtype(arr_or_dtype)
File "/usr/local/easybuild/software/Python/2.7.12-goolf-
2015a/lib/python2.7/site-packages/pandas-0.16.1-py2.7-linux-
x86_64.egg/pandas/core/common.py", line 2458, in _get_dtype
return arr_or_dtype.dtype
File "/usr/local/easybuild/software/Python/2.7.12-goolf-
2015a/lib/python2.7/site-packages/pandas-0.16.1-py2.7-linux-
x86_64.egg/pandas/core/generic.py", line 2083, in __getattr__
(type(self).__name__, name))
AttributeError: 'DataFrame' object has no attribute 'dtype'

The to_datetime works when I load Python/3.5.2-intel-2016.u3, but that causes other problems. I am inexperienced with Unix operating systems and as I don’t have admin rights to software on the cluster, I am pretty tied to using 2.7.12


问:
Is it possible to extract value of a parameter in Verilog
I was trying to generalize a module that had the parameter "int max=15". Is there some way to set an output of the module to the value of the parameter. For example, if the parameter max was set to the value 8, zout would be set to the value of 4'b1000.</p>

```<code>    module example
    #(parameter int max=15,
    parameter int bw=$clog2(m))
    (input logic ............,
    .........................,
    output logic [b-1:0] zout);
    assign zout = [value of max];
</code>```

答:
You can directly assign it:</p>

```<code>module example #(
    parameter int max=15,
    parameter int b=$clog2(max+1)
) (
    output logic [b-1:0] zout
);

    assign zout = max[b-1:0];

endmodule
</code>```

Body:
I was trying to generalize a module that had the parameter "int max=15". Is there some way to set an output of the module to the value of the parameter. For example, if the parameter max was set to the value 8, zout would be set to the value of 4'b1000.

    module example
    #(parameter int max=15,
    parameter int bw=$clog2(m))
    (input logic ............,
    .........................,
    output logic [b-1:0] zout);
    assign zout = [value of max];

Body:
You can directly assign it:

module example #(
    parameter int max=15,
    parameter int b=$clog2(max+1)
) (
    output logic [b-1:0] zout
);

    assign zout = max[b-1:0];

endmodule


问:
Alter WordPress theme nav bar positioning
I am attempting to move a WP theme's nav bar next to its designated logo area to no avail (like this: http://screencast.com/t/UsPhTZ3SM) Any ideas? Here is the header.php code: http://pastebin.com/mr7mtpMG

Many thanks,

Alex

答:
If I were you and trying to simply move the Nav under the header, I would just switch these sections.  But that's me, and I'm a big fan of trial and error...

```<code><div id="top-header"> <!-- top navigation bar -->
     .....
</div><!--end header-->

<div class="clear"></div>

<div id="header"><!-- header -->
     .....
</div><!-- end header -->
</code>```

Switch to:

```<code><div id="header"><!-- header -->
     .....
</div><!-- end header -->

<div class="clear"></div>

<div id="top-header"> <!-- top navigation bar -->
     .....
</div><!--end header-->
</code>```

But again, I'm the type of person that doesn't mind breaking things in the interest of learning...

Body:
If I were you and trying to simply move the Nav under the header, I would just switch these sections.  But that's me, and I'm a big fan of trial and error...

<div id="top-header"> <!-- top navigation bar -->
     .....
</div><!--end header-->

<div class="clear"></div>

<div id="header"><!-- header -->
     .....
</div><!-- end header -->

Switch to:

<div id="header"><!-- header -->
     .....
</div><!-- end header -->

<div class="clear"></div>

<div id="top-header"> <!-- top navigation bar -->
     .....
</div><!--end header-->

But again, I'm the type of person that doesn't mind breaking things in the interest of learning...


问:
How can I parse a List inside a List in Flutter?
I'm having problem parsin this json because I can parse "indice" but I can parse "capitulos". I get the error:
Exception has occurred. _TypeError (type 'String' is not a subtype of type 'Map')
How can I parse a list inside a list, please?
I read a great article by Pooja Bhaumik but id does not covert this example.

```<code>[
    {
        "id": "1",
        "title": "title",
        "origem": "origin",
        "tipo": "type",
        "indice": [
            {
                "id": 1,
                "title": "title 1"
            },
            {
                "id": 2,
                "title": "title 2"
            },
        ],
        "capitulos": [
            [
                "chapter 1 text 1",
                "chapter 1 text 2",
                "chapter 1 text 3"
            ],
            [
                "chapter 2 text 1",
                "chapter 2 text 2",
                "chapter 2 text 3"
            ],
        ]
    }
]
</code>```

My model:

```<code>class DocumentosList {
  final List<Documento> documentos;

  DocumentosList({
    this.documentos,
  });

  factory DocumentosList.fromJson(List<dynamic> parsedJson) {
    List<Documento> documentos = new List<Documento>();
    documentos = parsedJson.map((i) => Documento.fromJson(i)).toList();

    return new DocumentosList(documentos: documentos);
  }
}

class Documento {
  String id;
  String title;
  String origem;
  String tipo;
  List<IndiceItem> indice;
  List<Capitulos> capitulos;

  Documento({
    this.id,
    this.title,
    this.origem,
    this.tipo,
    this.indice,
    this.capitulos,
  });

  factory Documento.fromJson(Map<String, dynamic> parsedJson) {
    var list = parsedJson['indice'] as List;
    List<IndiceItem> indice = list.map((i) => IndiceItem.fromJson(i)).toList();

    var listCapitulos = parsedJson['capitulos'];
    List<Capitulos> capitulos =
        listCapitulos.map((i) => Capitulos.fromJson(i)).toList();

    return new Documento(
      id: parsedJson['id'],
      title: parsedJson['title'],
      origem: parsedJson['origem'],
      indice: indice,
      capitulos: capitulos,
    );
  }
}

class IndiceItem {
  String id;
  String title;

  IndiceItem({
    this.id,
    this.title,
  });

  factory IndiceItem.fromJson(Map<String, dynamic> parsedJson) {
    return IndiceItem(
      id: parsedJson['id'].toString(),
      title: parsedJson['title'],
    );
  }
}

class Capitulos {
  final List<Capitulo> capitulos;

  Capitulos({this.capitulos});

  factory Capitulos.fromJson(List<dynamic> parsedJson) {
    List<Capitulo> capitulos = new List<Capitulo>();
    capitulos = parsedJson.map((i) => Capitulo.fromJson(i)).toList();

    return new Capitulos(capitulos: capitulos);
  }
}

class Capitulo {
  final List<String> paragrafos;

  Capitulo({this.paragrafos});

  factory Capitulo.fromJson(Map<String, dynamic> parsedJson) {
    var paragrafosFromJson = parsedJson['paragrafos'];
    List<String> paragrafosList = paragrafosFromJson.cast<String>();

    return new Capitulo(
      paragrafos: paragrafosList,
    );
  }
}
</code>```

答:
Nothing special here, since the inner list has String type, you should use

```<code>List<List<String>> capitulos
</code>```

and you should make necessary changes for fromJson and toJson as well.

Body:
I'm having problem parsin this json because I can parse "indice" but I can parse "capitulos". I get the error:
Exception has occurred. _TypeError (type 'String' is not a subtype of type 'Map')
How can I parse a list inside a list, please?
I read a great article by Pooja Bhaumik but id does not covert this example.

[
    {
        "id": "1",
        "title": "title",
        "origem": "origin",
        "tipo": "type",
        "indice": [
            {
                "id": 1,
                "title": "title 1"
            },
            {
                "id": 2,
                "title": "title 2"
            },
        ],
        "capitulos": [
            [
                "chapter 1 text 1",
                "chapter 1 text 2",
                "chapter 1 text 3"
            ],
            [
                "chapter 2 text 1",
                "chapter 2 text 2",
                "chapter 2 text 3"
            ],
        ]
    }
]

My model:

class DocumentosList {
  final List<Documento> documentos;

  DocumentosList({
    this.documentos,
  });

  factory DocumentosList.fromJson(List<dynamic> parsedJson) {
    List<Documento> documentos = new List<Documento>();
    documentos = parsedJson.map((i) => Documento.fromJson(i)).toList();

    return new DocumentosList(documentos: documentos);
  }
}

class Documento {
  String id;
  String title;
  String origem;
  String tipo;
  List<IndiceItem> indice;
  List<Capitulos> capitulos;

  Documento({
    this.id,
    this.title,
    this.origem,
    this.tipo,
    this.indice,
    this.capitulos,
  });

  factory Documento.fromJson(Map<String, dynamic> parsedJson) {
    var list = parsedJson['indice'] as List;
    List<IndiceItem> indice = list.map((i) => IndiceItem.fromJson(i)).toList();

    var listCapitulos = parsedJson['capitulos'];
    List<Capitulos> capitulos =
        listCapitulos.map((i) => Capitulos.fromJson(i)).toList();

    return new Documento(
      id: parsedJson['id'],
      title: parsedJson['title'],
      origem: parsedJson['origem'],
      indice: indice,
      capitulos: capitulos,
    );
  }
}

class IndiceItem {
  String id;
  String title;

  IndiceItem({
    this.id,
    this.title,
  });

  factory IndiceItem.fromJson(Map<String, dynamic> parsedJson) {
    return IndiceItem(
      id: parsedJson['id'].toString(),
      title: parsedJson['title'],
    );
  }
}

class Capitulos {
  final List<Capitulo> capitulos;

  Capitulos({this.capitulos});

  factory Capitulos.fromJson(List<dynamic> parsedJson) {
    List<Capitulo> capitulos = new List<Capitulo>();
    capitulos = parsedJson.map((i) => Capitulo.fromJson(i)).toList();

    return new Capitulos(capitulos: capitulos);
  }
}

class Capitulo {
  final List<String> paragrafos;

  Capitulo({this.paragrafos});

  factory Capitulo.fromJson(Map<String, dynamic> parsedJson) {
    var paragrafosFromJson = parsedJson['paragrafos'];
    List<String> paragrafosList = paragrafosFromJson.cast<String>();

    return new Capitulo(
      paragrafos: paragrafosList,
    );
  }
}

Body:
Nothing special here, since the inner list has String type, you should use

List<List<String>> capitulos

and you should make necessary changes for fromJson and toJson as well.


问:
How to get specific message from other folder rather than Inbox using (WebKlex)
```<code>$oFolder = $oClient->getFolder('INBOX.Drafts');<br>
$oFolder = $oMessage = $oFolder->getMessage($uid = 2);
</code>```

This function only return or get specific message from inbox but it not work on other folder like spam, drafts, junk, etc ,
I'm using Laravel library https://github.com/Webklex/laravel-imap#folderclass

答:
As Elias Soares mentioned above; use getFolders() to retrieve information about all the folders. Then get the complete path for a given folder name.

And then use that folder name to fetch your message.

You can use this code as example:

```<code>$mailBoxes = $oClient->getFolders();
$folder = $request->input("folder");

$folder = getFolderPath($mailBoxes,$folder);

$oFolder = $oClient->getFolder($folder);
</code>```

And the code for getFolderPath():

```<code>function getFolderPath($mailBoxes,$folder){

        $flag=0;
        foreach($mailBoxes as $mailBox){
            if(strtolower($folder)==strtolower($mailBox->name)){
                $curFolder = $mailBox->name;
                $flag=1;
            }

            foreach ($mailBox->children as $child){
                if(strtolower($folder)==strtolower($child->name)){
                    $curFolder = $child->full_name;
                    $flag=1;
                    break;
                }
            }

            if($flag==1){
                break;
            }
        }

        if(!empty($curFolder)){
            $folder = $curFolder;
        }

        return $folder;
    }
</code>```

Body:
$oFolder = $oClient->getFolder('INBOX.Drafts');

$oFolder = $oMessage = $oFolder->getMessage($uid = 2);

This function only return or get specific message from inbox but it not work on other folder like spam, drafts, junk, etc ,
I'm using Laravel library https://github.com/Webklex/laravel-imap#folderclass

Body:
As Elias Soares mentioned above; use getFolders() to retrieve information about all the folders. Then get the complete path for a given folder name.

And then use that folder name to fetch your message.

You can use this code as example:

$mailBoxes = $oClient->getFolders();
$folder = $request->input("folder");

$folder = getFolderPath($mailBoxes,$folder);

$oFolder = $oClient->getFolder($folder);

And the code for getFolderPath():

function getFolderPath($mailBoxes,$folder){

        $flag=0;
        foreach($mailBoxes as $mailBox){
            if(strtolower($folder)==strtolower($mailBox->name)){
                $curFolder = $mailBox->name;
                $flag=1;
            }

            foreach ($mailBox->children as $child){
                if(strtolower($folder)==strtolower($child->name)){
                    $curFolder = $child->full_name;
                    $flag=1;
                    break;
                }
            }

            if($flag==1){
                break;
            }
        }

        if(!empty($curFolder)){
            $folder = $curFolder;
        }

        return $folder;
    }


问:
I can't Update my prefab at Unity because the option from override are blacked out
I'm a beginner at unity and  I have had a little problem in my unity project. I can't update  my prefab because the option from override are blacked out, look the image below:

Image of my unity project

ok,  Unity said that there's a invalid script which is contained in Prefab. But I don't what's the script and how to exclude it from Prefab, therefore I don't know how to resolve the issue. Can someone help me???

答:
You need to right click on gameobject
Then select unpack prefab completely
Then remove those bad scripts then make it prefab by drag drop</p>


问:
Lottery program c# saving and comparing winning numbers in lists
I have seemed to hit a dead-end in my coding of a lottery program in c# and I am looking for some pointer. What I am trying to do is let the user enter 7 numbers, which will be their lottery "ticket" then I want to draw one or multiple 7 digits winning numbers and compare it to the user's number and see how many times they had 5 correct answers, 6 correct answers and so on. This is what I currently am doing

```<code>while(a counter < the number of times I want to draw a winning number )
{
 add the users 7 numbers to a list

 add 7 random numbers to a list

 compare and see how many winnings

 track how many times 5 correct, 6 correct, etc

 loop until number of times I want to draw a winning number

}
</code>```

this does work, but if I draw a winning number 100 000 times, some of the lots will repeat so to say, and i don't want that

this is what I would want to do

add the users 7 digits to some sort of list (easy)

add 1000(for example) unique winning lots to a list (2, 1, 16, 32, 5, 9, 17 could be a winner for example)

compare the users 7 numbers to the 1000 winning lots and see how many times I got a certain amount of numbers correct

can I get some pointers or ideas of how I should accomplish this? maybe I can use a HashSet? since they only allow unique numbers, but how would I add the lots to the list since I don't want to add them like this 7321114181923 but rather 7 32 11 14 18 19 23

答:
One simplistic way of doing this would be to store the winning number combination in a list (as a single winning combination), and then you can have a list of lists that holds all the winning combinations.

Similarly, store the user's number combination in a list, and then you can see how many matches those numbers had with the winning numbers.

For example:

```<code>private static readonly Random Rnd = new Random();

// A helper function that returns a list of unique, random numbers from 1 to 49
private static List<int> GetRandomLotteryTicket()
{
    var possibilites = Enumerable.Range(1, 49).ToList();
    var ticket = new List<int>();

    for (int i = 0; i < 7; i++)
    {
        // Choose a random number from the possibilites
        var randomNumber = possibilites[Rnd.Next(possibilites.Count)];
        ticket.Add(randomNumber);
        // Then remove it so we don't select it a second time
        possibilites.Remove(randomNumber);
    }

    return ticket;
}

static void Main()
{
    // 5 random lottery tickets added as sample data
    var winningTickets = new List<List<int>>
    {
        GetRandomLotteryTicket(),
        GetRandomLotteryTicket(),
        GetRandomLotteryTicket(),
        GetRandomLotteryTicket(),
        GetRandomLotteryTicket()
    };

    // Normally you'd get this from the user, this is just sample data
    var userTicket = GetRandomLotteryTicket();

    Console.WriteLine($"Your numbers are: {string.Join("-", userTicket)}\n");

    foreach (var winningTicket in winningTickets)
    {
        var matchCount = winningTicket.Intersect(userTicket).Count();
        Console.WriteLine($"You matched {matchCount} numbers " +
            $"with this ticket: {string.Join("-", winningTicket)}");
    }

    GetKeyFromUser("\nPress any key to exit...");
}
</code>```

Output

Body:
I have seemed to hit a dead-end in my coding of a lottery program in c# and I am looking for some pointer. What I am trying to do is let the user enter 7 numbers, which will be their lottery "ticket" then I want to draw one or multiple 7 digits winning numbers and compare it to the user's number and see how many times they had 5 correct answers, 6 correct answers and so on. This is what I currently am doing

while(a counter < the number of times I want to draw a winning number )
{
 add the users 7 numbers to a list

 add 7 random numbers to a list

 compare and see how many winnings

 track how many times 5 correct, 6 correct, etc

 loop until number of times I want to draw a winning number

}

this does work, but if I draw a winning number 100 000 times, some of the lots will repeat so to say, and i don't want that

this is what I would want to do

add the users 7 digits to some sort of list (easy)

add 1000(for example) unique winning lots to a list (2, 1, 16, 32, 5, 9, 17 could be a winner for example)

compare the users 7 numbers to the 1000 winning lots and see how many times I got a certain amount of numbers correct

can I get some pointers or ideas of how I should accomplish this? maybe I can use a HashSet? since they only allow unique numbers, but how would I add the lots to the list since I don't want to add them like this 7321114181923 but rather 7 32 11 14 18 19 23

Body:
One simplistic way of doing this would be to store the winning number combination in a list (as a single winning combination), and then you can have a list of lists that holds all the winning combinations.

Similarly, store the user's number combination in a list, and then you can see how many matches those numbers had with the winning numbers.

For example:

private static readonly Random Rnd = new Random();

// A helper function that returns a list of unique, random numbers from 1 to 49
private static List<int> GetRandomLotteryTicket()
{
    var possibilites = Enumerable.Range(1, 49).ToList();
    var ticket = new List<int>();

    for (int i = 0; i < 7; i++)
    {
        // Choose a random number from the possibilites
        var randomNumber = possibilites[Rnd.Next(possibilites.Count)];
        ticket.Add(randomNumber);
        // Then remove it so we don't select it a second time
        possibilites.Remove(randomNumber);
    }

    return ticket;
}

static void Main()
{
    // 5 random lottery tickets added as sample data
    var winningTickets = new List<List<int>>
    {
        GetRandomLotteryTicket(),
        GetRandomLotteryTicket(),
        GetRandomLotteryTicket(),
        GetRandomLotteryTicket(),
        GetRandomLotteryTicket()
    };

    // Normally you'd get this from the user, this is just sample data
    var userTicket = GetRandomLotteryTicket();

    Console.WriteLine($"Your numbers are: {string.Join("-", userTicket)}\n");

    foreach (var winningTicket in winningTickets)
    {
        var matchCount = winningTicket.Intersect(userTicket).Count();
        Console.WriteLine($"You matched {matchCount} numbers " +
            $"with this ticket: {string.Join("-", winningTicket)}");
    }

    GetKeyFromUser("\nPress any key to exit...");
}

Output


问:
Minimum path Algorithm
I know it's not quite a programming issue but a math problem instead but I'll hope someone of you could answer me :)

I'm looking for an algorithm that let me find minimum path across n points if I know all the distances between all the points.

For example: I have twelve points (A, B, C, ... H) and I know all the distances between couples of points (AB, BC, ..., GH, ecc...). If I want to go from A to H passing all the others points with the minimum path, wich way I need to take?

I know trying all the possible ways and choose the shortest isn't a good way (for 12 points you have 12! possible ways and I need to use this algorithm for more than 12 points...) but all the other algorithm I've found are too difficult to understand (like the Dijkstra one).

Can someone help me explaining me a way to implement a useful algorithm? I'm programming with Java but I don't know how I can write down the Dijkstra one (I can't understand it) and I haven't other ideas...

答:
Traveling Salesman Problem.

Here is my solution (I know mine is brute force, but I just wanted to share my solution):

```<code>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Locale;

import javax.swing.JSplitPane;

/* VPW Template */

public class Main
{

    /**
     * @param args
     */
    public static void main(String[] args) throws IOException
    {
        new Main().start();
    }

    public float startX, startY;
    public int cityCount;
    public float citiesX[], citiesY[];
    public float distances[];
    public float shortest = Float.MAX_VALUE;

    public void start() throws IOException
    {
        /* Read the stuff */
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] input = new String[Integer.parseInt(br.readLine())];
        cityCount = input.length;
        citiesX = new float[input.length];
        citiesY = new float[input.length];
        for (int i = 0; i < input.length; ++i)
        {
            input[i] = br.readLine();
            String line = (input[i]);
            String[] lineElements = line.split(" ");
            float x = Float.parseFloat(lineElements[0]);
            float y = Float.parseFloat(lineElements[1]);
            citiesX[i] = x;
            citiesY[i] = y;
        }
        /* Read current position */
        String line = (br.readLine());
        String[] lineElements = line.split(" ");
        startX = Float.parseFloat(lineElements[0]);
        startY = Float.parseFloat(lineElements[1]);
        /* Compute distances */
        computeAllDistances();
        solve();
        System.out.println(String.format(Locale.US, "%.1f", shortest));
    }

    public void solve()
    {
        for (int i = 1; i <= cityCount; ++i)
        {
            boolean[] wentTo = new boolean[cityCount];
            wentTo[i - 1] = true;
            step(wentTo, i, distances[distanceIndex(0, i)]);
        }
    }

    public void step(boolean[] wentTo, int currentCity, float distance)
    {
        int wentToCount = 0;
        for (int i = 1; i <= cityCount; ++i)
        {
            if (wentTo[i - 1])
            {
                ++wentToCount;
                continue;
            }
            boolean[] copy = new boolean[cityCount];
            System.arraycopy(wentTo, 0, copy, 0, cityCount);
            copy[i - 1] = true;
            float dist = distance + distances[distanceIndex(currentCity, i)];
            step(copy, i, dist);
        }
        if (wentToCount == cityCount)
        {
            if (shortest > distance)
            {
                shortest = distance;
            }
        }
    }

    public void computeAllDistances()
    {
//      int count = (int) countDistances(cityCount + 1);
//      System.out.println("Compute Distances (" + count + ")");
        distances = new float[cityCount * cityCount];
        for (int i = 0; i <= cityCount; ++i)
        {
            for (int j = i + 1; j <= cityCount; ++j)
            {
                float x1, y1, x2, y2;
                if (i == 0)
                {
                    x1 = startX;
                    y1 = startY;
                } else
                {
                    x1 = citiesX[i - 1];
                    y1 = citiesY[i - 1];
                }
                x2 = citiesX[j - 1];
                y2 = citiesY[j - 1];
                float xDiff = x1 - x2;
                float yDiff = y1 - y2;
                float dist = (float) Math.sqrt(xDiff * xDiff + yDiff * yDiff);
//              System.out.printf("Distance (%d, %d)(%d) = %f\n", i, j, distanceIndex(i, j), dist);
                distances[distanceIndex(i, j)] = dist;
            }
        }
    }

    public int distanceIndex(int c1, int c2)
    {
        if (c1 == c2)
            throw new IllegalArgumentException("Cities are the same! (" + c1 + ")");
        if (c1 < c2)
        {
            return c1 * cityCount + c2 - 1;
        } else
        {
            return c2 * cityCount + c1 - 1;
        }
    }

    public long countDistances(long l)
    {
        if (l == 0 || l == 1)
            return 0;
        return (l - 1) + countDistances(l - 1);
    }

}
</code>```

Usage:

Input:

```<code>[number of cities]
[x] [y]     (city 0)
[x] [y]     (city 1)
[x] [y]     (city 2)
[x] [y]     (city 3)
.....
[x] [y]     (of your current position)
</code>```

Output:

```<code>[The shortest distance you have to travel.]
</code>```

Example:

Input:

```<code>11
3 3
7 1
4 4
2 10
40 2
15 9
7 13
16 23
8 0
4 8
10 10
5 10
</code>```

Output:

```<code>83.2
</code>```

Title: Minimum path Algorithm

Body:
Traveling Salesman Problem.

Here is my solution (I know mine is brute force, but I just wanted to share my solution):

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Locale;

import javax.swing.JSplitPane;

/* VPW Template */

public class Main
{

    /**
     * @param args
     */
    public static void main(String[] args) throws IOException
    {
        new Main().start();
    }

    public float startX, startY;
    public int cityCount;
    public float citiesX[], citiesY[];
    public float distances[];
    public float shortest = Float.MAX_VALUE;

    public void start() throws IOException
    {
        /* Read the stuff */
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] input = new String[Integer.parseInt(br.readLine())];
        cityCount = input.length;
        citiesX = new float[input.length];
        citiesY = new float[input.length];
        for (int i = 0; i < input.length; ++i)
        {
            input[i] = br.readLine();
            String line = (input[i]);
            String[] lineElements = line.split(" ");
            float x = Float.parseFloat(lineElements[0]);
            float y = Float.parseFloat(lineElements[1]);
            citiesX[i] = x;
            citiesY[i] = y;
        }
        /* Read current position */
        String line = (br.readLine());
        String[] lineElements = line.split(" ");
        startX = Float.parseFloat(lineElements[0]);
        startY = Float.parseFloat(lineElements[1]);
        /* Compute distances */
        computeAllDistances();
        solve();
        System.out.println(String.format(Locale.US, "%.1f", shortest));
    }

    public void solve()
    {
        for (int i = 1; i <= cityCount; ++i)
        {
            boolean[] wentTo = new boolean[cityCount];
            wentTo[i - 1] = true;
            step(wentTo, i, distances[distanceIndex(0, i)]);
        }
    }

    public void step(boolean[] wentTo, int currentCity, float distance)
    {
        int wentToCount = 0;
        for (int i = 1; i <= cityCount; ++i)
        {
            if (wentTo[i - 1])
            {
                ++wentToCount;
                continue;
            }
            boolean[] copy = new boolean[cityCount];
            System.arraycopy(wentTo, 0, copy, 0, cityCount);
            copy[i - 1] = true;
            float dist = distance + distances[distanceIndex(currentCity, i)];
            step(copy, i, dist);
        }
        if (wentToCount == cityCount)
        {
            if (shortest > distance)
            {
                shortest = distance;
            }
        }
    }

    public void computeAllDistances()
    {
//      int count = (int) countDistances(cityCount + 1);
//      System.out.println("Compute Distances (" + count + ")");
        distances = new float[cityCount * cityCount];
        for (int i = 0; i <= cityCount; ++i)
        {
            for (int j = i + 1; j <= cityCount; ++j)
            {
                float x1, y1, x2, y2;
                if (i == 0)
                {
                    x1 = startX;
                    y1 = startY;
                } else
                {
                    x1 = citiesX[i - 1];
                    y1 = citiesY[i - 1];
                }
                x2 = citiesX[j - 1];
                y2 = citiesY[j - 1];
                float xDiff = x1 - x2;
                float yDiff = y1 - y2;
                float dist = (float) Math.sqrt(xDiff * xDiff + yDiff * yDiff);
//              System.out.printf("Distance (%d, %d)(%d) = %f\n", i, j, distanceIndex(i, j), dist);
                distances[distanceIndex(i, j)] = dist;
            }
        }
    }

    public int distanceIndex(int c1, int c2)
    {
        if (c1 == c2)
            throw new IllegalArgumentException("Cities are the same! (" + c1 + ")");
        if (c1 < c2)
        {
            return c1 * cityCount + c2 - 1;
        } else
        {
            return c2 * cityCount + c1 - 1;
        }
    }

    public long countDistances(long l)
    {
        if (l == 0 || l == 1)
            return 0;
        return (l - 1) + countDistances(l - 1);
    }

}

Usage:

Input:

[number of cities]
[x] [y]     (city 0)
[x] [y]     (city 1)
[x] [y]     (city 2)
[x] [y]     (city 3)
.....
[x] [y]     (of your current position)

Output:

[The shortest distance you have to travel.]

Example:

Input:

11
3 3
7 1
4 4
2 10
40 2
15 9
7 13
16 23
8 0
4 8
10 10
5 10

Output:

83.2


问:
After trying alot of comand I am getting the same ERROR (nodemon: not found command)

nodemon: not found command

I tried with many links to solve nodemon not found command but it is not working.

Always facing the same issue.

答:
nodemon: not found command.
I tried with many links but was not working, then I tried with the below steps it worked fine.

Follow this step it worked for me.

step1 : sudo su

step2 : npm install -g nodemon --save-dev

It is working fine.


问:
Can't get an ajax response in Codeigniter
I am new to codeigniter and trying to build a login system. My controllers and my model are working fine, the only issue is that the url changes and appears to be domainName/controller/function which I don't like so I googled and made an AJAX function, but then when I'm adding AJAX, the function always returns the error function and not the success function part.

My View

```<code><!-- <form class="login100-form validate-form" method="POST" action="<?php echo base_url(); ?>welcome/login_validation"> -->
                <form class="login100-form validate-form" method="POST" id="login">
                    <span class="login100-form-title">Member Login</span>

                    <div class="text-center">
                        <span class="text-danger"><?php echo $this->session->flashdata("error"); ?></span>
                    </div>

                    <div class="wrap-input100 validate-input" data-validate="Valid email is required: ex@abc.xyz">
                        <input class="input100" type="email" name="email" id="email" placeholder="Email" value="<?php echo set_value('email'); ?>" >
                        <span class="focus-input100"></span>
                        <span class="symbol-input100">
                            <i class="fa fa-envelope" aria-hidden="true"></i>
                        </span>
                        <span class="text-danger"><?php echo form_error('email'); ?></span>
                    </div>

                    <div class="wrap-input100 validate-input" data-validate="Password is required">
                        <input class="input100" type="password" name="password" id="password" placeholder="Password" value="<?php echo set_value('password'); ?>">
                        <span class="focus-input100"></span>
                        <span class="symbol-input100">
                            <i class="fa fa-lock" aria-hidden="true"></i>
                        </span>
                        <span class="text-danger"><?php echo form_error('password'); ?></span>
                    </div>

                    <div class="container-login100-form-btn">
                        <button class="login100-form-btn" type="submit">Login</button>
                    </div>

                    <div class="text-center p-t-12">
                        <span class="txt1">Forgot</span>
                        <a class="txt2" href="">Username / Password?</a>
                    </div>

                    <!-- <div class="text-center p-t-136">
                        <a class="txt2" href="#">
                            Create your Account
                            <i class="fa fa-long-arrow-right m-l-5" aria-hidden="true"></i>
                        </a>
                    </div> -->
                </form>
</code>```

My Controller

```<code>class Welcome extends CI_Controller {
    public function login_validation(){
            $this->load->library('form_validation');
            $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email', array(
                'required' => '%s feild cannot be empty',
                'valid_email' => 'Please Enter a Valid Email'
            ));
            $this->form_validation->set_rules('password', 'Password', 'required');

            if($this->form_validation->run()){
                $email = $this->input->post('email');
                $password = $this->input->post('password');

                $this->load->model('main_model');
                // $data['can_login'] = $this->main_model->login($email, $password);
                echo json_encode($data);

                //With Session
                if($this->main_model->login($email, $password)){
                    $user_session = array(
                        "email" =>  $email
                    );
                    $this->session->set_userdata($user_session);
                    redirect(base_url() . 'welcome/check_user_session');

                }
                else{
                    $this->session->set_flashdata('error', 'Invalid Email or Password');
                    $this->index();
                }
            }
            else{
                $this->index();
            }
        }

        public function check_user_session(){
            if($this->session->userdata('email') != ''){
                // echo $this->session->userdata('email');
                redirect(base_url() . 'welcome/user_info');
            }
            else{
                redirect(base_url() . 'welcome/index');
                $this->session->set_flashdata('error', 'Your are already loged in');
            }
        }
}
</code>```

My Model

```<code><?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Main_model extends CI_Model{

    public function login($email, $password){
        $this->db->where("email", $email);
        $this->db->where("password", $password);
        $can_login = $this->db->get("users");

        if($can_login->num_rows() > 0){
            return true;
        }
        else{
            return false;
        }
    }
}

?>
</code>```

My AJAX function

```<code><script type="text/javascript">
        $(document).ready(function(){
            $('#login').submit(function(e){
                e.preventDefault();
                // var user_email = $('#email').val();
                var user_email = $("input[name='email']").val();
                var user_password = $('#password').val();

                $.ajax({
                    method: 'POST',
                    url: '<?php echo base_url(); ?>welcome/login_validation',
                    dataType: 'json',
                    // data: new FormData(this),
                    data: {
                        email: user_email,
                        password: user_password
                    },
                    contentType: false,
                    processData: false,

                    success: function(res){
                        alert(res);
                        alert('Loged In');

                    },
                    error: function(data){
                        //alert('Unsuccessful');
                        console.log(data);
                    }
                });
            });
        });
    </script>
</code>```

答:
The main issue (and there may be others) is what you do in the controller.

A function that responds to an ajax request must return something to the server. Your ajax setup expects to get JSON back from the server. But you seem to be trying (depending on circumstances) to load a view (i.e. '$this->index();') or to redirect to a different page. Neither of these two actions is appropriate for a function that is handling an ajax request.

login_validation() should probably do only one thing

```<code>echo json_encode($data);
</code>```

Where $data['can_login'] is set to either true or false.

Back at $ajax.success: you respond accordingly.

If you want to redirect you will have to use javascript to get that done.

Body:
I am new to codeigniter and trying to build a login system. My controllers and my model are working fine, the only issue is that the url changes and appears to be domainName/controller/function which I don't like so I googled and made an AJAX function, but then when I'm adding AJAX, the function always returns the error function and not the success function part.

My View

                <form class="login100-form validate-form" method="POST" id="login">
                    Member Login

                        <?php echo $this->session->flashdata("error"); ?>

                        <input class="input100" type="email" name="email" id="email" placeholder="Email" value="<?php echo set_value('email'); ?>" >

                        <?php echo form_error('email'); ?>

                        <input class="input100" type="password" name="password" id="password" placeholder="Password" value="<?php echo set_value('password'); ?>">

                        <?php echo form_error('password'); ?>

                        <button class="login100-form-btn" type="submit">Login</button>

                        Forgot
                        Username / Password?

                </form>

My Controller

class Welcome extends CI_Controller {
    public function login_validation(){
            $this->load->library('form_validation');
            $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email', array(
                'required' => '%s feild cannot be empty',
                'valid_email' => 'Please Enter a Valid Email'
            ));
            $this->form_validation->set_rules('password', 'Password', 'required');

            if($this->form_validation->run()){
                $email = $this->input->post('email');
                $password = $this->input->post('password');

                $this->load->model('main_model');
                // $data['can_login'] = $this->main_model->login($email, $password);
                echo json_encode($data);

                //With Session
                if($this->main_model->login($email, $password)){
                    $user_session = array(
                        "email" =>  $email
                    );
                    $this->session->set_userdata($user_session);
                    redirect(base_url() . 'welcome/check_user_session');

                }
                else{
                    $this->session->set_flashdata('error', 'Invalid Email or Password');
                    $this->index();
                }
            }
            else{
                $this->index();
            }
        }

        public function check_user_session(){
            if($this->session->userdata('email') != ''){
                // echo $this->session->userdata('email');
                redirect(base_url() . 'welcome/user_info');
            }
            else{
                redirect(base_url() . 'welcome/index');
                $this->session->set_flashdata('error', 'Your are already loged in');
            }
        }
}

My Model

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Main_model extends CI_Model{

    public function login($email, $password){
        $this->db->where("email", $email);
        $this->db->where("password", $password);
        $can_login = $this->db->get("users");

        if($can_login->num_rows() > 0){
            return true;
        }
        else{
            return false;
        }
    }
}

?>

My AJAX function

Body:
The main issue (and there may be others) is what you do in the controller.

A function that responds to an ajax request must return something to the server. Your ajax setup expects to get JSON back from the server. But you seem to be trying (depending on circumstances) to load a view (i.e. '$this->index();') or to redirect to a different page. Neither of these two actions is appropriate for a function that is handling an ajax request.

login_validation() should probably do only one thing

echo json_encode($data);

Where $data['can_login'] is set to either true or false.

Back at $ajax.success: you respond accordingly.

If you want to redirect you will have to use javascript to get that done.


问:
ScriptApp.getService().getUrl() points to dev URL. How can I get it to point to exec production URL?
ScriptApp.getService().getUrl() is generating a dev URL.    How can I make it generate the exec production URL?</p>

答:
How about this answer? Please think of this as just one of several possible answers.

Issue and workaround:

If you are enabling V8 runtime, in the current stage, it seems that when V8 runtime is enabled, ScriptApp.getService().getUrl() returns the dev URL like https://script.google.com/macros/s/###/dev, and when V8 runtime is disabled, it returns the exec URL like https://script.google.com/macros/s/###/exec. I think that this might be one of bugs for V8.

If you want to directly retrieve the exec URL with enabling V8, as the current workaround, how about retrieving it using the method of projects.deployments.list in Apps Script API? You can test it at "Try this API". Of course, this can be used with Google Apps Script.

Reference:

Method: projects.deployments.list

If I misunderstood your situation and this was not the direction you want, I apologize.


问:
Google Firebase - how to delete Crash reports?
Have I finally gone blind or is there not an obvious way to delete Firebase Crash reports through the Google Firebase web console? My Android app is successfully logging reports but now I have a flood of "development crashes" that are eating up a lot of my view in the console.  It makes it very difficult to find actual beta user crashes (especially since I also can't seem to filter the crashes by date/time). Any help is much appreciated. </p>

答:
It has the option to Close the issue in the GUI.
I have attached the screenshot for reference..