问:
How to fix bootstrap dropdown menu positioning
I'm trying to implement a notifications system and the notifications dropdown button is positioned to the right of my nav bar when I click it shows the result but part of it is always out of the browser view. I didn't start this project and god knows what has been included here all I know is that my bootstrap is 4.0.0 beta

Ive tried using .dropdown-menu.dropdown-menu-right bit it still remains the same

```<code>.dropdown{"data-behavior" => "notifications"}
  %button#dropdownMenuButton.btn.btn-secondary.dropdown-toggle{"aria-expanded" => "false", "aria-haspopup" => "true", "data-behavior" => "notifications-link", "data-toggle" => "dropdown", :type => "button"}
    %i.fa.fa-bell
    %span{"data-behavior" => "unread-count"}
  .dropdown-menu{"aria-labelledby" => "dropdownMenuButton", "data-behavior" => "notification-items"}
</code>```

答: Finally found an answer my bootstrap.css was just overwritten by another css file that had its own dropdown style </p>

Body:
I'm trying to implement a notifications system and the notifications dropdown button is positioned to the right of my nav bar when I click it shows the result but part of it is always out of the browser view. I didn't start this project and god knows what has been included here all I know is that my bootstrap is 4.0.0 beta

Ive tried using .dropdown-menu.dropdown-menu-right bit it still remains the same

.dropdown{"data-behavior" => "notifications"}
  %button#dropdownMenuButton.btn.btn-secondary.dropdown-toggle{"aria-expanded" => "false", "aria-haspopup" => "true", "data-behavior" => "notifications-link", "data-toggle" => "dropdown", :type => "button"}
    %i.fa.fa-bell
    %span{"data-behavior" => "unread-count"}
  .dropdown-menu{"aria-labelledby" => "dropdownMenuButton", "data-behavior" => "notification-items"}


来源: stackexchange

问:
How to make first row have specific name and image?
I have application which populate uitableview with some properties received from an api call. So my question is how i can make first cell for example have name "Back" and some image and after that start populate other cells with properties received from api call? If someone can post some example it would be awesome.

答:
You can try this

```<code> override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "CellId")
   switch indexPath.row {
    case 0:
        cell.textLabel!.text = "back"
        cell.imageView?.image = UIImage(named: "back.png")
        break
    default:
        cell.textLabel!.text =  array[indexPath.row - 1]
        break
    }
   retun cell
 }

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return arrayCount + 1
}
</code>```

Another solution using TableView header:

```<code>override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "CellId")
        cell.textLabel!.text =  array[indexPath.row]
        retun cell
 }

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return arrayCount
}

    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
      let  btn = UIButton(frame: CGRect(x: 10, y: 10, width: 60, height: 30))
      btn.setTitle("Back", for: .normal)
      btn.setImage(UIImage(named: "BarCodeIcon.png"), for: .normal)
      btn.setTitle("Scan the Barcode", for: .normal)
      btn.titleEdgeInsets = UIEdgeInsets(top: 0.0, left: 42.0, bottom: 0.0, right: 0.0)
      btn.contentHorizontalAlignment = .left
      btn.addTarget(self, action: "btnTapped:", for: .touchUpInside)
    }

   @objc func btnTapped(sender: UIButton) {
   }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You can try this

 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "CellId")
   switch indexPath.row {
    case 0:
        cell.textLabel!.text = "back"
        cell.imageView?.image = UIImage(named: "back.png")
        break
    default:
        cell.textLabel!.text =  array[indexPath.row - 1]
        break
    }
   retun cell
 }

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return arrayCount + 1
}

Another solution using TableView header:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "CellId")
        cell.textLabel!.text =  array[indexPath.row]
        retun cell
 }

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return arrayCount
}

    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
      let  btn = UIButton(frame: CGRect(x: 10, y: 10, width: 60, height: 30))
      btn.setTitle("Back", for: .normal)
      btn.setImage(UIImage(named: "BarCodeIcon.png"), for: .normal)
      btn.setTitle("Scan the Barcode", for: .normal)
      btn.titleEdgeInsets = UIEdgeInsets(top: 0.0, left: 42.0, bottom: 0.0, right: 0.0)
      btn.contentHorizontalAlignment = .left
      btn.addTarget(self, action: "btnTapped:", for: .touchUpInside)
    }

   @objc func btnTapped(sender: UIButton) {
   }


问:
Does git pull change HEAD?
I understand how git checkout changes the HEAD pointer but what about git pull?

HEAD can be seen as the 'current branch' but when you execute git pull and your current branch is altered. Does it affect HEAD pointer? Why?

答:
According to git-scm

More precisely, git pull runs git fetch with the given parameters and calls git merge to "merge the retrieved branch heads into the current branch".

Note : The double quotes have been added by me for highlighting.

Does it affect HEAD pointer?

Yes, if newer commits have been pulled.

Why?

Because the HEAD refers to the most recent commit. As you have pulled latest changes (read commits), the HEAD has to refer to the newer commits pulled.

Title: Does git pull change HEAD?


问:
Eigen 3.4 .reshaped()
I want to reshape an Eigen vector into a matrix and then take the .colwise().sum().

The reshape command as explained in the Eigen tutorial isn't compiling (https://eigen.tuxfamily.org/dox-devel/group__TutorialReshape.html)

Hence my question is as much about Eigen version numbering (has Eigen 3.4 been released?) as about the reshape command itself (my compile error says "Eigen::VectorXd has no member named 'reshaped'") and advice about an efficient alternative to the following:

VectorXd phi = X * beta;
ArrayXd sumPhi = phi.reshaped(4,12).colwise().sum();

答:
Eigen 3.4 has not been released (as of May 2019), I suggest trying out the development branch.

As phi is an actual object (and not an expression), you could achieve the same using a Map:

```<code>ArrayXd sumPhi = MatrixXd::Map(phi.data(),4,12).colwise().sum();
</code>```

This should work with any version of Eigen (at least since 3.0), but is less safe as it does not ensure that the number of elements actually match (if phi has less than 4*12 elements, this could access invalid memory).

Title: Eigen 3.4 .reshaped()

Body:
Eigen 3.4 has not been released (as of May 2019), I suggest trying out the development branch.

As phi is an actual object (and not an expression), you could achieve the same using a Map:

ArrayXd sumPhi = MatrixXd::Map(phi.data(),4,12).colwise().sum();

This should work with any version of Eigen (at least since 3.0), but is less safe as it does not ensure that the number of elements actually match (if phi has less than 4*12 elements, this could access invalid memory).


问:
How to pipe password to sudo with zenity, pv and dd
I want to let users write an ISO to a USB pen drive from within Thunar or Dolphin.

For this I've created a bash script which uses dd, pv and zenity.

Currently I'm using pkexec to ask for a password before the dd command is executed, but the pkexec window and the zenity progress window are both opened at the same time. I'd like to open a window for the root password first after which the zenity progress window should be opened.

I tried to ask for the password with zenity first after which I pipe the password to sudo but wherever I put the "echo $PWD", the password is not piped into sudo.

```<code>#!/bin/bash

TITLE='Zenity Progress Test'

PASSWORD=$(zenity --password \
                     --width=300 \
                     --title="$TITLE")
if [ ! -z "$PASSWORD" ]; then
    echo "Your password: $PASSWORD"
    dd if=/dev/zero of="$PWD/testfile1" bs=1M count=100
    pv -n testfile1 2> >(zenity --progress \
                                           --width=300 \
                                           --title="$TITLE" \
                                           --percentage=0 \
                                           --auto-close \
                                           --auto-kill) | echo "$PASSWORD" | sudo -S dd of="$PWD/testfile2" bs=64k oflag=dsync
    echo "$PASSWORD" | sudo -S rm "$PWD/testfile1" "$PWD/testfile2"
else
    echo 'No password provided'
    exit 1
fi
</code>```

The zenity progress window just flashes by and nothing is transferred, most likely because the password is not piped into sudo.

If you replace "echo $PASSWORD | sudo -S" with "pkexec" the code functions but with both the pkexec window and the zenity progress window opened together.

Any ideas on how to solve this puzzle?

答:
Use param -S for read from stdin</p>

```<code>$echo <password> | sudo -S <command>
</code>```

Body:
I want to let users write an ISO to a USB pen drive from within Thunar or Dolphin.

For this I've created a bash script which uses dd, pv and zenity.

Currently I'm using pkexec to ask for a password before the dd command is executed, but the pkexec window and the zenity progress window are both opened at the same time. I'd like to open a window for the root password first after which the zenity progress window should be opened.

I tried to ask for the password with zenity first after which I pipe the password to sudo but wherever I put the "echo $PWD", the password is not piped into sudo.

#!/bin/bash

TITLE='Zenity Progress Test'

PASSWORD=$(zenity --password \
                     --width=300 \
                     --title="$TITLE")
if [ ! -z "$PASSWORD" ]; then
    echo "Your password: $PASSWORD"
    dd if=/dev/zero of="$PWD/testfile1" bs=1M count=100
    pv -n testfile1 2> >(zenity --progress \
                                           --width=300 \
                                           --title="$TITLE" \
                                           --percentage=0 \
                                           --auto-close \
                                           --auto-kill) | echo "$PASSWORD" | sudo -S dd of="$PWD/testfile2" bs=64k oflag=dsync
    echo "$PASSWORD" | sudo -S rm "$PWD/testfile1" "$PWD/testfile2"
else
    echo 'No password provided'
    exit 1
fi

The zenity progress window just flashes by and nothing is transferred, most likely because the password is not piped into sudo.

If you replace "echo $PASSWORD | sudo -S" with "pkexec" the code functions but with both the pkexec window and the zenity progress window opened together.

Any ideas on how to solve this puzzle?

Body:
Use param -S for read from stdin

$echo <password> | sudo -S <command>


问:
Hunch authentication on android phone redirect
I am working authentication on an android phone which sends the user to Hunch to authentication after clicking a log in button. This sets up a new intent as below:

```<code>Intent intent = new Intent(Intent.ACTION_VIEW);
    Uri data = Uri.parse("hunch.com/authorize/v1/?app_id=1234&next=hoosheer-hunch-app://");
    intent.setData(data);
    startActivity(intent);
</code>```

This is my manifest file

```<code><activity android:name="hunch" android:label="hunch">
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:scheme="hoosheer-hunch-app" />
        </intent-filter>
    </activity>
</code>```

It gives me this error:

```<code>04-12 17:04:22.574: ERROR/AndroidRuntime(838): android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=hunch.com/authorize/v1/?app_id=1234&next=hoosheer-hunch-app:// }
</code>```

But I have similar code working for logging in using Foursquare. The hunch.java class contains an onResume method

答:
Hunch does not currently support custom URL schemes such as hoosheer-hunch-app://

Until we implement this functionality you should use the following URL to authenticate:

http://hunch.com/authorize/v1/?app_id=1234&next=/

After authorizing your application, the user will be redirected to

http://hunch.com/?auth_token_key=4d3d3d3d3&user_id=hn_5678&next=%2F

You should monitor the ACTION_VIEW Intent for the URL change, pull the auth_token_key out of the URL, and then exchange it for an auth_token using the get-auth-token API call.

ContentLicense: CC BY-SA 3.0

Body:
I am working authentication on an android phone which sends the user to Hunch to authentication after clicking a log in button. This sets up a new intent as below:

Intent intent = new Intent(Intent.ACTION_VIEW);
    Uri data = Uri.parse("hunch.com/authorize/v1/?app_id=1234&next=hoosheer-hunch-app://");
    intent.setData(data);
    startActivity(intent);

This is my manifest file

<activity android:name="hunch" android:label="hunch">
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:scheme="hoosheer-hunch-app" />
        </intent-filter>
    </activity>

It gives me this error:

04-12 17:04:22.574: ERROR/AndroidRuntime(838): android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=hunch.com/authorize/v1/?app_id=1234&next=hoosheer-hunch-app:// }

But I have similar code working for logging in using Foursquare. The hunch.java class contains an onResume method


问:
Waves: Get 15 mnemonic words from a hex seed
Is there a way to get the 15 mnemonic words from a given hex seed?

Any method in the waves JS crypto library to do this?

答:
If by hex seed you mean byteEncoded or base58encoded seed, then yes:

```<code>const {libs} = require('@waves/waves-transactions')

// convert base58 string to bytes
const encoded = 'xrv7ffrv2A9g5pKSxt7gHGrPYJgRnsEMDyc4G7srbia6PhXYLDKVsDxnqsEqhAVbbko7N1tDyaSrWCZBoMyvdwaFNjWNPjKdcoZTKbKr2Vw9vu53Uf4dYpyWCyvfPbRskHfgt9q'
const bytes =  libs.crypto.base58decode(encoded)
// if string is hex encoded use this function instead
// const bytes libs.crypto.hexStringToByteArray(encoded)
const decoded = libs.marshall.parsePrimitives.P_STRING_FIXED(bytes.length)(bytes)

console.log(decoded)
</code>```

Otherwise it is not, since hash function is irreversible

Body:
If by hex seed you mean byteEncoded or base58encoded seed, then yes:

const {libs} = require('@waves/waves-transactions')

// convert base58 string to bytes
const encoded = 'xrv7ffrv2A9g5pKSxt7gHGrPYJgRnsEMDyc4G7srbia6PhXYLDKVsDxnqsEqhAVbbko7N1tDyaSrWCZBoMyvdwaFNjWNPjKdcoZTKbKr2Vw9vu53Uf4dYpyWCyvfPbRskHfgt9q'
const bytes =  libs.crypto.base58decode(encoded)
// if string is hex encoded use this function instead
// const bytes libs.crypto.hexStringToByteArray(encoded)
const decoded = libs.marshall.parsePrimitives.P_STRING_FIXED(bytes.length)(bytes)

console.log(decoded)

Otherwise it is not, since hash function is irreversible


问:
Post Request shows 403 not found error even tough permission class in django rest framework view sets is set to allow any
I am trying to store the data in the form using post method. To do that i have set the permissions as AllowAny. I have checked the POST method using Postman and it works but when I use axios to post the same data it returns 403 error.

I have already tried using fixes provided in the given link description but that add more exceptions.
CSRF with Django, React+Redux using Axios

The error description as given in console

```<code>Error: Request failed with status code 403
    at createError (createError.js:16)
    at settle (settle.js:18)
    at XMLHttpRequest.handleLoad (xhr.js:77)
</code>```

Python django rest framework code

```<code>#viewset class from python
class feedbackViewSet(viewsets.ModelViewSet):
    queryset = feedback.objects.all()
    permission_classes = [
        permissions.AllowAny
    ]
    serializer_class = feedbackSerializer
</code>```

Java script code using axios to POST the data to the server

```<code>//axios post method
export const addFeedback = feedback => dispatch => {
  axios
    .post("/api/feedbacks/", feedback)
    .then(res => {
      dispatch({
        type: ADD_FEEDBACK,
        payload: res.data
      });
    })
    .catch(err => console.log(err));
};
</code>```

Form code contains the on submit methods that are to be called.

```<code>//form component code
import React, { Component } from "react";

import { connect } from "react-redux";
import PropTypes from "prop-types";
import { addFeedback } from "../../actions/feedbacks";

export class Form extends Component {
  state = {
    name: "",
    email: "",
    description: ""
  };

  static propTypes = {
    addFeedback: PropTypes.func.isRequired
  };

  onChange = e => this.setState({ [e.target.name]: e.target.value });

  onSubmit = e => {
    e.preventDefault();
    const { name, email, description } = this.state;
    const feedback = { name, email, description };
    this.props.addFeedback(feedback);
  };
  render() {
    const { name, email, description } = this.state;
    return (
      //some form generation code
    );
  }
}

export default connect(
  null,
  { addFeedback }
)(Form);
</code>```

答:
Check out that link Axios

I assume that you are trying to send a MIME type of x-www-form-urlencoded, which needs to manually stringify your data.

```<code>const qs = require('qs');
axios.post('/foo', qs.stringify({ 'bar': 123 }));
</code>```

Body:
I am trying to store the data in the form using post method. To do that i have set the permissions as AllowAny. I have checked the POST method using Postman and it works but when I use axios to post the same data it returns 403 error.

I have already tried using fixes provided in the given link description but that add more exceptions.
CSRF with Django, React+Redux using Axios

The error description as given in console

Error: Request failed with status code 403
    at createError (createError.js:16)
    at settle (settle.js:18)
    at XMLHttpRequest.handleLoad (xhr.js:77)

Python django rest framework code

#viewset class from python
class feedbackViewSet(viewsets.ModelViewSet):
    queryset = feedback.objects.all()
    permission_classes = [
        permissions.AllowAny
    ]
    serializer_class = feedbackSerializer

Java script code using axios to POST the data to the server

//axios post method
export const addFeedback = feedback => dispatch => {
  axios
    .post("/api/feedbacks/", feedback)
    .then(res => {
      dispatch({
        type: ADD_FEEDBACK,
        payload: res.data
      });
    })
    .catch(err => console.log(err));
};

Form code contains the on submit methods that are to be called.

//form component code
import React, { Component } from "react";

import { connect } from "react-redux";
import PropTypes from "prop-types";
import { addFeedback } from "../../actions/feedbacks";

export class Form extends Component {
  state = {
    name: "",
    email: "",
    description: ""
  };

  static propTypes = {
    addFeedback: PropTypes.func.isRequired
  };

  onChange = e => this.setState({ [e.target.name]: e.target.value });

  onSubmit = e => {
    e.preventDefault();
    const { name, email, description } = this.state;
    const feedback = { name, email, description };
    this.props.addFeedback(feedback);
  };
  render() {
    const { name, email, description } = this.state;
    return (
      //some form generation code
    );
  }
}

export default connect(
  null,
  { addFeedback }
)(Form);

Body:
Check out that link Axios

I assume that you are trying to send a MIME type of x-www-form-urlencoded, which needs to manually stringify your data.

const qs = require('qs');
axios.post('/foo', qs.stringify({ 'bar': 123 }));


问:
How to find if we have two or more equal minimum values in specific columns
I have this problem I was hoping someone could help.

I have a very large data frame (close to 20000000 observations)in R with about 43 columns, in four of those columns I need to find whether there is more than one equal minimum value below 200, then if we have rows where more than one column has the same value that meets this criteria I need to flag that row to TRUE (in a a new flag column). Please note that those columns include NA values, and NAs should not be used (when NA is present in the columns being compared, returns NA)

the goal is to look up the values in each row for columns a1 to a4 and find whether the minimum value that does not exceed 200, occurs in more than one column per row

for simplicity let's say that this is how my data data look like

```<code>head(mydata)
t1  a1  a2  a3  a4
34  NA  NA  NA  NA
26  10  15  250 150
34  20  20  100 30
35  5   5   10  5
25  45  100 3   45
31 400 310 500 310
")
</code>```

the goal is to look up the values in each row for columns a1 to a4 and find whether the minimum value that does not exceed 200, occurs in more than one column per row, if it does return true if not, false

the expected result will look like this

```<code>head(mydata)
t1  a1  a2  a3  a4  flag
34  NA  NA  NA  NA  NA
26  10  15  250 150 FALSE
34  20  20  100 30  TRUE
35  5   5   10  5   TRUE
25  45  100 3   45  FALSE
31 400 310 500 310  FALSE
")
</code>```

Thank you in advance.

答:
Here is a base R way to do it</p>

```<code>#Get the column indices where a1, a2, a3 and a4 are there
inds <- match(paste0("a", 1:4), names(df))

#Get row-wise minimum
min_val <- do.call(pmin, df[inds])

#Check if there are more than one occurrence of minimum value
# and if minimum value is less than 200.
df$flag <- rowSums(df[inds] == min_val) > 1 & min_val < 200

df
#  t1  a1  a2  a3  a4  flag
#1 34  NA  NA  NA  NA    NA
#2 26  10  15 250 150 FALSE
#3 34  20  20 100  30  TRUE
#4 35   5   5  10   5  TRUE
#5 25  45 100   3  45 FALSE
#6 31 400 310 500 310 FALSE
</code>```

Body:
I have this problem I was hoping someone could help.

I have a very large data frame (close to 20000000 observations)in R with about 43 columns, in four of those columns I need to find whether there is more than one equal minimum value below 200, then if we have rows where more than one column has the same value that meets this criteria I need to flag that row to TRUE (in a a new flag column). Please note that those columns include NA values, and NAs should not be used (when NA is present in the columns being compared, returns NA)

the goal is to look up the values in each row for columns a1 to a4 and find whether the minimum value that does not exceed 200, occurs in more than one column per row

for simplicity let's say that this is how my data data look like

head(mydata)
t1  a1  a2  a3  a4
34  NA  NA  NA  NA
26  10  15  250 150
34  20  20  100 30
35  5   5   10  5
25  45  100 3   45
31 400 310 500 310
")

the goal is to look up the values in each row for columns a1 to a4 and find whether the minimum value that does not exceed 200, occurs in more than one column per row, if it does return true if not, false

the expected result will look like this

head(mydata)
t1  a1  a2  a3  a4  flag
34  NA  NA  NA  NA  NA
26  10  15  250 150 FALSE
34  20  20  100 30  TRUE
35  5   5   10  5   TRUE
25  45  100 3   45  FALSE
31 400 310 500 310  FALSE
")

Thank you in advance.

Body:
Here is a base R way to do it

#Get the column indices where a1, a2, a3 and a4 are there
inds <- match(paste0("a", 1:4), names(df))

#Get row-wise minimum
min_val <- do.call(pmin, df[inds])

#Check if there are more than one occurrence of minimum value
# and if minimum value is less than 200.
df$flag <- rowSums(df[inds] == min_val) > 1 & min_val < 200

df
#  t1  a1  a2  a3  a4  flag
#1 34  NA  NA  NA  NA    NA
#2 26  10  15 250 150 FALSE
#3 34  20  20 100  30  TRUE
#4 35   5   5  10   5  TRUE
#5 25  45 100   3  45 FALSE
#6 31 400 310 500 310 FALSE


问:
Extract URL with and without custom URL schemes from text using RegEx
I am looking for a way to extract URLs from text using RegEx. There are plenty of questions and very good answers here on SF but i did not find a RegEx solution that is capable of extracting URLs whith custom schemes as well.

Here are a few examples where i need the URLs extracted from:

```<code>Text: Send me a message on whatsapp whatsapp://send?text=Hello+World. I will get in touch!
-> Should extract whatsapp://send?text=Hello+World

Text: Some text google.com
-> Should extract google.com

Text: There are many nice people on https://www.stackoverflow.com
-> Should extract https://www.stackoverflow.com

Text: You can send visit my Facebook profile on fb://myhappyprofile.
-> Should extract fb://myhappyprofile

Text: https://www.google.com
-> Should extract https://www.google.com
</code>```

The solutions i found so far explicitly extracted URLs starting with http:// https:// or ://. In those solutions, the protocols had to be specified within the expression.

The expression i got the most results from is the following expression:

```<code>(http|ftp|https|whatsapp|fb):\/\/([\w_-]+(?:(?:\.[\w_-]+)?))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?
</code>```

Live Demo

Here i am listing the URL schemes ("deep links") to apps like WhatsApp and Facebook.
Unfortunately, that does not scale very well.

Any help on this would be very appreciated!

答:
If I'm reading this correctly, what you are wanting is to have a generic way to detect the protocol being used for the URL so you don't need to maintain a list of 100 different ones?

If so, then replacing your protocol list with a standard character capture should do the job.

Assuming that:

URLs will always contain "://" to separate the protocol from the location

a protocol will be a minimum of 2 characters and a maximum of 20 (though you can adjust that to suit your requirements

That would mean that the following should do the job

```<code>([a-zA-Z]{2,20}):\/\/([\w_-]+(?:(?:\.[\w_-]+)?))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?
</code>```

https://regex101.com/r/epzXQv/2

Body:
I am looking for a way to extract URLs from text using RegEx. There are plenty of questions and very good answers here on SF but i did not find a RegEx solution that is capable of extracting URLs whith custom schemes as well.

Here are a few examples where i need the URLs extracted from:

Text: Send me a message on whatsapp whatsapp://send?text=Hello+World. I will get in touch!
-> Should extract whatsapp://send?text=Hello+World

Text: Some text google.com
-> Should extract google.com

Text: There are many nice people on https://www.stackoverflow.com
-> Should extract https://www.stackoverflow.com

Text: You can send visit my Facebook profile on fb://myhappyprofile.
-> Should extract fb://myhappyprofile

Text: https://www.google.com
-> Should extract https://www.google.com

The solutions i found so far explicitly extracted URLs starting with http:// https:// or ://. In those solutions, the protocols had to be specified within the expression.

The expression i got the most results from is the following expression:

(http|ftp|https|whatsapp|fb):\/\/([\w_-]+(?:(?:\.[\w_-]+)?))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?

Live Demo

Here i am listing the URL schemes ("deep links") to apps like WhatsApp and Facebook.
Unfortunately, that does not scale very well.

Any help on this would be very appreciated!

Body:
If I'm reading this correctly, what you are wanting is to have a generic way to detect the protocol being used for the URL so you don't need to maintain a list of 100 different ones?

If so, then replacing your protocol list with a standard character capture should do the job.

Assuming that:

URLs will always contain "://" to separate the protocol from the location

a protocol will be a minimum of 2 characters and a maximum of 20 (though you can adjust that to suit your requirements

That would mean that the following should do the job

([a-zA-Z]{2,20}):\/\/([\w_-]+(?:(?:\.[\w_-]+)?))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?

https://regex101.com/r/epzXQv/2


问:
RegEx for replacing the middle letter
Invalid regular expression: Invalid group

I tried except ( ) , fixed and changed . to $
but does not work

```<code>var name = 'ABC'
var pattern = /(?<=.{1})./
return name.replace(pattern, " * ")
</code>```

I want to replace like 'A*C'

Invalid regular expression: Invalid group

答:
Your pattern uses a lookbehind which has limit browser support.

If the lookbehind is supported, the pattern (which can be shortened to (?<=.). will match any char if what is on the left is any char.

That will match B in ABC but also in ABCD so is does not matches the middle char.

Another option could be to use:

```<code>^(.).(?=.$)
</code>```

In the replacement use (without leading and trailing spaces):

```<code>$1*
</code>```

Note that the dot . matches any char except a newline so it will also match a space. If you don't want to match a space you could use \S instead.

var name = 'ABC';
var pattern = /^(.).(?=.$)/;
console.log(name.replace(pattern, "$1*"));```
</div>
</div>
</p>

<p>You might replace the middle char without a regex:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let strings = [
  "A",
  "AB",
  "ABC",
  "ABCD",
  "ABCDE",
  "ABCDEF",
  "ABCDEFG",
  "ABCDEFGH",
  "ABCDEFGHI"
].reduce(function(a, c) {
  if (c.length % 2 === 1) {
    let evenHalf = (c.length - 1) / 2;
    a.push(c.substr(0, evenHalf) + '*' + c.substr(evenHalf + 1));
  }
  return a;
}, []);

console.log(strings);</code>```

Title: RegEx for replacing the middle letter

Body:
Invalid regular expression: Invalid group

I tried except ( ) , fixed and changed . to $
but does not work

var name = 'ABC'
var pattern = /(?<=.{1})./
return name.replace(pattern, " * ")

I want to replace like 'A*C'

Invalid regular expression: Invalid group

Body:
Your pattern uses a lookbehind which has limit browser support.

If the lookbehind is supported, the pattern (which can be shortened to (?<=.). will match any char if what is on the left is any char.

That will match B in ABC but also in ABCD so is does not matches the middle char.

Another option could be to use:

^(.).(?=.$)

In the replacement use (without leading and trailing spaces):

$1*

Note that the dot . matches any char except a newline so it will also match a space. If you don't want to match a space you could use \S instead.

var name = 'ABC';
var pattern = /^(.).(?=.$)/;
console.log(name.replace(pattern, "$1*"));

You might replace the middle char without a regex:

let strings = [
  "A",
  "AB",
  "ABC",
  "ABCD",
  "ABCDE",
  "ABCDEF",
  "ABCDEFG",
  "ABCDEFGH",
  "ABCDEFGHI"
].reduce(function(a, c) {
  if (c.length % 2 === 1) {
    let evenHalf = (c.length - 1) / 2;
    a.push(c.substr(0, evenHalf) + '*' + c.substr(evenHalf + 1));
  }
  return a;
}, []);

console.log(strings);


问:
How to use Rebus.Logging.ILog
Is it possible to use ILog below with Azure Function logging or Serilog etc?

I cannot find code example on how to use it.

Rebus.Logging.ILog

```<code>  .Options(o =>
    {
    o.Decorate<IErrorHandler>(c =>
       new ErrorMessageHandler(c.Get<IErrorHandler>(), c.Get<ILog>()));
</code>```

答:
It's certainly possibly – but since Rebus' loggers are created with a type (the type works as a context of sorts – I think Serilog calls it "source context"), you do not inject the logger, you inject a logger factory:

.Options(o =>
{
    o.Decorate<IErrorHandler>(c => {
        var errorHandler = c.Get<IErrorHandler>();
        var loggerFactory = c.Get<IRebusLoggerFactory>();
        return new ErrorMessageHandler(errorHandler, loggerFactory));
    });
}
```

<p>and then, in the constructor of <code>ErrorMessageHandler</code>, you can get the logger:</p>

<pre class="lang-cs prettyprint-override"><code>public class ErrorMessageHandler : IErrorHandler
{
    readonly IErrorHandler errorHandler;
    readonly ILog log;

    public ErrorMessageHandler(IErrorHandler errorHandler, IRebusLoggerFactory loggerFactory)
    {
        this.errorHandler = errorHandler;
        log = loggerFactory.GetLogger<ErrorMessageHandler>();
    }

    public async Task HandlePoisonMessage(TransportMessage transportMessage, ITransactionContext transactionContext, Exception exception)
    {
        // do stuff in here
    }
}
</code>```

Title: How to use Rebus.Logging.ILog

Body:
Is it possible to use ILog below with Azure Function logging or Serilog etc?

I cannot find code example on how to use it.

Rebus.Logging.ILog

  .Options(o =>
    {
    o.Decorate<IErrorHandler>(c =>
       new ErrorMessageHandler(c.Get<IErrorHandler>(), c.Get<ILog>()));

Body:
It's certainly possibly – but since Rebus' loggers are created with a type (the type works as a context of sorts – I think Serilog calls it "source context"), you do not inject the logger, you inject a logger factory:

.Options(o =>
{
    o.Decorate<IErrorHandler>(c => {
        var errorHandler = c.Get<IErrorHandler>();
        var loggerFactory = c.Get<IRebusLoggerFactory>();
        return new ErrorMessageHandler(errorHandler, loggerFactory));
    });
}

and then, in the constructor of ErrorMessageHandler, you can get the logger:

public class ErrorMessageHandler : IErrorHandler
{
    readonly IErrorHandler errorHandler;
    readonly ILog log;

    public ErrorMessageHandler(IErrorHandler errorHandler, IRebusLoggerFactory loggerFactory)
    {
        this.errorHandler = errorHandler;
        log = loggerFactory.GetLogger<ErrorMessageHandler>();
    }

    public async Task HandlePoisonMessage(TransportMessage transportMessage, ITransactionContext transactionContext, Exception exception)
    {
        // do stuff in here
    }
}


问:
html link tag color not changing after clicked
Link color not changing after i clicked.
I used side navigation bar css style with links.
Here is my css styling:

i tried with active but still not working.

```<code>.sidenav
{
height: 100%;
width: 200px;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: #06799f;
overflow-x: hidden;
padding-top: 20px;
}

.sidenav a
{
padding: 15px 20px 4px 18px;
text-decoration: none;
font-size: 25px;
color: #f1f1f1;
display: block;
}

.sidenav a:hover
{
color: #000000;
}

.sidenav a: active
{
color: black;
}

@media screen and (max-height: 450px) {
.sidenav {padding-top: 15px;}
.sidenav a {font-size: 18px;}
}
</code>```

expected:
is the change of link color when cliked

答:
You can add the :visited pseudo class to style visited links. (Documentation)

```<code>.sidenav a:visited {
    color: #BA55D3;
}
</code>```

Using :active as you proposed only changes the color while pressing the link.

Body:
Link color not changing after i clicked.
I used side navigation bar css style with links.
Here is my css styling:

i tried with active but still not working.

.sidenav
{
height: 100%;
width: 200px;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: #06799f;
overflow-x: hidden;
padding-top: 20px;
}

.sidenav a
{
padding: 15px 20px 4px 18px;
text-decoration: none;
font-size: 25px;
color: #f1f1f1;
display: block;
}

.sidenav a:hover
{
color: #000000;
}

.sidenav a: active
{
color: black;
}

@media screen and (max-height: 450px) {
.sidenav {padding-top: 15px;}
.sidenav a {font-size: 18px;}
}

expected:
is the change of link color when cliked

Body:
You can add the :visited pseudo class to style visited links. (Documentation)

.sidenav a:visited {
    color: #BA55D3;
}

Using :active as you proposed only changes the color while pressing the link.


问:
Silverlight 3 WCF Multiple Servers
Please help...I'm going crazy....I have a wcf service that exists on a few different servers.  I need to dynamically change the endpoint address on my silverlight client depending on the environment its in. I'm currently getting a very detailed 404 error (sarcasm) when I try to change the address through code or by manually updating the client config file.

However, when I right-click on the service reference and go to configure service on my client I can change the address and it works.

I have the following service.

```<code><system.serviceModel>
 <bindings>
  <basicHttpBinding>
    <binding name="DrawingServiceBasicHttp">
      <readerQuotas maxStringContentLength="2147483647" />
    </binding>
  </basicHttpBinding>
</bindings>

<service behaviorConfiguration="md" name="My.DrawingService">
    <endpoint address="Services"
              binding="basicHttpBinding"
              bindingConfiguration="DrawingServiceBasicHttp"
              name="DrawingServiceEndPoint"
              contract="MyServices.IDrawingService" />
    <endpoint address="mex"
              binding="mexHttpBinding"
              bindingConfiguration=""
              name="DrawingMex"
              contract="IMetadataExchange" />
 <behaviors>
  <serviceBehaviors>
    <behavior name="md">
      <serviceMetadata httpGetEnabled="true"/>
      <serviceDebug includeExceptionDetailInFaults="true"/>
    </behavior>
  </serviceBehaviors>
</behaviors>
</code>```

My client config

```<code><bindings>
        <basicHttpBinding>
            <binding name="DrawingServiceEndPoint" maxBufferSize="2147483647"
                maxReceivedMessageSize="2147483647">
                <security>
                    <transport>
                        <extendedProtectionPolicy policyEnforcement="Never" />
                    </transport>
                </security>
            </binding>
        </basicHttpBinding>
    </bindings>
    <client>
        <endpoint address="http://MyHostName/Services/DrawingService.svc/Services"
            binding="basicHttpBinding" bindingConfiguration="DrawingServiceEndPoint"
            contract="EvalDrawingService.IDrawingService" name="DrawingServiceEndPoint" />
    </client>
</code>```

In Code trying to set the address:

```<code>EvalDrawingService.DrawingServiceClient client = new EvalDrawingService.DrawingServiceClient("DrawingServiceEndPoint", GetServiceAddress());
</code>```

I have verified the address being spit out by GetServiceAddress() is there and that I can use the browser to verify it exists (not to mention I can connect to it using the wcftestclient).

The Exception:

{System.ServiceModel.CommunicationException: The remote server returned an error: NotFound. ---> System.Net.WebException: The remote server returned an error: NotFound. ---> System.Net.WebException: The remote server returned an error: NotFound.
    at System.Net.Browser.BrowserHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
    at System.Net.Browser.BrowserHttpWebRequest.<>c_DisplayClass5.b_4(Object sendState)
    at System.Net.Browser.AsyncHelper.<>c_DisplayClass4.b_1(Object sendState)
    --- End of inner exception stack trace ---
    at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
    at System.Net.Browser.BrowserHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
    at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelAsyncRequest.CompleteGetResponse(IAsyncResult result)
    --- End of inner exception stack trace ---
    at System.ServiceModel.AsyncResult.End[TAsyncResult](IAsyncResult result)
    at System.ServiceModel.Channels.ServiceChannel.SendAsyncResult.End(SendAsyncResult result)
    at System.ServiceModel.Channels.ServiceChannel.EndCall(String action, Object[] outs, IAsyncResult result)
    at System.ServiceModel.ClientBase1.ChannelBase1.EndInvoke(String methodName, Object[] args, IAsyncResult result)
    at EvaluaionAncillaryControl.EvalDrawingService.DrawingServiceClient.DrawingServiceClientChannel.EndGetEvalAreaDrawing(IAsyncResult result)
    at EvaluaionAncillaryControl.EvalDrawingService.DrawingServiceClient.EvaluaionAncillaryControl.EvalDrawingService.IDrawingService.EndGetEvalAreaDrawing(IAsyncResult result)
    at EvaluaionAncillaryControl.EvalDrawingService.DrawingServiceClient.OnEndGetEvalAreaDrawing(IAsyncResult result)
    at System.ServiceModel.ClientBase`1.OnAsyncCallCompleted(IAsyncResult result)}

答:
(RESOLUTION)
I was able to find the answer by observing what was being done in the first link in the answer from @rboarman. The link is to a blog writtent by Omar Al Zabir.  http://omaralzabir.com/dynamically-set-wcf-endpoint-in-silverlight/

I used the below method:

```<code>public class DynamicEndpointHelper
{
// Put the development server site URL including the trailing slash
// This should be same as what's set in the Dropthings web project's
// properties as the URL of the site in development server
private const string BaseUrl = "http://localhost:8000/Dropthings/";

public static string ResolveEndpointUrl(string endpointUrl, string xapPath)
{
    string baseUrl = xapPath.Substring(0, xapPath.IndexOf("ClientBin"));
    string relativeEndpointUrl = endpointUrl.Substring(BaseUrl.Length);
    string dynamicEndpointUrl = baseUrl + relativeEndpointUrl;
    return dynamicEndpointUrl;
}
}
</code>```

and called it in this manner:

```<code>DynamicEndpointHelper.ResolveEndpointUrl(service.Endpoint.Address.Uri.ToString(),
    App.Current.Host.Source.ToString()));
</code>```

This allowed me to see that the proper way would have been to call use an address like:

```<code>http://MyServer/Services/MyService.svc/Services //This is what I specified it in the web.config
</code>```

instead of just

```<code>http://MyServer/Services/MyService.svc/
</code>```

I thought that the address "Services" in the service config was a relative address to my .svc file, but obviously I was wrong.

Title: Silverlight 3 WCF Multiple Servers

Body:
Please help...I'm going crazy....I have a wcf service that exists on a few different servers.  I need to dynamically change the endpoint address on my silverlight client depending on the environment its in. I'm currently getting a very detailed 404 error (sarcasm) when I try to change the address through code or by manually updating the client config file.

However, when I right-click on the service reference and go to configure service on my client I can change the address and it works.

I have the following service.

<system.serviceModel>
 <bindings>
  <basicHttpBinding>
    <binding name="DrawingServiceBasicHttp">
      <readerQuotas maxStringContentLength="2147483647" />
    </binding>
  </basicHttpBinding>
</bindings>

<service behaviorConfiguration="md" name="My.DrawingService">
    <endpoint address="Services"
              binding="basicHttpBinding"
              bindingConfiguration="DrawingServiceBasicHttp"
              name="DrawingServiceEndPoint"
              contract="MyServices.IDrawingService" />
    <endpoint address="mex"
              binding="mexHttpBinding"
              bindingConfiguration=""
              name="DrawingMex"
              contract="IMetadataExchange" />
 <behaviors>
  <serviceBehaviors>
    <behavior name="md">
      <serviceMetadata httpGetEnabled="true"/>
      <serviceDebug includeExceptionDetailInFaults="true"/>
    </behavior>
  </serviceBehaviors>
</behaviors>

My client config

<bindings>
        <basicHttpBinding>
            <binding name="DrawingServiceEndPoint" maxBufferSize="2147483647"
                maxReceivedMessageSize="2147483647">
                <security>
                    <transport>
                        <extendedProtectionPolicy policyEnforcement="Never" />
                    </transport>
                </security>
            </binding>
        </basicHttpBinding>
    </bindings>
    <client>
        <endpoint address="http://MyHostName/Services/DrawingService.svc/Services"
            binding="basicHttpBinding" bindingConfiguration="DrawingServiceEndPoint"
            contract="EvalDrawingService.IDrawingService" name="DrawingServiceEndPoint" />
    </client>

In Code trying to set the address:

EvalDrawingService.DrawingServiceClient client = new EvalDrawingService.DrawingServiceClient("DrawingServiceEndPoint", GetServiceAddress());

I have verified the address being spit out by GetServiceAddress() is there and that I can use the browser to verify it exists (not to mention I can connect to it using the wcftestclient).

The Exception:

{System.ServiceModel.CommunicationException: The remote server returned an error: NotFound. ---> System.Net.WebException: The remote server returned an error: NotFound. ---> System.Net.WebException: The remote server returned an error: NotFound.
    at System.Net.Browser.BrowserHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
    at System.Net.Browser.BrowserHttpWebRequest.<>c_DisplayClass5.b_4(Object sendState)
    at System.Net.Browser.AsyncHelper.<>c_DisplayClass4.b_1(Object sendState)
    --- End of inner exception stack trace ---
    at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
    at System.Net.Browser.BrowserHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
    at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelAsyncRequest.CompleteGetResponse(IAsyncResult result)
    --- End of inner exception stack trace ---
    at System.ServiceModel.AsyncResult.End[TAsyncResult](IAsyncResult result)
    at System.ServiceModel.Channels.ServiceChannel.SendAsyncResult.End(SendAsyncResult result)
    at System.ServiceModel.Channels.ServiceChannel.EndCall(String action, Object[] outs, IAsyncResult result)
    at System.ServiceModel.ClientBase1.ChannelBase1.EndInvoke(String methodName, Object[] args, IAsyncResult result)
    at EvaluaionAncillaryControl.EvalDrawingService.DrawingServiceClient.DrawingServiceClientChannel.EndGetEvalAreaDrawing(IAsyncResult result)
    at EvaluaionAncillaryControl.EvalDrawingService.DrawingServiceClient.EvaluaionAncillaryControl.EvalDrawingService.IDrawingService.EndGetEvalAreaDrawing(IAsyncResult result)
    at EvaluaionAncillaryControl.EvalDrawingService.DrawingServiceClient.OnEndGetEvalAreaDrawing(IAsyncResult result)
    at System.ServiceModel.ClientBase`1.OnAsyncCallCompleted(IAsyncResult result)}

Body:
(RESOLUTION)
I was able to find the answer by observing what was being done in the first link in the answer from @rboarman. The link is to a blog writtent by Omar Al Zabir.  http://omaralzabir.com/dynamically-set-wcf-endpoint-in-silverlight/

I used the below method:

public class DynamicEndpointHelper
{
// Put the development server site URL including the trailing slash
// This should be same as what's set in the Dropthings web project's
// properties as the URL of the site in development server
private const string BaseUrl = "http://localhost:8000/Dropthings/";

public static string ResolveEndpointUrl(string endpointUrl, string xapPath)
{
    string baseUrl = xapPath.Substring(0, xapPath.IndexOf("ClientBin"));
    string relativeEndpointUrl = endpointUrl.Substring(BaseUrl.Length);
    string dynamicEndpointUrl = baseUrl + relativeEndpointUrl;
    return dynamicEndpointUrl;
}
}

and called it in this manner:

DynamicEndpointHelper.ResolveEndpointUrl(service.Endpoint.Address.Uri.ToString(),
    App.Current.Host.Source.ToString()));

This allowed me to see that the proper way would have been to call use an address like:

http://MyServer/Services/MyService.svc/Services //This is what I specified it in the web.config

instead of just

http://MyServer/Services/MyService.svc/

I thought that the address "Services" in the service config was a relative address to my .svc file, but obviously I was wrong.


问:
I want to upgrade all npm packages in node-loopback application
I have a node application, with installed all node packages compatible to node version 0.10.25,

But now I have to upgrade all the packages compatible to current node version i.e. node version 10.15.3

I've tried two ways till now i.e.

1.) npm upgrade --save

2.) hardcoded packages updated version in package.json file, and then run.

```<code>npm install --save
</code>```

But I've ended Up with error like

```<code>Error: Cannot resolve path "loopback/server/middleware/compress"
</code>```

After above error I tried

```<code>npm install compress --save
</code>```

after that also Same error.

My previous package.json file looks like

```<code>...
  "dependencies": {
    "compression": "^1.0.3",
    "ejs": "^1.0.0",
    "email-templates": "^1.2.1",
    "errorhandler": "^1.1.1",
    "loopback": "^2.8.0",
    "loopback-boot": "^2.4.0",
    "loopback-component-storage": "^1.5.0",
    "loopback-connector-mysql": "^2.1.1",
    "loopback-datasource-juggler": "^2.7.0",
    "mysql": "^2.17.1",
    "nodemailer": "^1.3.4",
    "nodemailer-smtp-transport": "^1.0.3",
    "q": "^1.4.1",
    "request": "^2.88.0",
    "serve-favicon": "^2.0.1",
    "strongloop": "^6.0.3"
  },
  "optionalDependencies": {
    "loopback-explorer": "^1.1.0"
  },
  "devDependencies": {
    "jshint": "^2.5.6"
  },
...
</code>```

My current package.json file looks like below (Mannually find updated version of all packages from https://www.npmjs.com/package/ )

```<code> ...
  "dependencies": {
    "compression": "^1.7.4",
    "ejs": "^2.6.1",
    "email-templates": "^5.0.4",
    "errorhandler": "^1.5.1",
    "loopback": "^3.25.1",
    "loopback-boot": "^2.28.0",
    "loopback-component-storage": "^3.6.0",
    "loopback-connector-mysql": "^5.3.1",
    "loopback-datasource-juggler": "^4.6.2",
    "mysql": "^2.17.1",
    "nodemailer": "^6.1.0",
    "nodemailer-smtp-transport": "^2.7.4",
    "nodemon": "^1.19.1",
    "q": "^1.5.1",
    "request": "^2.88.0",
    "serve-favicon": "^2.5.0",
    "strongloop": "^6.0.3"
  },
  "optionalDependencies": {
    "loopback-component-explorer": "^6.4.0"
  },
  "devDependencies": {
    "jshint": "^2.10.2"
  },
  "repository": {
    "type": "",
    "url": ""
  },
  "description": "orders"
}
...
</code>```

I have to extent The application which meet the business logic For that I need to install very many new packages but not available / compatible with my current packages ,

Any reference or advice for doing so would be really helpful for me.

Thanks In Advance

答:
Since you are upgrading many dependencies to a higher semver-major version, you need to deal with breaking changes introduced in those versions.

LoopBack provides a migration guide for developers upgrading from 2.x to 3.x, see https://loopback.io/doc/en/lb3/Migrating-to-3.0.html.

Error: Cannot resolve path "loopback/server/middleware/compress"

LoopBack 3.x upgraded Express from 2.x to 3.x (IIRC) and as a result, popular middleware is no longer bundled - applications have to install and load them explicitly.

I see that you already have compression listed in your dependencies, so now you need to change the code calling require('loopback/server/middleware/compress') to call require(compression') instead. Check also your server/middleware.json file, LoopBack applications usually configure middleware through that config file.

"loopback-datasource-juggler": "^4.6.2",

In LoopBack 3.0, we moved loopback-datasource-juggler from peerDependencies to regular dependencies, LoopBack applications are no longer depending on juggler directly. Please remove this entry from your package.json.

See https://loopback.io/doc/en/lb3/Migrating-to-3.0.html#edit-packagejson and https://loopback.io/doc/en/lb3/3.0-Release-Notes.html#loopback-datasource-juggler-is-now-a-regular-dependency-of-loopback

Body:
I have a node application, with installed all node packages compatible to node version 0.10.25,

But now I have to upgrade all the packages compatible to current node version i.e. node version 10.15.3

I've tried two ways till now i.e.

1.) npm upgrade --save

2.) hardcoded packages updated version in package.json file, and then run.

npm install --save

But I've ended Up with error like

Error: Cannot resolve path "loopback/server/middleware/compress"

After above error I tried

npm install compress --save

after that also Same error.

My previous package.json file looks like

...
  "dependencies": {
    "compression": "^1.0.3",
    "ejs": "^1.0.0",
    "email-templates": "^1.2.1",
    "errorhandler": "^1.1.1",
    "loopback": "^2.8.0",
    "loopback-boot": "^2.4.0",
    "loopback-component-storage": "^1.5.0",
    "loopback-connector-mysql": "^2.1.1",
    "loopback-datasource-juggler": "^2.7.0",
    "mysql": "^2.17.1",
    "nodemailer": "^1.3.4",
    "nodemailer-smtp-transport": "^1.0.3",
    "q": "^1.4.1",
    "request": "^2.88.0",
    "serve-favicon": "^2.0.1",
    "strongloop": "^6.0.3"
  },
  "optionalDependencies": {
    "loopback-explorer": "^1.1.0"
  },
  "devDependencies": {
    "jshint": "^2.5.6"
  },
...

My current package.json file looks like below (Mannually find updated version of all packages from https://www.npmjs.com/package/ )

 ...
  "dependencies": {
    "compression": "^1.7.4",
    "ejs": "^2.6.1",
    "email-templates": "^5.0.4",
    "errorhandler": "^1.5.1",
    "loopback": "^3.25.1",
    "loopback-boot": "^2.28.0",
    "loopback-component-storage": "^3.6.0",
    "loopback-connector-mysql": "^5.3.1",
    "loopback-datasource-juggler": "^4.6.2",
    "mysql": "^2.17.1",
    "nodemailer": "^6.1.0",
    "nodemailer-smtp-transport": "^2.7.4",
    "nodemon": "^1.19.1",
    "q": "^1.5.1",
    "request": "^2.88.0",
    "serve-favicon": "^2.5.0",
    "strongloop": "^6.0.3"
  },
  "optionalDependencies": {
    "loopback-component-explorer": "^6.4.0"
  },
  "devDependencies": {
    "jshint": "^2.10.2"
  },
  "repository": {
    "type": "",
    "url": ""
  },
  "description": "orders"
}
...

I have to extent The application which meet the business logic For that I need to install very many new packages but not available / compatible with my current packages ,

Any reference or advice for doing so would be really helpful for me.

Thanks In Advance


问:
How to open pdf from ajax response
I am trying to open a PDF document received as a response text, in a new browser tab.

My controller code is :

```<code>$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord,'HTML');
$objWriter->save('helloWorld.html');
$pdf = App::make('dompdf.wrapper');
$pdf->loadHTML('helloWorld.html');
$data = $pdf->stream();
return $data;
</code>```

And the ajax code so far (not working) :

```<code>$('body').on('click', '.printInvoice', function () {
    var purchase_id = $(this).data("id");
        $.ajax({
            type: "GET",
            url: "/purchases/print" + '/' + purchase_id,
            success: function (data) {
                console.log(data);
                var blob = data;
                var link = document.createElement('a');
                link.href = window.URL.createObjectURL(blob);
                link.download = "PdfName-" + new Date().getTime() + ".pdf";
                document.body.appendChild(link);
                link.click();
            },
            error: function (data) {
                var data2 = JSON.parse(data.responseText);
                alert(data2['errors']);
            }
        });
});
</code>```

The code above is generating the following error :
'createObjectURL' on 'URL': No function was found that matched the signature provided.

Please help to fix the above code, or give a better solution to the problem.

答:
Don't do this way,
I have a better option for you!

Don't send information via ajax. use window.location.href

example code:

```<code>$('body').on('click', '.printInvoice', function () {
   var purchase_id = $(this).data("id");
   window.location.href = "/purchases/print" + '/' + purchase_id;
});
</code>```

Don't forget to die at end of the route.

Title: How to open pdf from ajax response

Body:
I am trying to open a PDF document received as a response text, in a new browser tab.

My controller code is :

$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord,'HTML');
$objWriter->save('helloWorld.html');
$pdf = App::make('dompdf.wrapper');
$pdf->loadHTML('helloWorld.html');
$data = $pdf->stream();
return $data;

And the ajax code so far (not working) :

$('body').on('click', '.printInvoice', function () {
    var purchase_id = $(this).data("id");
        $.ajax({
            type: "GET",
            url: "/purchases/print" + '/' + purchase_id,
            success: function (data) {
                console.log(data);
                var blob = data;
                var link = document.createElement('a');
                link.href = window.URL.createObjectURL(blob);
                link.download = "PdfName-" + new Date().getTime() + ".pdf";
                document.body.appendChild(link);
                link.click();
            },
            error: function (data) {
                var data2 = JSON.parse(data.responseText);
                alert(data2['errors']);
            }
        });
});

The code above is generating the following error :
'createObjectURL' on 'URL': No function was found that matched the signature provided.

Please help to fix the above code, or give a better solution to the problem.

Body:
Don't do this way,
I have a better option for you!

Don't send information via ajax. use window.location.href

example code:

$('body').on('click', '.printInvoice', function () {
   var purchase_id = $(this).data("id");
   window.location.href = "/purchases/print" + '/' + purchase_id;
});

Don't forget to die at end of the route.


问:
Multiple Image Upload in Laravel tweak to add additional field
I have a need to upload multiple images. This code below works well. This is using Intervention Image plugin. I am trying to customise this code to add another field which is a ForeignKey value to the parent of this image model.  $request has the value coming from form. How to save it along with images?

The value is:

$request('vehicle_id')

How can tweak the below method so as save includes this vehicle_id as well?

```<code>public function uploadImage(Request $request)
        {
            $request->validate([
                'image' => 'required',
                'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
            ]);

    //check if image exist
    if ($request->hasFile('image')) {
        $images = $request->file('image');

        // create new directory for uploading image if doesn't exist
        if( ! File::exists('images/'.auth()->user()->id)) {
            $org_img = File::makeDirectory('images/'.auth()->user()->id, 0777, true);
        }

        // loop through each image to save and upload
        foreach($images as $key => $image) {
            //create new instance of Photo class
            $newPhoto = new $this->photo;
            //get file name of image  and concatenate with 4 random integer for unique
            $filename = rand(1111,9999).time().'.'.$image->getClientOriginalExtension();
            //path of image for upload
            $org_path = 'images/'.auth()->user()->id . $filename;

            $newPhoto->image     = 'images/'.auth()->user()->id.$filename;

            //don't upload file when unable to save name to database
            if ( ! $newPhoto->save()) {
                return false;
            }

            // upload image to server
            if ($org_img == true) {
               Image::make($image)->fit(900, 500, function ($constraint) {
                       $constraint->upsize();
                   })->save($org_path);
            }

        }
    }

    return redirect('/home')->with('success','Images Uploaded');

}
</code>```

答:
I found solution

```<code>public function uploadImage(Request $request)
    {
        $request->validate([
            'image' => 'required',
            'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
            'vehicle' => 'required'
        ]);

    //check if image exist
    if ($request->hasFile('image')) {
        $images = $request->file('image');

        // create new directory for uploading image if doesn't exist
        if( ! File::exists('images/'.auth()->user()->id.'/')) {
            $org_img = File::makeDirectory('images/'.auth()->user()->id.'/', 0777, true);
        }

        // loop through each image to save and upload
        foreach($images as $key => $image) {
            //create new instance of Photo class
            $newPhoto = new $this->photo;
            //get file name of image  and concatenate with 4 random integer for unique
            $filename = rand(1111,9999).time().'.'.$image->getClientOriginalExtension();
            //path of image for upload
            $org_path = 'images/'.auth()->user()->id.'/' . $filename;

            $newPhoto->image     = 'images/'.auth()->user()->id.'/' . $filename;
            $newPhoto->vehicle = $request->input('vehicle');
            //don't upload file when unable to save name to database
            if ( ! $newPhoto->save()) {
                return false;
            }
            // upload image to server
           Image::make($image)->fit(900, 500, function ($constraint) {
                   $constraint->upsize();
               })->save($org_path);

        }
    }

    return redirect('/home')->with('success','Images Uploaded');
</code>```

Body:
I have a need to upload multiple images. This code below works well. This is using Intervention Image plugin. I am trying to customise this code to add another field which is a ForeignKey value to the parent of this image model.  $request has the value coming from form. How to save it along with images?

The value is:

$request('vehicle_id')

How can tweak the below method so as save includes this vehicle_id as well?

public function uploadImage(Request $request)
        {
            $request->validate([
                'image' => 'required',
                'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
            ]);

    //check if image exist
    if ($request->hasFile('image')) {
        $images = $request->file('image');

        // create new directory for uploading image if doesn't exist
        if( ! File::exists('images/'.auth()->user()->id)) {
            $org_img = File::makeDirectory('images/'.auth()->user()->id, 0777, true);
        }

        // loop through each image to save and upload
        foreach($images as $key => $image) {
            //create new instance of Photo class
            $newPhoto = new $this->photo;
            //get file name of image  and concatenate with 4 random integer for unique
            $filename = rand(1111,9999).time().'.'.$image->getClientOriginalExtension();
            //path of image for upload
            $org_path = 'images/'.auth()->user()->id . $filename;

            $newPhoto->image     = 'images/'.auth()->user()->id.$filename;

            //don't upload file when unable to save name to database
            if ( ! $newPhoto->save()) {
                return false;
            }

            // upload image to server
            if ($org_img == true) {
               Image::make($image)->fit(900, 500, function ($constraint) {
                       $constraint->upsize();
                   })->save($org_path);
            }

        }
    }

    return redirect('/home')->with('success','Images Uploaded');

}

Body:
I found solution

public function uploadImage(Request $request)
    {
        $request->validate([
            'image' => 'required',
            'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
            'vehicle' => 'required'
        ]);

    //check if image exist
    if ($request->hasFile('image')) {
        $images = $request->file('image');

        // create new directory for uploading image if doesn't exist
        if( ! File::exists('images/'.auth()->user()->id.'/')) {
            $org_img = File::makeDirectory('images/'.auth()->user()->id.'/', 0777, true);
        }

        // loop through each image to save and upload
        foreach($images as $key => $image) {
            //create new instance of Photo class
            $newPhoto = new $this->photo;
            //get file name of image  and concatenate with 4 random integer for unique
            $filename = rand(1111,9999).time().'.'.$image->getClientOriginalExtension();
            //path of image for upload
            $org_path = 'images/'.auth()->user()->id.'/' . $filename;

            $newPhoto->image     = 'images/'.auth()->user()->id.'/' . $filename;
            $newPhoto->vehicle = $request->input('vehicle');
            //don't upload file when unable to save name to database
            if ( ! $newPhoto->save()) {
                return false;
            }
            // upload image to server
           Image::make($image)->fit(900, 500, function ($constraint) {
                   $constraint->upsize();
               })->save($org_path);

        }
    }

    return redirect('/home')->with('success','Images Uploaded');


问:
understanding Zend\Form\Element\Date
I have two issues while using the Zend-Form date element.

First: field binding
The edit action within my controller doesn't fillin an existing date. For example birthday. The field is just empty. (with an element type text, there is no problem).

Here how I instanciated the field:

```<code>        $this->add([
        'name' => 'geburtstag',
        'type' => 'date',
        'options' => [
            'label' => 'Geburtstag:',
            'format' => 'dd/mm/yyyy',
        ],
    ]);
</code>```

And here my controller action.

```<code>    public function addAction()
{
    $form = new AnsprechpartnerForm(NULL, $this->db);
    $form->get('submit')->setValue('save');
    $request = $this->getRequest();
    if (! $request->isPost()) {
        return ['form' => $form];
    }
    $ansprechpartner = new Ansprechpartner();
    $form->setInputFilter($ansprechpartner->getInputFilter());
    $form->setData($request->getPost());
    if (! $form->isValid()) {
        return ['form' => $form];
    }
    $ansprechpartner->exchangeArray($form->getData());
    $this->ansprechpartnerTable->saveAnsprechpartner($ansprechpartner);
    return $this->redirect()->toRoute('ansprechpartner');
}
</code>```

No inputFilter at the moment, I tried with and without.

Second: validation

I have trouble filling in dates. While I don't use any filters for this field, I would expect, I could fill any date in.

Interesting I get the message double.

答:
I solved it.

The date element expects the format y-m-d. Now I gave it directly to the field after binding the form. The format in the field is now also korrekt.

```<code>$form->bind($notizen);
$form->get('submit')->setAttribute('value', 'edit');
$filter = new \Zend\Filter\DateTimeFormatter();
$filter->setFormat('Y-m-d');
$dat = $filter->filter($notizen->datum);
$form->get('datum')->setValue($dat);
</code>```

Could be more convenient I guess.

Title: understanding Zend\Form\Element\Date

Body:
I have two issues while using the Zend-Form date element.

First: field binding
The edit action within my controller doesn't fillin an existing date. For example birthday. The field is just empty. (with an element type text, there is no problem).

Here how I instanciated the field:

        $this->add([
        'name' => 'geburtstag',
        'type' => 'date',
        'options' => [
            'label' => 'Geburtstag:',
            'format' => 'dd/mm/yyyy',
        ],
    ]);

And here my controller action.

    public function addAction()
{
    $form = new AnsprechpartnerForm(NULL, $this->db);
    $form->get('submit')->setValue('save');
    $request = $this->getRequest();
    if (! $request->isPost()) {
        return ['form' => $form];
    }
    $ansprechpartner = new Ansprechpartner();
    $form->setInputFilter($ansprechpartner->getInputFilter());
    $form->setData($request->getPost());
    if (! $form->isValid()) {
        return ['form' => $form];
    }
    $ansprechpartner->exchangeArray($form->getData());
    $this->ansprechpartnerTable->saveAnsprechpartner($ansprechpartner);
    return $this->redirect()->toRoute('ansprechpartner');
}

No inputFilter at the moment, I tried with and without.

Second: validation

I have trouble filling in dates. While I don't use any filters for this field, I would expect, I could fill any date in.

Interesting I get the message double.

Body:
I solved it.

The date element expects the format y-m-d. Now I gave it directly to the field after binding the form. The format in the field is now also korrekt.

$form->bind($notizen);
$form->get('submit')->setAttribute('value', 'edit');
$filter = new \Zend\Filter\DateTimeFormatter();
$filter->setFormat('Y-m-d');
$dat = $filter->filter($notizen->datum);
$form->get('datum')->setValue($dat);

Could be more convenient I guess.


问:
jQuery refresh SexyCombo Cascading Inputs
Using sexy-combo with countries, and another with cities. Whenever the user selects a country I fill the second combobox with the corresponding cities with Ajax, without doing any postback.

The problem is that the sexy combo renders the nice combobox using my html select only the first time when the page is loaded. When I update the items in the html select for the cities, it's not being refreshed so there are no values in there...

Do you know what function must I call to "refresh" the combobox, just like it would be refreshed when I do a postback?

Any hint is very welcomed! Thanks a lot.

答:
Create another method in the script, e.g. below "changeOptions":

```<code>custom_update: function($select) {
    $select = $($select);
    $select.each(function() {
        if ("SELECT" != this.tagName.toUpperCase()) {
            return;
        }

        var my_text = $("#"+ this.id + " option:selected").text();
        var my_val = $("#"+ this.id + " option:selected").val();
        var $this = $(this);
        var $wrapper  = $this.parent();
        var $input = $wrapper.find("input[type='text']");
        var $listWrapper = $wrapper.find("ul").parent();

        $listWrapper.removeClass("visible").
        addClass("invisible");
        $wrapper.css("zIndex", "0");
        $listWrapper.css("zIndex", "99999");

        //$input.val("");
        $wrapper.data("sc:optionsChanged", "yes");
        var $selectbox = $this;
        $selectbox.parent().find("input[type='text']").val($selectbox.find("option:eq(" + my_val + ")").text());
        $selectbox.parent().data("sc:lastEvent", "click");
        $selectbox.find("option:eq(" + my_val + ")").attr('selected','selected');
    });
},
</code>```

And call it like:

```<code>$.sexyCombo.custom_update($("#myselectlist"));
</code>```

Body:
Create another method in the script, e.g. below "changeOptions":

custom_update: function($select) {
    $select = $($select);
    $select.each(function() {
        if ("SELECT" != this.tagName.toUpperCase()) {
            return;
        }

        var my_text = $("#"+ this.id + " option:selected").text();
        var my_val = $("#"+ this.id + " option:selected").val();
        var $this = $(this);
        var $wrapper  = $this.parent();
        var $input = $wrapper.find("input[type='text']");
        var $listWrapper = $wrapper.find("ul").parent();

        $listWrapper.removeClass("visible").
        addClass("invisible");
        $wrapper.css("zIndex", "0");
        $listWrapper.css("zIndex", "99999");

        //$input.val("");
        $wrapper.data("sc:optionsChanged", "yes");
        var $selectbox = $this;
        $selectbox.parent().find("input[type='text']").val($selectbox.find("option:eq(" + my_val + ")").text());
        $selectbox.parent().data("sc:lastEvent", "click");
        $selectbox.find("option:eq(" + my_val + ")").attr('selected','selected');
    });
},

And call it like:

$.sexyCombo.custom_update($("#myselectlist"));


问:
How can I get numeric value of Sunday to 1
I am trying to get numeric value of Sunday as 1

```<code>$day_of_week = date('N', strtotime('Sunday'));
</code>```

returns 7.

Can I get 1 instead of 7?

答:
Can I get 1 instead of 7?

A short look into the manual for date should have enabled you to discover that there’s not only the format specifier N, which gives you

1 (for Monday) through 7 (for Sunday)

but also w, which gives you

0 (for Sunday) through 6 (for Saturday)

So if you want values from 1 for Sunday to 7 for Saturday, then all you need to do is use that, and add 1 to it afterwards:

```<code>$day_of_week = date('w', strtotime('Sunday')) + 1;
</code>```

Body:
I am trying to get numeric value of Sunday as 1

$day_of_week = date('N', strtotime('Sunday'));

returns 7.

Can I get 1 instead of 7?

Body:
Can I get 1 instead of 7?

A short look into the manual for date should have enabled you to discover that there’s not only the format specifier N, which gives you

1 (for Monday) through 7 (for Sunday)

but also w, which gives you

0 (for Sunday) through 6 (for Saturday)

So if you want values from 1 for Sunday to 7 for Saturday, then all you need to do is use that, and add 1 to it afterwards:

$day_of_week = date('w', strtotime('Sunday')) + 1;


问:
NopCommerce : Error while running the 'Keep alive' schedule task
I have been getting this error on Nopcommerce all day, the site was workign normally before then all of a sudden started getting

Error while running the 'Keep alive' schedule task. The remote server
  returned an error: (500) Internal Server Error.System.Net.WebException:

The remote server returned an error: (500) Internal Server Error.

  at System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest&
  request)    at System.Net.WebClient.DownloadString(Uri address)    at
  System.Net.WebClient.DownloadString(String address)    at
  Nop.Services.Common.KeepAliveTask.Execute() in
  C:\Users\spadmin\Documents\WebStorm\CVLWeb\Libraries\Nop.Services\Common\KeepAliveTask.cs:line
  27    at Nop.Services.Tasks.Task.Execute(Boolean throwException,
  Boolean dispose, Boolean ensureRunOnOneWebFarmInstance) in
  C:\Users\spadmin\Documents\WebStorm\CVLWeb\Libraries\Nop.Services\Tasks\Task.cs:line
  163

I have tried all the suggestion from the forum which include updating the KeepAlive link in Common/KeepAlive.cs, to create a file ina folder called KeepAlive in the Root.

The WebSite was running fine until this morning when the error started showing up. I am running version 3.9 of NopCommerce on Azure Website.

答:
first check this
1.Go to admin area > configuration > stores > your store details and ensure that store URL is entered with HTTP://</p>


问:
In Laravel, how can I bind a model instance if I need a session parameter?
I want to make a singleton binding of a domain model in register method of AppServiceProvider, but I have saved the id of the selected model in session and this information is not accessible in AppServiceProvider.

Has somebody any idea how I can solve my problem?
This is my code.

class AppServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->singleton(Domain::class, function ($app)
        {
            $request = request();

            if ($request->has('d'))
            {
                session(['domain' => $request->get('d')]);

                $domain = Domain::find($request->get('d'));
            }
            else
            {
                $domain = Domain::find(session('domain'));
            }

            return !is_null($domain) ? $domain : new Domain();
        });
    }

    public function boot()
    {
        //
    }
}
```

session('domain') is always null.

Thank you

答:
You can use the session in your AppProvider, cause the MW didnt start till there. For more help or other ways read here:
Link 1
Link 2

If you want to use the variable from your session inside the boot method you should use the view composer.

```<code>public function boot()
{
    view()->composer('*', function ($view)
    {
        $view->with('myVar', \Session::get('varFromSession') );
    });
}
</code>```

Body:
I want to make a singleton binding of a domain model in register method of AppServiceProvider, but I have saved the id of the selected model in session and this information is not accessible in AppServiceProvider.

Has somebody any idea how I can solve my problem?
This is my code.

class AppServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->singleton(Domain::class, function ($app)
        {
            $request = request();

            if ($request->has('d'))
            {
                session(['domain' => $request->get('d')]);

                $domain = Domain::find($request->get('d'));
            }
            else
            {
                $domain = Domain::find(session('domain'));
            }

            return !is_null($domain) ? $domain : new Domain();
        });
    }

    public function boot()
    {
        //
    }
}

session('domain') is always null.

Thank you

Body:
You can use the session in your AppProvider, cause the MW didnt start till there. For more help or other ways read here:
Link 1
Link 2

If you want to use the variable from your session inside the boot method you should use the view composer.

public function boot()
{
    view()->composer('*', function ($view)
    {
        $view->with('myVar', \Session::get('varFromSession') );
    });
}


问:
jquery autocomplete complex html Result
I need an autocomplete text box for my search and I will use jQuery UI for this. I'm using an ASP.NET Core API to get search result in json format. My search result should be grouping with bootstrap collapse panel and group members showing in a table. Every group has different fields and then has different tables. What is the best solution for this case? Thanks. </p>

```<code> $('#SearchTextBox').autocomplete({
                        source: 'api/user/search/'
                    });
</code>```

答:
My answer may be super late. But i hope this would help some one else. Basically i created this in mvc-5. You should modify it according to your needs.   </p>

```<code>$("#txtsearchpatient").autocomplete({
        source: function (request, response) {
            $.ajax({
                url: '@Url.Action("SearchPatient")',
                dataType: "json",
                data: { search: $("#txtsearchpatient").val() },
                success: function (data) {
                    if (data.length > 0) {
                        response($.map(data, function (item) {
                            return {
                                id: item.Id,
                                value: item.Name
                            };
                        }));
                    }
                    else {
                        $("#emptysearchdiv").hide();
                        var result = [
                            {
                                id:0,
                                label: 'No matches found',
                                value: ""
                            }
                        ];
                        response(result);
                    }
                },
                error: function (xhr, status, error) {
                }
            });
        },
        autoFocus: true,
        select: function (event, ui) {
    $(this).val(ui.item.value);

    var value = ui.item.value;
    var id = ui.item.id;
        },
        search: function (e, u) {
            $(this).addClass('loader');
        },
        response: function (e, u) {
            $(this).removeClass('loader');
        }
    });

public JsonResult SearchPatient(string search)
    {
        Regex RE_Numbers = new Regex(@"^\d+$");
        if(RE_Numbers.IsMatch(search) == true)
        {
            var sdsds = db.Patient.Where(x =>
 x.PhoneNumber.Contains(search)).Select(x => new {
                Id = x.Id,
                Name = "Name: " + x.Name + " | " + "EmailId: " + x.EmailId + " | " +
 "Phone: " + x.PhoneNumber + " | " + "Age: " + x.Age
            }).ToList();
            return Json(sdsds, JsonRequestBehavior.AllowGet);
        }
        else if(search.Contains("@") == true || search.Contains(".com") == true)
        {
            var sdsds = db.Patient.Where(x => x.EmailId.Contains(search)).Select(x =>
new {
                Id = x.Id,
                Name = "Name: " + x.Name + " | " + "EmailId: " + x.EmailId + " | " +
"Phone: " + x.PhoneNumber + " | " + "Age: " + x.Age
            }).ToList();
            return Json(sdsds, JsonRequestBehavior.AllowGet);
        }
        else
        {
            var sdsds = db.Patient.Where(x => x.Name.Contains(search)).Select(x =>
new {
                Id = x.Id,
                Name = "Name: " + x.Name + " | " + "EmailId: " + x.EmailId + " | " +
"Phone: " + x.PhoneNumber + " | " + "Age: " + x.Age
            }).ToList();
            return Json(sdsds, JsonRequestBehavior.AllowGet);
        }
    }
</code>```

Title: jquery autocomplete complex html Result

Body:
I need an autocomplete text box for my search and I will use jQuery UI for this. I'm using an ASP.NET Core API to get search result in json format. My search result should be grouping with bootstrap collapse panel and group members showing in a table. Every group has different fields and then has different tables. What is the best solution for this case? Thanks.

 $('#SearchTextBox').autocomplete({
                        source: 'api/user/search/'
                    });

Body:
My answer may be super late. But i hope this would help some one else. Basically i created this in mvc-5. You should modify it according to your needs.

$("#txtsearchpatient").autocomplete({
        source: function (request, response) {
            $.ajax({
                url: '@Url.Action("SearchPatient")',
                dataType: "json",
                data: { search: $("#txtsearchpatient").val() },
                success: function (data) {
                    if (data.length > 0) {
                        response($.map(data, function (item) {
                            return {
                                id: item.Id,
                                value: item.Name
                            };
                        }));
                    }
                    else {
                        $("#emptysearchdiv").hide();
                        var result = [
                            {
                                id:0,
                                label: 'No matches found',
                                value: ""
                            }
                        ];
                        response(result);
                    }
                },
                error: function (xhr, status, error) {
                }
            });
        },
        autoFocus: true,
        select: function (event, ui) {
    $(this).val(ui.item.value);

    var value = ui.item.value;
    var id = ui.item.id;
        },
        search: function (e, u) {
            $(this).addClass('loader');
        },
        response: function (e, u) {
            $(this).removeClass('loader');
        }
    });

public JsonResult SearchPatient(string search)
    {
        Regex RE_Numbers = new Regex(@"^\d+$");
        if(RE_Numbers.IsMatch(search) == true)
        {
            var sdsds = db.Patient.Where(x =>
 x.PhoneNumber.Contains(search)).Select(x => new {
                Id = x.Id,
                Name = "Name: " + x.Name + " | " + "EmailId: " + x.EmailId + " | " +
 "Phone: " + x.PhoneNumber + " | " + "Age: " + x.Age
            }).ToList();
            return Json(sdsds, JsonRequestBehavior.AllowGet);
        }
        else if(search.Contains("@") == true || search.Contains(".com") == true)
        {
            var sdsds = db.Patient.Where(x => x.EmailId.Contains(search)).Select(x =>
new {
                Id = x.Id,
                Name = "Name: " + x.Name + " | " + "EmailId: " + x.EmailId + " | " +
"Phone: " + x.PhoneNumber + " | " + "Age: " + x.Age
            }).ToList();
            return Json(sdsds, JsonRequestBehavior.AllowGet);
        }
        else
        {
            var sdsds = db.Patient.Where(x => x.Name.Contains(search)).Select(x =>
new {
                Id = x.Id,
                Name = "Name: " + x.Name + " | " + "EmailId: " + x.EmailId + " | " +
"Phone: " + x.PhoneNumber + " | " + "Age: " + x.Age
            }).ToList();
            return Json(sdsds, JsonRequestBehavior.AllowGet);
        }
    }


问:
Any way to put an if statement in the function call argument?
I found out that we can use the ternary op inside the function call argument:

def foo(n):
    print(n)
```

<pre class="lang-py prettyprint-override"><code>a, b = 1, 2
foo(a if a>b else b)
# prints 2
</code>```

I wonder is there a way to use if without the else in the function call argument? so something like if it's true, pass a to it, if not, don't pass anything.

I've tried

foo(a if a>b else pass)
foo(a if a>b)
foo(if a>b: a)
foo(a>b and a)
```

<p>None of the above works.</p>

<p>Thanks for your help.</p>

<p>Edit-----</p>

<p>Sorry, let me rephrase my question.</p>

<p>What I'm asking for is a way to determine whether I should pass the argument based on a condition.</p>

<p>So basically I have to call a big function that takes a lot of kwargs, say:</p>

<pre class="lang-py prettyprint-override"><code># function call
thefunc(
    a=1,
    b=2,
    c=3,
    d=4,
    e=5
    #...
)
</code>```

And all of the args are options which its up to me, or in some cases, a condition.

Since the argument list is so big that writing function calls inside the if statement is not preferred, so I need to know is there a way to, say:

thefunc(
    a=1,
    #if condition: b=2,
    c=3,
    ....
)
```

So to determine whether to give the kwarg or not. Its okay if there isn't, just need to know, thanks.

答:
Ternary operator needs both if- and else- substatements. Instead of trying to use only-if, you can use default function arguments:

```<code>def foo(n=None):
</code>```

Pass None to the function, if needed:

foo(a if a > b else None)

And check inside for the None - non-None argument:

```<code>def foo(n=None):
    if n:
        print(n)
</code>```

Body:
I found out that we can use the ternary op inside the function call argument:

def foo(n):
    print(n)

a, b = 1, 2
foo(a if a>b else b)
# prints 2

I wonder is there a way to use if without the else in the function call argument? so something like if it's true, pass a to it, if not, don't pass anything.

I've tried

foo(a if a>b else pass)
foo(a if a>b)
foo(if a>b: a)
foo(a>b and a)

None of the above works.

Thanks for your help.

Edit-----

Sorry, let me rephrase my question.

What I'm asking for is a way to determine whether I should pass the argument based on a condition.

So basically I have to call a big function that takes a lot of kwargs, say:

# function call
thefunc(
    a=1,
    b=2,
    c=3,
    d=4,
    e=5
    #...
)

And all of the args are options which its up to me, or in some cases, a condition.

Since the argument list is so big that writing function calls inside the if statement is not preferred, so I need to know is there a way to, say:

thefunc(
    a=1,
    #if condition: b=2,
    c=3,
    ....
)

So to determine whether to give the kwarg or not. Its okay if there isn't, just need to know, thanks.

Body:
Ternary operator needs both if- and else- substatements. Instead of trying to use only-if, you can use default function arguments:

def foo(n=None):

Pass None to the function, if needed:

foo(a if a > b else None)

And check inside for the None - non-None argument:

def foo(n=None):
    if n:
        print(n)


问:
Get array value using Angular Dropdown
I am trying to use Angular Dropdown. The JSON is as follows-

```<code>{
       {
      "bookId":"1",
      "authors":{ "author1", "author2"}
       }
       {
      "bookId":"2",
      "authors":{ "author2", "author3"}
       }
}
</code>```

Have created a class named Book which stores the above values in Book Array named books.

In html code have the following -

```<code> <select [(ngModel)]="book.id" (ngModelChange)='onBookSelected($event)'>
            <option *ngFor="let book of books"
            [value] = "book.authors">{{book.id}}</option>
          </select>
</code>```

In the component have the onBookSelected as follows-

```<code>onBookSelected(val: any)
{
  console.log(val);
}
</code>```

I dont get the list of authors but get

```<code>[object Object],[object Object],[object Object]
</code>```

I also tried creating an array of class author and using it as follows-

```<code>onBookSelected(authorList : any)
{
  console.log(authorList );
}
</code>```

But get same output as

```<code>   [object Object],[object Object],[object Object]
</code>```

Could someone please help to get list of authors when the book is selected from the dropdown. Thanks

答:
you need do some changes in order get the authors

```<code><select [(ngModel)]="selectedBookId" (ngModelChange)='onBookSelected($event)'>
            <option *ngFor="let book of books"
            [value] = "book.id">{{book.id}}</option>
</select>
</code>```

and then in the onBookSelected($event)

component.ts

```<code>     let books=   {
           {
          "bookId":"1",
          "authors":{ "author1", "author2"}
           }
           {
          "bookId":"2",
          "authors":{ "author2", "author3"}
           }
     }

    onBookSelected(event){
       Object.values(this.books).forEach(book =>{
             if(book.bookId == this.selectedBookId){
                 console.log(Object.values(book.authors))
             }
       })
    }
</code>```

Title: Get array value using Angular Dropdown

Body:
I am trying to use Angular Dropdown. The JSON is as follows-

{
       {
      "bookId":"1",
      "authors":{ "author1", "author2"}
       }
       {
      "bookId":"2",
      "authors":{ "author2", "author3"}
       }
}

Have created a class named Book which stores the above values in Book Array named books.

In html code have the following -

 <select [(ngModel)]="book.id" (ngModelChange)='onBookSelected($event)'>
            <option *ngFor="let book of books"
            [value] = "book.authors">{{book.id}}</option>
          </select>

In the component have the onBookSelected as follows-

onBookSelected(val: any)
{
  console.log(val);
}

I dont get the list of authors but get

[object Object],[object Object],[object Object]

I also tried creating an array of class author and using it as follows-

onBookSelected(authorList : any)
{
  console.log(authorList );
}

But get same output as

   [object Object],[object Object],[object Object]

Could someone please help to get list of authors when the book is selected from the dropdown. Thanks

Body:
you need do some changes in order get the authors

<select [(ngModel)]="selectedBookId" (ngModelChange)='onBookSelected($event)'>
            <option *ngFor="let book of books"
            [value] = "book.id">{{book.id}}</option>
</select>

and then in the onBookSelected($event)

component.ts

     let books=   {
           {
          "bookId":"1",
          "authors":{ "author1", "author2"}
           }
           {
          "bookId":"2",
          "authors":{ "author2", "author3"}
           }
     }

    onBookSelected(event){
       Object.values(this.books).forEach(book =>{
             if(book.bookId == this.selectedBookId){
                 console.log(Object.values(book.authors))
             }
       })
    }


问:
RabbitMQ multiple consumers across multiple queues - messages delayed from being processed
We have recently experienced unexpected behaviour with our application that is powered by RabbitMQ.
RabbitMQ version is 3.6.12 and we are using .NET Client 5.0.1

The application subscribes to two queues, one for commands, and another for events - we also use manual acknowledgements.
Our application is configured to have 7 consumers. Each has its own channel(IModel) and each has its own EventingBasicConsumer
We end up processing messages when EventingBasicConsumer.Received is fired.

Our application must process messages as close as possible to when they are routed onto the queues and to date we have not had issues.
However recently, we have seen that when one of our messages being processed takes a long time to complete, it delays when another message is to be processed although there are many consumers available (6) that are not busy.

Note we have observed that this issue does not happen when an application is only subscribing to a single queue, it becomes an issue when there is multiple queues involved.

This is best illustrated using the following example:

We have a simple consuming application that subscribes to two queues,
one for commands and one for events. This application have 7
consumers, each with their own channel and EventingBasicConsumer We
start a simple publishing application, that publishes 20 messages, a
second apart. Every message is an event so is published to the event
queue except for the 5th and 10th messages, which are commands and
sent to the command queue. Note that every event is processed without
delay whereas commands take 30 seconds

The following table describes what we are observing in relation to assigning multiple channels to messages across multiple queues:

Once Message5 completes after 30 seconds with C1, then Messaqe9 is assigned immediately to C1 and is processed without delay
Once Message10 completes after 30 seconds with C2, then Messaqe11 is assigned immediately to C2 and is processed without delay

Hence, to us it looks like the assignment of channels is done independently per queue - meaning you can have delayed execution if some messages take a long time to process.

Is it possible that when multiple consumers are subscribing to multiple queues, RabbitMQ can assign a message to be handled by a consumer that is busy even if there are consumers that are currently idle?

Is there any documentation that explains the RabbitMQ algorithm that selects which consumers EventingBasicConsumer.received fires from a collection of consumers?

答:
We have fixed this issue.

In the RMQ documentation (https://www.rabbitmq.com/api-guide.html#consuming) we came across the following:
"Each Channel has its own dispatch thread. For the most common use case of one Consumer per Channel, this means Consumers do not hold up other Consumers. If you have multiple Consumers per Channel be aware that a long-running Consumer may hold up dispatch of callbacks to other Consumers on that Channel.”

In our code, we had 2 consumers per channel, meaning consumers could hold up other consumers.
We changed to have one consumer per channel and that fixed the issue.


问:
Can you access Vue component lifecycle hooks externally?
I am using a component library within my web app and I'd like to attach functionality to one of the provided components.

So let's say I have a .vue file

```<code><template>
   <div>
      ... some stuff
      <LibraryComponent />
   </div>
</template>

<script>
import LibraryComponent from 'library'

export default {
   components: {
      LibraryComponent
   }
}
</script>
</code>```

I would love to be able to reach into the LibraryComponent and attach a method to the mounted hook from the parent. I figure I can update the code of the component itself in node_modules but that seems like a bad solution if the package gets updated.

答:
Vue’s lifecycle hooks emit their own custom events.

Take a look at this article:

Vue.js Component Hooks as Events

Body:
I am using a component library within my web app and I'd like to attach functionality to one of the provided components.

So let's say I have a .vue file

<template>

      ... some stuff
      <LibraryComponent />

</template>

I would love to be able to reach into the LibraryComponent and attach a method to the mounted hook from the parent. I figure I can update the code of the component itself in node_modules but that seems like a bad solution if the package gets updated.


问:
Hidden features of Eclipse
Alright it can be a lame question, but everybody uses these things differently.  What's some of the best time savers out there for this IDE.

Tom

答: Don't forget Ctrl+Shift+L, which displays a list of all the keyboard shortcut combinations (just in case you forget any of those listed here).

OwnerDisplayName: DIA Tom

ContentLicense: CC BY-SA 2.5

Title: Hidden features of Eclipse

LastEditorDisplayName: unwind

OwnerDisplayName: Ben


问:
Writing a abstract function turns integer into string

Possible Duplicate:

  Easiest way to convert int to string in C++

```<code>class MyInteger
{
   MyInteger() : m_val(0) { }
   MyInteger()( int _val ) : m_val( _val ) {}
  ~MyInteger() {}
};

MyInteger myInteger(10);
std::string s = (std::string)myInteger
</code>```

How can I write C++ function to get "10" in s??
I am new to C++.

Thanks you very much.

答:
In addition to the above methods you can overload the casting operator like this:

```<code>class MyInteger
{
  ...
  operator std::string() { /* string conversion method here */ }
};
</code>```

as stated in the following link
Overload typecasts

Body:
Possible Duplicate:

  Easiest way to convert int to string in C++

class MyInteger
{
   MyInteger() : m_val(0) { }
   MyInteger()( int _val ) : m_val( _val ) {}
  ~MyInteger() {}
};

MyInteger myInteger(10);
std::string s = (std::string)myInteger

How can I write C++ function to get "10" in s??
I am new to C++.

Thanks you very much.

Body:
In addition to the above methods you can overload the casting operator like this:

class MyInteger
{
  ...
  operator std::string() { /* string conversion method here */ }
};

as stated in the following link
Overload typecasts