问:
Flutter json.decode issue <!doctype html> error
I am trying to integrate stripe payment in my Flutter project with backend Laravel. For some reason I am getting error at json.decode.

E/flutter (10999): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)]
Unhandled Exception: FormatException: Unexpected character (at
character 1) E/flutter (10999): <!doctype html>

```<code>FlatButton(
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(7.0)),
                    color: Colors.redAccent,
                    onPressed: () {
                      var payment = Payment();
                      payment.name = _cardHolderName.text;
                      payment.email = _cardHolderEmail.text;
                      payment.cardNumber = _cardNumber.text;
                      payment.expiryMonth = _expiryMonth.text;
                      payment.expiryYear = _expiryYear.text;
                      payment.cvcNumber = _cvcNumber.text;

                      _makePayment(context, payment);

                    },
                    child: Text('Make Payment',
                        style: TextStyle(color: Colors.white)),
                  ),
</code>```
```<code>void _makePayment(BuildContext context, Payment payment) async {
    PaymentService _paymentService = PaymentService();
    var paymentData = await _paymentService.makePayment(payment);
    var result = json.decode(paymentData.body);

    if (result['result'] == true) {
      CartService _cartService = CartService();
      this.widget.cartItems.forEach((cartItem){
        _cartService.deleteCartItemById(cartItem.productId);
      });
      _showPaymentSuccessMessage(context);
      Timer(Duration(seconds: 2), () {
        Navigator.pop(context);
        Navigator.push(
            context, MaterialPageRoute(builder: (context) => HomeScreen()));
      });
    }
  }
</code>```

Payment Service

```<code>class PaymentService {
  Repository _repository;

  PaymentService(){
    _repository = Repository();
  }

  makePayment(Payment payment) async {
    return await _repository.httpPost('make-payment', payment.toJson());
  }
}
</code>```

Laravel Code

```<code>public function makePayment(Request $request)
    {
        \Stripe\Stripe::setApiKey('sk_test_7422pw1lMsdRfN2FaPmfFKlt00AtiIJD9O');

        $token = Token::create([
            'card'=>[
                'number'=>$request-input('cardNumber'),
                'exp_month'=>$request-input('expiryMonth'),
                'exp_year'=>$request-input('expiryYear'),
                'cvc'=>$request-input('cvcNumber')
                ]

            ]);

\Stripe\PaymentIntent::create([
  'amount' => 1000,
  'currency' => 'inr',
  'source'  => $token,
  'receipt_email' => $request->input('email'),
]);
    }
</code>```

Error

```<code>E/flutter (10999): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: FormatException: Unexpected character (at character 1)
E/flutter (10999): <!doctype html>
E/flutter (10999): ^
E/flutter (10999):
E/flutter (10999): #0      _ChunkedJsonParser.fail (dart:convert-patch/convert_patch.dart:1394:5)
E/flutter (10999): #1      _ChunkedJsonParser.parseNumber (dart:convert-patch/convert_patch.dart:1261:9)
E/flutter (10999): #2      _ChunkedJsonParser.parse (dart:convert-patch/convert_patch.dart:926:22)
E/flutter (10999): #3      _parseJson (dart:convert-patch/convert_patch.dart:31:10)
E/flutter (10999): #4      JsonDecoder.convert (dart:convert/json.dart:495:36)
E/flutter (10999): #5      JsonCodec.decode (dart:convert/json.dart:153:41)
E/flutter (10999): #6      _PaymentScreenState._makePayment (package:factory2homes/screens/payment_screen.dart:160:23)
E/flutter (10999): <asynchronous suspension>
E/flutter (10999): #7      _PaymentScreenState.build.<anonymous closure> (package:factory2homes/screens/payment_screen.dart:142:23)
E/flutter (10999): #8      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:706:14)
E/flutter (10999): #9      _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:789:36)
E/flutter (10999): #10     GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24)
E/flutter (10999): #11     TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:486:11)
E/flutter (10999): #12     BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:264:5)
E/flutter (10999): #13     BaseTapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:236:7)
E/flutter (10999): #14     GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:156:27)
E/flutter (10999): #15     GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:222:20)
E/flutter (10999): #16     GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:198:22)
E/flutter (10999): #17     GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:156:7)
E/flutter (10999): #18     GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:102:7)
E/flutter (10999): #19     GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:86:7)
E/flutter (10999): #20     _rootRunUnary (dart:async/zone.dart:1138:13)
E/flutter (10999): #21     _CustomZone.runUnary (dart:async/zone.dart:1031:19)
E/flutter (10999): #22     _CustomZone.runUnaryGuarded (dart:async/zone.dart:933:7)
E/flutter (10999): #23     _invoke1 (dart:ui/hooks.dart:273:10)
E/flutter (10999): #24     _dispatchPointerDataPacket (dart:ui/hooks.dart:182:5)
E/flutter (10999):
</code>```

答:
This error happens when the server return an html body or some error occurred on the server side while handling your request. Try to use debugger and watch the response of the request to see if response status is 200 and also check the response body to see what the server is sending for your request.

Also try to wrap you jsonDecode inside try-catch to handle future exceptions.

Body:
I am trying to integrate stripe payment in my Flutter project with backend Laravel. For some reason I am getting error at json.decode.

E/flutter (10999): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)]
Unhandled Exception: FormatException: Unexpected character (at
character 1) E/flutter (10999): <!doctype html>

FlatButton(
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(7.0)),
                    color: Colors.redAccent,
                    onPressed: () {
                      var payment = Payment();
                      payment.name = _cardHolderName.text;
                      payment.email = _cardHolderEmail.text;
                      payment.cardNumber = _cardNumber.text;
                      payment.expiryMonth = _expiryMonth.text;
                      payment.expiryYear = _expiryYear.text;
                      payment.cvcNumber = _cvcNumber.text;

                      _makePayment(context, payment);

                    },
                    child: Text('Make Payment',
                        style: TextStyle(color: Colors.white)),
                  ),

void _makePayment(BuildContext context, Payment payment) async {
    PaymentService _paymentService = PaymentService();
    var paymentData = await _paymentService.makePayment(payment);
    var result = json.decode(paymentData.body);

    if (result['result'] == true) {
      CartService _cartService = CartService();
      this.widget.cartItems.forEach((cartItem){
        _cartService.deleteCartItemById(cartItem.productId);
      });
      _showPaymentSuccessMessage(context);
      Timer(Duration(seconds: 2), () {
        Navigator.pop(context);
        Navigator.push(
            context, MaterialPageRoute(builder: (context) => HomeScreen()));
      });
    }
  }

Payment Service

class PaymentService {
  Repository _repository;

  PaymentService(){
    _repository = Repository();
  }

  makePayment(Payment payment) async {
    return await _repository.httpPost('make-payment', payment.toJson());
  }
}

Laravel Code

public function makePayment(Request $request)
    {
        \Stripe\Stripe::setApiKey('sk_test_7422pw1lMsdRfN2FaPmfFKlt00AtiIJD9O');

        $token = Token::create([
            'card'=>[
                'number'=>$request-input('cardNumber'),
                'exp_month'=>$request-input('expiryMonth'),
                'exp_year'=>$request-input('expiryYear'),
                'cvc'=>$request-input('cvcNumber')
                ]

            ]);

\Stripe\PaymentIntent::create([
  'amount' => 1000,
  'currency' => 'inr',
  'source'  => $token,
  'receipt_email' => $request->input('email'),
]);
    }

Error

E/flutter (10999): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: FormatException: Unexpected character (at character 1)
E/flutter (10999): <!doctype html>
E/flutter (10999): ^
E/flutter (10999):
E/flutter (10999): #0      _ChunkedJsonParser.fail (dart:convert-patch/convert_patch.dart:1394:5)
E/flutter (10999): #1      _ChunkedJsonParser.parseNumber (dart:convert-patch/convert_patch.dart:1261:9)
E/flutter (10999): #2      _ChunkedJsonParser.parse (dart:convert-patch/convert_patch.dart:926:22)
E/flutter (10999): #3      _parseJson (dart:convert-patch/convert_patch.dart:31:10)
E/flutter (10999): #4      JsonDecoder.convert (dart:convert/json.dart:495:36)
E/flutter (10999): #5      JsonCodec.decode (dart:convert/json.dart:153:41)
E/flutter (10999): #6      _PaymentScreenState._makePayment (package:factory2homes/screens/payment_screen.dart:160:23)
E/flutter (10999): <asynchronous suspension>
E/flutter (10999): #7      _PaymentScreenState.build.<anonymous closure> (package:factory2homes/screens/payment_screen.dart:142:23)
E/flutter (10999): #8      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:706:14)
E/flutter (10999): #9      _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:789:36)
E/flutter (10999): #10     GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24)
E/flutter (10999): #11     TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:486:11)
E/flutter (10999): #12     BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:264:5)
E/flutter (10999): #13     BaseTapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:236:7)
E/flutter (10999): #14     GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:156:27)
E/flutter (10999): #15     GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:222:20)
E/flutter (10999): #16     GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:198:22)
E/flutter (10999): #17     GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:156:7)
E/flutter (10999): #18     GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:102:7)
E/flutter (10999): #19     GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:86:7)
E/flutter (10999): #20     _rootRunUnary (dart:async/zone.dart:1138:13)
E/flutter (10999): #21     _CustomZone.runUnary (dart:async/zone.dart:1031:19)
E/flutter (10999): #22     _CustomZone.runUnaryGuarded (dart:async/zone.dart:933:7)
E/flutter (10999): #23     _invoke1 (dart:ui/hooks.dart:273:10)
E/flutter (10999): #24     _dispatchPointerDataPacket (dart:ui/hooks.dart:182:5)
E/flutter (10999):


来源: stackexchange

问:
Scrapy - How to stop meta refresh redirect?
This is the website I am crawling. I had no problem at first, but then I encountered this error.

```<code>[scrapy] DEBUG: Redirecting (meta refresh) to <GET https://www.propertyguru.com.my/distil_r_captcha.html?requestId=9f8ba25c-3673-40d3-bfe2-6e01460be915&httpReferrer=%2Fproperty-for-rent%2F1> from <GET https://www.propertyguru.com.my/property-for-rent/1>
</code>```

Website knows I am a bot and redirects me to a page with a captcha code. I think handle_httpstatus_list or dont_redirect doesn't work because redirection isn't done with http status codes. This is my crawler's code. Is there any way to stop this redirection?

```<code>class MySpider(CrawlSpider):

    name = 'myspider'

    start_urls = [
        'https://www.propertyguru.com.my/property-for-rent/1',
    ]

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'
    }
    meta = {
        'dont_redirect': True
    }

    def parse(self, response):
        items = response.css('div.header-container h3.ellipsis a.nav-link::attr(href)').getall()

        if items:
            for item in items:
                if item.startswith('/property-listing/'):
                    yield scrapy.Request(
                        url='https://www.propertyguru.com.my{}'.format(item),
                        method='GET',
                        headers=self.headers,
                        meta=self.meta,
                        callback=self.parse_items
                    )

    def parse_items(self, response):
        from scrapy.shell import inspect_response
        inspect_response(response, self)
</code>```

UPDATE: I tried those settings, but they didn't work either.

```<code>custom_settings = {
    'DOWNLOAD_DELAY': 5,
    'DOWNLOAD_TIMEOUT': 360,
    'CONCURRENT_REQUESTS_PER_DOMAIN': 1,
    'CONCURRENT_ITEMS': 1,
    'REDIRECT_MAX_METAREFRESH_DELAY': 200,
    'REDIRECT_MAX_TIMES': 40,
}
</code>```

答:
To stop meta refresh, simply disable it in the crawler settings.py file:

```<code>METAREFRESH_ENABLED = False
</code>```

https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#metarefreshmiddleware-settings

ContentLicense: CC BY-SA 4.0

Body:
This is the website I am crawling. I had no problem at first, but then I encountered this error.

[scrapy] DEBUG: Redirecting (meta refresh) to <GET https://www.propertyguru.com.my/distil_r_captcha.html?requestId=9f8ba25c-3673-40d3-bfe2-6e01460be915&httpReferrer=%2Fproperty-for-rent%2F1> from <GET https://www.propertyguru.com.my/property-for-rent/1>

Website knows I am a bot and redirects me to a page with a captcha code. I think handle_httpstatus_list or dont_redirect doesn't work because redirection isn't done with http status codes. This is my crawler's code. Is there any way to stop this redirection?

class MySpider(CrawlSpider):

    name = 'myspider'

    start_urls = [
        'https://www.propertyguru.com.my/property-for-rent/1',
    ]

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'
    }
    meta = {
        'dont_redirect': True
    }

    def parse(self, response):
        items = response.css('div.header-container h3.ellipsis a.nav-link::attr(href)').getall()

        if items:
            for item in items:
                if item.startswith('/property-listing/'):
                    yield scrapy.Request(
                        url='https://www.propertyguru.com.my{}'.format(item),
                        method='GET',
                        headers=self.headers,
                        meta=self.meta,
                        callback=self.parse_items
                    )

    def parse_items(self, response):
        from scrapy.shell import inspect_response
        inspect_response(response, self)

UPDATE: I tried those settings, but they didn't work either.

custom_settings = {
    'DOWNLOAD_DELAY': 5,
    'DOWNLOAD_TIMEOUT': 360,
    'CONCURRENT_REQUESTS_PER_DOMAIN': 1,
    'CONCURRENT_ITEMS': 1,
    'REDIRECT_MAX_METAREFRESH_DELAY': 200,
    'REDIRECT_MAX_TIMES': 40,
}

Body:
To stop meta refresh, simply disable it in the crawler settings.py file:

METAREFRESH_ENABLED = False

https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#metarefreshmiddleware-settings


问:
How to count specific symbol in google sheets
I have a list of word that is separated by comma.
So I just want to count each comma and return the total amount in one cell.
I used:

=ArrayFormula(len(REGEXREPLACE(B2:B11, "[^,]", "")))

While it will count comma of each cell but it display the total per cell instead of total of all cells.
So how do I have the total commas count to display in one cell only?
thanks.

答:
That's pretty straightforward:

```<code>=sum(ArrayFormula(len(REGEXREPLACE(B2:B11, "[^,]", ""))))
</code>```

Body:
That's pretty straightforward:

=sum(ArrayFormula(len(REGEXREPLACE(B2:B11, "[^,]", ""))))


问:
Hi How do i workout this mysql query question
List the course number, the offering number, and the average GPA of students enrolled. Only include courses offered in winter term in which the average GPA of enrolled students is greater than 3.0.
Database

Here is the database, if you need anything else let me know
I have tried this but can't seem to get anywhere

```<code>SELECT O.CourseNo, E.offerNo, S.StdGPA
FROM Offering O JOIN
Student S JOIN
Enrollment E
WHERE O.OfferNo = E.OfferNo
AND E.stdSSN = S.StdSSN
AND O.OffTerm = "WINTER"
AND S.StdGPA > 3.0;
</code>```

答:
Try this query.</p>

```<code>SELECT O.CourseNo, E.offerNo, S.StdGPA FROM Offering O INNER JOIN Enrollment E
ON O.OfferNo = E.OfferNo INNER JOIN Student S
ON E.stdSSN = S.StdSSN WHERE O.OffTerm = "WINTER" AND S.StdGPA > 3
</code>```

Body:
List the course number, the offering number, and the average GPA of students enrolled. Only include courses offered in winter term in which the average GPA of enrolled students is greater than 3.0.
Database

Here is the database, if you need anything else let me know
I have tried this but can't seem to get anywhere

SELECT O.CourseNo, E.offerNo, S.StdGPA
FROM Offering O JOIN
Student S JOIN
Enrollment E
WHERE O.OfferNo = E.OfferNo
AND E.stdSSN = S.StdSSN
AND O.OffTerm = "WINTER"
AND S.StdGPA > 3.0;

Body:
Try this query.

SELECT O.CourseNo, E.offerNo, S.StdGPA FROM Offering O INNER JOIN Enrollment E
ON O.OfferNo = E.OfferNo INNER JOIN Student S
ON E.stdSSN = S.StdSSN WHERE O.OffTerm = "WINTER" AND S.StdGPA > 3


问:
Python: simple list merging based on intersections
Consider there are some lists of integers as:

```<code>#--------------------------------------
0 [0,1,3]
1 [1,0,3,4,5,10,...]
2 [2,8]
3 [3,1,0,...]
...
n []
#--------------------------------------
</code>```

The question is to merge lists having at least one common element. So the results only for the given part will be as follows:

```<code>#--------------------------------------
0 [0,1,3,4,5,10,...]
2 [2,8]
#--------------------------------------
</code>```

What is the most efficient way to do this on large data (elements are just numbers)?
Is tree structure something to think about?
I do the job now by converting lists to sets and iterating for intersections, but it is slow! Furthermore I have a feeling that is so-elementary! In addition, the implementation lacks something (unknown) because some lists remain unmerged sometime! Having said that, if you were proposing self-implementation please be generous and provide a simple sample code [apparently Python is my favoriate :)] or pesudo-code.

Update 1:
Here is the code I was using:

```<code>#--------------------------------------
lsts = [[0,1,3],
        [1,0,3,4,5,10,11],
        [2,8],
        [3,1,0,16]];
#--------------------------------------
</code>```

The function is (buggy!!):

```<code>#--------------------------------------
def merge(lsts):
    sts = [set(l) for l in lsts]
    i = 0
    while i < len(sts):
        j = i+1
        while j < len(sts):
            if len(sts[i].intersection(sts[j])) > 0:
                sts[i] = sts[i].union(sts[j])
                sts.pop(j)
            else: j += 1                        #---corrected
        i += 1
    lst = [list(s) for s in sts]
    return lst
#--------------------------------------
</code>```

The result is:

```<code>#--------------------------------------
>>> merge(lsts)
>>> [0, 1, 3, 4, 5, 10, 11, 16], [8, 2]]
#--------------------------------------
</code>```

Update 2:
To my experience the code given by Niklas Baumstark below showed to be a bit faster for the simple cases. Not tested the method given by "Hooked" yet, since it is completely different approach (by the way it seems interesting).
The testing procedure for all of these could be really hard or impossible to be ensured of the results. The real data set I will use is so large and complex, so it is impossible to trace any error just by repeating. That is I need to be 100% satisfied of the reliability of the method before pushing it in its place within a large code as a module. Simply for now Niklas's method is faster and the answer for simple sets is correct of course.

However how can I be sure that it works well for real large data set? Since I will not be able to trace the errors visually!

Update 3:
Note that reliability of the method is much more important than speed for this problem. I will be hopefully able to translate the Python code to Fortran for the maximum performance finally.

Update 4:

There are many interesting points in this post and generously given answers, constructive comments. I would recommend reading all thoroughly. Please accept my appreciation for the development of the question, amazing answers and constructive comments and discussion.

答:
```<code>from itertools import combinations

def merge(elements_list):
    d = {index: set(elements) for index, elements in enumerate(elements_list)}

    while any(not set.isdisjoint(d[i], d[j]) for i, j in combinations(d.keys(), 2)):
        merged = set()
        for i, j in combinations(d.keys(), 2):
            if not set.isdisjoint(d[i], d[j]):
                d[i] = set.union(d[i], d[j])
                merged.add(j)

        for k in merged:
            d.pop(k)

    return [v for v in d.values() if v]

lst = [[65, 17, 5, 30, 79, 56, 48, 62],
       [6, 97, 32, 93, 55, 14, 70, 32],
       [75, 37, 83, 34, 9, 19, 14, 64],
       [43, 71],
       [],
       [89, 49, 1, 30, 28, 3, 63],
       [35, 21, 68, 94, 57, 94, 9, 3],
       [16],
       [29, 9, 97, 43],
       [17, 63, 24]]

print(merge(lst))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Consider there are some lists of integers as:

#--------------------------------------
0 [0,1,3]
1 [1,0,3,4,5,10,...]
2 [2,8]
3 [3,1,0,...]
...
n []
#--------------------------------------

The question is to merge lists having at least one common element. So the results only for the given part will be as follows:

#--------------------------------------
0 [0,1,3,4,5,10,...]
2 [2,8]
#--------------------------------------

What is the most efficient way to do this on large data (elements are just numbers)?
Is tree structure something to think about?
I do the job now by converting lists to sets and iterating for intersections, but it is slow! Furthermore I have a feeling that is so-elementary! In addition, the implementation lacks something (unknown) because some lists remain unmerged sometime! Having said that, if you were proposing self-implementation please be generous and provide a simple sample code [apparently Python is my favoriate :)] or pesudo-code.

Update 1:
Here is the code I was using:

#--------------------------------------
lsts = [[0,1,3],
        [1,0,3,4,5,10,11],
        [2,8],
        [3,1,0,16]];
#--------------------------------------

The function is (buggy!!):

#--------------------------------------
def merge(lsts):
    sts = [set(l) for l in lsts]
    i = 0
    while i < len(sts):
        j = i+1
        while j < len(sts):
            if len(sts[i].intersection(sts[j])) > 0:
                sts[i] = sts[i].union(sts[j])
                sts.pop(j)
            else: j += 1                        #---corrected
        i += 1
    lst = [list(s) for s in sts]
    return lst
#--------------------------------------

The result is:

#--------------------------------------
>>> merge(lsts)
>>> [0, 1, 3, 4, 5, 10, 11, 16], [8, 2]]
#--------------------------------------

Update 2:
To my experience the code given by Niklas Baumstark below showed to be a bit faster for the simple cases. Not tested the method given by "Hooked" yet, since it is completely different approach (by the way it seems interesting).
The testing procedure for all of these could be really hard or impossible to be ensured of the results. The real data set I will use is so large and complex, so it is impossible to trace any error just by repeating. That is I need to be 100% satisfied of the reliability of the method before pushing it in its place within a large code as a module. Simply for now Niklas's method is faster and the answer for simple sets is correct of course.

However how can I be sure that it works well for real large data set? Since I will not be able to trace the errors visually!

Update 3:
Note that reliability of the method is much more important than speed for this problem. I will be hopefully able to translate the Python code to Fortran for the maximum performance finally.

Update 4:

There are many interesting points in this post and generously given answers, constructive comments. I would recommend reading all thoroughly. Please accept my appreciation for the development of the question, amazing answers and constructive comments and discussion.


问:
Re-render header after user logs in or logs out in react
so the question may seem a little confusing so let me explain,
this is my index file

```<code><Router>
   <Header />
   <Switch>
      <Route exact path="/" component={HomePage} >
      </Route>
      <Route exact path="/Login/:step?" component={Login}>
      </Route>
   </Switch>
</Router>
</code>```

and here is basically how i handle getting to homepage after user logs in

```<code>this.props.history.push("/")
</code>```

so the problem here is when i do that the header component doesn't re-render and cause of that i can't call my api inside componentDidMount() inside of header to update user information.

答:
Put Header in HomePage

and if you need put also in Login page.. but I don't think the login need the same header like in Homepage.

The main router component should be clean.

```<code><Router>
   <Switch>
      <Route exact path="/" component={HomePage} >
        <Header />
      </Route>
      <Route exact path="/Login/:step?" component={Login}>
        <Header />
      </Route>
   </Switch>
</Router>
</code>```

If your app is getting big for - update user information - think of using state management like Redux

Body:
so the question may seem a little confusing so let me explain,
this is my index file

<Router>

   <Switch>
      <Route exact path="/" component={HomePage} >
      </Route>
      <Route exact path="/Login/:step?" component={Login}>
      </Route>
   </Switch>
</Router>

and here is basically how i handle getting to homepage after user logs in

this.props.history.push("/")

so the problem here is when i do that the header component doesn't re-render and cause of that i can't call my api inside componentDidMount() inside of header to update user information.

Body:
Put Header in HomePage

and if you need put also in Login page.. but I don't think the login need the same header like in Homepage.

The main router component should be clean.

<Router>
   <Switch>
      <Route exact path="/" component={HomePage} >
        <Header />
      </Route>
      <Route exact path="/Login/:step?" component={Login}>
        <Header />
      </Route>
   </Switch>
</Router>

If your app is getting big for - update user information - think of using state management like Redux


问:
Locking the Aspect Ratio of an NSDocument's window
I have a document based application and I am trying to lock the aspect ratio of the document's window. The content of the document is a custom view which I can easily set an aspect ratio. However, when I resize the window, there is a black background that fills the space between the view and the window. I have tried overriding the aspectRatio of the window in my documents class however that does not seem to do the trick.

```<code>- (NSSize)aspectRatio {
    return NSMakeSize(600,480);
}
</code>```

I also tried setting the windows aspect ratio once the nib is loaded. This did the trick when my app was not document based.

```<code>[window setAspectRatio:window.frame.size];
</code>```

I have one more kicker... Assuming that I can lock in the window's aspect ratio, I want to override that when the user clicks the Zoom button to put the app at full screen. Then and only then will I want to fill the space between the view and the window.

I have been researching for quite sometime and just cannot find a solution.

答:
there is a black background that fills the space between the view and the window

Can’t you just set the window background to a different colour?

I have tried overriding the aspectRatio of the window in my documents class

In your subclass of NSDocument? If overriding -aspectRatio works, it should be in a subclass of NSWindow. However, you should use -setAspectRatio:.

I also tried setting the windows aspect ratio once the nib is loaded. This did the trick when my app was not document based.

This works regardless of the window belonging to a document- or non-document-based application.

I want to override that when the user clicks the Zoom button to put the app at full screen

You can have a window delegate that implements –windowShouldZoom:toFrame:, which is part of the NSWindowDelegate protocol.

Since the OP is developing a document-based application with no custom subclass of NSWindow or NSWindowController, implementing:

```<code>- (void)windowControllerDidLoadNib:(NSWindowController *)aController
{
    [super windowControllerDidLoadNib:aController];
    [[aController window] setAspectRatio:(NSSize){600,400}];
}
</code>```

in the NSDocument subclass is the only change needed to set the aspect ratio on a project based upon the document-based application template in Xcode.

In general, I’d advise against having a NSDocument subclass that is responsible for windows as well as documents. In my opinion, a better design is to have the NSDocument subclass deal with documents only, and create a subclass of NSWindowController that deals with windows only — think functional cohesion or the single responsibility principle.

Body:
I have a document based application and I am trying to lock the aspect ratio of the document's window. The content of the document is a custom view which I can easily set an aspect ratio. However, when I resize the window, there is a black background that fills the space between the view and the window. I have tried overriding the aspectRatio of the window in my documents class however that does not seem to do the trick.

- (NSSize)aspectRatio {
    return NSMakeSize(600,480);
}

I also tried setting the windows aspect ratio once the nib is loaded. This did the trick when my app was not document based.

[window setAspectRatio:window.frame.size];

I have one more kicker... Assuming that I can lock in the window's aspect ratio, I want to override that when the user clicks the Zoom button to put the app at full screen. Then and only then will I want to fill the space between the view and the window.

I have been researching for quite sometime and just cannot find a solution.

Body:
there is a black background that fills the space between the view and the window

Can’t you just set the window background to a different colour?

I have tried overriding the aspectRatio of the window in my documents class

In your subclass of NSDocument? If overriding -aspectRatio works, it should be in a subclass of NSWindow. However, you should use -setAspectRatio:.

I also tried setting the windows aspect ratio once the nib is loaded. This did the trick when my app was not document based.

This works regardless of the window belonging to a document- or non-document-based application.

I want to override that when the user clicks the Zoom button to put the app at full screen

You can have a window delegate that implements –windowShouldZoom:toFrame:, which is part of the NSWindowDelegate protocol.

Since the OP is developing a document-based application with no custom subclass of NSWindow or NSWindowController, implementing:

- (void)windowControllerDidLoadNib:(NSWindowController *)aController
{
    [super windowControllerDidLoadNib:aController];
    [[aController window] setAspectRatio:(NSSize){600,400}];
}

in the NSDocument subclass is the only change needed to set the aspect ratio on a project based upon the document-based application template in Xcode.

In general, I’d advise against having a NSDocument subclass that is responsible for windows as well as documents. In my opinion, a better design is to have the NSDocument subclass deal with documents only, and create a subclass of NSWindowController that deals with windows only — think functional cohesion or the single responsibility principle.


问:
Python ElementTree generate not well formed XML file with special character '\x0b'
I used ElementTree to generate xml with special character of '\x0b', then use minidom to parse it. It will throw not well-formed error.

import xml.etree.ElementTree as ET
from xml.dom import minidom
root = ET.Element('root')
root.text='\x0b'
xml = ET.tostring(root, 'UTF-8')
print(xml)
pretty_tree = minidom.parseString(xml)
```

<p><strong>Generated XML</strong>: <code><root>\x0b</root></code> </p>

<p><strong>Error</strong>: </p>

```Traceback (most recent call last):
  File "testXml.py", line 7, in <module>
    pretty_tree = minidom.parseString(xml)
  File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/xml/dom/minidom.py", line 1968, in parseString
    return expatbuilder.parseString(string)
  File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/xml/dom/expatbuilder.py", line 925, in parseString
    return builder.parseString(string)
  File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/xml/dom/expatbuilder.py", line 223, in parseString
    parser.Parse(string, True)
xml.parsers.expat.ExpatError: not well-formed (invalid token): line 1, column 6
```

答:
This behaviour has been raised as a bug in the past and resolved as "won't fix".

The author of the ElementTree module commented

For ET, [this behaviour is] very much on purpose.  Validating data provided by every
single application would kill performance for all of them, even if only a
small minority would ever try to serialize data that cannot be represented
in XML.

The closing comment (by the maintainer of lxml, who is also a Python core dev) includes these observations:

This is a tricky decision. lxml, for example, validates user input, but that's because it has to process it anyway and does it along the way directly on input (and very efficiently in C code). ET, on the other hand, is rather lenient about what it allows users to do and doesn't apply much processing to user input. It even allows invalid trees during processing and only expects the tree to be serialisable when requested to serialise it.

I think that's a fair behaviour, because most user input will be ok and shouldn't need to suffer the performance penalty of validating all input. Null-characters are a very rare thing to find in text, for example, and I think it's reasonable to let users handle the few cases by themselves where they can occur.

...

In the end, users who really care about correct output should run some kind of schema validation over it after serialisation, as that would detect not only data issues but also structural and logical issues (such as a missing or empty attribute), specifically for their target data format. In some cases, it might even detect random data corruption due to old non-ECC RAM in the server machine. :)

...

So in summary, ET.tostring will generate xml which is not well-formed, and this is by design.  If necessary, the output can be parsed to check that it is well-formed, using ET.fromstring or another parser.  Alternatively, lxml can be used instead of ElementTree.

Body:
I used ElementTree to generate xml with special character of '\x0b', then use minidom to parse it. It will throw not well-formed error.

import xml.etree.ElementTree as ET
from xml.dom import minidom
root = ET.Element('root')
root.text='\x0b'
xml = ET.tostring(root, 'UTF-8')
print(xml)
pretty_tree = minidom.parseString(xml)

Generated XML: <root>\x0b</root>

Error:

Traceback (most recent call last):
  File "testXml.py", line 7, in <module>
    pretty_tree = minidom.parseString(xml)
  File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/xml/dom/minidom.py", line 1968, in parseString
    return expatbuilder.parseString(string)
  File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/xml/dom/expatbuilder.py", line 925, in parseString
    return builder.parseString(string)
  File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/xml/dom/expatbuilder.py", line 223, in parseString
    parser.Parse(string, True)
xml.parsers.expat.ExpatError: not well-formed (invalid token): line 1, column 6


问:
Docker images disappearing over time
I loaded some docker images running

```<code>docker load --input <file>
</code>```

I can then see these images when executing

```<code>docker image ls
</code>```

After a while images start disappearing. Every few minutes there are less and less images listed. I did not run any of images yet. What could be the cause of this issue?

EDIT: This issue arises with docker inside minikube VM.

答:
As mention in @mk_sta answer to fix issue you need:

Create or edit /var/lib/kubelet/config.yaml with

```<code>apiVersion: kubelet.config.k8s.io/v1beta1
kind: KubeletConfiguration
evictionHard:
    imagefs.available: "5%"
</code>```

Default value is 15%

```<code>minikube stop
minikube start --extra-config=kubelet.config=/var/lib/kubelet/config.yaml
</code>```

Or free more space on docker partition.

https://kubernetes.io/docs/tasks/administer-cluster/kubelet-config-file/#create-the-config-file

https://kubernetes.io/docs/tasks/administer-cluster/out-of-resource/#hard-eviction-thresholds

Title: Docker images disappearing over time

Body:
I loaded some docker images running

docker load --input <file>

I can then see these images when executing

docker image ls

After a while images start disappearing. Every few minutes there are less and less images listed. I did not run any of images yet. What could be the cause of this issue?

EDIT: This issue arises with docker inside minikube VM.

Body:
As mention in @mk_sta answer to fix issue you need:

Create or edit /var/lib/kubelet/config.yaml with

apiVersion: kubelet.config.k8s.io/v1beta1
kind: KubeletConfiguration
evictionHard:
    imagefs.available: "5%"

Default value is 15%

minikube stop
minikube start --extra-config=kubelet.config=/var/lib/kubelet/config.yaml

Or free more space on docker partition.

https://kubernetes.io/docs/tasks/administer-cluster/kubelet-config-file/#create-the-config-file

https://kubernetes.io/docs/tasks/administer-cluster/out-of-resource/#hard-eviction-thresholds


问:
Prevent recalculations of User Defined Functions used in named ranges
I have three UDF's:

```<code>Private Function IsInArray(stringToBeFound As Variant, arr As Variant) As Boolean
    IsInArray = Not IsError(Application.Match(stringToBeFound, arr, 0))
End Function
</code>```

This function checks if something is in the array.

```<code>Private Function data_to_array(data As Range)

Dim arrArray As Variant
Dim cell As Range
Dim z As Integer

z = 0

ReDim arrArray(1 To data.Cells.Count)
For Each cell In data
    z = z + 1
    arrArray(z) = cell.Value
Next cell

data_to_array = arrArray
End Function
</code>```

This function extracts selected range values and puts them into an array.

```<code>Private Function plot_vals(data As Variant, custom_arr As Variant)

Dim arrPlot As Variant
ReDim arrPlot(1 To UBound(data)) As Variant
Dim c As Integer
Dim cl As Integer

cl = 0

For c = 1 To UBound(data)
    cl = cl + 1
    If IsInArray(cl, custom_arr) Then
        arrPlot(cl) = data(cl)
    Else
        arrPlot(cl) = CVErr(xlErrNA)
    End If
Next c

plot_vals = arrPlot
End Function
</code>```

The last UDF loops through the data array from second UDF and if index/position of value in data_array is in custom_array, then it returns its value. Otherwise it puts an error into an array.

Data looks like this:

These functions are used like this in Excel:

data_to_array(A1:A5) - this UDF creates an array(1 to 5) with values from cells A1:A5.

plot_vals(data_to_array(A1:A5), {1,5}) - this UDF creates an array(1 to 5), and uses second argument to retrieve first and fifth values while putting errors in the other indexes. The result is array of for example: {5,error,error,error,1}

If I used the function on above data like this: plot_vals(data_to_array(A1:A5), {1,2}) then the result would be an array {5,4,error,error,error}

That plot_vals UDF is used in named range and that named range is used to plot values on chart.
Data is stored in named range myData and the function in second named range is used like this:
plot_vals(myData,{1,5}).

Everything works, I can plot it on chart, all is good but when the named ranges are used on charts, every time I change something in my workbook all functions are recalculated like... 10 times each one, instead of once. It causes Excel to slow down/freeze if those functions are used many times. I have tried to search about function volatility and how to turn it off (it should be turned off by default?), but nothing seems to be working and I do not know how to stop that from happening. I have tried to recreate this in Excel using standard Excel functions in named ranges, but I cannot find a correct function to do what I want. UDF is exactly what I need.

When these named ranges are NOT used in charts then nothing happens, but as soon as I use the named range on chart then it recalculates everything on even a minor change of a workbook. Minor change meaning - copying / pasting / adding rows etc.

How can I stop that from happening? How to recalculate UDF's only once?

EDIT on further research:

I have tried the potential solutions provided by Charles Williams:
https://fastexcel.wordpress.com/2011/11/25/writing-efficient-vba-udfs-part-7-udfs-calculated-multiple-times/

His potential solutions do not change anything.

I have also tried using Sheet_Change event, changing calculations to manual and then back to automatic. It helps but it clears the clipboard (unacceptable) and it causes issues with my other macros, so it is a "no-go" solution.

It is also worth noting, that as soon as the chart is deleted and the UDF's remain in named ranges, everything is working nice and smooth. But when those named ranges are in chart series formulas, everything is recalculating 100's of times.

答:
You should be able to prevent unnecessary additional calculations by including

```<code>Application.EnableEvent = False
Application.Calculation = xlManual
</code>```

at the start of your functions and

```<code>Application.EnableEvents = True
Application.Calculation = xlAutomatic
</code>```

at the end of your functions. This prevents your spreadsheet from attempting to update and recalculate whenever you make a minor change. If you feel it necessary, you can add

```<code>Worksheet.Calculate
</code>```

at some point in your code to force a recalculation of the current sheet.

Body:
I have three UDF's:

Private Function IsInArray(stringToBeFound As Variant, arr As Variant) As Boolean
    IsInArray = Not IsError(Application.Match(stringToBeFound, arr, 0))
End Function

This function checks if something is in the array.

Private Function data_to_array(data As Range)

Dim arrArray As Variant
Dim cell As Range
Dim z As Integer

z = 0

ReDim arrArray(1 To data.Cells.Count)
For Each cell In data
    z = z + 1
    arrArray(z) = cell.Value
Next cell

data_to_array = arrArray
End Function

This function extracts selected range values and puts them into an array.

Private Function plot_vals(data As Variant, custom_arr As Variant)

Dim arrPlot As Variant
ReDim arrPlot(1 To UBound(data)) As Variant
Dim c As Integer
Dim cl As Integer

cl = 0

For c = 1 To UBound(data)
    cl = cl + 1
    If IsInArray(cl, custom_arr) Then
        arrPlot(cl) = data(cl)
    Else
        arrPlot(cl) = CVErr(xlErrNA)
    End If
Next c

plot_vals = arrPlot
End Function

The last UDF loops through the data array from second UDF and if index/position of value in data_array is in custom_array, then it returns its value. Otherwise it puts an error into an array.

Data looks like this:

These functions are used like this in Excel:

data_to_array(A1:A5) - this UDF creates an array(1 to 5) with values from cells A1:A5.

plot_vals(data_to_array(A1:A5), {1,5}) - this UDF creates an array(1 to 5), and uses second argument to retrieve first and fifth values while putting errors in the other indexes. The result is array of for example: {5,error,error,error,1}

If I used the function on above data like this: plot_vals(data_to_array(A1:A5), {1,2}) then the result would be an array {5,4,error,error,error}

That plot_vals UDF is used in named range and that named range is used to plot values on chart.
Data is stored in named range myData and the function in second named range is used like this:
plot_vals(myData,{1,5}).

Everything works, I can plot it on chart, all is good but when the named ranges are used on charts, every time I change something in my workbook all functions are recalculated like... 10 times each one, instead of once. It causes Excel to slow down/freeze if those functions are used many times. I have tried to search about function volatility and how to turn it off (it should be turned off by default?), but nothing seems to be working and I do not know how to stop that from happening. I have tried to recreate this in Excel using standard Excel functions in named ranges, but I cannot find a correct function to do what I want. UDF is exactly what I need.

When these named ranges are NOT used in charts then nothing happens, but as soon as I use the named range on chart then it recalculates everything on even a minor change of a workbook. Minor change meaning - copying / pasting / adding rows etc.

How can I stop that from happening? How to recalculate UDF's only once?

EDIT on further research:

I have tried the potential solutions provided by Charles Williams:
https://fastexcel.wordpress.com/2011/11/25/writing-efficient-vba-udfs-part-7-udfs-calculated-multiple-times/

His potential solutions do not change anything.

I have also tried using Sheet_Change event, changing calculations to manual and then back to automatic. It helps but it clears the clipboard (unacceptable) and it causes issues with my other macros, so it is a "no-go" solution.

It is also worth noting, that as soon as the chart is deleted and the UDF's remain in named ranges, everything is working nice and smooth. But when those named ranges are in chart series formulas, everything is recalculating 100's of times.

Body:
You should be able to prevent unnecessary additional calculations by including

Application.EnableEvent = False
Application.Calculation = xlManual

at the start of your functions and

Application.EnableEvents = True
Application.Calculation = xlAutomatic

at the end of your functions. This prevents your spreadsheet from attempting to update and recalculate whenever you make a minor change. If you feel it necessary, you can add

Worksheet.Calculate

at some point in your code to force a recalculation of the current sheet.


问:
Intellij (java) run/debug configuration "No main class not specified" Azure Functions
I have a Intellij Java project with an Azure Functions HttpTrigger in it (API endpoint, basically).

I have some environment variables that I wanted to add to the Run/Debug Configuration on IntelliJ via the Run > Edit Configurations > Application on the main toolbar at the top. I wanted to pass the environment variables here, so I don't have to save them inside Windows, but its saying "no main class is specified" but I don't have any main method here (public static void main(String[] args)) because this is just a repo with an Azure function inside of it.

How can I launch this configuration and bypass this message? If I'm able to bypass this, and starting up this project by running func start in the terminal, should that command go in the VM options box?

答:
Just as @Andrey said in the comment, run configuration is meant to be used for running applications that have public static void main(String[] args)) method. That's why you got No Main class specified error.

If you want to add environment variables, you can add them to local.settings.json file. They are stored in the environment variables.

Reference:

Create your first Azure function with Java and IntelliJ

https://medium.com/awesome-azure/azure-reading-application-settings-in-azure-functions-asp-net-core-1dea56cf67cf


问:
Network File share access on GKE cluster - Windows node pool
We are Containerizing dotnet application on GKE cluster(Windows node-pool). We have a requirement, where multiple pods can access same shared space(persistent volume). Also it should support "ReadWriteMany" AccessMode. We have explored below option:

GCE Persistent disk accessed by Persistent volume.(It doesn't support ReadWriteMany. Only one pod can access the disk).

Network File Share(NFS). Currently not supported for windows node pools.

Filestore fits the solutions but expensive and managed by google.

We are looking other options to fit our requirement. Please help.

答:
I've been trying to solve the same problem - accessing shared filesystem from 2 Windows pods (ASP.NET application on IIS + console application). I wasn't able to use the Filestore because it requires an NFSClient (Install-WindowsFeature NFS-Client) and I couldn't install it into the containers (during container build or runtime) since it requires a computer restart - maybe i'm missing sth here.

The options I've found:

If you need to create a simple temporary demo application that can run on single VM you can run both pods on a single instance, create a Persistent Disk, attach it to the instance with gcloud compute instances attach-disk, RDP into the instance, mount the disk and provide the disk to the pods as a hostPath.
That's the solution I'm using now.

Create an SMB share (on a separate VM or using a Docker container https://hub.docker.com/r/dperson/samba/ and access it from the pods using New-SmbMapping -LocalPath $shareletter -RemotePath $dhcpshare -Username $shareuser -Password $sharepasswd -Persistent $true. This solution worked for my console application but the web application couldn't access the files (even though I've set the application pool on IIS to run as Local System). The SMB could also be mounted from the instance using the New-SmbGlobalMapping - the flexvolume does that https://github.com/microsoft/K8s-Storage-Plugins/tree/master/flexvolume/windows. I haven't explored that option and I think it would have the same problem (IIS not seeing the files).

I think the best (most secure and reliable) solution would be to setup an Active Directory Domain Controller and SMB share on separate VM and provide access to it to the containers using gMSA: https://learn.microsoft.com/en-us/virtualization/windowscontainers/manage-containers/manage-serviceaccounts
https://kubernetes.io/docs/tasks/configure-pod-container/configure-gmsa/
That doesn't seem easy though.


问:
Subtraction without minus sign in C
How can I subtract two integers in C without the - operator?

答:
Iff:

The Minuend is greater or equal to 0, or

The Subtrahend is greater or equal to 0, or

The Subtrahend and the Minuend are less than 0

multiply the Minuend by -1 and add the result to the Subtrahend:

```<code>SUB + (MIN * -1)
</code>```

Else multiply the Minuend by 1 and add the result to the Subtrahend.

```<code>SUB + (MIN * 1)
</code>```

Example (Try it online):

```<code>#include <stdio.h>

int subtract (int a, int b)
{
    if ( a >= 0 || b >= 0 || ( a < 0 && b < 0 ) )
    {
        return a + (b * -1);
    }

    return a + (b * 1);
}

int main (void)
{
    int x = -1;
    int y = -5;
    printf("%d - %d = %d", x, y, subtract(x, y) );
}
</code>```

Output:

```<code>-1 - -5 = 4
</code>```

OwnerDisplayName: pragadheesh

Title: Subtraction without minus sign in C

LastEditorDisplayName: David Schmitt

Body:
Iff:

The Minuend is greater or equal to 0, or

The Subtrahend is greater or equal to 0, or

The Subtrahend and the Minuend are less than 0

multiply the Minuend by -1 and add the result to the Subtrahend:

SUB + (MIN * -1)

Else multiply the Minuend by 1 and add the result to the Subtrahend.

SUB + (MIN * 1)

Example (Try it online):

#include <stdio.h>

int subtract (int a, int b)
{
    if ( a >= 0 || b >= 0 || ( a < 0 && b < 0 ) )
    {
        return a + (b * -1);
    }

    return a + (b * 1);
}

int main (void)
{
    int x = -1;
    int y = -5;
    printf("%d - %d = %d", x, y, subtract(x, y) );
}

Output:

-1 - -5 = 4


问:
Symfony route redirection based on roles
I am trying to redirect the route based on the Role after registration / login. After the registration, I am redirecting the route to this secure_area, to route according to the user roles.

```<code>/**
 * @Route("/secure", name="secure_area")
 *
 * @throws \Exception
 */
public function indexAction()
{
    if ($this->isGranted('ROLE_USER1')) {
        return $this->redirectToRoute('user1');
    }

    if ($this->isGranted('ROLE_USER2')) {
        return $this->redirectToRoute('user2');
    }
    throw new \Exception(AccessDeniedException::class);
}
</code>```

In both cases, I am landing to the route user1. How can I make it redirect the route according to the user roles?

security.yaml

```<code>role_hierarchy:
    ROLE_ADMIN: ROLE_USER2
    ROLE_USER2: ROLE_USER1
    ROLE_USER1: ROLE_USER1
access_control:
    - { path: ^/admin, roles: ROLE_ADMIN }
    - { path: ^/user2, roles: ROLE_USER2 }
    - { path: ^/user1, roles: ROLE_USER1 }
</code>```

答:
```<code><?php

// Change the namespace according to the location of this class in your bundle
namespace AppBundle\Listeners;

use FOS\UserBundle\Model\UserManagerInterface;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Routing\Router;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;

class LoginListener
{
    protected $userManager;
    protected $router;
    protected $security;
    protected $dispatcher;

    public function __construct(UserManagerInterface $userManager, Router $router, SecurityContext $security, EventDispatcher $dispatcher)
    {
        $this->userManager = $userManager;
        $this->router = $router;
        $this->security = $security;
        $this->dispatcher = $dispatcher;
    }

    public function onSecurityInteractiveLogin(InteractiveLoginEvent $event)
    {
        $this->dispatcher->addListener(KernelEvents::RESPONSE, array($this, 'onKernelResponse'));
    }

    public function onKernelResponse(FilterResponseEvent $event)
    {
        // Important: redirect according to user Role
        if ($this->security->isGranted('ROLE_ADMIN')) {
            $event->setResponse(new RedirectResponse($this->router->generate("admin_homepage")));
        } elseif ($this->security->isGranted('ROLE_MANAGER')) {
            $event->setResponse(new RedirectResponse($this->router->generate("manager_homepage")));
        } else {
            $event->setResponse(new RedirectResponse($this->router->generate("default_homepage")));
        }
    }
}
</code>```

You can implement LoginListener like this that will handle your role based redirection.

Body:
I am trying to redirect the route based on the Role after registration / login. After the registration, I am redirecting the route to this secure_area, to route according to the user roles.

/**
 * @Route("/secure", name="secure_area")
 *
 * @throws \Exception
 */
public function indexAction()
{
    if ($this->isGranted('ROLE_USER1')) {
        return $this->redirectToRoute('user1');
    }

    if ($this->isGranted('ROLE_USER2')) {
        return $this->redirectToRoute('user2');
    }
    throw new \Exception(AccessDeniedException::class);
}

In both cases, I am landing to the route user1. How can I make it redirect the route according to the user roles?

security.yaml

role_hierarchy:
    ROLE_ADMIN: ROLE_USER2
    ROLE_USER2: ROLE_USER1
    ROLE_USER1: ROLE_USER1
access_control:
    - { path: ^/admin, roles: ROLE_ADMIN }
    - { path: ^/user2, roles: ROLE_USER2 }
    - { path: ^/user1, roles: ROLE_USER1 }

Body:
<?php

// Change the namespace according to the location of this class in your bundle
namespace AppBundle\Listeners;

use FOS\UserBundle\Model\UserManagerInterface;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Routing\Router;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;

class LoginListener
{
    protected $userManager;
    protected $router;
    protected $security;
    protected $dispatcher;

    public function __construct(UserManagerInterface $userManager, Router $router, SecurityContext $security, EventDispatcher $dispatcher)
    {
        $this->userManager = $userManager;
        $this->router = $router;
        $this->security = $security;
        $this->dispatcher = $dispatcher;
    }

    public function onSecurityInteractiveLogin(InteractiveLoginEvent $event)
    {
        $this->dispatcher->addListener(KernelEvents::RESPONSE, array($this, 'onKernelResponse'));
    }

    public function onKernelResponse(FilterResponseEvent $event)
    {
        // Important: redirect according to user Role
        if ($this->security->isGranted('ROLE_ADMIN')) {
            $event->setResponse(new RedirectResponse($this->router->generate("admin_homepage")));
        } elseif ($this->security->isGranted('ROLE_MANAGER')) {
            $event->setResponse(new RedirectResponse($this->router->generate("manager_homepage")));
        } else {
            $event->setResponse(new RedirectResponse($this->router->generate("default_homepage")));
        }
    }
}

You can implement LoginListener like this that will handle your role based redirection.


问:
The code is running through all loops despite if statements
I'm using ejs. No matter what my statement returns(no matter what currentGame is), my output is always 12. I've tried implementing break; or return; and tried using other loops like switch case or while, but it didn't help.

If I make console.log in each loop, I get {1, 2, 3...12} as output.

"<%var x%>"

  "<%for(var i=1; i<=12; i++){%>"
  if(currentGame === "<%=i%>"){
      "<%x=i;%>"
  }

"<%}%>"
console.log("<%=x%>")
```

<p>And the resulting code I get in my browser is:</p>

```        ""

  ""
  if(currentGame === "1"){
      ""
  }

""
  if(currentGame === "2"){
      ""
  }

""
  if(currentGame === "3"){
      ""
  }

""
  if(currentGame === "4"){
      ""
  }

""
  if(currentGame === "5"){
      ""
  }

""
  if(currentGame === "6"){
      ""
  }

""
  if(currentGame === "7"){
      ""
  }

""
  if(currentGame === "8"){
      ""
  }

""
  if(currentGame === "9"){
      ""
  }

""
  if(currentGame === "10"){
      ""
  }

""
  if(currentGame === "11"){
      ""
  }

""
  if(currentGame === "12"){
      ""
  }

""
console.log("12")
```

答:
The problem is that your code is assigning to your server-side x variable unconditionally, here:

```<code>"<%var x%>"

"<%for(var i=1; i<=12; i++){%>"
if(currentGame === "<%=i%>"){
    "<%x=i;%>" // <===================================
}

"<%}%>"
console.log("<%=x%>")
</code>```

The if is client-side code, it doesn't have any effect on the server-side logic. The server-side logic in that code looks like this:

```<code>var x

for(var i=1; i<=12; i++){
    x=i;
}
</code>```

Which is the problem. x will always be 12.

Stepping back, though, from the specific code you've posted: Using server-side code to generate client-side code is almost never a good idea. Instead, write your client code and your server code separately, so this kind of confusion doesn't arise.

Body:
I'm using ejs. No matter what my statement returns(no matter what currentGame is), my output is always 12. I've tried implementing break; or return; and tried using other loops like switch case or while, but it didn't help.

If I make console.log in each loop, I get {1, 2, 3...12} as output.

"<%var x%>"

  "<%for(var i=1; i<=12; i++){%>"
  if(currentGame === "<%=i%>"){
      "<%x=i;%>"
  }

"<%}%>"
console.log("<%=x%>")

And the resulting code I get in my browser is:

        ""

  ""
  if(currentGame === "1"){
      ""
  }

""
  if(currentGame === "2"){
      ""
  }

""
  if(currentGame === "3"){
      ""
  }

""
  if(currentGame === "4"){
      ""
  }

""
  if(currentGame === "5"){
      ""
  }

""
  if(currentGame === "6"){
      ""
  }

""
  if(currentGame === "7"){
      ""
  }

""
  if(currentGame === "8"){
      ""
  }

""
  if(currentGame === "9"){
      ""
  }

""
  if(currentGame === "10"){
      ""
  }

""
  if(currentGame === "11"){
      ""
  }

""
  if(currentGame === "12"){
      ""
  }

""
console.log("12")

Body:
The problem is that your code is assigning to your server-side x variable unconditionally, here:

"<%var x%>"

"<%for(var i=1; i<=12; i++){%>"
if(currentGame === "<%=i%>"){
    "<%x=i;%>" // <===================================
}

"<%}%>"
console.log("<%=x%>")

The if is client-side code, it doesn't have any effect on the server-side logic. The server-side logic in that code looks like this:

var x

for(var i=1; i<=12; i++){
    x=i;
}

Which is the problem. x will always be 12.

Stepping back, though, from the specific code you've posted: Using server-side code to generate client-side code is almost never a good idea. Instead, write your client code and your server code separately, so this kind of confusion doesn't arise.


问:
Retrieve email IDs from the Azure AD group using
I have AD groups created and is in Azure. Examples of the Azure AD group name is something like this Azure_ABC_XYZ_DEV, Azure_ABC_XYZ_Test etc... There are multiple different members with in each of the groups. I need to retrieve those member's email IDs and then need to send email based on certain conditions. I cannot use Azure AD connector available in logic apps to retrieve group members due to some company reasons. To send email I will be using SMTP connector(Which is fine). So, I will  have to use Azure function/Microsoft graph using C# to fetch those email IDs. Can some one please guide me how to do this. May be step by step approach for the code. Thanks in Advance! Help is much appreciated.
enter image description here</p>

答:
You can List members of a group. There is a mail property that is what you want.

```<code>GraphServiceClient graphClient = new GraphServiceClient( authProvider );

var members = await graphClient.Groups["{id}"].Members
    .Request()
    .GetAsync();
</code>```

Then you could Send mail to the email addresses you get from the previous step.

```<code>GraphServiceClient graphClient = new GraphServiceClient( authProvider );

var message = new Message
{
    Subject = "Meet for lunch?",
    Body = new ItemBody
    {
        ContentType = BodyType.Text,
        Content = "The new cafeteria is open."
    },
    ToRecipients = new List<Recipient>()
    {
        new Recipient
        {
            EmailAddress = new EmailAddress
            {
                Address = "fannyd@contoso.onmicrosoft.com"
            }
        }
    },
    CcRecipients = new List<Recipient>()
    {
        new Recipient
        {
            EmailAddress = new EmailAddress
            {
                Address = "danas@contoso.onmicrosoft.com"
            }
        }
    }
};

var saveToSentItems = false;

await graphClient.Me
    .SendMail(message,saveToSentItems)
    .Request()
    .PostAsync();
</code>```

Body:
You can List members of a group. There is a mail property that is what you want.

GraphServiceClient graphClient = new GraphServiceClient( authProvider );

var members = await graphClient.Groups["{id}"].Members
    .Request()
    .GetAsync();

Then you could Send mail to the email addresses you get from the previous step.

GraphServiceClient graphClient = new GraphServiceClient( authProvider );

var message = new Message
{
    Subject = "Meet for lunch?",
    Body = new ItemBody
    {
        ContentType = BodyType.Text,
        Content = "The new cafeteria is open."
    },
    ToRecipients = new List<Recipient>()
    {
        new Recipient
        {
            EmailAddress = new EmailAddress
            {
                Address = "fannyd@contoso.onmicrosoft.com"
            }
        }
    },
    CcRecipients = new List<Recipient>()
    {
        new Recipient
        {
            EmailAddress = new EmailAddress
            {
                Address = "danas@contoso.onmicrosoft.com"
            }
        }
    }
};

var saveToSentItems = false;

await graphClient.Me
    .SendMail(message,saveToSentItems)
    .Request()
    .PostAsync();


问:
Parsing a tab-delimited text file to replace columns with one vertical list (Python)
I'm very new to Python and I know this is a pretty basic question. I have a text file with columns of data. I want to remove the columns and make it one long list.

I have the following code:

```<code>for line in open('feddocs_2011.txt', 'r'):
    segmentedLine = line.split("/t")
    print segmentedLine
</code>```

This seems to create a separate string for each line, but I think I may need to loop through each of those new strings to split those next. I thought it would have put everything following a tab on a new line. I tried the following, but got an error message that "list" doesn't have a split function.

```<code>while segmentedLine:
    item = segmentedLine.split("\t")
    print item
</code>```

Thanks very much for any input.

答:
if I understand correctly, what you're after is:</p>

```<code>import itertools
print '\n'.join(list(itertools.chain(*[line.strip().split(',') for line in open('feddocs_2011.txt', 'r')])))
</code>```

Body:
I'm very new to Python and I know this is a pretty basic question. I have a text file with columns of data. I want to remove the columns and make it one long list.

I have the following code:

for line in open('feddocs_2011.txt', 'r'):
    segmentedLine = line.split("/t")
    print segmentedLine

This seems to create a separate string for each line, but I think I may need to loop through each of those new strings to split those next. I thought it would have put everything following a tab on a new line. I tried the following, but got an error message that "list" doesn't have a split function.

while segmentedLine:
    item = segmentedLine.split("\t")
    print item

Thanks very much for any input.

Body:
if I understand correctly, what you're after is:

import itertools
print '\n'.join(list(itertools.chain(*[line.strip().split(',') for line in open('feddocs_2011.txt', 'r')])))


问:
Generate Signed Bundle: Errors while building Bundle file. 'other' has different root
The following error occur when I tried to Generate Signed Bundle. Note: Error occurs after I updated my android studio 3.6.3 to version 4.0 and Gradle build to 6.1.1.
* What went wrong:
Execution failed for task ':app:signReleaseBundle'.

A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
  'other' has different root

答:
Same here. Looks like it does not like to build to another drive letter.
i.e. Key store path is on D: and destination folder on E: and I get the message 'other' has different root. Note that the file seems to be produced on E: anyway.
When I change destination folder to D: it's all ok.</p>


问:
Mails sent by PHPMailer becomes spam
```<code>$mail = new PHPMailer(true);
            try {
                //Server settings
                $mail->AddReplyTo('from@from.com','Post');
                $mail->SMTPDebug = 1;
                $mail->isSMTP();
                $mail->Host = 'smtp.example.com';
                $mail->SMTPAuth = true;
                $mail->SMTPSecure = 'ssl';
                $mail->Username = 'from@from.com';
                $mail->Password = 'loginPassword';
                $mail->Port = 465;
                $mail->isHTML(true);

                $mail->setFrom('from@from.com,'Name');
                $mail->addAddress('to@to.com', 'Name');

                //Content
                $mail->isHTML(true);
                $mail->Subject = $mailSub;
                $mail->Body    = $mailMsg;
                $mail->AltBody = $mailMsgAlt;

                $mail->send();
                echo "Mail sent!;
            }catch (Exception $e){
                echo "Mail not sent! Try again.";
            }
</code>```

This is how my code looks like, ofc the $mailSub, $mailMsg, $mailMsgAlt variables are defined!
Can you help me please, I can't find why the mails always go to the spam folder.

答:
The mail is put into spam folder by the recipient mail handler and it doesn't depend on the sender ( but actually it does and we'll look at it ).

A mail is marked as spam depending on the previous feedback from other mass users or same user. But internally, if the mail is not sent through a trusted mail redirector, with proper certification and encryption, it will be marked as spam.

A trusted mail redirector is who authenticates the email id of the sender, as the receiver can't do it. In this case, we can use whatever from address we want, but the mail redirector won't check whether we actually own that email id. So it is not a trusted mail redirector.

For example, if you are using Gmail API for sending an email, you will have a unique API key to prove that you are the owner of the from address you use. If the API key is wrong, you will get an error and the email won't be sent. That way, spam emails are prevented.

Title: Mails sent by PHPMailer becomes spam

Body:
$mail = new PHPMailer(true);
            try {
                //Server settings
                $mail->AddReplyTo('from@from.com','Post');
                $mail->SMTPDebug = 1;
                $mail->isSMTP();
                $mail->Host = 'smtp.example.com';
                $mail->SMTPAuth = true;
                $mail->SMTPSecure = 'ssl';
                $mail->Username = 'from@from.com';
                $mail->Password = 'loginPassword';
                $mail->Port = 465;
                $mail->isHTML(true);

                $mail->setFrom('from@from.com,'Name');
                $mail->addAddress('to@to.com', 'Name');

                //Content
                $mail->isHTML(true);
                $mail->Subject = $mailSub;
                $mail->Body    = $mailMsg;
                $mail->AltBody = $mailMsgAlt;

                $mail->send();
                echo "Mail sent!;
            }catch (Exception $e){
                echo "Mail not sent! Try again.";
            }

This is how my code looks like, ofc the $mailSub, $mailMsg, $mailMsgAlt variables are defined!
Can you help me please, I can't find why the mails always go to the spam folder.


问:
How to get to root and then execute shell commands in Python3 on Ubuntu?
I am running some shell commands with os.system that needs to be run as root.

I tried-

```<code>os.system("sudo su")
os.system("other commands")
</code>```

and also-

```<code>home_dir = os.system("sudo su")
os.system("other commands")
</code>```

But both the above scripts just become root and then stop executing, so the rest of my commands aren't executed.

I'm running Python 3.6.9 on an Ubuntu 18.04 VM.

答:
The root privileges gained by sudo only apply to the command that is run through sudo, and do not raise the privileges of the caller (in this case, your python script). So your first command os.system("sudo su") would run an interactive root shell, but after you have exited from that and then your python code does the subsequent call to os.system("other commands"), these will run under its ordinary user privileges.

You could run each command one at a time via sudo:

```<code>os.system("sudo some_command")
os.system("sudo some_other_command")
</code>```

Note that each command will be separately logged by sudo in the system log, and that even if there are several commands, sudo shouldn't ask for a password more than once within a short time interval.

Or if you need to do a sequence of steps like changing directories that might not be possible in the caller (for example, if the directory is not accessible by the non-root user that is running the python script), then you could do for example:

```<code>os.system("sudo sh -c 'cd some_dir && some_other_command'")
</code>```

(Just for info, && is similar to ; but the other command is only run if the cd succeeded, so it is safer, although this point relates to shell syntax rather than python.)

If there are a lot of commands, of course you also have the option of just making a separate "helper" shell-script and running the entire script through sudo.

```<code>os.system("sudo sh /path/to/myscript.sh")
</code>```

Finally to note, if you are running your python script in a non-interactive environment, you may need to tell sudo not to prompt for a password, at least for the relevant invoking user and target commands.  For details, do man sudoers and look for examples involving NOPASSWD.

Body:
I am running some shell commands with os.system that needs to be run as root.

I tried-

os.system("sudo su")
os.system("other commands")

and also-

home_dir = os.system("sudo su")
os.system("other commands")

But both the above scripts just become root and then stop executing, so the rest of my commands aren't executed.

I'm running Python 3.6.9 on an Ubuntu 18.04 VM.

Body:
The root privileges gained by sudo only apply to the command that is run through sudo, and do not raise the privileges of the caller (in this case, your python script). So your first command os.system("sudo su") would run an interactive root shell, but after you have exited from that and then your python code does the subsequent call to os.system("other commands"), these will run under its ordinary user privileges.

You could run each command one at a time via sudo:

os.system("sudo some_command")
os.system("sudo some_other_command")

Note that each command will be separately logged by sudo in the system log, and that even if there are several commands, sudo shouldn't ask for a password more than once within a short time interval.

Or if you need to do a sequence of steps like changing directories that might not be possible in the caller (for example, if the directory is not accessible by the non-root user that is running the python script), then you could do for example:

os.system("sudo sh -c 'cd some_dir && some_other_command'")

(Just for info, && is similar to ; but the other command is only run if the cd succeeded, so it is safer, although this point relates to shell syntax rather than python.)

If there are a lot of commands, of course you also have the option of just making a separate "helper" shell-script and running the entire script through sudo.

os.system("sudo sh /path/to/myscript.sh")

Finally to note, if you are running your python script in a non-interactive environment, you may need to tell sudo not to prompt for a password, at least for the relevant invoking user and target commands.  For details, do man sudoers and look for examples involving NOPASSWD.


问:
How do I change the width of the country picker in flutter?

I am implementing country code picker and mobile number field.

How do I change the size of the country picker so that both the country picker and the mobile number text field are properly place.

Code is as follow

```<code>Row(
                      children: <Widget>[
                        Expanded(
                          //SizedBox(height: 20.0),
                          child: CountryPicker(
                            dense: true,
                            showFlag: false, //displays flag, true by default
                            showDialingCode:true, //displays dialing code, false by default
                            showName: true, //displays country name, true by default
                            showCurrency: false, //eg. 'British pound'
                            showCurrencyISO: false,
                            onChanged: (Country country) {
                              setState(() => _selected = country);
                              print(country.dialingCode);
                              countryCode = country.dialingCode;
                              },
                            selectedCountry: _selected,
                          ),
                        ),
                        Expanded(
                          //SizedBox(height: 20.0),
                          child: TextFormField(
                            decoration: InputDecoration(
                              labelText: 'Mobile no.',
                              border: OutlineInputBorder(),
                            ),
                            validator: (val) => val.length != 10
                                ? 'Enter a mobile number of 10 digits'
                                : null,
                            onChanged: (val) {
                              setState(() => phone = val);
                              phoneno = phone;
                              },
                          ),
                        ),
                      ],
                    ),
</code>```

Image is attached below

答:
Give first Expanded widget the flex value of 1 and second Expanded 3.

What happens is that the width gets divided into 4 equal parts (1+3), and 1 part is occupied by the first Expanded widget, and the remaining 3 parts get occupied by second Expanded widget. You can play around various proportions to meet your UI needs.

```<code>
Row(
            children: <Widget>[
              Expanded(
                flex: 1,
                //SizedBox(height: 20.0),
                child: CountryPicker(
                  dense: true,
                  showFlag: false, //displays flag, true by default
                  showDialingCode:
                      true, //displays dialing code, false by default
                  showName: true, //displays country name, true by default
                  showCurrency: false, //eg. 'British pound'
                  showCurrencyISO: false,
                  onChanged: (Country country) {
                    setState(() => _selected = country);
                    print(country.dialingCode);
                    countryCode = country.dialingCode;
                  },
                  selectedCountry: _selected,
                ),
              ),
              Expanded(
                flex: 3,
                //SizedBox(height: 20.0),
                child: TextFormField(
                  decoration: InputDecoration(
                    labelText: 'Mobile no.',
                    border: OutlineInputBorder(),
                  ),
                  validator: (val) => val.length != 10
                      ? 'Enter a mobile number of 10 digits'
                      : null,
                  onChanged: (val) {
                    setState(() => phone = val);
                    phoneno = phone;
                  },
                ),
              ),
            ],
          ),
</code>```

Body:
I am implementing country code picker and mobile number field.

How do I change the size of the country picker so that both the country picker and the mobile number text field are properly place.

Code is as follow

Row(
                      children: <Widget>[
                        Expanded(
                          //SizedBox(height: 20.0),
                          child: CountryPicker(
                            dense: true,
                            showFlag: false, //displays flag, true by default
                            showDialingCode:true, //displays dialing code, false by default
                            showName: true, //displays country name, true by default
                            showCurrency: false, //eg. 'British pound'
                            showCurrencyISO: false,
                            onChanged: (Country country) {
                              setState(() => _selected = country);
                              print(country.dialingCode);
                              countryCode = country.dialingCode;
                              },
                            selectedCountry: _selected,
                          ),
                        ),
                        Expanded(
                          //SizedBox(height: 20.0),
                          child: TextFormField(
                            decoration: InputDecoration(
                              labelText: 'Mobile no.',
                              border: OutlineInputBorder(),
                            ),
                            validator: (val) => val.length != 10
                                ? 'Enter a mobile number of 10 digits'
                                : null,
                            onChanged: (val) {
                              setState(() => phone = val);
                              phoneno = phone;
                              },
                          ),
                        ),
                      ],
                    ),

Image is attached below

Body:
Give first Expanded widget the flex value of 1 and second Expanded 3.

What happens is that the width gets divided into 4 equal parts (1+3), and 1 part is occupied by the first Expanded widget, and the remaining 3 parts get occupied by second Expanded widget. You can play around various proportions to meet your UI needs.

Row(
            children: <Widget>[
              Expanded(
                flex: 1,
                //SizedBox(height: 20.0),
                child: CountryPicker(
                  dense: true,
                  showFlag: false, //displays flag, true by default
                  showDialingCode:
                      true, //displays dialing code, false by default
                  showName: true, //displays country name, true by default
                  showCurrency: false, //eg. 'British pound'
                  showCurrencyISO: false,
                  onChanged: (Country country) {
                    setState(() => _selected = country);
                    print(country.dialingCode);
                    countryCode = country.dialingCode;
                  },
                  selectedCountry: _selected,
                ),
              ),
              Expanded(
                flex: 3,
                //SizedBox(height: 20.0),
                child: TextFormField(
                  decoration: InputDecoration(
                    labelText: 'Mobile no.',
                    border: OutlineInputBorder(),
                  ),
                  validator: (val) => val.length != 10
                      ? 'Enter a mobile number of 10 digits'
                      : null,
                  onChanged: (val) {
                    setState(() => phone = val);
                    phoneno = phone;
                  },
                ),
              ),
            ],
          ),


问:
Published messages in a reactive Redis topic aren't sent to the client
During the process of implementing GraphQL subscriptions I came up with a poor man's solution to pub/sub with custom topics that looks as follows:

// The map is a custom class, just to handle multiple clients subscribed to the same data
// and we just create one FluxSink per client which is internally stored in a Set
private static final ConcurrentMultiMap<Long, FluxSink<String>> subscribers =
      new ConcurrentMultiMap<>();

public Publisher<String> subscribeToMessages(final Long id) {
  return Flux.create(
      newSubscriber ->
          subscribers.add(
              id,
              newSubscriber.onDispose(() -> subscribers.remove(id, newSubscriber))),
      OverflowStrategy.LATEST);
}

public void publish(final Long id, final String message) {
  Optional.of(id)
      .map(subscribers::get)
      .ifPresent(
          subscribers ->
              subscribers.forEach(
                  subscriber -> subscriber.next(message)));
}
```

<p>Moving onward I wanted to replace this implementation with a Redis-backed solution using the <code>RedissonReactiveClient</code> as I stumbled upon the <code>RTopicReactive::getMessages</code> method that returns a <code>Flux</code>. Basically the previous code looks now as follows:</p>

<pre class="lang-java prettyprint-override"><code>public Publisher<String> subscribeToMessages(final Long id) {
  val topic = redissonReactiveClient.getTopic("messages/" + id.toString());
  return topic.getMessages(String.class);
}

public void publish(final Long id, final String message) {
  val topic = redissonReactiveClient.getTopic("messages/" + id.toString());
  topic.publish(message);
}
</code>```

Unfortunately though, this doesn't work as expected. The updates are published correctly as far as I can tell (since I connected to the redis instance and SUBSCRIBEd to it once to check the data) and even after letting my GraphQL client subscribe to the server the Mono returned by publish indicates that there is one subscriber, my GraphQL client. However it isn't updating its data and the network tab in the browser shows no websocket message of published data from the server. Therefore I assume that the data exposed via the Flux in the subscribeToMessages method is malformed or so.

Is there anything I have to keep in mind when attempting to use the getMessages method of the topic?

答:
You forgot to invoke subscribe on both publishers. It should be like this:</p>

```<code>public void publish(final Long id, final String message) {
   val topic = redissonReactiveClient.getTopic("messages/" + id.toString());
   topic.publish(message).doOnSuccess(res -> {

       // ...

   }).subscribe();
}

public void subscribeToMessages(final Long id) {
   val topic = redissonReactiveClient.getTopic("messages/" + id.toString());
   return topic.getMessages(String.class).doOnNext(res -> {

       // ...

   }).subscribe();
}
</code>```

Body:
During the process of implementing GraphQL subscriptions I came up with a poor man's solution to pub/sub with custom topics that looks as follows:

// The map is a custom class, just to handle multiple clients subscribed to the same data
// and we just create one FluxSink per client which is internally stored in a Set
private static final ConcurrentMultiMap<Long, FluxSink<String>> subscribers =
      new ConcurrentMultiMap<>();

public Publisher<String> subscribeToMessages(final Long id) {
  return Flux.create(
      newSubscriber ->
          subscribers.add(
              id,
              newSubscriber.onDispose(() -> subscribers.remove(id, newSubscriber))),
      OverflowStrategy.LATEST);
}

public void publish(final Long id, final String message) {
  Optional.of(id)
      .map(subscribers::get)
      .ifPresent(
          subscribers ->
              subscribers.forEach(
                  subscriber -> subscriber.next(message)));
}

Moving onward I wanted to replace this implementation with a Redis-backed solution using the RedissonReactiveClient as I stumbled upon the RTopicReactive::getMessages method that returns a Flux. Basically the previous code looks now as follows:

public Publisher<String> subscribeToMessages(final Long id) {
  val topic = redissonReactiveClient.getTopic("messages/" + id.toString());
  return topic.getMessages(String.class);
}

public void publish(final Long id, final String message) {
  val topic = redissonReactiveClient.getTopic("messages/" + id.toString());
  topic.publish(message);
}

Unfortunately though, this doesn't work as expected. The updates are published correctly as far as I can tell (since I connected to the redis instance and SUBSCRIBEd to it once to check the data) and even after letting my GraphQL client subscribe to the server the Mono returned by publish indicates that there is one subscriber, my GraphQL client. However it isn't updating its data and the network tab in the browser shows no websocket message of published data from the server. Therefore I assume that the data exposed via the Flux in the subscribeToMessages method is malformed or so.

Is there anything I have to keep in mind when attempting to use the getMessages method of the topic?

Body:
You forgot to invoke subscribe on both publishers. It should be like this:

public void publish(final Long id, final String message) {
   val topic = redissonReactiveClient.getTopic("messages/" + id.toString());
   topic.publish(message).doOnSuccess(res -> {

       // ...

   }).subscribe();
}

public void subscribeToMessages(final Long id) {
   val topic = redissonReactiveClient.getTopic("messages/" + id.toString());
   return topic.getMessages(String.class).doOnNext(res -> {

       // ...

   }).subscribe();
}


问:
How can I not receive notifications while I have a certain screen open? - Android
In my application I have several activities and one is chat. In this screen I have the ID of who is chatting with me and every time I send a message a push notification is sent with the message and the id of the person with whom I am chatting. While I'm chatting with this person I need to block notifications from them and only receive them if I don't have an open chat with that person. How do I do this? I'm using Firebase as a backend.</p>

```<code>class MyFirebaseMessagingService : FirebaseMessagingService() {

    override fun onMessageReceived(remoteMessage: RemoteMessage) {

        remoteMessage.notification?.let { notification ->

            val data = remoteMessage.data
            val type = data["type"] // chat message,like etc
            val id = data["id"] //userId

            val notificationChannelId = getString(R.string.default_notification_channel_id)
            val soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)

            val intent = setIntent(remoteMessage).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)

            val pendingIntent = PendingIntent.getActivity(this,
                    0,
                    intent,
                    PendingIntent.FLAG_CANCEL_CURRENT)

            val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                val notificationChannel = NotificationChannel(notificationChannelId, CHANNEL_SPEEACHT, NotificationManager.IMPORTANCE_DEFAULT)
                notificationManager.createNotificationChannel(notificationChannel)
            }

            val notificationBuilder = NotificationCompat.Builder(this, notificationChannelId)
                    .setContentTitle(notification.title ?: "")
                    .setContentText(notification.body ?: "")
                    .setSmallIcon(R.drawable.ic_stat)
                    .setSound(soundUri)
                    .setColor(ContextCompat.getColor(applicationContext, R.color.colorNotification))
                    .setAutoCancel(true)
                    .setContentIntent(pendingIntent)

            notificationManager.notify(0, notificationBuilder.build())
        }
    }
</code>```

答:
I think this is not firebase-cloud-messaging related, because firebase-cloud-messaging is just a message channel, so you should do it in your own bussiness code.

A suggested way is that you can make a condition. if the activity is visable and the userid you received in onMessageReceived is the same as the userid you are chatting with, then you should not create your own notification in onMessageReceived function.

Body:
In my application I have several activities and one is chat. In this screen I have the ID of who is chatting with me and every time I send a message a push notification is sent with the message and the id of the person with whom I am chatting. While I'm chatting with this person I need to block notifications from them and only receive them if I don't have an open chat with that person. How do I do this? I'm using Firebase as a backend.

class MyFirebaseMessagingService : FirebaseMessagingService() {

    override fun onMessageReceived(remoteMessage: RemoteMessage) {

        remoteMessage.notification?.let { notification ->

            val data = remoteMessage.data
            val type = data["type"] // chat message,like etc
            val id = data["id"] //userId

            val notificationChannelId = getString(R.string.default_notification_channel_id)
            val soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)

            val intent = setIntent(remoteMessage).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)

            val pendingIntent = PendingIntent.getActivity(this,
                    0,
                    intent,
                    PendingIntent.FLAG_CANCEL_CURRENT)

            val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                val notificationChannel = NotificationChannel(notificationChannelId, CHANNEL_SPEEACHT, NotificationManager.IMPORTANCE_DEFAULT)
                notificationManager.createNotificationChannel(notificationChannel)
            }

            val notificationBuilder = NotificationCompat.Builder(this, notificationChannelId)
                    .setContentTitle(notification.title ?: "")
                    .setContentText(notification.body ?: "")
                    .setSmallIcon(R.drawable.ic_stat)
                    .setSound(soundUri)
                    .setColor(ContextCompat.getColor(applicationContext, R.color.colorNotification))
                    .setAutoCancel(true)
                    .setContentIntent(pendingIntent)

            notificationManager.notify(0, notificationBuilder.build())
        }
    }


问:
Automatically translate images to have same position for an object
Let's say you have various images like below.

Is there a function in Python OpenCV to automatically translate horizontally an image so that the main object has roughly the same position than on a reference image (the first image)?

In math words, it would be just computing:

```<code>score[x] = image_correlation(ref_image, image2.translate_horizontally(x))
</code>```

for all possible x in range(-200,200) (if the image width is 200)

and take x that maximizes this score.

Before redoing this from scratch, is this feature already present in OpenCV?

(Using center of mass of images? other techniques involving a image_correlation function already present in OpenCV? Or Scale Invariant Feature Transform techniques?)

Example:

reference image:

image2:

 --> automatically translated to -->

答:
I finally solved it quite easily: you must provide a background reference (with only green background in my case) ref.png.

Then a background subtraction + center of mass works well:

```<code>import cv2
import scipy.ndimage as ndi

backSub = cv2.createBackgroundSubtractorMOG2()  # or backSub = cv.createBackgroundSubtractorKNN()

frame = cv2.imread('ref.png')
backSub.apply(frame)
frame = cv2.imread('1.png')
mask = backSub.apply(frame)
cv2.imwrite('mask.png', mask)
print(ndi.center_of_mass(mask))
</code>```

Result: (63.6349484521314, 164.158143799214)

We can then compare this center of mass for consecutive frames and do the appropriate translation.

Body:
Let's say you have various images like below.

Is there a function in Python OpenCV to automatically translate horizontally an image so that the main object has roughly the same position than on a reference image (the first image)?

In math words, it would be just computing:

score[x] = image_correlation(ref_image, image2.translate_horizontally(x))

for all possible x in range(-200,200) (if the image width is 200)

and take x that maximizes this score.

Before redoing this from scratch, is this feature already present in OpenCV?

(Using center of mass of images? other techniques involving a image_correlation function already present in OpenCV? Or Scale Invariant Feature Transform techniques?)

Example:

reference image:

image2:

 --> automatically translated to -->

Body:
I finally solved it quite easily: you must provide a background reference (with only green background in my case) ref.png.

Then a background subtraction + center of mass works well:

import cv2
import scipy.ndimage as ndi

backSub = cv2.createBackgroundSubtractorMOG2()  # or backSub = cv.createBackgroundSubtractorKNN()

frame = cv2.imread('ref.png')
backSub.apply(frame)
frame = cv2.imread('1.png')
mask = backSub.apply(frame)
cv2.imwrite('mask.png', mask)
print(ndi.center_of_mass(mask))

Result: (63.6349484521314, 164.158143799214)

We can then compare this center of mass for consecutive frames and do the appropriate translation.