问:
When should one use RxJava Observable and when simple Callback on Android?
I'm working on networking for my app. So I decided to try out Square's Retrofit. I see that they support simple Callback

```<code>@GET("/user/{id}/photo")
void getUserPhoto(@Path("id") int id, Callback<Photo> cb);
</code>```

and RxJava's Observable

```<code>@GET("/user/{id}/photo")
Observable<Photo> getUserPhoto(@Path("id") int id);
</code>```

Both look pretty similar at first glance, but when it gets to implementation it gets interesting...

While with simple callback implementation would look similar to this:

```<code>api.getUserPhoto(photoId, new Callback<Photo>() {
    @Override
    public void onSuccess() {
    }
});
</code>```

which is quite simple and straightforward. And with Observable it quickly gets verbose and quite complicated.

```<code>public Observable<Photo> getUserPhoto(final int photoId) {
    return Observable.create(new Observable.OnSubscribeFunc<Photo>() {
        @Override
        public Subscription onSubscribe(Observer<? super Photo> observer) {
            try {
                observer.onNext(api.getUserPhoto(photoId));
                observer.onCompleted();
            } catch (Exception e) {
                observer.onError(e);
            }

            return Subscriptions.empty();
        }
    }).subscribeOn(Schedulers.threadPoolForIO());
}
</code>```

And that is not it. You still have to do something like this:

```<code>Observable.from(photoIdArray)
        .mapMany(new Func1<String, Observable<Photo>>() {
            @Override
            public Observable<Photo> call(Integer s) {
                return getUserPhoto(s);
            }
        })
        .subscribeOn(Schedulers.threadPoolForIO())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Action1<Photo>() {
            @Override
            public void call(Photo photo) {
                //save photo?
            }
        });
</code>```

Am I missing something here? Or is this a wrong case to use Observables?
When would/should one prefer Observable over simple Callback?

Update

Using retrofit is much simpler than example above as @Niels showed in his answer or in Jake Wharton's example project U2020. But essentially the question stays the same - when should one use one way or the other?

答: I personally prefer to use Rx to get api responses in cases that I have to do filter, map or something like that on the data Or in cases that I have to do another api calls based on previous calls responses</p>

Body:
I'm working on networking for my app. So I decided to try out Square's Retrofit. I see that they support simple Callback

@GET("/user/{id}/photo")
void getUserPhoto(@Path("id") int id, Callback<Photo> cb);

and RxJava's Observable

@GET("/user/{id}/photo")
Observable<Photo> getUserPhoto(@Path("id") int id);

Both look pretty similar at first glance, but when it gets to implementation it gets interesting...

While with simple callback implementation would look similar to this:

api.getUserPhoto(photoId, new Callback<Photo>() {
    @Override
    public void onSuccess() {
    }
});

which is quite simple and straightforward. And with Observable it quickly gets verbose and quite complicated.

public Observable<Photo> getUserPhoto(final int photoId) {
    return Observable.create(new Observable.OnSubscribeFunc<Photo>() {
        @Override
        public Subscription onSubscribe(Observer<? super Photo> observer) {
            try {
                observer.onNext(api.getUserPhoto(photoId));
                observer.onCompleted();
            } catch (Exception e) {
                observer.onError(e);
            }

            return Subscriptions.empty();
        }
    }).subscribeOn(Schedulers.threadPoolForIO());
}

And that is not it. You still have to do something like this:

Observable.from(photoIdArray)
        .mapMany(new Func1<String, Observable<Photo>>() {
            @Override
            public Observable<Photo> call(Integer s) {
                return getUserPhoto(s);
            }
        })
        .subscribeOn(Schedulers.threadPoolForIO())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Action1<Photo>() {
            @Override
            public void call(Photo photo) {
                //save photo?
            }
        });

Am I missing something here? Or is this a wrong case to use Observables?
When would/should one prefer Observable over simple Callback?

Update

Using retrofit is much simpler than example above as @Niels showed in his answer or in Jake Wharton's example project U2020. But essentially the question stays the same - when should one use one way or the other?


来源: stackexchange

问:
chain promise in sequential way
i know that this problem has been studied a thousand times, but i tried plenty of solutions, it still not works.

I want to chain promises from http get, but i need to wait for the previous before running the next one, because the get method returns me a number which is pushed in an array, and it needs to be ordered correctly.

What i have tried : put every promise in an array and then use reduce method, but it didn't work.
I think the tricky thing is that i have condition of one of the params of my get whose value changes.
these values are in an array so i tried to perform a forEach with an await but it didn't work.

So here is my current code :

```<code>async getAEObservable(checkIn: Date, checkOut: Date, adults: number, HotelID) {
    var In = checkIn;
    var Out =checkOut;

    var  promises=[];

    var id = []
    HotelID.forEach(element =>
      id.push(element))

    var index=0
    var ind = HotelID[0]
    if (HotelID.length !== 0) {
    if (ind !== "NULLNULL") {
      console.log('ok')
      const httpOptions = {
        headers: new HttpHeaders({
          'Content-Type': 'application/json',
          'Ama-Pos': '{"agentSine": "A9998WS","agentUserID": "AA","agentDutyCode": "GS","agencyDetails":{"currencyCode": "EUR","identifiers": [{"type": "IATA","id": "QIJI12151"}],"address":{"cityCode": "NCE","countryCode": "FR"}}}'
        })
      };

        let checkIn_param = this.transformDate(checkIn);
        let checkOut_param = this.transformDate(checkOut);
        let apiUrl = `${this.apiRoot_v0}?hotelIds=${ind.toString()}&checkInDate=${checkIn_param}&checkOutDate=${checkOut_param}&roomQuantity=1&adults=2&radius=5&radiusUnit=KM&rateCodes=RAC&paymentPolicy=NONE&includeClosed=true&bestRateOnly=true&view=FULL&sort=NONE`
        let url = `${apiUrl}`;
        console.log(url)
        return await this.apiCall(url, httpOptions, checkIn, checkOut, adults, HotelID); // here we are calling a function which contain a api call inside this function we are resolving the promise
      } else {

        // here we are not creating a promise bcs here we have simple push operation

        this.resAE.price.push(0)
        this.getAEObservable(checkIn, checkOut, adults, HotelID.slice(1));
        return this.resAE
      }
    }
    else {return this.resAE}
      }

async apiCall(url, httpOptions,checkIn, checkOut, adults, HotelID) {
   await new Promise(async (resolve, reject) => {
    await this.httpClient.get<any>(url, httpOptions).toPromise().then(result => {
      console.log(result)
      var price = result['data']['0']['offers']['0']['price']['total'];

      console.log(price)

      this.resAE.price.push(price);
      console.log(this.resAE)

  return this.resAE
    }).then(async resp => { if (HotelID.length !=0){
       this.getAEObservable(checkIn, checkOut, adults, HotelID.slice(1));}
      else{
      resolve();}
    }).catch(this.handleError)

  })

}

async apiCall(url, httpOptions,checkIn, checkOut, adults, HotelID) {
  return await new Promise(async (resolve, reject) => {
    this.httpClient.get<any>(url, httpOptions).toPromise().then(result => {
      console.log(result)
      var price = result['data']['0']['offers']['0']['price']['total'];

      console.log(price)

      this.resAE.price.push(price);
      console.log(this.resAE)

      return this.resAE;
    }).then(resp => { if (HotelID.length ===0){

      return this.resAE

    } else {
      this.getAEObservable(checkIn, checkOut, adults, HotelID.slice(1));
      resolve()};
    }).catch(this.handleError)
  })
}
</code>```

The ides is to perform the first get, fill my array, and when is it finished, proceed to the next get call, by calling the function itself, but by removing the first element of HotelID, i used for the previous get.

The array is filled, so there is no problem other that is it not well  i think...

I just edit my question to say that the console.log(url) shows me that the url are created in the good order

答:
you can try like this.

```<code>async getAEObservable(checkIn: Date, checkOut: Date, adults: number, HotelID) {
 console.log(HotelID);
    var In = checkIn;
    var Out =checkOut;

    var  promises=[];

    var id = []
    HotelID.forEach(element =>
    id.push(element))
    console.log(id)
    var index=0
    var ind = HotelID[0]
      if (ind !== "NULLNULL") {
        console.log('ok')
        const httpOptions = {
          headers: new HttpHeaders({
            'Content-Type': 'application/json',
            'Ama-Pos': '{"agentSine": "A9998WS","agentUserID": "AA","agentDutyCode": "GS","agencyDetails":{"currencyCode": "EUR","identifiers": [{"type": "IATA","id": "QIJI12151"}],"address":{"cityCode": "NCE","countryCode": "FR"}}}'
          })
        };

        let checkIn_param = this.transformDate(checkIn);
        let checkOut_param = this.transformDate(checkOut);
        let apiUrl = `${this.apiRoot_v0}?hotelIds=${ind.toString()}&checkInDate=${checkIn_param}&checkOutDate=${checkOut_param}&roomQuantity=1&adults=2&radius=5&radiusUnit=KM&rateCodes=RAC&paymentPolicy=NONE&includeClosed=true&bestRateOnly=true&view=FULL&sort=NONE`
        let url = `${apiUrl}`;
        console.log(url)
        return await apiCall(url, httpOptions); // here we are calling a function which contain a api call inside this function we are resolving the promise
      } else {

        // here we are not creating a promise bcs here we have simple push operation

        this.resAE.price.push(0)
        this.getAEObservable(checkIn, checkOut, adults, HotelID.slice(1));
        return this.resAE
      }

</code>```

here is the api call function

```<code>apiCall(url, httpOptions) {
 return new Promise((resolve, reject) => {
this.httpClient.get<any>(url, httpOptions).toPromise().then(res => {
            console.log(res)
            var price = res.data[0].offers[0].price.total;
            console.log(price)
            this.resAE.price.push( price);
            console.log(this.resAE)
            console.log(id)
            console.log(id.slice(1))
            return this.resAE;
          }).then( resp => {
             this.getAEObservable(checkIn, checkOut, adults, HotelID.slice(1))
             resolve();
         }).catch(this.handleError)
})
}

</code>```

ContentLicense: CC BY-SA 4.0

Title: chain promise in sequential way

Body:
i know that this problem has been studied a thousand times, but i tried plenty of solutions, it still not works.

I want to chain promises from http get, but i need to wait for the previous before running the next one, because the get method returns me a number which is pushed in an array, and it needs to be ordered correctly.

What i have tried : put every promise in an array and then use reduce method, but it didn't work.
I think the tricky thing is that i have condition of one of the params of my get whose value changes.
these values are in an array so i tried to perform a forEach with an await but it didn't work.

So here is my current code :

async getAEObservable(checkIn: Date, checkOut: Date, adults: number, HotelID) {
    var In = checkIn;
    var Out =checkOut;

    var  promises=[];

    var id = []
    HotelID.forEach(element =>
      id.push(element))

    var index=0
    var ind = HotelID[0]
    if (HotelID.length !== 0) {
    if (ind !== "NULLNULL") {
      console.log('ok')
      const httpOptions = {
        headers: new HttpHeaders({
          'Content-Type': 'application/json',
          'Ama-Pos': '{"agentSine": "A9998WS","agentUserID": "AA","agentDutyCode": "GS","agencyDetails":{"currencyCode": "EUR","identifiers": [{"type": "IATA","id": "QIJI12151"}],"address":{"cityCode": "NCE","countryCode": "FR"}}}'
        })
      };

        let checkIn_param = this.transformDate(checkIn);
        let checkOut_param = this.transformDate(checkOut);
        let apiUrl = `${this.apiRoot_v0}?hotelIds=${ind.toString()}&checkInDate=${checkIn_param}&checkOutDate=${checkOut_param}&roomQuantity=1&adults=2&radius=5&radiusUnit=KM&rateCodes=RAC&paymentPolicy=NONE&includeClosed=true&bestRateOnly=true&view=FULL&sort=NONE`
        let url = `${apiUrl}`;
        console.log(url)
        return await this.apiCall(url, httpOptions, checkIn, checkOut, adults, HotelID); // here we are calling a function which contain a api call inside this function we are resolving the promise
      } else {

        // here we are not creating a promise bcs here we have simple push operation

        this.resAE.price.push(0)
        this.getAEObservable(checkIn, checkOut, adults, HotelID.slice(1));
        return this.resAE
      }
    }
    else {return this.resAE}
      }

async apiCall(url, httpOptions,checkIn, checkOut, adults, HotelID) {
   await new Promise(async (resolve, reject) => {
    await this.httpClient.get<any>(url, httpOptions).toPromise().then(result => {
      console.log(result)
      var price = result['data']['0']['offers']['0']['price']['total'];

      console.log(price)

      this.resAE.price.push(price);
      console.log(this.resAE)

  return this.resAE
    }).then(async resp => { if (HotelID.length !=0){
       this.getAEObservable(checkIn, checkOut, adults, HotelID.slice(1));}
      else{
      resolve();}
    }).catch(this.handleError)

  })

}

async apiCall(url, httpOptions,checkIn, checkOut, adults, HotelID) {
  return await new Promise(async (resolve, reject) => {
    this.httpClient.get<any>(url, httpOptions).toPromise().then(result => {
      console.log(result)
      var price = result['data']['0']['offers']['0']['price']['total'];

      console.log(price)

      this.resAE.price.push(price);
      console.log(this.resAE)

      return this.resAE;
    }).then(resp => { if (HotelID.length ===0){

      return this.resAE

    } else {
      this.getAEObservable(checkIn, checkOut, adults, HotelID.slice(1));
      resolve()};
    }).catch(this.handleError)
  })
}

The ides is to perform the first get, fill my array, and when is it finished, proceed to the next get call, by calling the function itself, but by removing the first element of HotelID, i used for the previous get.

The array is filled, so there is no problem other that is it not well  i think...

I just edit my question to say that the console.log(url) shows me that the url are created in the good order

Body:
you can try like this.

async getAEObservable(checkIn: Date, checkOut: Date, adults: number, HotelID) {
 console.log(HotelID);
    var In = checkIn;
    var Out =checkOut;

    var  promises=[];

    var id = []
    HotelID.forEach(element =>
    id.push(element))
    console.log(id)
    var index=0
    var ind = HotelID[0]
      if (ind !== "NULLNULL") {
        console.log('ok')
        const httpOptions = {
          headers: new HttpHeaders({
            'Content-Type': 'application/json',
            'Ama-Pos': '{"agentSine": "A9998WS","agentUserID": "AA","agentDutyCode": "GS","agencyDetails":{"currencyCode": "EUR","identifiers": [{"type": "IATA","id": "QIJI12151"}],"address":{"cityCode": "NCE","countryCode": "FR"}}}'
          })
        };

        let checkIn_param = this.transformDate(checkIn);
        let checkOut_param = this.transformDate(checkOut);
        let apiUrl = `${this.apiRoot_v0}?hotelIds=${ind.toString()}&checkInDate=${checkIn_param}&checkOutDate=${checkOut_param}&roomQuantity=1&adults=2&radius=5&radiusUnit=KM&rateCodes=RAC&paymentPolicy=NONE&includeClosed=true&bestRateOnly=true&view=FULL&sort=NONE`
        let url = `${apiUrl}`;
        console.log(url)
        return await apiCall(url, httpOptions); // here we are calling a function which contain a api call inside this function we are resolving the promise
      } else {

        // here we are not creating a promise bcs here we have simple push operation

        this.resAE.price.push(0)
        this.getAEObservable(checkIn, checkOut, adults, HotelID.slice(1));
        return this.resAE
      }

here is the api call function

apiCall(url, httpOptions) {
 return new Promise((resolve, reject) => {
this.httpClient.get<any>(url, httpOptions).toPromise().then(res => {
            console.log(res)
            var price = res.data[0].offers[0].price.total;
            console.log(price)
            this.resAE.price.push( price);
            console.log(this.resAE)
            console.log(id)
            console.log(id.slice(1))
            return this.resAE;
          }).then( resp => {
             this.getAEObservable(checkIn, checkOut, adults, HotelID.slice(1))
             resolve();
         }).catch(this.handleError)
})
}


问:
PHP Open Source eCommerce Software
I hope you are good today, my query is a simple one i am searching for an open source ecommerce solution that can be extended with my own modules etc.

after scouring google there are loads of open source solutions and different websites recommend different solutions.

I trust the community of stack far more than random websites on google, so can you please make recommendations on systems you have previously used and how you found them on an overall.

Thanks in advance.

答:
For a big application, you could take a look at Magento : it's a robust solution, with both a community and an entreprise version.

Another idea (that might be lighter) might be PrestaShop.

Some might suggest you osCommerce, but it's an old software -- and even if it had much success some years ago, it doesn't really anymore now (I've never used it myself, but some colleagues of mine have worked with it -- and have since switched to Magento).

ContentLicense: CC BY-SA 3.0

Title: PHP Open Source eCommerce Software


问:
Pentaho spoon:insert/update does DROP COLUMN?
I am doing insert/update step (text file to DB) on spoon and I have a question.
Suppose that in my text file I have 10 columns and in my DB I have 18, because 8 columns will be completed from another text file later.

On insert/update step, I chose a key to look up the value (which is client_id, for example) and on "Update fields", I did mappings for those 10 columns. When I checked SQL query, I saw those 8 columns will be dropped.
But I want to keep them. Any solution for it?

答:
The Insert/Update step will NOT drop columns when run normally.

The SQL button inspects the table and suggests changes based on the fields you specified in the step. It's only a convenience for quick ETL development, for example when sending rows from text files to staging table using a Table Output step. It only drops columns if you execute the script it generates. Don't do that and your columns will be perfectly safe!


问:
How to model in UML Use Case Diagram a different external system based on the role of the primary actor?
I am modeling a software that requires to be interfaced with an optical tracking sensor, to measure the pose of some objects through optical markers.
A general user interacts with this sensor (say External System 1) in two different use cases (say UC1 and UC2).
I would like to model also the possibility that an admin user interacts with the software through the same use cases UC1 and UC2, but he can be interfaced with a software simulator (say External System 2) that simulates the real optical sensor.

I'm trying to model this scenario in a Use-Case diagram, but I am uncertain about the proper modeling of the presence of the simulator and the admin role.
I wouldn't create a second pair of Use Case, because they are supposed to be exactly the same adopted by the general user.
With reference to the Figure, I thought to add some dependency arrows (dashed) from the UCs to the External System 2 also, but this way would sound as also the general user could interact with the simulator, while this should not be allowed.

I apologize if this question could appear to be quite trivial, but these are my first experiences with software UML modeling.
Thank you in advance for your help.

答:
Start with looking at your basic system like this

So basically your system is measuring something using a sensor. This Sensor can be either a real sensor or a simulator. User must not really care (though he knows what is attached). But the Measuring System will really not (!) care. So the simulator must simulate whatever is needed so the system will think it's a normal sensor.

Now that simulator is another system:

From the perspective of that system you look at Measuring System as external actor. Plus it offers an admin the possibility to set parameters for the test cycle.


问:
Next js doesn't update URL
I have the following component:

```<code>import React, {Component} from "react";
import fetch from 'isomorphic-unfetch';
import {Router} from '../routes';

class About extends Component {
  state = {
    results: null,
    postcode: null
  }

  handleOnChange = e => {
    this.setState({
      postcode: e.target.value
    });
  }

  handleOnSubmit = e => {
    e.preventDefault();
      // calling the api passing the postcode
      console.log(this.state.postcode)
    fetch(`http://localhost:3001/${this.state.postcode}`)
      .then(response => response.json())
      .then(data => {
          this.setState({
            results: data
          })
      })
      .catch(error => console.error(error))

      Router.pushRoute('/about', {postcode: this.state.postcode})
  }

  render() {
    console.log(this.state.results)
   return(
    <form>
      <input name="postcode" onChange={this.handleOnChange} />
      <button onClick={this.handleOnSubmit}>submit postcode</button>
    </form>
   )
  }
}

About.getInitialProps = async function(context) {
  console.log('context: ', context.query)
  return {
    results: 'data'
  }
}

export default About;
</code>```

and my routes file like so:

```<code>const routes = module.exports = require('next-routes')()

routes
.add('index')
.add('about', '/about/:postcode', 'about');
</code>```

however when I submit the form I would expect the URL to be updated with the submitted value like so:

```<code>http://localhost:3000/about/ => http://localhost:3000/about/postcodeValueSubmitted
</code>```

It doesn't throw any error but the URL remains:

```<code>http://localhost:3000/about
</code>```

I would need the value to be updated so that I can use 'getInitialProps' to do the server side rendering.

答:
Replace:

```<code>Router.pushRoute('/about', {postcode: this.state.postcode})
</code>```

With:

```<code>Router.pushRoute(`/about/${this.state.postCode}`)
</code>```

Title: Next js doesn't update URL

Body:
I have the following component:

import React, {Component} from "react";
import fetch from 'isomorphic-unfetch';
import {Router} from '../routes';

class About extends Component {
  state = {
    results: null,
    postcode: null
  }

  handleOnChange = e => {
    this.setState({
      postcode: e.target.value
    });
  }

  handleOnSubmit = e => {
    e.preventDefault();
      // calling the api passing the postcode
      console.log(this.state.postcode)
    fetch(`http://localhost:3001/${this.state.postcode}`)
      .then(response => response.json())
      .then(data => {
          this.setState({
            results: data
          })
      })
      .catch(error => console.error(error))

      Router.pushRoute('/about', {postcode: this.state.postcode})
  }

  render() {
    console.log(this.state.results)
   return(
    <form>
      <input name="postcode" onChange={this.handleOnChange} />
      <button onClick={this.handleOnSubmit}>submit postcode</button>
    </form>
   )
  }
}

About.getInitialProps = async function(context) {
  console.log('context: ', context.query)
  return {
    results: 'data'
  }
}

export default About;

and my routes file like so:

const routes = module.exports = require('next-routes')()

routes
.add('index')
.add('about', '/about/:postcode', 'about');

however when I submit the form I would expect the URL to be updated with the submitted value like so:

http://localhost:3000/about/ => http://localhost:3000/about/postcodeValueSubmitted

It doesn't throw any error but the URL remains:

http://localhost:3000/about

I would need the value to be updated so that I can use 'getInitialProps' to do the server side rendering.

Body:
Replace:

Router.pushRoute('/about', {postcode: this.state.postcode})

With:

Router.pushRoute(`/about/${this.state.postCode}`)


问:
SQL+Fetch rows with latest date+Case when row_number()+Duplicates
I have a table with fields(id, date, product) with below sample data

```<code>id  date    Product current_Flag    Expected_flag
14834   2019-01-03 00:00:00 A   1   1
14834   2019-01-31 00:00:00 B   0   0
14834   2019-02-28 00:00:00 C   0   0
14834   2019-03-30 00:00:00 C   0   0
14834   2019-01-03 00:00:00 D   0   1
</code>```

I'm trying the case when row_number() over (partition by id order by date) = 1 then 1 else 0 end as flag,
But for a particular distinct Id with min date, it is getting flag as 1, but I need to flag as for a particular Id & min date and product as 1 flag as shown in Expected_flag

```<code>case when row_number() over (partition by id order by date) = 1 then 1 else 0 end as flag
</code>```

答:
You need dense_rank() instead :

```<code>case when dense_rank() over (partition by id order by date) = 1 then 1 else 0 end as Expected_flag
</code>```

Body:
I have a table with fields(id, date, product) with below sample data

id  date    Product current_Flag    Expected_flag
14834   2019-01-03 00:00:00 A   1   1
14834   2019-01-31 00:00:00 B   0   0
14834   2019-02-28 00:00:00 C   0   0
14834   2019-03-30 00:00:00 C   0   0
14834   2019-01-03 00:00:00 D   0   1

I'm trying the case when row_number() over (partition by id order by date) = 1 then 1 else 0 end as flag,
But for a particular distinct Id with min date, it is getting flag as 1, but I need to flag as for a particular Id & min date and product as 1 flag as shown in Expected_flag

case when row_number() over (partition by id order by date) = 1 then 1 else 0 end as flag

Body:
You need dense_rank() instead :

case when dense_rank() over (partition by id order by date) = 1 then 1 else 0 end as Expected_flag


问:
How to disable redirections in ktor-client
I am creating simple HTTP request with ktor-client (ApacheHttpClient engine)

```<code>val client = HttpClient(Apache) {
    engine {
        followRedirects = false
        this@HttpClient.expectSuccess = false
    }
}
</code>```

and using it to submit a form

```<code>client.submitForm<HttpResponse>(
        url = "https://foo.com/login",
        formParameters = Parameters.build {
            append("_username", username)
            append("_password", password)
        })
</code>```

In logs, I can see a correct response with 302-redirection which I want to get and obtain a cookie from it. But instead, I see that the client moves on and makes several more requests and finally fails with:

io.ktor.client.features.SendCountExceedException: Max send count 20 exceeded

How can I completely disable 302-based redirections in ktor-client?

答:
ktor-client follows redirects by default, to prevent infinite redirects use:</p>

```<code>val client = HttpClient(HttpClientEngine) {
    followRedirects = false
}
</code>```

Body:
I am creating simple HTTP request with ktor-client (ApacheHttpClient engine)

val client = HttpClient(Apache) {
    engine {
        followRedirects = false
        this@HttpClient.expectSuccess = false
    }
}

and using it to submit a form

client.submitForm<HttpResponse>(
        url = "https://foo.com/login",
        formParameters = Parameters.build {
            append("_username", username)
            append("_password", password)
        })

In logs, I can see a correct response with 302-redirection which I want to get and obtain a cookie from it. But instead, I see that the client moves on and makes several more requests and finally fails with:

io.ktor.client.features.SendCountExceedException: Max send count 20 exceeded

How can I completely disable 302-based redirections in ktor-client?

Body:
ktor-client follows redirects by default, to prevent infinite redirects use:

val client = HttpClient(HttpClientEngine) {
    followRedirects = false
}


问:
How to Insert New Rows (with a condition) in Excel using Python / Pandas
I am trying to insert new rows into an excel using pandas data-frame when a particular columns has a specific condition

For ex:

```<code>Input

    A   B   C   D   E
0   AA  111 2   2
1   CC  222 8   12
2   DD  333 3   3

Output
    A   B   C   D   E (Output Column)
0   AA  111 2   2   111-2
1   CC  222 8   8   222-8
2   CC  222 9   9   222-9
3   CC  222 10  10  222-10
4   CC  222 11  11  222-11
5   CC  222 12  12  222-12
6   DD  333 3   3   333-3
</code>```

If you see here the Column C and D has a range of 8-12 for Row # 1. So I need to split the row accordingly. If C and D are same, no appending of new rows.

答:
Another solution, using Index.repeat to create the output frame, then groupby.cumcount and str concatenation to update the values of columns C, D and E:

```<code>df1 = df.loc[df.index.repeat((df.D - df.C).add(1))]
df1['C'] = df1['C'] + df1.groupby('A').cumcount()
df1['D'] = df1['C']
df1['E'] = df['B'].astype(str) + '-' + df1['C'].astype(str)
</code>```

[out]

```<code>    A    B   C   D       E
0  AA  111   2   2   111-2
1  CC  222   8   8   222-8
1  CC  222   9   9   222-9
1  CC  222  10  10  222-10
1  CC  222  11  11  222-11
1  CC  222  12  12  222-12
2  DD  333   3   3   333-3
</code>```

Body:
I am trying to insert new rows into an excel using pandas data-frame when a particular columns has a specific condition

For ex:

Input

    A   B   C   D   E
0   AA  111 2   2
1   CC  222 8   12
2   DD  333 3   3

Output
    A   B   C   D   E (Output Column)
0   AA  111 2   2   111-2
1   CC  222 8   8   222-8
2   CC  222 9   9   222-9
3   CC  222 10  10  222-10
4   CC  222 11  11  222-11
5   CC  222 12  12  222-12
6   DD  333 3   3   333-3

If you see here the Column C and D has a range of 8-12 for Row # 1. So I need to split the row accordingly. If C and D are same, no appending of new rows.

Body:
Another solution, using Index.repeat to create the output frame, then groupby.cumcount and str concatenation to update the values of columns C, D and E:

df1 = df.loc[df.index.repeat((df.D - df.C).add(1))]
df1['C'] = df1['C'] + df1.groupby('A').cumcount()
df1['D'] = df1['C']
df1['E'] = df['B'].astype(str) + '-' + df1['C'].astype(str)

[out]

    A    B   C   D       E
0  AA  111   2   2   111-2
1  CC  222   8   8   222-8
1  CC  222   9   9   222-9
1  CC  222  10  10  222-10
1  CC  222  11  11  222-11
1  CC  222  12  12  222-12
2  DD  333   3   3   333-3


问:
Highcharts problem of dynamic data processing
I am using the API highcharts to display the number of visitors to my site by country. I receive the data via mysql and I have this table in php:

```<code><?php $data = Array ( [0] => Array ( [name] => DE [y] => 1 ) [1] => Array ( [name] => FR [y] => 3 ) [2] => Array ( [name] => US [y] => 1 ) [3] => Array ( [name] => XX [y] => 1 ) ); ?>
</code>```

Then at the bottom of my php file, I put my js:

var g_donnes = '<?php echo json_encode($data); ?>';
Highcharts.chart('container', {
  chart: {
    plotBackgroundColor: null,
    plotBorderWidth: null,
    plotShadow: false,
    type: 'pie'
  },
  title: {
    text: 'Browser market shares in January, 2018'
  },
  tooltip: {
    pointFormat: '{series.name}: {point.percentage:.1f}%'
  },
  plotOptions: {
    pie: {
      allowPointSelect: true,
      cursor: 'pointer',
      dataLabels: {
        enabled: true,
        format: '{point.name}: {point.percentage:.1f} %',
        style: {
          color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
        }
      }
    }
  },
  series: [{
    name: 'Brands',
    colorByPoint: true,
    data: g_donnes
  }]
});```

So when I make a console.log (g_donnes), I have this table [{"name":"DE","y":1},{"name":"FR","y":3},{"name":"US","y":1},{"name":"XX","y":1}], but cons g_donnes is not treated by the code at the level of data: g_donnes

Thanks for your help

答:
You don't need quotes:

```<code>var g_donnes = <?php echo json_encode($data); ?>;
</code>```

With quotes your g_donnes is string, and not an array which is required by your code.

Body:
I am using the API highcharts to display the number of visitors to my site by country. I receive the data via mysql and I have this table in php:

<?php $data = Array ( [0] => Array ( [name] => DE [y] => 1 ) [1] => Array ( [name] => FR [y] => 3 ) [2] => Array ( [name] => US [y] => 1 ) [3] => Array ( [name] => XX [y] => 1 ) ); ?>

Then at the bottom of my php file, I put my js:

var g_donnes = '<?php echo json_encode($data); ?>';
Highcharts.chart('container', {
  chart: {
    plotBackgroundColor: null,
    plotBorderWidth: null,
    plotShadow: false,
    type: 'pie'
  },
  title: {
    text: 'Browser market shares in January, 2018'
  },
  tooltip: {
    pointFormat: '{series.name}: {point.percentage:.1f}%'
  },
  plotOptions: {
    pie: {
      allowPointSelect: true,
      cursor: 'pointer',
      dataLabels: {
        enabled: true,
        format: '{point.name}: {point.percentage:.1f} %',
        style: {
          color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
        }
      }
    }
  },
  series: [{
    name: 'Brands',
    colorByPoint: true,
    data: g_donnes
  }]
});

So when I make a console.log (g_donnes), I have this table [{"name":"DE","y":1},{"name":"FR","y":3},{"name":"US","y":1},{"name":"XX","y":1}], but cons g_donnes is not treated by the code at the level of data: g_donnes

Thanks for your help

Body:
You don't need quotes:

var g_donnes = <?php echo json_encode($data); ?>;

With quotes your g_donnes is string, and not an array which is required by your code.


问:
How to set basepath/prefix in Loopback 4?
I want to set basepath to my application. I updated with

```<code>await app.restServer.basePath('/api/v1');
</code>```

in my "index.js" at my project root folder. But when I'm trying to access the explorer, throwing errors as "Cant get explorer".

```<code>    await app.basePath('/api/v1');
       await app.restServer.basePath('/api/v1');
     this.static('/', path.join(__dirname, '../public'));
this.bind(RestBindings.SequenceActions.SEND).toProvider(Validateprovider);
        this.bind(RestExplorerBindings.CONFIG).to({
          path: path.resolve('/explorer'),
        });
</code>```

Once the application is loaded, am able to access this URL: http://127.0.0.1:8020/api/v1
But when I click on explorer in the same page. Its not redirecting to explorer, instead giving error as

"   Cannot GET /explorer/"

Please let me know how to access explorer with the prefix which I have mentioned.

答:
You need to do this in application.ts.

```<code>this.bind(RestExplorerBindings.CONFIG).to({
  path: '/api/v1',
});
</code>```

For more details, you can refer to the doc here.

Body:
I want to set basepath to my application. I updated with

await app.restServer.basePath('/api/v1');

in my "index.js" at my project root folder. But when I'm trying to access the explorer, throwing errors as "Cant get explorer".

    await app.basePath('/api/v1');
       await app.restServer.basePath('/api/v1');
     this.static('/', path.join(__dirname, '../public'));
this.bind(RestBindings.SequenceActions.SEND).toProvider(Validateprovider);
        this.bind(RestExplorerBindings.CONFIG).to({
          path: path.resolve('/explorer'),
        });

Once the application is loaded, am able to access this URL: http://127.0.0.1:8020/api/v1
But when I click on explorer in the same page. Its not redirecting to explorer, instead giving error as

"   Cannot GET /explorer/"

Please let me know how to access explorer with the prefix which I have mentioned.

Body:
You need to do this in application.ts.

this.bind(RestExplorerBindings.CONFIG).to({
  path: '/api/v1',
});

For more details, you can refer to the doc here.


问:
R - Subset string from nth position to first dot
I have a list of filenames like this:

datalist

```<code>EU_AU_abc100.dat
EU_AU_abc200.dat
EU_AU_abc300.dat
EU_AU_abc.dat
</code>```

I want to have this:

```<code>abc100
abc200
abc300
abc
</code>```

How can I do that? I know the substr(datalist, start = 6, stop = 12) for example, but that doesnt suit for the last example. Any idea how to solve this? Can I use the .dat as stop-marker somehow?

答:
Using gsub

```<code>gsub('.*_([^_]+)\\.dat','\\1',c("datalist EU_AU_abc100.dat","EU_AU_abc.dat"))
[1] "abc100" "abc"
</code>```

.*_ any character followed by a _

([^_]+) capture any character except a _ between .*_ and .dat as group 1. Then returns this group \\1

Body:
I have a list of filenames like this:

datalist

EU_AU_abc100.dat
EU_AU_abc200.dat
EU_AU_abc300.dat
EU_AU_abc.dat

I want to have this:

abc100
abc200
abc300
abc

How can I do that? I know the substr(datalist, start = 6, stop = 12) for example, but that doesnt suit for the last example. Any idea how to solve this? Can I use the .dat as stop-marker somehow?

Body:
Using gsub

gsub('.*_([^_]+)\\.dat','\\1',c("datalist EU_AU_abc100.dat","EU_AU_abc.dat"))
[1] "abc100" "abc"

.*_ any character followed by a _

([^_]+) capture any character except a _ between .*_ and .dat as group 1. Then returns this group \\1


问:
How do you change Background for a Button MouseOver in WPF?
I have a button on my page with this XAML:

```<code><Button Content="Button" HorizontalAlignment="Left" VerticalAlignment="Bottom"
    Width="50" Height="50" HorizontalContentAlignment="Left"
    BorderBrush="{x:Null}" Foreground="{x:Null}" Margin="50,0,0,0">
    <Button.Style>
        <Style TargetType="Button">
            <Setter Property="Background" Value="Green"/>
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="Background" Value="Red"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>
</code>```

But when I put mouse over my button, button's background changes to default windows gray background.
What's The Problem?

This is the button picture before and after mouseover:

Before:

After:

答:
For change button style

1st: define resource styles

```<code><Window.Resources>

    <Style x:Key="OvergroundIn" TargetType="Button">

        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Grid Background="#FF16832F">
                        <ContentPresenter TextBlock.Foreground="White" TextBlock.TextAlignment="Center" Margin="0,8,0,0" ></ContentPresenter>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>

        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">

                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="Button">
                            <Grid Background="#FF06731F">
                                <ContentPresenter TextBlock.Foreground="White" TextBlock.TextAlignment="Center" Margin="0,8,0,0" ></ContentPresenter>
                            </Grid>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>

            </Trigger>
        </Style.Triggers>

    </Style>

    <Style x:Key="OvergroundOut" TargetType="Button">

        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Grid Background="#FFF35E5E">
                        <ContentPresenter TextBlock.Foreground="White" TextBlock.TextAlignment="Center" Margin="0,8,0,0" ></ContentPresenter>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>

        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">

                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="Button">
                            <Grid Background="#FFE34E4E">
                                <ContentPresenter TextBlock.Foreground="White" TextBlock.TextAlignment="Center" Margin="0,8,0,0" ></ContentPresenter>
                            </Grid>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>

            </Trigger>
        </Style.Triggers>

    </Style>

</Window.Resources>
</code>```

2nd define button code

```<code>                           <Border Grid.Column="2" BorderBrush="LightGray" BorderThickness="2" CornerRadius="3" Margin="2,2,2,2"  >
                                <Button Name="btnFichar" BorderThickness="0" Click="BtnFichar_Click">
                                    <Button.Content>
                                        <Grid>
                                            <TextBlock Margin="0,7,0,7" TextAlignment="Center">Fichar</TextBlock>
                                        </Grid>
                                    </Button.Content>
                                </Button>
                            </Border>
</code>```

3th code behind

```<code>    public void ShowStatus()
    {
        switch (((MainDto)this.DataContext).State)
        {
            case State.IN:
                this.btnFichar.BorderBrush = new SolidColorBrush(Color.FromRgb(243, 94, 94));
                this.btnFichar.Style = Resources["OvergroundIn"] as Style;
                this.btnFichar.Content = "Fichar Salida";
                break;

            case State.OUT:
                this.btnFichar.BorderBrush = new SolidColorBrush(Color.FromRgb(76, 106, 83));
                this.btnFichar.Style = Resources["OvergroundOut"] as Style;
                this.btnFichar.Content = "Fichar Entrada";
                break;

        }
    }
</code>```

Body:
I have a button on my page with this XAML:

<Button Content="Button" HorizontalAlignment="Left" VerticalAlignment="Bottom"
    Width="50" Height="50" HorizontalContentAlignment="Left"
    BorderBrush="{x:Null}" Foreground="{x:Null}" Margin="50,0,0,0">
    <Button.Style>

        </Style>
    </Button.Style>
</Button>

But when I put mouse over my button, button's background changes to default windows gray background.
What's The Problem?

This is the button picture before and after mouseover:

Before:

After:

Body:
For change button style

1st: define resource styles

<Window.Resources>

    <Style x:Key="OvergroundIn" TargetType="Button">

        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Grid Background="#FF16832F">
                        <ContentPresenter TextBlock.Foreground="White" TextBlock.TextAlignment="Center" Margin="0,8,0,0" ></ContentPresenter>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>

        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">

                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="Button">
                            <Grid Background="#FF06731F">
                                <ContentPresenter TextBlock.Foreground="White" TextBlock.TextAlignment="Center" Margin="0,8,0,0" ></ContentPresenter>
                            </Grid>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>

            </Trigger>
        </Style.Triggers>

    </Style>

    <Style x:Key="OvergroundOut" TargetType="Button">

        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Grid Background="#FFF35E5E">
                        <ContentPresenter TextBlock.Foreground="White" TextBlock.TextAlignment="Center" Margin="0,8,0,0" ></ContentPresenter>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>

        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">

                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="Button">
                            <Grid Background="#FFE34E4E">
                                <ContentPresenter TextBlock.Foreground="White" TextBlock.TextAlignment="Center" Margin="0,8,0,0" ></ContentPresenter>
                            </Grid>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>

            </Trigger>
        </Style.Triggers>

    </Style>

</Window.Resources>

2nd define button code

                           <Border Grid.Column="2" BorderBrush="LightGray" BorderThickness="2" CornerRadius="3" Margin="2,2,2,2"  >
                                <Button Name="btnFichar" BorderThickness="0" Click="BtnFichar_Click">
                                    <Button.Content>
                                        <Grid>
                                            <TextBlock Margin="0,7,0,7" TextAlignment="Center">Fichar</TextBlock>
                                        </Grid>
                                    </Button.Content>
                                </Button>
                            </Border>

3th code behind

    public void ShowStatus()
    {
        switch (((MainDto)this.DataContext).State)
        {
            case State.IN:
                this.btnFichar.BorderBrush = new SolidColorBrush(Color.FromRgb(243, 94, 94));
                this.btnFichar.Style = Resources["OvergroundIn"] as Style;
                this.btnFichar.Content = "Fichar Salida";
                break;

            case State.OUT:
                this.btnFichar.BorderBrush = new SolidColorBrush(Color.FromRgb(76, 106, 83));
                this.btnFichar.Style = Resources["OvergroundOut"] as Style;
                this.btnFichar.Content = "Fichar Entrada";
                break;

        }
    }


问:
Changing transform-origin using jQuery?
I'm using code below to change the transform-origin but each time I got this error:

app.min.js:3 actionator::exeJavaScript - this.execUserJs is not a function

Here is the code:

```<code>var item = $('.slide-object.slide-object-vectorshape.shown[data-model-id="62wRqp3LlYN_pointer"]')

$(item).css({
  'transform-origin': 124px 124px;
  -webkit-transform-origin: 124px 124px;
});
</code>```

The selector works ok, but I can't find a working way to change the transform-origin in Chrome? What am I missing and how can I fix this?

答:
Your -webkit-transform-origin property will give you a parse error. Wrap it in quotes:

```<code>'-webkit-transform-origin': ...
</code>```

Title: Changing transform-origin using jQuery?

Body:
I'm using code below to change the transform-origin but each time I got this error:

app.min.js:3 actionator::exeJavaScript - this.execUserJs is not a function

Here is the code:

var item = $('.slide-object.slide-object-vectorshape.shown[data-model-id="62wRqp3LlYN_pointer"]')

$(item).css({
  'transform-origin': 124px 124px;
  -webkit-transform-origin: 124px 124px;
});

The selector works ok, but I can't find a working way to change the transform-origin in Chrome? What am I missing and how can I fix this?

Body:
Your -webkit-transform-origin property will give you a parse error. Wrap it in quotes:

'-webkit-transform-origin': ...


问:
Regarding to save previous record in asp.net
Hi
I have one label for question, radiobuttonlist for their answers, next button to move next question & previous button. I am displaying one question per page after clicking next button next question appears, but when i click previous button previous question appears.
But i want previous question with earlier selected answer when i click to previous button.
Asp.net c# Thank you.</p>

答:
Either store and load Question and answer values in the session.

or have one page with a multiview and swich views when navigating between 'pages' this way the viewstate information will be preserved.


问:
How to share my webpage to twitter in a card
I have done as the guide in Optimize Tweets with Cards, but it does not work like put my image and description in a card to share to others.

I want to share my webpage in a card for twitter.

```<code><meta name="twitter:card" content="summary" />
<meta name="twitter:title" content="summary" />
<meta name="twitter:creator" content="summary" />
<meta name="twitter:image" content="https://stackoverflow.com/questions/56339282/how-to-share-my-webpage-to-twitter-in-a-card/are_6b65b534.jpg" />
<meta name="twitter:description"   content="@ViewBag.Description" />
</code>```

As I put the guide code in my webpage, I still just get a url when I share my webpage.

Thanks for your help.

答: You have to state the full URL of the image for it to work. Test it here: https://cards-dev.twitter.com/validator</p>

Body:
I have done as the guide in Optimize Tweets with Cards, but it does not work like put my image and description in a card to share to others.

I want to share my webpage in a card for twitter.

<meta name="twitter:card" content="summary" />
<meta name="twitter:title" content="summary" />
<meta name="twitter:creator" content="summary" />
<meta name="twitter:image" content="https://stackoverflow.com/questions/56339282/how-to-share-my-webpage-to-twitter-in-a-card/are_6b65b534.jpg" />
<meta name="twitter:description"   content="@ViewBag.Description" />

As I put the guide code in my webpage, I still just get a url when I share my webpage.

Thanks for your help.


问:
Configuring Sonarqube analysis in CI build in VSTS
I am trying to run sonarqube analysis on code commit itself .
I have added 1) prepare analysis configuration and 2) run code analysis, tasks in CI build.
But I am getting an error :
" No agent found in pool mypool which satisfies the specified demands: msbuild visualstudio java
Agent.Version -gtVersion 2.119.1"

Can anyone please guide on what the issue is ?
Thanks in Advance !

答:
Configuring Sonarqube analysis in CI build in VSTS

According to the error message:

error : " No agent found in pool mypool which satisfies the specified
  demands: msbuild visualstudio java Agent.Version -gtVersion 2.119.1"

Which means that your private agent does not meet all the demands you set, including msbuild, visualstudio, java, Agent.Version -gtVersion 2.119.1.

So, you should double check if your private agent has those demands, you could move those demands one by one, to check which one is not up to the requirements.

AFAIK, to configure Sonarqube analysis in CI build in Azure Devops, we need following demands:

Make sure the .NET Framework v4.6+ is installed

Make sure the Java Runtime Environment 8 is installed

Install the extension SonarQube from the marketplace

Check the document Analyzing with SonarQube Extension for VSTS-TFS for some details.

Hope this helps.


问:
Regular Expression in Java for Password Pattern
The regex not working for "At least one Alphabets,At least one Digits and At least one Special Characters" and "At least one Digits and At least one Special Characters"

For example :

```<code>String passwordpattern="A9009"; //Not working for  pattern3
</code>```

Note:It should check atleast one Alphabets, Digits and Special Characters

and

```<code>String passwordpattern="A3566523"; //Not working for  pattern4
</code>```

Note:It should check at least one Special character and at least Digit

```<code>    //Alphabets, Digits and Special Characters
            String pattern3 = "[^\\\\w\\\\d]*(([0-9]+.*[A-Za-z]+.*[!#%&'()*+,-:;<=>?@}{]+.*)|[A-Za-z]+.*[0-9]+.*[!#%&'()*+,-:;<=>?@}{]+.*|[!#%&'()*+,-:;<=>?@}{]+.*[A-Za-z]+.*[0-9]+.*|[!#%&'()*+,-:;<=>?@}{]+.*[0-9]+.*[A-Za-z]+.*|[A-Za-z]+.*[!#%&'()*+,-:;<=>?@}{]+.*[0-9]+.*|[0-9]+.*[!#%&'()*+,-:;<=>?@}{]+.*[A-Za-z]+.*)";

   //Digits and Special Characters
  String pattern4 = "([^\\\\w\\\\d]*(([!#%&'()*+,-:;<=>?@}{]+.*[0-9]+.*)|[0-9]+.*([!#%&'()*+,-:;<=>?@]+.*)))";
</code>```

答:
For these type of assertions it is better to use lookahead assertions.

"At least one Alphabets,At least one Digits and At least one Special Characters"

```<code>^(?=.*\pL)(?=.*\d)(?=.*\W).+$
</code>```

\pL matches any unicode letter, \d matches any digit and \W any non-word character.

at least one Special character and at least Digit

```<code>^(?=.*\d)(?=.*\W).+$
</code>```

Note that while using matches method there is no need to use anchors.

Body:
The regex not working for "At least one Alphabets,At least one Digits and At least one Special Characters" and "At least one Digits and At least one Special Characters"

For example :

String passwordpattern="A9009"; //Not working for  pattern3

Note:It should check atleast one Alphabets, Digits and Special Characters

and

String passwordpattern="A3566523"; //Not working for  pattern4

Note:It should check at least one Special character and at least Digit

    //Alphabets, Digits and Special Characters
            String pattern3 = "[^\\\\w\\\\d]*(([0-9]+.*[A-Za-z]+.*[!#%&'()*+,-:;<=>?@}{]+.*)|[A-Za-z]+.*[0-9]+.*[!#%&'()*+,-:;<=>?@}{]+.*|[!#%&'()*+,-:;<=>?@}{]+.*[A-Za-z]+.*[0-9]+.*|[!#%&'()*+,-:;<=>?@}{]+.*[0-9]+.*[A-Za-z]+.*|[A-Za-z]+.*[!#%&'()*+,-:;<=>?@}{]+.*[0-9]+.*|[0-9]+.*[!#%&'()*+,-:;<=>?@}{]+.*[A-Za-z]+.*)";

   //Digits and Special Characters
  String pattern4 = "([^\\\\w\\\\d]*(([!#%&'()*+,-:;<=>?@}{]+.*[0-9]+.*)|[0-9]+.*([!#%&'()*+,-:;<=>?@]+.*)))";

Body:
For these type of assertions it is better to use lookahead assertions.

"At least one Alphabets,At least one Digits and At least one Special Characters"

^(?=.*\pL)(?=.*\d)(?=.*\W).+$

\pL matches any unicode letter, \d matches any digit and \W any non-word character.

at least one Special character and at least Digit

^(?=.*\d)(?=.*\W).+$

Note that while using matches method there is no need to use anchors.


问:
Special case in singly connected graph
I'm trying to write an algorithm to determine whether a giving graph is singly connected. The homework definition says that a singly connected graph means between two nodes, there is at most one simple path.

I see lots of answer here says that using DFS-visit for each node, and if there's a black node been visited, it means there are two simple paths. As a result, the given graph is not simply connected.

I rewrite DFS algorithm to achieve that, but the problem is it can solve all the given graph except one special case. I already consider the situation which there are multiple edges between two nodes, but it does not work.

So my question is that is there any special case which can not be solved by using DFS-visit for each node?

def dsf(self, source):
    source.color = 'g'
    for node in source.next:
        if node.color == 'w':
            if not self.dsf(node):
                return False
        elif node.color == 'b':
            return False
    source.color = 'b'
    return True
```

<p>if dsf encounter black node, it will return False and terminate the function.</p>

<pre class="lang-py prettyprint-override"><code>def singly(self):
    for node in self.nodes:
        if not self.dsf(node):
            return False
        self.__clear()
    return True
</code>```

And then using this function to check each node in the graph. Self.__clear can reset all the node's color back to white.

The algorithms work for all the case except for one special case.

答:
Is there any special case which can not be solved by using DFS-visit for each node?

No, dfs must perfectly solve your problem.

Keep trying to find a bug. This code might help you. It computes all connected components in undirected graph.

Title: Special case in singly connected graph

Body:
I'm trying to write an algorithm to determine whether a giving graph is singly connected. The homework definition says that a singly connected graph means between two nodes, there is at most one simple path.

I see lots of answer here says that using DFS-visit for each node, and if there's a black node been visited, it means there are two simple paths. As a result, the given graph is not simply connected.

I rewrite DFS algorithm to achieve that, but the problem is it can solve all the given graph except one special case. I already consider the situation which there are multiple edges between two nodes, but it does not work.

So my question is that is there any special case which can not be solved by using DFS-visit for each node?

def dsf(self, source):
    source.color = 'g'
    for node in source.next:
        if node.color == 'w':
            if not self.dsf(node):
                return False
        elif node.color == 'b':
            return False
    source.color = 'b'
    return True

if dsf encounter black node, it will return False and terminate the function.

def singly(self):
    for node in self.nodes:
        if not self.dsf(node):
            return False
        self.__clear()
    return True

And then using this function to check each node in the graph. Self.__clear can reset all the node's color back to white.

The algorithms work for all the case except for one special case.


问:
jQuery Tools Overlay Fired onClick of a Table Row? How?
I'm using the pretty straightforward jQuery Tools Overlay setup to load external content into the overlay. Check it out here. Basically, it works by using a standard  like this: Overlay. When you click Overlay, content.html loads in an overlay. Nice and easy!

I'm running into trouble because I want to have the overlay triggered by click of an entire table row. Is this possible? How would I make that happen?

答:
There is an easier way of doing this. In order to trigger a specific overlay on any specific event you just need to do</p>

```<code>$('#overlay').overlay().load();
</code>```

Body:
There is an easier way of doing this. In order to trigger a specific overlay on any specific event you just need to do

$('#overlay').overlay().load();


问:
Error uploading image file to Google Drive using REST API
I am working with the Google Drive for the first time. I am trying to upload a jpg file to my Google Drive through my app. I have completed the OAuth 2.0 authorization for account login and drive permission. I have successfully uploaded the file to Google Drive also following the instructions given here https://developers.google.com/drive/api/v3/manage-uploads?refresh=1

The issue is with the uploaded file. The image is not saved there as an image. What should be the form of the request body here?

Here is the code snippet I have used to upload the image file using Google REST API.

```<code>OkHttpClient client = new OkHttpClient();
            RequestBody body = RequestBody.create(MediaType.parse("application/json"), file);
            Request request = new Request.Builder()
                    .url("https://www.googleapis.com/upload/drive/v3/files?uploadType=media")
                    .addHeader("Content-Type", "image/jpeg")
                    .addHeader("Content-Length", "36966.4")
                    .addHeader("Authorization", String.format("Bearer %s", accessToken))
                    .post(body)
                    .build();
            Response response = null;
            try {
                response = client.newCall(request).execute();
                successCode = String.valueOf(response.code());
            }catch (IOException e){
                e.printStackTrace();
            }
</code>```

Here "file" is the Base64 encoded string of the image.

Its just giving the expected http ok 200 code. Also need to know how to set the title for the file while uploading on Google Drive.

答:
This is the complete example using googleapiclient

```<code>//variables
private GoogleApiClient mGoogleApiClient;
private Bitmap mBitmapToSave;
</code>```

now call this method on button click

```<code>//method to save file(Image type)
private void saveFileToDrive() {

    final Bitmap image = mBitmapToSave;
    Drive.DriveApi.newDriveContents(mGoogleApiClient)
            .setResultCallback(new ResultCallback<DriveContentsResult>() {

        @Override
        public void onResult(DriveContentsResult result) {

            if (!result.getStatus().isSuccess()) {
                Log.i("ERROR", "Failed to create new contents.");
                return;
            }

            OutputStream outputStream = result.getDriveContents().getOutputStream();
            // Write the bitmap data from it.
            ByteArrayOutputStream bitmapStream = new ByteArrayOutputStream();
            image.compress(Bitmap.CompressFormat.PNG, 100, bitmapStream);
            try {
                outputStream.write(bitmapStream.toByteArray());
            } catch (IOException e1) {
                Log.i("ERROR", "Unable to write file contents.");
            }
            // Create the initial metadata - MIME type and title.
            // Note that the user will be able to change the title later.
            MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
                    .setMimeType("image/jpeg").setTitle("Android Photo.png").build();
            // Create an intent for the file chooser, and start it.
            IntentSender intentSender = Drive.DriveApi
                    .newCreateFileActivityBuilder()
                    .setInitialMetadata(metadataChangeSet)
                    .setInitialDriveContents(result.getDriveContents())
                    .build(mGoogleApiClient);
            try {
                startIntentSenderForResult(
                        intentSender, REQUEST_CODE_CREATOR, null, 0, 0, 0);
            } catch (SendIntentException e) {
                Log.i("ERROR", "Failed to launch file chooser.");
            }
        }
    });
}

@Override
protected void onResume() {
    super.onResume();
    if (mGoogleApiClient == null) {
        // Create the API client and bind it to an instance variable.
        // We use this instance as the callback for connection and connection
        // failures.
        // Since no account name is passed, the user is prompted to choose.
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(Drive.API)
                .addScope(Drive.SCOPE_FILE)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
    }
    // Connect the client. Once connected, the camera is launched.
    mGoogleApiClient.connect();
}

@Override
protected void onPause() {
    if (mGoogleApiClient != null) {
        mGoogleApiClient.disconnect();
    }
    super.onPause();
}
</code>```

Ref Upload image to a google drive using google drive api programatically in android

Body:
I am working with the Google Drive for the first time. I am trying to upload a jpg file to my Google Drive through my app. I have completed the OAuth 2.0 authorization for account login and drive permission. I have successfully uploaded the file to Google Drive also following the instructions given here https://developers.google.com/drive/api/v3/manage-uploads?refresh=1

The issue is with the uploaded file. The image is not saved there as an image. What should be the form of the request body here?

Here is the code snippet I have used to upload the image file using Google REST API.

OkHttpClient client = new OkHttpClient();
            RequestBody body = RequestBody.create(MediaType.parse("application/json"), file);
            Request request = new Request.Builder()
                    .url("https://www.googleapis.com/upload/drive/v3/files?uploadType=media")
                    .addHeader("Content-Type", "image/jpeg")
                    .addHeader("Content-Length", "36966.4")
                    .addHeader("Authorization", String.format("Bearer %s", accessToken))
                    .post(body)
                    .build();
            Response response = null;
            try {
                response = client.newCall(request).execute();
                successCode = String.valueOf(response.code());
            }catch (IOException e){
                e.printStackTrace();
            }

Here "file" is the Base64 encoded string of the image.

Its just giving the expected http ok 200 code. Also need to know how to set the title for the file while uploading on Google Drive.

Body:
This is the complete example using googleapiclient

//variables
private GoogleApiClient mGoogleApiClient;
private Bitmap mBitmapToSave;

now call this method on button click

//method to save file(Image type)
private void saveFileToDrive() {

    final Bitmap image = mBitmapToSave;
    Drive.DriveApi.newDriveContents(mGoogleApiClient)
            .setResultCallback(new ResultCallback<DriveContentsResult>() {

        @Override
        public void onResult(DriveContentsResult result) {

            if (!result.getStatus().isSuccess()) {
                Log.i("ERROR", "Failed to create new contents.");
                return;
            }

            OutputStream outputStream = result.getDriveContents().getOutputStream();
            // Write the bitmap data from it.
            ByteArrayOutputStream bitmapStream = new ByteArrayOutputStream();
            image.compress(Bitmap.CompressFormat.PNG, 100, bitmapStream);
            try {
                outputStream.write(bitmapStream.toByteArray());
            } catch (IOException e1) {
                Log.i("ERROR", "Unable to write file contents.");
            }
            // Create the initial metadata - MIME type and title.
            // Note that the user will be able to change the title later.
            MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
                    .setMimeType("image/jpeg").setTitle("Android Photo.png").build();
            // Create an intent for the file chooser, and start it.
            IntentSender intentSender = Drive.DriveApi
                    .newCreateFileActivityBuilder()
                    .setInitialMetadata(metadataChangeSet)
                    .setInitialDriveContents(result.getDriveContents())
                    .build(mGoogleApiClient);
            try {
                startIntentSenderForResult(
                        intentSender, REQUEST_CODE_CREATOR, null, 0, 0, 0);
            } catch (SendIntentException e) {
                Log.i("ERROR", "Failed to launch file chooser.");
            }
        }
    });
}

@Override
protected void onResume() {
    super.onResume();
    if (mGoogleApiClient == null) {
        // Create the API client and bind it to an instance variable.
        // We use this instance as the callback for connection and connection
        // failures.
        // Since no account name is passed, the user is prompted to choose.
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(Drive.API)
                .addScope(Drive.SCOPE_FILE)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
    }
    // Connect the client. Once connected, the camera is launched.
    mGoogleApiClient.connect();
}

@Override
protected void onPause() {
    if (mGoogleApiClient != null) {
        mGoogleApiClient.disconnect();
    }
    super.onPause();
}

Ref Upload image to a google drive using google drive api programatically in android


答:
The object you are passing to .css is not a valid object..

```<code>$(item).css({
    'transform-origin': '124px 124px',
    '-webkit-transform-origin': '124px 124px'
});
</code>```

Title: Changing transform-origin using jQuery?

Body:
The object you are passing to .css is not a valid object..

$(item).css({
    'transform-origin': '124px 124px',
    '-webkit-transform-origin': '124px 124px'
});


问:
Using SIM800C send post request, get "ERROR" when setting URL(short) parameter
I'm using sim800c to send post request, everything look good, but it happaned that i got “ERROR” responed from modem when setting "URL", the url i set is short like"http://procedure.xxxxtech.com:1234".Then it will lanch recived event in module, but get data from modem error.Actually,the postdata was not sent.Once this happaned, it wont fix until remove power and plug in agian,then set url(i mean cold reboot fix, hot reboot is no use).

It is a situation that is very difficult to reproduce, and only appeared twice by now.

i changed url, it work well, but changed back, it still failed.

i check the log of http server, no data shown in log about request.

i tried empty url, it do return "ERROR",and lanch recived event and failed just like my problem .But my problem echo the cmd i wrote in, that is url is right.

i tried error url which is just no response url, everything is ok.

About the url format, first time it appeared i used format like http://entry.xxx.com/entry/ObtainRouteUrl, and i changed it to http://procedure.xxxxtech.com:1234, it sent request successfully, then i changee it back, failed still.The second time it appeared , the format we used is http://procedure.xxxxtech.com:1234, so it seems has nothing to do with the url format.

```<code>AT+HTTPTERM
modem recv: AT+HTTPTERM
ERROR

AT+SAPBR=1,1
modem recv: AT+SAPBR=1,1

modem recv:
OK

AT+HTTPINIT
modem recv: AT+HTTPINITOK

AT+HTTPPARA="CID",1
modem recv: AT+HTTPPARA="CID",1OK

AT+HTTPPARA="REDIR",1
modem recv: AT+HTTPPARA="REDIR",1OK

AT+HTTPPARA="URL","http://procedure.xxxxtech.com:1234"
modem recv: AT+HTTPPARA="URL","http://procedure.xxxxtech.com:1234"
ERROR

AT+HTTPPARA="CONTENT","application/json;charset=utf-8"

modem recv: AT+HTTPPARA="CONTENT","application/json;charset=utf-8"
OK

AT+HTTPPARA="TIMEOUT",50
modem recv: AT+HTTPPARA="TIMEOUT",50
OK

AT+HTTPSSL=0
modem recv: AT+HTTPSSL=0
OK

AT+HTTPDATA=199,100000
modem recv: AT+HTTPDATA=199,100000
DOWNLOAD
post data: {"appId":"306382023969210368","ctVsn":"13.1.18","devTp":"AT-XL3","did":"865209034329046","osTp":"RTOS","osVsn":"Nucleus","ts":"2004-01-01 08:02:31.000 +0800","sig":"08D74DEA267707685A883D40003FE2F8"}
modem recv:
OK

AT+HTTPACTION=1
modem recv: AT+HTTPACTION=1
ERROR

AT+HTTPREAD
modem recv: AT+HTTPREAD
+HTTPREAD: 199
{"appId":"306382023969210368","ctVsn":"13.1.18","devTp":"AT-XL3","did":"865209034329046","osTp":"RTOS","osVsn":"Nucleus","ts":"2004-01-01 08:02:31.000 +0800","sig":"08D74DEA267707685A883D40003FE2F8"}
OK

AT+HTTPTERM
modem recv: AT+HTTPTERM
OK

AT+SAPBR=0,1
modem recv: AT+SAPBR=0,1
modem recv:
OK
</code>```

http should work just right and send data , but didn't send data and hard to fix.

答:
AT-command manual describes "URL" in the following way:

```<code>"http://'server'/'path':'tcpPort'"
</code>```

In your command, the 'path' is missing:

```<code>AT+HTTPPARA="URL","http://procedure.xxxxtech.com:1234"
</code>```

Could you try to add path of your default page to the url. For example:

```<code>AT+HTTPPARA="URL","http://procedure.xxxxtech.com/index.html:1234"
</code>```

Body:
I'm using sim800c to send post request, everything look good, but it happaned that i got “ERROR” responed from modem when setting "URL", the url i set is short like"http://procedure.xxxxtech.com:1234".Then it will lanch recived event in module, but get data from modem error.Actually,the postdata was not sent.Once this happaned, it wont fix until remove power and plug in agian,then set url(i mean cold reboot fix, hot reboot is no use).

It is a situation that is very difficult to reproduce, and only appeared twice by now.

i changed url, it work well, but changed back, it still failed.

i check the log of http server, no data shown in log about request.

i tried empty url, it do return "ERROR",and lanch recived event and failed just like my problem .But my problem echo the cmd i wrote in, that is url is right.

i tried error url which is just no response url, everything is ok.

About the url format, first time it appeared i used format like http://entry.xxx.com/entry/ObtainRouteUrl, and i changed it to http://procedure.xxxxtech.com:1234, it sent request successfully, then i changee it back, failed still.The second time it appeared , the format we used is http://procedure.xxxxtech.com:1234, so it seems has nothing to do with the url format.

AT+HTTPTERM
modem recv: AT+HTTPTERM
ERROR

AT+SAPBR=1,1
modem recv: AT+SAPBR=1,1

modem recv:
OK

AT+HTTPINIT
modem recv: AT+HTTPINITOK

AT+HTTPPARA="CID",1
modem recv: AT+HTTPPARA="CID",1OK

AT+HTTPPARA="REDIR",1
modem recv: AT+HTTPPARA="REDIR",1OK

AT+HTTPPARA="URL","http://procedure.xxxxtech.com:1234"
modem recv: AT+HTTPPARA="URL","http://procedure.xxxxtech.com:1234"
ERROR

AT+HTTPPARA="CONTENT","application/json;charset=utf-8"

modem recv: AT+HTTPPARA="CONTENT","application/json;charset=utf-8"
OK

AT+HTTPPARA="TIMEOUT",50
modem recv: AT+HTTPPARA="TIMEOUT",50
OK

AT+HTTPSSL=0
modem recv: AT+HTTPSSL=0
OK

AT+HTTPDATA=199,100000
modem recv: AT+HTTPDATA=199,100000
DOWNLOAD
post data: {"appId":"306382023969210368","ctVsn":"13.1.18","devTp":"AT-XL3","did":"865209034329046","osTp":"RTOS","osVsn":"Nucleus","ts":"2004-01-01 08:02:31.000 +0800","sig":"08D74DEA267707685A883D40003FE2F8"}
modem recv:
OK

AT+HTTPACTION=1
modem recv: AT+HTTPACTION=1
ERROR

AT+HTTPREAD
modem recv: AT+HTTPREAD
+HTTPREAD: 199
{"appId":"306382023969210368","ctVsn":"13.1.18","devTp":"AT-XL3","did":"865209034329046","osTp":"RTOS","osVsn":"Nucleus","ts":"2004-01-01 08:02:31.000 +0800","sig":"08D74DEA267707685A883D40003FE2F8"}
OK

AT+HTTPTERM
modem recv: AT+HTTPTERM
OK

AT+SAPBR=0,1
modem recv: AT+SAPBR=0,1
modem recv:
OK

http should work just right and send data , but didn't send data and hard to fix.

Body:
AT-command manual describes "URL" in the following way:

"http://'server'/'path':'tcpPort'"

In your command, the 'path' is missing:

AT+HTTPPARA="URL","http://procedure.xxxxtech.com:1234"

Could you try to add path of your default page to the url. For example:

AT+HTTPPARA="URL","http://procedure.xxxxtech.com/index.html:1234"


问:
Download Kafka or confluent platform in package distributed CDH 5.16
I have installed CDH 5.16 Express using packages in a RHEL server. I am trying to install Kafka now and i observed that it can be installed only if CDH is installed as parcels.

1) Is it possible to install Kafka or confluent platform" separately in the server and use it along withCDH` components.

2) Is there any other workaround to install Kafka using Cloudera Manager

答:
In order use the CDK 4.0 (cloudera distribution of Kafka) with Cloudera 5.13, I was forced to install CDK 4.0 as a parcel.

I had a cloudera quickstart docker VM that I downloaded. It runs without Kerberos authentication. After starting the quickstart VM, I separately installed the quickstart Kafka from Apache kafka's website. This was required as the kafka packaged within cloudera was a older version. Since, this was non kerberos environment, the Kafka server upon startup started using the zookeeper that was running in quickstart VM. This way I achieved connection of Kafka with cloudera VM.

If you are new to CDH/CM then I suggest you first try and use the Kafka service that is bundled within Cloudera. Go to 'Add Service' within Cloudera drop-down and select kafka. Enabling this Kafka service will give you a set of brokers for kafka to run. Also, Kafka needs Zookeeper to run. Zookeeper comes by default in Cloudera. So, you would get a working cluster with kafka enabled in it. You can think of changing to the latest version of Kafka (using the approach mentioned above) once you are comfortable with inbuilt tools of CDH/CM.


问:
How to uninstall jdk 12.0.1 from Mac OS?
I want to uninstall java version 12.0.1 on macbook pro.

I have installed java 12.0.1 but its not supported for my eclipse Kepler version..

I have tried by some commands in terminal but its all not workout.

Could anyone help me to uninstall Java 12 ?

答:
By using this commands, can easily uninstall java from macOS.

java -version
sudo rm -rf /Library/Java/*
sudo rm -rf /Library/PreferencePanes/Java*
sudo rm -rf /Library/Internet\ Plug-Ins/Java*
```

Run java -version again to confirm if java was successfully uninstalled.

Body:
By using this commands, can easily uninstall java from macOS.

java -version
sudo rm -rf /Library/Java/*
sudo rm -rf /Library/PreferencePanes/Java*
sudo rm -rf /Library/Internet\ Plug-Ins/Java*

Run java -version again to confirm if java was successfully uninstalled.


问:
Why is rest of function code cleared when firing window.location.reload?
I want to begin counting the current session when the user has logged in. Because I store user details in sessionStorage, I need to do a location.reload in order for API-requests to be able to access the token in sessionStorage. The problem is that once I do the reload, the remaining code in the function is cleared, or neglected. I tried consol logging and it shows for about half a second then the console is cleared. How come, and how might I go about to still fire my setTimeout function and make it persist?</p>

```<code>loginUser: function(username, password) {
    var loginDetails = {"username": username, "password": password};
    return loginResource.save({}, loginDetails).$promise.then(function(response){
        var user = {
            name: username,
            token: response.token,
        }
        sessionStorage.user = angular.toJson(user);
        $window.location.reload();
    })
    .catch(function(reason) {
        console.warn("Failed login", reason);
        throw reason;
    });
},

beginCountdown: function() {
    console.log('begin');
    setTimeout(function(){
        sessionStorage.removeItem('user');
        $window.location.reload();
    }, 3000)
},
</code>```

答:
Because I store user details in sessionStorage, I need to do a location.reload in order for API-requests to be able to access the token in sessionStorage.

That isn't true.

```<code>sessionStorage.setItem('key', 'value');
let data = sessionStorage.getItem('key');
console.log(data);
</code>```

… shows the data stored in line 1 and retrieved in line 2.

once I do the reload, the remaining code in the function is cleared, or neglected.

The page is the environment in which your JavaScript runs in.

Reloading the page is equivalent to rebooting the computer and wondering why a Windows application doesn't maintain its state. It's possible to write a program in JS which saves it's state and reloads it when it is opened again, but you don't seem to be doing that.

Don't reload the page. Address the real problem. (Which is most likely that you are reading data from session storage when you load the JavaScript program, and then only writing updates to session storage and not to the variables where you are keeping the copy of that data you are working with.)

Body:
I want to begin counting the current session when the user has logged in. Because I store user details in sessionStorage, I need to do a location.reload in order for API-requests to be able to access the token in sessionStorage. The problem is that once I do the reload, the remaining code in the function is cleared, or neglected. I tried consol logging and it shows for about half a second then the console is cleared. How come, and how might I go about to still fire my setTimeout function and make it persist?

loginUser: function(username, password) {
    var loginDetails = {"username": username, "password": password};
    return loginResource.save({}, loginDetails).$promise.then(function(response){
        var user = {
            name: username,
            token: response.token,
        }
        sessionStorage.user = angular.toJson(user);
        $window.location.reload();
    })
    .catch(function(reason) {
        console.warn("Failed login", reason);
        throw reason;
    });
},

beginCountdown: function() {
    console.log('begin');
    setTimeout(function(){
        sessionStorage.removeItem('user');
        $window.location.reload();
    }, 3000)
},

Body:
Because I store user details in sessionStorage, I need to do a location.reload in order for API-requests to be able to access the token in sessionStorage.

That isn't true.

sessionStorage.setItem('key', 'value');
let data = sessionStorage.getItem('key');
console.log(data);

… shows the data stored in line 1 and retrieved in line 2.

once I do the reload, the remaining code in the function is cleared, or neglected.

The page is the environment in which your JavaScript runs in.

Reloading the page is equivalent to rebooting the computer and wondering why a Windows application doesn't maintain its state. It's possible to write a program in JS which saves it's state and reloads it when it is opened again, but you don't seem to be doing that.

Don't reload the page. Address the real problem. (Which is most likely that you are reading data from session storage when you load the JavaScript program, and then only writing updates to session storage and not to the variables where you are keeping the copy of that data you are working with.)


问:
How to send one msg to next module after receiving all messages from previous module in OMNET++
Need your help.

I have three modules  Module A, Module B and Module C.

Module A sends 20 messages to Module B.  I want to send one packet to Module C after receiving all 20 messages from Module A. how I can deal with this situation on handleMessage ?

At the moment it is running like a loop. on every arrival its sending a msg out. what i need is to collect all the messages from previous module, collect data from them, prepare a single message and send one msg to next module.

=================================================

Thanks 000102,

your first solution working perfectly fine. I am only struggling with second solution. so please help me out on this. Please check the below code and let me know where I am wrong.

```<code>class ModuleB: public cSimpleModule
{
protected:
    virtual void initialize() override;
    virtual void handleMessage(cMessage *msg) override;
private:
    bool sentMessage = false;
    simtime_t lastMessageReceivedAt;
    simtime_t timer;
};

void ModuleB::initialize()
{

}

void ModuleB::handleMessage(cMessage *msg)
{
       if(simTime() - lastMessageReceivedAt >= timer && sentMessage == false)
            {
                 EV << counter << " messages to receive before sending.\n";
                // Data collection
            }
            else
            {
                lastMessageReceivedAt = simTime();
                EV << " Send message to Module C.\n";
                cMessage *newMsg = new cMessage("Message")
                send(newMsg, "out");
                sentMessage = true;
            }
}
</code>```

答:
I think you are looking for something like this:</p>

```<code>class ModuleB : public cSimpleModule {
  private:
    int counter;

  protected:
    virtual void initialize() override;
    virtual void handleMessage(cMessage *msg) override;
};

void ModuleB::initialize() {
    counter = 20;
}

void ModuleB::handleMessage(cMessage *msg) {
    counter--;
    if (counter > 0) {
        EV << counter << " messages to receive before sending.\n";
        // Data collection
    }
    else {
        EV << " Send message to Module C.\n";
        cMessage *newMsg = new cMessage("Message");
        send(newMsg, "out");
    }
}
</code>```

Body:
Need your help.

I have three modules  Module A, Module B and Module C.

Module A sends 20 messages to Module B.  I want to send one packet to Module C after receiving all 20 messages from Module A. how I can deal with this situation on handleMessage ?

At the moment it is running like a loop. on every arrival its sending a msg out. what i need is to collect all the messages from previous module, collect data from them, prepare a single message and send one msg to next module.

=================================================

Thanks 000102,

your first solution working perfectly fine. I am only struggling with second solution. so please help me out on this. Please check the below code and let me know where I am wrong.

class ModuleB: public cSimpleModule
{
protected:
    virtual void initialize() override;
    virtual void handleMessage(cMessage *msg) override;
private:
    bool sentMessage = false;
    simtime_t lastMessageReceivedAt;
    simtime_t timer;
};

void ModuleB::initialize()
{

}

void ModuleB::handleMessage(cMessage *msg)
{
       if(simTime() - lastMessageReceivedAt >= timer && sentMessage == false)
            {
                 EV << counter << " messages to receive before sending.\n";
                // Data collection
            }
            else
            {
                lastMessageReceivedAt = simTime();
                EV << " Send message to Module C.\n";
                cMessage *newMsg = new cMessage("Message")
                send(newMsg, "out");
                sentMessage = true;
            }
}

Body:
I think you are looking for something like this:

class ModuleB : public cSimpleModule {
  private:
    int counter;

  protected:
    virtual void initialize() override;
    virtual void handleMessage(cMessage *msg) override;
};

void ModuleB::initialize() {
    counter = 20;
}

void ModuleB::handleMessage(cMessage *msg) {
    counter--;
    if (counter > 0) {
        EV << counter << " messages to receive before sending.\n";
        // Data collection
    }
    else {
        EV << " Send message to Module C.\n";
        cMessage *newMsg = new cMessage("Message");
        send(newMsg, "out");
    }
}


问:
Bullet color in Xaringan presentation
Is it possible to change the bullet colors in Xaringan presentation? The text should have a different color.

I have not find any option in xaringanthemer package neither going through the css file. I could not find any information  remark.js documentation.

答:
You can change the bullet point colour by adding a custom CSS to the YAML header of your Xaringan presentation.

Following is a fully reproducible minimal example.

Markdown file

```<code>title: "Example"
author: "Author"
date: "`r Sys.Date()`"
output:
  xaringan::moon_reader:
    css:
        - default
        - default-fonts
        - custom.css
    lib_dir: libs
    nature:
      highlightStyle: github
      highlightLines: true
      countIncrementalSlides: false
---

```{r setup, include=FALSE}
options(htmltools.dir.version = FALSE)
```

## Change bullet point colour

* An item
* Another item
</code>```

Custom custom.css

We have taken the relevant CSS code to theme the bullet points from here.

ul {
  list-style: none; /* Remove default bullets */
}

ul li::before {
  content: "\2022";  /* Add content: \2022 is the CSS Code/unicode for a bullet */
  color: red; /* Change the color */
  font-weight: bold; /* If you want it to be bold */
  display: inline-block; /* Needed to add space between the bullet and the text */
  width: 1em; /* Also needed for space (tweak if needed) */
  margin-left: -1em; /* Also needed for space (tweak if needed) */
}
```

Output

Title: Bullet color in Xaringan presentation

Body:
You can change the bullet point colour by adding a custom CSS to the YAML header of your Xaringan presentation.

Following is a fully reproducible minimal example.

Markdown file

title: "Example"
author: "Author"
date: "`r Sys.Date()`"
output:
  xaringan::moon_reader:
    css:
        - default
        - default-fonts
        - custom.css
    lib_dir: libs
    nature:
      highlightStyle: github
      highlightLines: true
      countIncrementalSlides: false
---

```{r setup, include=FALSE}
options(htmltools.dir.version = FALSE)
```

## Change bullet point colour

* An item
* Another item

Custom custom.css

We have taken the relevant CSS code to theme the bullet points from here.

ul {
  list-style: none; /* Remove default bullets */
}

ul li::before {
  content: "\2022";  /* Add content: \2022 is the CSS Code/unicode for a bullet */
  color: red; /* Change the color */
  font-weight: bold; /* If you want it to be bold */
  display: inline-block; /* Needed to add space between the bullet and the text */
  width: 1em; /* Also needed for space (tweak if needed) */
  margin-left: -1em; /* Also needed for space (tweak if needed) */
}

Output


问:
PHP: allow_url_include
Quick...possibly stupid question.

When allow_url_include is set to off, does that prohibit other computers from remotely including the files on my site, or does it say that I'm not allowed to remotely include files from other sites?

答:
As said in the php manual:
http://www.php.net/manual/en/filesystem.configuration.php#ini.allow-url-include
is for including remote files, only if you let your directory to reach the source, others can include your php files.

Then is the second suggestion

Title: PHP: allow_url_include


问:
How to avoid repeating dependency versions in a multi-module Gradle project?
There's a sample Spring Boot project here that contains two modules.

The build.gradle for one of the modules looks like this:

```<code>buildscript {
    ext { springBootVersion = '2.1.4.RELEASE' }
    repositories { mavenCentral() }
    dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") }
}

plugins {
    id "io.spring.dependency-management" version "1.0.5.RELEASE"
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

bootJar {
    baseName = 'gs-multi-module-application'
    version = '0.0.1-SNAPSHOT'
}
sourceCompatibility = 1.8

repositories { mavenCentral() }

dependencies {
    compile('org.springframework.boot:spring-boot-starter-actuator')
    compile('org.springframework.boot:spring-boot-starter-web')
    compile project(':library')
    testCompile('org.springframework.boot:spring-boot-starter-test')
}
</code>```

The other module's build.gradle looks like this:

```<code>buildscript {
    repositories { mavenCentral() }
}

plugins { id "io.spring.dependency-management" version "1.0.5.RELEASE" }

ext { springBootVersion = '2.1.4.RELEASE' }

apply plugin: 'java'
apply plugin: 'eclipse'

jar {
    baseName = 'gs-multi-module-library'
    version = '0.0.1-SNAPSHOT'
}
sourceCompatibility = 1.8

repositories { mavenCentral() }

dependencies {
    compile('org.springframework.boot:spring-boot-starter')
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

dependencyManagement {
    imports { mavenBom("org.springframework.boot:spring-boot-dependencies:${springBootVersion}") }
}
</code>```

The springBootVersion = '2.1.4.RELEASE' is declared in both modules. For a 2 module project that might not be a problem, but if my project had 10 modules and I wanted to make sure that all modules always depend on the same version of Spring Boot, it would be inconvenient and error-prone to repeat this version in every module.

Similarly, I might want to add a dependency on commons-io to both of these modules, and ensure they both always depend on the same version of commons-io.

How can I avoid repeating the version numbers in each and every build.gradle file?

答:
See this Gradle documentation : a good practice in Gradle is to configure subprojects which share common traits in a single place, for example in the root project's build script (or using custom plugins)

EDIT the solution proposed here is no longer considered as good practice from Gradle team (the link above does not even mention subproject bloc in latests Gradle version doc);  thank you @buggy for the warning .

In your example taken from Spring boot documentation, this pattern could be applied to centralize Spring boot and other common dependencies versions in a single place, but you could go further and also configure other common traits (Java plugin configuration, repositoties, etc..)

Here is how I would re-write the Spring example to make it cleaner and DRY:

Root project

```<code>/**
 * Add Springboot plugin into build script classpath (without applying it)
 * This is this only place where you need to define the Springboot version.
 *
 * See https://docs.spring.io/spring-boot/docs/current/gradle-plugin/reference/html/#managing-dependencies-using-in-isolation
 */
plugins {
    id "org.springframework.boot" version "2.1.4.RELEASE" apply false
}

// Set version for dependencies share between subprojects
ext {
    commonsIoVersion = "2.6"
}

subprojects {
    // common config for all Java subprojects
    apply plugin: "java"
    apply plugin: "eclipse"
    sourceCompatibility = 1.8
    repositories {
        mavenCentral()
    }

    // apply Spring Boot's dependency management plugin
    apply plugin: "io.spring.dependency-management"
}
</code>```

Library sub-project

```<code>// no need for additional plugins

jar {
    baseName = 'gs-multi-module-library'
    version = '0.0.1-SNAPSHOT'
}

dependencies {
    implementation('org.springframework.boot:spring-boot-starter')
    implementation "commons-io:commons-io:${commonsIoVersion}"

    testCompile('org.springframework.boot:spring-boot-starter-test')
}

dependencyManagement {
    imports {
        mavenBom org.springframework.boot.gradle.plugin.SpringBootPlugin.BOM_COORDINATES
    }
}
</code>```

Application sub-project

```<code>plugins {
    id "org.springframework.boot"
}

bootJar {
    baseName = 'gs-multi-module-application'
    version = '0.0.1-SNAPSHOT'
}

dependencies {
    implementation  project(':library')

    implementation ('org.springframework.boot:spring-boot-starter-actuator')
    implementation ('org.springframework.boot:spring-boot-starter-web')
    implementation "commons-io:commons-io:${commonsIoVersion}"

    // could also be configured in root project.
    testCompile('org.springframework.boot:spring-boot-starter-test')
}
</code>```

Notes

this solution uses the new plugins {} DSL only (no need for old buildscript block)

version of the io.spring.dependency-management should not be configured explicitly, it will be inherit from Spring boot plugin

Body:
There's a sample Spring Boot project here that contains two modules.

The build.gradle for one of the modules looks like this:

buildscript {
    ext { springBootVersion = '2.1.4.RELEASE' }
    repositories { mavenCentral() }
    dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") }
}

plugins {
    id "io.spring.dependency-management" version "1.0.5.RELEASE"
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

bootJar {
    baseName = 'gs-multi-module-application'
    version = '0.0.1-SNAPSHOT'
}
sourceCompatibility = 1.8

repositories { mavenCentral() }

dependencies {
    compile('org.springframework.boot:spring-boot-starter-actuator')
    compile('org.springframework.boot:spring-boot-starter-web')
    compile project(':library')
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

The other module's build.gradle looks like this:

buildscript {
    repositories { mavenCentral() }
}

plugins { id "io.spring.dependency-management" version "1.0.5.RELEASE" }

ext { springBootVersion = '2.1.4.RELEASE' }

apply plugin: 'java'
apply plugin: 'eclipse'

jar {
    baseName = 'gs-multi-module-library'
    version = '0.0.1-SNAPSHOT'
}
sourceCompatibility = 1.8

repositories { mavenCentral() }

dependencies {
    compile('org.springframework.boot:spring-boot-starter')
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

dependencyManagement {
    imports { mavenBom("org.springframework.boot:spring-boot-dependencies:${springBootVersion}") }
}

The springBootVersion = '2.1.4.RELEASE' is declared in both modules. For a 2 module project that might not be a problem, but if my project had 10 modules and I wanted to make sure that all modules always depend on the same version of Spring Boot, it would be inconvenient and error-prone to repeat this version in every module.

Similarly, I might want to add a dependency on commons-io to both of these modules, and ensure they both always depend on the same version of commons-io.

How can I avoid repeating the version numbers in each and every build.gradle file?

Body:
See this Gradle documentation : a good practice in Gradle is to configure subprojects which share common traits in a single place, for example in the root project's build script (or using custom plugins)

EDIT the solution proposed here is no longer considered as good practice from Gradle team (the link above does not even mention subproject bloc in latests Gradle version doc);  thank you @buggy for the warning .

In your example taken from Spring boot documentation, this pattern could be applied to centralize Spring boot and other common dependencies versions in a single place, but you could go further and also configure other common traits (Java plugin configuration, repositoties, etc..)

Here is how I would re-write the Spring example to make it cleaner and DRY:

Root project

/**
 * Add Springboot plugin into build script classpath (without applying it)
 * This is this only place where you need to define the Springboot version.
 *
 * See https://docs.spring.io/spring-boot/docs/current/gradle-plugin/reference/html/#managing-dependencies-using-in-isolation
 */
plugins {
    id "org.springframework.boot" version "2.1.4.RELEASE" apply false
}

// Set version for dependencies share between subprojects
ext {
    commonsIoVersion = "2.6"
}

subprojects {
    // common config for all Java subprojects
    apply plugin: "java"
    apply plugin: "eclipse"
    sourceCompatibility = 1.8
    repositories {
        mavenCentral()
    }

    // apply Spring Boot's dependency management plugin
    apply plugin: "io.spring.dependency-management"
}

Library sub-project

// no need for additional plugins

jar {
    baseName = 'gs-multi-module-library'
    version = '0.0.1-SNAPSHOT'
}

dependencies {
    implementation('org.springframework.boot:spring-boot-starter')
    implementation "commons-io:commons-io:${commonsIoVersion}"

    testCompile('org.springframework.boot:spring-boot-starter-test')
}

dependencyManagement {
    imports {
        mavenBom org.springframework.boot.gradle.plugin.SpringBootPlugin.BOM_COORDINATES
    }
}

Application sub-project

plugins {
    id "org.springframework.boot"
}

bootJar {
    baseName = 'gs-multi-module-application'
    version = '0.0.1-SNAPSHOT'
}

dependencies {
    implementation  project(':library')

    implementation ('org.springframework.boot:spring-boot-starter-actuator')
    implementation ('org.springframework.boot:spring-boot-starter-web')
    implementation "commons-io:commons-io:${commonsIoVersion}"

    // could also be configured in root project.
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

Notes

this solution uses the new plugins {} DSL only (no need for old buildscript block)

version of the io.spring.dependency-management should not be configured explicitly, it will be inherit from Spring boot plugin