问:
UnicodeEncodeError: 'charmap' codec can't encode characters in position 1082-1084: character maps to <undefined>
this is my first time using python, im trying to make CT asset to CSV

this is my code

tsv.py

```<code>
    def write(self, data):
        """
        Write list to TSV

        :param list data: Decoded list to write on TSV file
        """

        os.makedirs(os.path.dirname("./{0}".format(self.path)), exist_ok=True)
        self.tsv = open(self.path, "w", newline="\r\n")

        self.header = "\t".join(i for i in data[0]) + "\n"
        self.types = "\t".join(i for i in data[1]) + "\n"
        self.rows = "\n".join("\t".join(l) for l in data[2:]) + "\n"

        self.tsv.write(self.header + self.types + self.rows)
        if self.verbose:
            print("\nTSV write to \"{0}\" complete!\n".format(self.path))
</code>```

And I'm getting the following error:

```<code>line 48, in write
    self.tsv.write(self.header + self.types + self.rows)
File "C:\Users\ASUS\AppData\Local\Programs\Python\Python38-32\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position 1082-1084: character maps to <undefined>
</code>```

What can I do to fix this?

答:
The error message indicates that you are using Python 3 and that it is trying to write text using the Windows code page 1252 encoding.  The actual error is that your data contains a character which does not exist in this encoding. I would have expected Python 3 to write UTF-8 but it's not; perhaps you can add encoding="utf-8" to the open call if that is in fact what you want?

```<code>self.tsv = open(self.path, "w", newline="\r\n", encoding="utf-8")
</code>```

If your script works reliably for you, there is no real need to change it; but reinventing CSV/TSV writing is not a good idea -- you are ignoring several corner cases which the existing csv module in the Python standard library already handles.

```<code>import csv
import logging

class whatever: ...

    def write(self, data):
        """
        Write list to TSV

        :param list data: Decoded list to write on TSV file
        """

        os.makedirs(os.path.dirname("./{0}".format(self.path)), exist_ok=True)
        with open(self.path, "w", newline="", encoding="utf-8") as tsv:
            writer = csv.writer(tsv, delimiter="\t")
            writer.writerows(data)

        logging.info('TSV write to "%s" complete!', self.path))
</code>```

Your code also lacks self.tsv.close() which the above code doesn't need because the with handles that transparently.

Additionally, I switched to logging for the informational message. It similarly offers a canned solution which already knows how to write messages to standard error instead of standard output etc (though you might want to look at logging.basicConfig to set up the formatting to your liking -- I usually put logging.basicConfig('%(module)s:%(message)s') for simple command-line utilities).

Body:
this is my first time using python, im trying to make CT asset to CSV

this is my code

tsv.py

    def write(self, data):
        """
        Write list to TSV

        :param list data: Decoded list to write on TSV file
        """

        os.makedirs(os.path.dirname("./{0}".format(self.path)), exist_ok=True)
        self.tsv = open(self.path, "w", newline="\r\n")

        self.header = "\t".join(i for i in data[0]) + "\n"
        self.types = "\t".join(i for i in data[1]) + "\n"
        self.rows = "\n".join("\t".join(l) for l in data[2:]) + "\n"

        self.tsv.write(self.header + self.types + self.rows)
        if self.verbose:
            print("\nTSV write to \"{0}\" complete!\n".format(self.path))

And I'm getting the following error:

line 48, in write
    self.tsv.write(self.header + self.types + self.rows)
File "C:\Users\ASUS\AppData\Local\Programs\Python\Python38-32\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position 1082-1084: character maps to <undefined>

What can I do to fix this?

Body:
The error message indicates that you are using Python 3 and that it is trying to write text using the Windows code page 1252 encoding.  The actual error is that your data contains a character which does not exist in this encoding. I would have expected Python 3 to write UTF-8 but it's not; perhaps you can add encoding="utf-8" to the open call if that is in fact what you want?

self.tsv = open(self.path, "w", newline="\r\n", encoding="utf-8")

If your script works reliably for you, there is no real need to change it; but reinventing CSV/TSV writing is not a good idea -- you are ignoring several corner cases which the existing csv module in the Python standard library already handles.

import csv
import logging

class whatever: ...

    def write(self, data):
        """
        Write list to TSV

        :param list data: Decoded list to write on TSV file
        """

        os.makedirs(os.path.dirname("./{0}".format(self.path)), exist_ok=True)
        with open(self.path, "w", newline="", encoding="utf-8") as tsv:
            writer = csv.writer(tsv, delimiter="\t")
            writer.writerows(data)

        logging.info('TSV write to "%s" complete!', self.path))

Your code also lacks self.tsv.close() which the above code doesn't need because the with handles that transparently.

Additionally, I switched to logging for the informational message. It similarly offers a canned solution which already knows how to write messages to standard error instead of standard output etc (though you might want to look at logging.basicConfig to set up the formatting to your liking -- I usually put logging.basicConfig('%(module)s:%(message)s') for simple command-line utilities).


来源: stackexchange

问:
How to set the Google Analytics cookie only after another consent cookie is set and "true"?
I am using React/Nextjs for my website and the react-cookie-consent library. It creates a pop up where the user can agree to the cookie policy. If agreed, a cookie is set: CookieConsent with value "true".

Additionally, I want to use Google Analytics to track users if they agree (click Accept on the popup).

But it doesnt work: The Google Analytic cookies _ga and G_ENABLED_IDPS are set before the user clicks on the pop up.

Funny thing is, I only realized that on the Microsoft Edge Browser. In Chrome, these cookies are not set before the user gives consent.

This is my current code in _document.js:

          {/* Global Site Tag (gtag.js) - Google Analytics */}

答:
The way you were doing it is Opt-out. The GA cookie is always set, as soon as the client requests the gtag.js. This however doesn't comply with GDPR. What you should look into is Opt-in, so that no GA cookie is set without consenting.

The general idea is to async load the gtag.js once the client has consented. For full functionality of gtag functions you have to load the gtag.js on every page-load if the client already consented. Best practice to do this is with a cookieconsent cookie set on consent.
There's a widely used js library for this, which generates a popup and sets the consent-cookie for you.

Reference:

https://www.osano.com/cookieconsent/documentation/javascript-api/

You can generate code for the layout of your cookie banner by clicking Start Coding here:
https://www.osano.com/cookieconsent/download/
https://github.com/osano/cookieconsent/blob/dev/examples/example-7-javascript-api.html

Following code has to be implemented on every page in the  section:

<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/cookieconsent2/3.1.1/cookieconsent.min.css" />

```

<p><strong>Note:</strong> <br />
Make sure that the gtag.js is loaded on every page-load once the consent-cookie was set to <em>allow</em>. Use <code>event_callback</code> to see if a gtag event was sent. You can use the gtag function without checking for the consent-cookie. If gtag.js is not present it just adds elements to the <code>window.dataLayer</code> without any functionality. To avoid errors, the <code>function gtag()</code> has to be declared in global scope and before use.</p>

<pre class="lang-js prettyprint-override"><code>// cookie-check is not necessary when gtag is in global scope
//if(popup.hasConsented()) {
    gtag('event', 'sign_up', {
            'method': 'Google',
            'event_callback': function(){alert('event was sent');}
        });
//}
</code>```

You don't have to send an extra pageview event, unless you want to manually specify the path. setCookies() already sends the current document path along with the config

ContentLicense: CC BY-SA 4.0

Body:
The way you were doing it is Opt-out. The GA cookie is always set, as soon as the client requests the gtag.js. This however doesn't comply with GDPR. What you should look into is Opt-in, so that no GA cookie is set without consenting.

The general idea is to async load the gtag.js once the client has consented. For full functionality of gtag functions you have to load the gtag.js on every page-load if the client already consented. Best practice to do this is with a cookieconsent cookie set on consent.
There's a widely used js library for this, which generates a popup and sets the consent-cookie for you.

Reference:

https://www.osano.com/cookieconsent/documentation/javascript-api/

You can generate code for the layout of your cookie banner by clicking Start Coding here:
https://www.osano.com/cookieconsent/download/
https://github.com/osano/cookieconsent/blob/dev/examples/example-7-javascript-api.html

Following code has to be implemented on every page in the <head> section:

<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/cookieconsent2/3.1.1/cookieconsent.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/cookieconsent2/3.1.1/cookieconsent.min.js" data-cfasync="false"></script>
<script>
var popup;
window.addEventListener('load', function(){
  window.cookieconsent.initialise({
   //set revokeBtn if you don't want to see a tiny pullup bar overlapping your website
   //if revokeBtn is set, make sure to include a link to cookie settings in your footer
   //you can open your banner again with: popup.open();
   //revokeBtn: "<div class='cc-revoke'></div>",
   type: "opt-in",
   theme: "classic",
   palette: {
       popup: {
           background: "#000",
           text: "#fff"
        },
       button: {
           background: "#fd0",
           text: "#000"
        }
    },
    onInitialise: function(status) {
      // request gtag.js on page-load when the client already consented
      if(status == cookieconsent.status.allow) setCookies();
    },
    onStatusChange: function(status) {
      // resquest gtag cookies on a new consent
      if (this.hasConsented()) setCookies();
      else deleteCookies(this.options.cookie.name)
    },
/* enable this to hide the cookie banner outside GDPR regions
    law: {
      regionalLaw: false,
    },
    location: true,
    },
*/
    function (p) {
        popup = p;
  })
});

//it is absolutely crucial to define gtag in the global scope
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${GA_TRACKING_ID}', {'anonymize_ip': true});

function setCookies() {
    var s = document.createElement('script');
    s.type = "text/javascript"
    s.async = "true";
    s.src = "https://www.googletagmanager.com/gtag/js?id=${GA_TRACKING_ID}";
    var x = document.getElementsByTagName('script')[0];
    x.parentNode.insertBefore(s, x);

    // you can add facebook-pixel and other cookies here
};

function deleteCookies(cookieconsent_name) {
        var keep = [cookieconsent_name, "DYNSRV"];

        document.cookie.split(';').forEach(function(c) {
            c = c.split('=')[0].trim();
            if (!~keep.indexOf(c))
                document.cookie = c + '=;' + 'expires=Thu, 01 Jan 1970 00:00:00 UTC;path=/';
        });
};
</script>

Note:

Make sure that the gtag.js is loaded on every page-load once the consent-cookie was set to allow. Use event_callback to see if a gtag event was sent. You can use the gtag function without checking for the consent-cookie. If gtag.js is not present it just adds elements to the window.dataLayer without any functionality. To avoid errors, the function gtag() has to be declared in global scope and before use.

// cookie-check is not necessary when gtag is in global scope
//if(popup.hasConsented()) {
    gtag('event', 'sign_up', {
            'method': 'Google',
            'event_callback': function(){alert('event was sent');}
        });
//}

You don't have to send an extra pageview event, unless you want to manually specify the path. setCookies() already sends the current document path along with the config


问:
HTML MediaRecorder recording lags on 1080p stream
I am reading a 1080p and 720p external video camera stream through getUserMedia API with the following config

```<code>let c_constraints = {
        audio: false,
        video: {
            deviceId: { exact: videoValue },
            width: { min: 320, ideal: 1280, max: 1920 },
        height: { min: 144, ideal: 720, max: 1080 },
            framerate: { min: 15, ideal: 30, max: 60 }
        }
     }
     navigator.mediaDevices.getUserMedia(c_constraints)
        .then((stream) => c_handleStream(stream))
        .catch((e) => c_handleError(e));
</code>```

And recording the stream using following

```<code> try {
        c_recorder = new MediaRecorder(currentCameraStream);
     } catch (e) {
        throw e
     }
</code>```

Issue -> this works fine on high end devices, but on a device with 4GB RAM, Intel core i3 while recording in 1080p and 720p i get lags and the video is choppy only for first 3 seconds, but the remaining video is just fine.

also, on playing this recorded video in VLC media player, the timer directly jumps from 00:01 to 00:03,

if this was a memory/buffer issue, the other blobs would be affected too. am i missing something , should i use MediaRecorder in a different way, or with any different options.

PS: i have tried to use RecordRTC by Sir Muaz Khan, but it seems heavy for the CPU as CPU usage surges past 70% on the above mentioned machine which makes the machine super slow.

Please shed some light on this.

答: Finally got it working, in case if this helps anyone, if the machine you are recording is on a power saving mode, the audio/video not in sync issue can be resolved by enabling performance mode from control panel </p>

Body:
I am reading a 1080p and 720p external video camera stream through getUserMedia API with the following config

let c_constraints = {
        audio: false,
        video: {
            deviceId: { exact: videoValue },
            width: { min: 320, ideal: 1280, max: 1920 },
        height: { min: 144, ideal: 720, max: 1080 },
            framerate: { min: 15, ideal: 30, max: 60 }
        }
     }
     navigator.mediaDevices.getUserMedia(c_constraints)
        .then((stream) => c_handleStream(stream))
        .catch((e) => c_handleError(e));

And recording the stream using following

 try {
        c_recorder = new MediaRecorder(currentCameraStream);
     } catch (e) {
        throw e
     }

Issue -> this works fine on high end devices, but on a device with 4GB RAM, Intel core i3 while recording in 1080p and 720p i get lags and the video is choppy only for first 3 seconds, but the remaining video is just fine.

also, on playing this recorded video in VLC media player, the timer directly jumps from 00:01 to 00:03,

if this was a memory/buffer issue, the other blobs would be affected too. am i missing something , should i use MediaRecorder in a different way, or with any different options.

PS: i have tried to use RecordRTC by Sir Muaz Khan, but it seems heavy for the CPU as CPU usage surges past 70% on the above mentioned machine which makes the machine super slow.

Please shed some light on this.


问:
Community Site with Blogs and forums - Oxite, DNN or CS?
I need to do a community site with blogs and forums, and was looking at 3 options: Oxite, DNN and community server.
The frontend will be a mixture of ASP.NET and Silverlight. LiveID integration would be a plus.
Any suggestions?

Thanks.

答:
Oxite is quite new, and as far as I know doesn't support forums, so out of the box it's not going to do what you need. There are other, more mature blog engines in .Net listed on the oxite home page

When you say "the front end will be a mixture of ASP.NET and Silverlight" you seem to be indicating that you're going to be writing your own front end and want a starting point? How much of your own coding are you wanting to do?

But Oxite is open source, and is now getting towards the point where it can serve as a sample of best practices in ASP.NET MVC, i.e. cutting-edge stuff that other blog projects probably won't have. if it has benefit for you, that will be it.

Community server looks a lot more complete, but I have no experience on how usable it is. It's not clear if this is open-source or not, but it looks like you will need to pay for the larger editions. Are you willing to do this?

DNN means DotNetNuke? It's free like Oxite, and full-featured like Community server. I don't know much more about it.

OwnerDisplayName: theplastictoy

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Anthony

LastEditorDisplayName: Anthony


问:
Ignoring method calls in Mockito
With Mockito, is it possible to ignore a method call to a mock?

E.g. for the mock rugger created with mock(MyRugger.class):

```<code>class Pepe {

  public void runner() {
    rugger.doIt();
    rugger.flushIt();
    rugger.boilIt();
  }
}
</code>```

I need only test runner() but avoid the method flushIt().

答:
To reset a mock in Mockito, simply call reset on it. Note the very real concern mentioned in the above link and the JavaDoc for reset stating that it may represent bad design.

This should generally be avoided, but there are times when you simply need to do this. The below is an example on how to use it, not a good example of when to use it.

```<code>Object value = mock(Object.class);

when(value.equals(null)).thenReturn(true);
assertTrue(value.equals(null));
verify(value).equals(null);

reset(value);

assertFalse(value.equals(null));
verify(value).equals(null);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Ignoring method calls in Mockito

Body:
With Mockito, is it possible to ignore a method call to a mock?

E.g. for the mock rugger created with mock(MyRugger.class):

class Pepe {

  public void runner() {
    rugger.doIt();
    rugger.flushIt();
    rugger.boilIt();
  }
}

I need only test runner() but avoid the method flushIt().

Body:
To reset a mock in Mockito, simply call reset on it. Note the very real concern mentioned in the above link and the JavaDoc for reset stating that it may represent bad design.

This should generally be avoided, but there are times when you simply need to do this. The below is an example on how to use it, not a good example of when to use it.

Object value = mock(Object.class);

when(value.equals(null)).thenReturn(true);
assertTrue(value.equals(null));
verify(value).equals(null);

reset(value);

assertFalse(value.equals(null));
verify(value).equals(null);


问:
Java string calculator, first number is negative
So i have this code which i took from another question and its never answered, how would i have to change the code if String a = "-5+20-15+8" with the first number being negative, right now it gives an error.</p>

```<code> String a = "5+20-15+8";
    System.out.println(a);
    String operators[]=a.split("[0-9]+");
    String operands[]=a.split("[+-]");
    int agregate = Integer.parseInt(operands[0]);
    for(int i=1;i<operands.length;i++){
        if(operators[i].equals("+"))
            agregate += Integer.parseInt(operands[i]);
        else
            agregate -= Integer.parseInt(operands[i]);
    }
    System.out.println(agregate);
</code>```

答:
One quick way to fix it is to make sure you don't split at the first - when you split the string into operands.

```<code>String operands[]=a.split("(?<=\\d)[+-]");
</code>```

This regex asserts that the + or - must be followed by a digit.

This way, the first operand would be -5, which would then be correctly parsed by Integer.parseInt.

If you only need to handle addition and subtraction, here's another way to think about the problem: there are no operators, only operands. In -5+20-15+8, there are only the operands -5, +20, -15, +8, and you just need to add them all up. We can split the string into operands at a digit-[+-] boundary:

```<code>String[] operands = a.split("(?<=\\d)(?=[+-])");
</code>```

and then just sum them all up:

```<code>int result = 0;
for (int i = 0 ; i < operands.length ; i++) {
    result += Integer.parseInt(operands[i]);
}
// or:
// int result = Arrays.stream(operands).mapToInt(Integer::parseInt).sum();
System.out.println(result);
</code>```

Body:
So i have this code which i took from another question and its never answered, how would i have to change the code if String a = "-5+20-15+8" with the first number being negative, right now it gives an error.

 String a = "5+20-15+8";
    System.out.println(a);
    String operators[]=a.split("[0-9]+");
    String operands[]=a.split("[+-]");
    int agregate = Integer.parseInt(operands[0]);
    for(int i=1;i<operands.length;i++){
        if(operators[i].equals("+"))
            agregate += Integer.parseInt(operands[i]);
        else
            agregate -= Integer.parseInt(operands[i]);
    }
    System.out.println(agregate);

Body:
One quick way to fix it is to make sure you don't split at the first - when you split the string into operands.

String operands[]=a.split("(?<=\\d)[+-]");

This regex asserts that the + or - must be followed by a digit.

This way, the first operand would be -5, which would then be correctly parsed by Integer.parseInt.

If you only need to handle addition and subtraction, here's another way to think about the problem: there are no operators, only operands. In -5+20-15+8, there are only the operands -5, +20, -15, +8, and you just need to add them all up. We can split the string into operands at a digit-[+-] boundary:

String[] operands = a.split("(?<=\\d)(?=[+-])");

and then just sum them all up:

int result = 0;
for (int i = 0 ; i < operands.length ; i++) {
    result += Integer.parseInt(operands[i]);
}
// or:
// int result = Arrays.stream(operands).mapToInt(Integer::parseInt).sum();
System.out.println(result);


问:
What is the meaning of "boot" in "Spring-Boot" title
I know and understand, And have read a lot about

Spring-Boot

, and how it's improving the use of Spring framework.

But I'm still not sure what's the actual meaning of

"Boot"

in the context of this title.

It's mean that it's kick off Spring to more high place, or it gives you boots to walk with Spring? Or something else.

Didn't found any explanation about that.

I will be glad for an answer.

(the source of the name

"Spring"

is also interesting )

答:
Spring is a Framework of Java. Spring-Boot combined means Bootstrapping a Spring Application.

It simply means You have to configure your application to the bare minimum to get your Application up and Running.

Spring boot takes an 'Opinionated' view of what a basic Application should have.

Spring boot bootstraps your Application in such a way that it contains almost everything needed to run a full application.

Basically, Spring-Boot is a way to make a Spring Application up and running without a lot of configuration and boiler-plate code.


问:
Scrapy - pymongo not inserting items to DB
So im playing about with scrapy trying to learn, and using MongoDB as my DB ive come to a dead end.
Basically the scraping works as the items im fetching are showing in the terminal log, but i cant get the data to publish on my DB. The MONGO_URI is correct as i tried it in the python shell where i can create and store data..

Here are my files

items.py

```<code>
import scrapy

class MaterialsItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    title = scrapy.Field()
    price = scrapy.Field()
   ## url = scrapy.Field()
    pass
</code>```

spider.py

```<code>import scrapy
from scrapy.selector import Selector

from ..items import MaterialsItem

class mySpider(scrapy.Spider):
    name = "<placeholder for post>"
    allowed_domains = ["..."]
    start_urls = [
   ...
    ]

    def parse(self, response):
        products = Selector(response).xpath('//div[@class="content"]')

        for product in products:
                item = MaterialsItem()
                item['title'] = product.xpath("//a[@class='product-card__title product-card__title-v2']/text()").extract(),
                item['price'] = product.xpath("//div[@class='product-card__price-value ']/text()").extract()
               ## product['url'] =
                yield item
</code>```

settings.py

```<code>MONGO_PIPELINES = {
    'materials.pipelines.MongoPipeline': 300,
}

#setup mongo DB
MONGO_URI = "my MongoDB Atlas address"
MONGO_DB = "materials"

</code>```

pipelines.py

```<code>import pymongo

class MongoPipeline(object):

    collection_name = 'my-prices'

    def __init__(self, mongo_uri, mongo_db):
        self.mongo_uri = mongo_uri
        self.mongo_db = mongo_db

    @classmethod
    def from_crawler(cls, crawler):
        ## pull in information from settings.py
        return cls(
            mongo_uri=crawler.settings.get('MONGO_URI'),
            mongo_db=crawler.settings.get('MONGO_DB', ', <placeholder-spider name>')

        )

    def open_spider(self, spider):
        ## initializing spider
        ## opening db connection
        self.client = pymongo.MongoClient(self.mongo_uri)
        self.db = self.client[self.mongo_db]

    def close_spider(self, spider):
        ## clean up when spider is closed
        self.client.close()

    def process_item(self, item, spider):
        ## how to handle each post
        self.db[self.collection_name].insert(dict(item))
        logging.debug("Post added to MongoDB")
        return item
</code>```

Any help would be great!

**Edit

file structure

```<code>materials
  spiders
  my-spider
items.py
pipelines.py
settings.py
</code>```

答: what the code error and i think i need to beunder init if it posible can you upload it to git ? and i might try to have a look

Body:
So im playing about with scrapy trying to learn, and using MongoDB as my DB ive come to a dead end.
Basically the scraping works as the items im fetching are showing in the terminal log, but i cant get the data to publish on my DB. The MONGO_URI is correct as i tried it in the python shell where i can create and store data..

Here are my files

items.py

import scrapy

class MaterialsItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    title = scrapy.Field()
    price = scrapy.Field()
   ## url = scrapy.Field()
    pass

spider.py

import scrapy
from scrapy.selector import Selector

from ..items import MaterialsItem

class mySpider(scrapy.Spider):
    name = "<placeholder for post>"
    allowed_domains = ["..."]
    start_urls = [
   ...
    ]

    def parse(self, response):
        products = Selector(response).xpath('//div[@class="content"]')

        for product in products:
                item = MaterialsItem()
                item['title'] = product.xpath("//a[@class='product-card__title product-card__title-v2']/text()").extract(),
                item['price'] = product.xpath("//div[@class='product-card__price-value ']/text()").extract()
               ## product['url'] =
                yield item

settings.py

MONGO_PIPELINES = {
    'materials.pipelines.MongoPipeline': 300,
}

#setup mongo DB
MONGO_URI = "my MongoDB Atlas address"
MONGO_DB = "materials"

pipelines.py

import pymongo

class MongoPipeline(object):

    collection_name = 'my-prices'

    def __init__(self, mongo_uri, mongo_db):
        self.mongo_uri = mongo_uri
        self.mongo_db = mongo_db

    @classmethod
    def from_crawler(cls, crawler):
        ## pull in information from settings.py
        return cls(
            mongo_uri=crawler.settings.get('MONGO_URI'),
            mongo_db=crawler.settings.get('MONGO_DB', ', <placeholder-spider name>')

        )

    def open_spider(self, spider):
        ## initializing spider
        ## opening db connection
        self.client = pymongo.MongoClient(self.mongo_uri)
        self.db = self.client[self.mongo_db]

    def close_spider(self, spider):
        ## clean up when spider is closed
        self.client.close()

    def process_item(self, item, spider):
        ## how to handle each post
        self.db[self.collection_name].insert(dict(item))
        logging.debug("Post added to MongoDB")
        return item

Any help would be great!

**Edit

file structure

materials
  spiders
  my-spider
items.py
pipelines.py
settings.py


问:
How to insert a character at a certain position in a number without converting it into a string?
I have to insert "/" between 2020 and 0001 in the number 20200001. I know how to do it by converting the number to string, but I am unable to do it by not converting it.</p>

答:
In Javascript you can't have a "/" in a number. If this is a date you could convert it to a date with the "/" as a delimiter.

Here you can learn more about dates in Javascript:
https://www.w3schools.com/js/js_dates.asp


问:
Creating PersistentVolumes to cover many nodes with many disks
I'm deploying a large Kube cluster where each node has 80 SSDs. Each disk is mounted as /data/diskN (disk0 - disk79) on each node.

Example PV:

```<code>apiVersion: v1
kind: PersistentVolume
metadata:
  name: vol0022
spec:
  accessModes:
  - ReadWriteOnce
  capacity:
    storage: 100Gi
  local:
    path: /data/disk22
  nodeAffinity:
    required:
      nodeSelectorTerms:
      - matchExpressions:
        - key: "storage"
          operator: In
          values:
          - "true"
  persistentVolumeReclaimPolicy: Retain
  volumeMode: Filesystem
</code>```

Do I merely create enough PV's to cover (num_nodes * num_disk_per_node)?

ie:

If I have 10 nodes, I'll have 10 PV's where the path is "/data/disk0", another 10 where the path is "/data/disk1", and so on.

Thx

答:
Yes. If you try to create Persistent Volume for each of them.

A better way is to use a "StorageClass" (more information) like "Glusterfs" which will create a cluster for all the disk. Then you can directly create a PersistentVolumeClaim to claim some space without creating a PersistentVolume.

Body:
I'm deploying a large Kube cluster where each node has 80 SSDs. Each disk is mounted as /data/diskN (disk0 - disk79) on each node.

Example PV:

apiVersion: v1
kind: PersistentVolume
metadata:
  name: vol0022
spec:
  accessModes:
  - ReadWriteOnce
  capacity:
    storage: 100Gi
  local:
    path: /data/disk22
  nodeAffinity:
    required:
      nodeSelectorTerms:
      - matchExpressions:
        - key: "storage"
          operator: In
          values:
          - "true"
  persistentVolumeReclaimPolicy: Retain
  volumeMode: Filesystem

Do I merely create enough PV's to cover (num_nodes * num_disk_per_node)?

ie:

If I have 10 nodes, I'll have 10 PV's where the path is "/data/disk0", another 10 where the path is "/data/disk1", and so on.

Thx


问:
How to return result of test-connection from if statement?
I have solution but it looks ugly.
here is my cutted code

```<code>$Output= @()
$hosts = hosts.txt
foreach ($name in $hosts){
if (Test-Connection -ComputerName $name -Count 1 -ErrorAction SilentlyContinue){
   $Output+= Test-Connection -ComputerName $name -Count 1 -ErrorAction SilentlyContinue
  }
}
$Output | Out-file result.txt
</code>```

Is there any default variable containing result of Test-connection ?
I want to write something like $Output+= $result

答:
You need to get the content of the file using Get-Content. </p>

```<code>$Output= @()
$hosts = Get-Content hosts.txt
foreach ($name in $hosts){
if (Test-Connection -ComputerName $name -Count 1 -ErrorAction SilentlyContinue){
   $Output+= Test-Connection -ComputerName $name -Count 1 -ErrorAction SilentlyContinue
  }
}
$Output | Out-file result.txt
</code>```

Body:
I have solution but it looks ugly.
here is my cutted code

$Output= @()
$hosts = hosts.txt
foreach ($name in $hosts){
if (Test-Connection -ComputerName $name -Count 1 -ErrorAction SilentlyContinue){
   $Output+= Test-Connection -ComputerName $name -Count 1 -ErrorAction SilentlyContinue
  }
}
$Output | Out-file result.txt

Is there any default variable containing result of Test-connection ?
I want to write something like $Output+= $result

Body:
You need to get the content of the file using Get-Content.

$Output= @()
$hosts = Get-Content hosts.txt
foreach ($name in $hosts){
if (Test-Connection -ComputerName $name -Count 1 -ErrorAction SilentlyContinue){
   $Output+= Test-Connection -ComputerName $name -Count 1 -ErrorAction SilentlyContinue
  }
}
$Output | Out-file result.txt


问:
How to get the password and email form boxes to look the same in razor
In this image you can see that on my webpage the password editor box looks different compared to the Email text editor box. I looked at examples of having the same box used for both a password and text editor box and found this. Showing that by both of them having the form-control class they look the same. However my cshtml code also has both my editors using the form-control class, shown below

```<code>        <div class="form-group">
            @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Email, new { htmlAttributes = new {@class = "form-control"} })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.PasswordFor(model => model.Password, new { htmlAttributes = new {@class = "form-control" } })
            </div>
        </div>
</code>```

How do I edit my Password box to make it look the same as my Email box?

答:
I don't know what is causing this problem but it is one that i have seen before. One of the things you could do to fix this is using the @Html.EditorFor for the password and extending your htmlAttributes from new { htmlAttributes = new { @class = "form-control" } } to new { htmlAttributes = new { @class = "form-control", @type = "password" } }.

This would be your code

```<code><div class="form-group">
    @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
    </div>
</div>

<div class="form-group">
    @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control", @type = "password" } })
    </div>
</div>
</code>```

Hope this provides clarity.

Body:
In this image you can see that on my webpage the password editor box looks different compared to the Email text editor box. I looked at examples of having the same box used for both a password and text editor box and found this. Showing that by both of them having the form-control class they look the same. However my cshtml code also has both my editors using the form-control class, shown below

            @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.Email, new { htmlAttributes = new {@class = "form-control"} })

            @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.PasswordFor(model => model.Password, new { htmlAttributes = new {@class = "form-control" } })

How do I edit my Password box to make it look the same as my Email box?

Body:
I don't know what is causing this problem but it is one that i have seen before. One of the things you could do to fix this is using the @Html.EditorFor for the password and extending your htmlAttributes from new { htmlAttributes = new { @class = "form-control" } } to new { htmlAttributes = new { @class = "form-control", @type = "password" } }.

This would be your code

<div class="form-group">
    @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
    </div>
</div>

<div class="form-group">
    @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control", @type = "password" } })
    </div>
</div>

Hope this provides clarity.


问:
How to add discussion comments to the existing workitem card(Feature card) through API in Azure DevOps
I want to add discussion comments that is [System.History] to the existing card. How can I do it through API or is there any update WIQL query to update the card?</p>

答:
You can use the REST API. See here: https://learn.microsoft.com/en-us/rest/api/azure/devops/wit/comments/add?view=azure-devops-rest-5.1. As of 22.07.2020 the documentation there is still incorrect, see https://github.com/MicrosoftDocs/vsts-rest-api-specs/issues/313.

Sample Request (HTTP)

```<code>POST https://dev.azure.com/fabrikam/Fabrikam-Fiber-Git/_apis/wit/workItems/299/comments?api-version=5.1-preview.3
</code>```

Request Body (JSON)

```<code>{
  "text": "Moving to the right area path"
}
</code>```

Body:
You can use the REST API. See here: https://learn.microsoft.com/en-us/rest/api/azure/devops/wit/comments/add?view=azure-devops-rest-5.1. As of 22.07.2020 the documentation there is still incorrect, see https://github.com/MicrosoftDocs/vsts-rest-api-specs/issues/313.

Sample Request (HTTP)

POST https://dev.azure.com/fabrikam/Fabrikam-Fiber-Git/_apis/wit/workItems/299/comments?api-version=5.1-preview.3

Request Body (JSON)

{
  "text": "Moving to the right area path"
}


问:
How to check privilege based on string instead of table row?
In my web app the admin can assign a web page to a specific user, therefore that user can only access that specific page.

So to give an idea of how this works:

in my database I have a table with the web pages in, Webpage1.aspx, Webpage2.aspx etc.

The admin can create an user assign Webpage1.aspx to that user

Then when that user logs in they can only see the link to their page (all other links are hidden)

This is now the problem I have:

This works on a DataTable row number so when adding a new web form it re-arranges the DataTable row numbers which then when the user logs in again they can see all other links cause the table numbers have changed.

So to give a visual idea:

```<code>if (Session["Privilege"] != null)
        {
            DataTable dtPrivilege = (DataTable)Session["Privilege"];

            /* Dashboard */
            if (bool.Parse(dtPrivilege.Rows[1]["Read"].ToString()) == false && dtPrivilege.Rows[1]["FormName"].ToString() == "dashboard.aspx")
                lnkDashboard.Visible = false;

            /* Settings */
            if (bool.Parse(dtPrivilege.Rows[2]["Read"].ToString()) == false && dtPrivilege.Rows[2]["FormName"].ToString() == "general.aspx")
                lnkSettings.Visible = false;

            /* Web Pages */
            if (bool.Parse(dtPrivilege.Rows[0]["Read"].ToString()) == false)
                lnkWebpages.Visible = false;
            else
            {
                if (bool.Parse(dtPrivilege.Rows[0]["Read"].ToString()) == false && dtPrivilege.Rows[0]["FormName"].ToString() == "Webpage1.aspx")
                    lnkWebpage1.Visible = false;
            }
</code>```

So it reads by row number so when you add another page it messes up the row number and the 1st users saved in the database then gets the wrong link assigned to their privilege, because it moved the row number to 1 or 2 depending on how many web forms have been added.

So my question is, how can I make it so that it reads the string instead of the row number?  So for example

```<code>  if (Session["Privilege"] != null)
        {
            DataTable dtPrivilege = (DataTable)Session["Privilege"];

            /* Web Pages */
            if (bool.Parse(dtPrivilege.Rows[0]["Read"].ToString()) == false)
                lnkWebpages.Visible = false;
            else
            {
                if (bool.Parse(dtPrivilege.Rows[**Webpage1.aspx**]["Read"].ToString()) == false && dtPrivilege.Rows[0]["FormName"].ToString() == "Webpage1.aspx")
                    lnkWebpage1.Visible = false;
            }
</code>```

Is this possible and if so how can I achieve my goal?

Please let me know if you need more info or I haven't explained properly :-)

Thanks

答:
You can use Linq to achieve this.

Add using System.Linq; at the top of your .cs page.

Then add below line to generate IEnumerable(Array) of all rows inside dtPrivilege DataTable,

```<code>DataRow[] allRows = dtPrivilege.Select();
</code>```

And finally, add if blocks like below for all your webpages.

```<code>if (allRows.Any(x => x["FormName"].ToString() == "Webpage1.aspx" &&
                     x["Read"].ToString().ToLower() == "false"))
{
    lnkWebpage1.Visible = false;
}
</code>```

What above if block says:

It checks if there exists Any row in allRows, which has FormName = "Webpage1.aspx" and Read = "false". And if it exist, just set lnkWebpage1.Visible = false

Body:
In my web app the admin can assign a web page to a specific user, therefore that user can only access that specific page.

So to give an idea of how this works:

in my database I have a table with the web pages in, Webpage1.aspx, Webpage2.aspx etc.

The admin can create an user assign Webpage1.aspx to that user

Then when that user logs in they can only see the link to their page (all other links are hidden)

This is now the problem I have:

This works on a DataTable row number so when adding a new web form it re-arranges the DataTable row numbers which then when the user logs in again they can see all other links cause the table numbers have changed.

So to give a visual idea:

if (Session["Privilege"] != null)
        {
            DataTable dtPrivilege = (DataTable)Session["Privilege"];

            /* Dashboard */
            if (bool.Parse(dtPrivilege.Rows[1]["Read"].ToString()) == false && dtPrivilege.Rows[1]["FormName"].ToString() == "dashboard.aspx")
                lnkDashboard.Visible = false;

            /* Settings */
            if (bool.Parse(dtPrivilege.Rows[2]["Read"].ToString()) == false && dtPrivilege.Rows[2]["FormName"].ToString() == "general.aspx")
                lnkSettings.Visible = false;

            /* Web Pages */
            if (bool.Parse(dtPrivilege.Rows[0]["Read"].ToString()) == false)
                lnkWebpages.Visible = false;
            else
            {
                if (bool.Parse(dtPrivilege.Rows[0]["Read"].ToString()) == false && dtPrivilege.Rows[0]["FormName"].ToString() == "Webpage1.aspx")
                    lnkWebpage1.Visible = false;
            }

So it reads by row number so when you add another page it messes up the row number and the 1st users saved in the database then gets the wrong link assigned to their privilege, because it moved the row number to 1 or 2 depending on how many web forms have been added.

So my question is, how can I make it so that it reads the string instead of the row number?  So for example

  if (Session["Privilege"] != null)
        {
            DataTable dtPrivilege = (DataTable)Session["Privilege"];

            /* Web Pages */
            if (bool.Parse(dtPrivilege.Rows[0]["Read"].ToString()) == false)
                lnkWebpages.Visible = false;
            else
            {
                if (bool.Parse(dtPrivilege.Rows[**Webpage1.aspx**]["Read"].ToString()) == false && dtPrivilege.Rows[0]["FormName"].ToString() == "Webpage1.aspx")
                    lnkWebpage1.Visible = false;
            }

Is this possible and if so how can I achieve my goal?

Please let me know if you need more info or I haven't explained properly :-)

Thanks

Body:
You can use Linq to achieve this.

Add using System.Linq; at the top of your .cs page.

Then add below line to generate IEnumerable(Array) of all rows inside dtPrivilege DataTable,

DataRow[] allRows = dtPrivilege.Select();

And finally, add if blocks like below for all your webpages.

if (allRows.Any(x => x["FormName"].ToString() == "Webpage1.aspx" &&
                     x["Read"].ToString().ToLower() == "false"))
{
    lnkWebpage1.Visible = false;
}

What above if block says:

It checks if there exists Any row in allRows, which has FormName = "Webpage1.aspx" and Read = "false". And if it exist, just set lnkWebpage1.Visible = false


问:
Google Calendar API Service Account Error 401 Invalid credential
I'm trying to create a Google Calendar Service Account.

Here are my credentials:

Here's my service account definition (Site Wide delegation for service account is enabled):

Here's my "Manage API client access" page:

And this is my code:

```<code>        string userName = "xxx@yyy.it";
        string[] Scopes = { CalendarService.Scope.Calendar, CalendarService.Scope.CalendarEvents };
        string ApplicationName = "Client per quickstart";
        ServiceAccountCredential credential = GoogleCredential.FromFile(@"path\credentialjson.json").CreateScoped(Scopes).CreateWithUser(userName).UnderlyingCredential as ServiceAccountCredential;

        // Create Google Calendar API service.
        var service = new CalendarService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = ApplicationName
        });
        // THIS REQUEST FAILS!!
        var y = service.CalendarList.List().Execute();

</code>```

The service is created correctly but all requests fail with this error:

Code: 401, Message: "Invalid Credentials", Location: "Authorization", >LocationType: "header", Reason: "authError", Domain: "global"

I don't understand what I'm missing in the authorization header.

What should I set before the request that was not done when creating the service? Thanks!

答:
Do you see the text over the top of your credentials

OAuth 2.0 Client IDs

Go to google developer console click + create credentials pick service account from the drop down.  You need to ensure that you have downloaded the key fine for the Service account and not for the Oauth2 client.   The message you are seeing states that you have the wrong client type.  Try and download the service account key file again.

example of service account credentials

You have created oauth2 credentials not service account creditnals.

```<code>GoogleCredential credential;
                    using (var stream = new FileStream(serviceAccountCredentialFilePath, FileMode.Open, FileAccess.Read))
                    {
                        credential = GoogleCredential.FromStream(stream)
                             .CreateScoped(scopes);
                    }

                    // Create the  Analytics service.
                    return new CalendarService(new BaseClientService.Initializer()
                    {
                        HttpClientInitializer = credential,
                        ApplicationName = "Calendar Service account Authentication Sample",
                    });
</code>```

Body:
I'm trying to create a Google Calendar Service Account.

Here are my credentials:

Here's my service account definition (Site Wide delegation for service account is enabled):

Here's my "Manage API client access" page:

And this is my code:

        string userName = "xxx@yyy.it";
        string[] Scopes = { CalendarService.Scope.Calendar, CalendarService.Scope.CalendarEvents };
        string ApplicationName = "Client per quickstart";
        ServiceAccountCredential credential = GoogleCredential.FromFile(@"path\credentialjson.json").CreateScoped(Scopes).CreateWithUser(userName).UnderlyingCredential as ServiceAccountCredential;

        // Create Google Calendar API service.
        var service = new CalendarService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = ApplicationName
        });
        // THIS REQUEST FAILS!!
        var y = service.CalendarList.List().Execute();

The service is created correctly but all requests fail with this error:

Code: 401, Message: "Invalid Credentials", Location: "Authorization", >LocationType: "header", Reason: "authError", Domain: "global"

I don't understand what I'm missing in the authorization header.

What should I set before the request that was not done when creating the service? Thanks!

Body:
Do you see the text over the top of your credentials

OAuth 2.0 Client IDs

Go to google developer console click + create credentials pick service account from the drop down.  You need to ensure that you have downloaded the key fine for the Service account and not for the Oauth2 client.   The message you are seeing states that you have the wrong client type.  Try and download the service account key file again.

example of service account credentials

You have created oauth2 credentials not service account creditnals.

GoogleCredential credential;
                    using (var stream = new FileStream(serviceAccountCredentialFilePath, FileMode.Open, FileAccess.Read))
                    {
                        credential = GoogleCredential.FromStream(stream)
                             .CreateScoped(scopes);
                    }

                    // Create the  Analytics service.
                    return new CalendarService(new BaseClientService.Initializer()
                    {
                        HttpClientInitializer = credential,
                        ApplicationName = "Calendar Service account Authentication Sample",
                    });


问:
How to allow nodes of one GKE cluster to connect to another GKE
I have a GKE clusters setup, dev and stg let's say, and wanted apps running in pods on stg nodes to connect to dev master and execute some commands on that's GKE - I have all the setup I need and when I add from hand IP address of the nodes all works fine but the IP's are changing,

so my question is how can I add to Master authorised networks the ever-changing default-pool IPs of nodes from the other cluster?

EDIT: I think I found the solution, it's not the node IP but the NAT IP I have added to authorized networks, so assuming I don't change those I just need to add the NAT I guess, unless someone knows better solution ?

答:
What you really need to do is configure the kubectl in jenkins pipeline to connect to GKE Master IP. The master is responsible for accepting your commands (rollback, deployment, etc). See Configuring cluster access for kubectl

The Master IP is available in the Kubernetes Engine console along with the Certificate Authority certificate. A good approach is to use a service account token to authenticate with the master. See how to Login to GKE via service account with token.


问:
javascript variable value as a link
I have a variable and I would like to add a link for its value. This below example only returns the html. How can I make this a clickable link when its returned?</p>

```<code>var link = 'new link: <a href="http://test.com/" target="_blank"><b>Clink Here</font></b></a>'
</code>```

答:
This should help you:

```<code>var myDiv = document.createElement("div");
var link = 'new link: <a href="http://test.com/" target="_blank"><b>Clink Here</font></b></a>'
myDiv.innerHTML = link;
document.body.appendChild(myDiv);
</code>```

For the id:

```<code>myDiv.id = "myLink";
alert(document.getElementById('myLink').innerHTML);
</code>```

Title: javascript variable value as a link

Body:
I have a variable and I would like to add a link for its value. This below example only returns the html. How can I make this a clickable link when its returned?

var link = 'new link: Clink Here'

Body:
This should help you:

var myDiv = document.createElement("div");
var link = 'new link: <a href="http://test.com/" target="_blank"><b>Clink Here</font></b></a>'
myDiv.innerHTML = link;
document.body.appendChild(myDiv);

For the id:

myDiv.id = "myLink";
alert(document.getElementById('myLink').innerHTML);


问:
How to replace NA with set of values
I have the following data frame:

```<code>library(dplyr)
library(tibble)

df <- tibble(
  source = c("a", "b", "c", "d", "e"),
  score = c(10, 5, NA, 3, NA ) )

df
</code>```

It looks like this:

```<code># A tibble: 5 x 2
  source score
  <chr>  <dbl>
1 a         10 . # current max value
2 b          5
3 c         NA
4 d          3
5 e         NA
</code>```

What I want to do is to replace NA in score column with values ranging for existing max  + n onwards. Where n range from 1 to total number of rows of the df

Resulting in this (hand-coded) :

```<code>  source score
  a         10
  b          5
  c         11 # obtained from 10 + 1
  d          3
  e         12 #  obtained from 10 + 2
</code>```

How can I achieve that?

答:
Not quite elegant as compared to the base R solutions, but still possible:

```<code>library(data.table)
setDT(df)

max.score = df[, max(score, na.rm = TRUE)]
df[is.na(score), score :=(1:.N) + max.score]
</code>```

Or in one line but a bit slower:

```<code>df[is.na(score), score := (1:.N) + df[, max(score, na.rm = TRUE)]]
df
   source score
1:      a    10
2:      b     5
3:      c    11
4:      d     3
5:      e    12
</code>```

Title: How to replace NA with set of values

Body:
I have the following data frame:

library(dplyr)
library(tibble)

df <- tibble(
  source = c("a", "b", "c", "d", "e"),
  score = c(10, 5, NA, 3, NA ) )

df

It looks like this:

# A tibble: 5 x 2
  source score
  <chr>  <dbl>
1 a         10 . # current max value
2 b          5
3 c         NA
4 d          3
5 e         NA

What I want to do is to replace NA in score column with values ranging for existing max  + n onwards. Where n range from 1 to total number of rows of the df

Resulting in this (hand-coded) :

  source score
  a         10
  b          5
  c         11 # obtained from 10 + 1
  d          3
  e         12 #  obtained from 10 + 2

How can I achieve that?

Body:
Not quite elegant as compared to the base R solutions, but still possible:

library(data.table)
setDT(df)

max.score = df[, max(score, na.rm = TRUE)]
df[is.na(score), score :=(1:.N) + max.score]

Or in one line but a bit slower:

df[is.na(score), score := (1:.N) + df[, max(score, na.rm = TRUE)]]
df
   source score
1:      a    10
2:      b     5
3:      c    11
4:      d     3
5:      e    12


问:
How can I configure babel/preset-env to include core-js URLSearchParams polyfill?
I'm using URLSearchParams in my app. The code is transpiled with babel, using babel/preset-env and core-js@3 to include polyfills needed for the browsers I target.

This is my babelrc:

```<code>{
  "presets": [
    [
      "@babel/preset-env",
      {
        "modules": false,
        "corejs": "3",
        "useBuiltIns": "entry",
        "forceAllTransforms": true
      }
    ]
  ]
}
</code>```

Here is my .browserslistrc:

```<code>IE 11
Edge >= 14
last 2 Chrome versions
last 2 Firefox versions
</code>```

The problem is that even though I've specified IE11 in .browserslistrc, the polyfill for URLSearchParams is still not included in the final bundle. So far I've solved this by manually importing core-js/web/url-search-params.js but I would rather that was done automatically by babel/preset-env.

Can I configure babel/preset-env somehow to include the URLSearchParams polyfill from core-js?

答:
Since I'm getting upvotes on the question I should probably add my answer here as well.

The problem for me was that I was adding @babel/polyfill next to my entrypoint in my webpack config:

```<code>{
  entry: {
    "my.js": ["@babel/polyfill", "my.js"]
  }
}
</code>```

To fix my problem I removed @babel/polyfill from the entrypoint, and instead added the following to the top of my.js:

```<code>import "core-js/stable";
import "regenerator-runtime/runtime";
</code>```

Body:
I'm using URLSearchParams in my app. The code is transpiled with babel, using babel/preset-env and core-js@3 to include polyfills needed for the browsers I target.

This is my babelrc:

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "modules": false,
        "corejs": "3",
        "useBuiltIns": "entry",
        "forceAllTransforms": true
      }
    ]
  ]
}

Here is my .browserslistrc:

IE 11
Edge >= 14
last 2 Chrome versions
last 2 Firefox versions

The problem is that even though I've specified IE11 in .browserslistrc, the polyfill for URLSearchParams is still not included in the final bundle. So far I've solved this by manually importing core-js/web/url-search-params.js but I would rather that was done automatically by babel/preset-env.

Can I configure babel/preset-env somehow to include the URLSearchParams polyfill from core-js?

Body:
Since I'm getting upvotes on the question I should probably add my answer here as well.

The problem for me was that I was adding @babel/polyfill next to my entrypoint in my webpack config:

{
  entry: {
    "my.js": ["@babel/polyfill", "my.js"]
  }
}

To fix my problem I removed @babel/polyfill from the entrypoint, and instead added the following to the top of my.js:

import "core-js/stable";
import "regenerator-runtime/runtime";


问:
React-Redux useSelector typescript type for state
I'm using the useSelector(state => state.SLICE_NAME) hook from React-Redux however I'm having difficulty defining the state parameter. It is set by default as unknown so I get an error when I try to return state.SLICE_NAME (Error: Object is of type 'unknown').

How do I define the state type without having to manually create a separate state type and adding in every new state definition as they're created?

I've tried defining state as typeof store however that doesn't work.

Some code to help explain:

```<code>// navDrawer.ts

import { createSlice } from "redux-starter-kit";

// navDrawer initial state
export interface NavDrawerInitialState {
  open: boolean;
}

const navDrawerInitialState: NavDrawerInitialState = {
  open: false
};

// Create state slice
const { actions, reducer } = createSlice({
  slice: "navDrawer",
  initialState: navDrawerInitialState,
  reducers: {
    open: (state: NavDrawerInitialState) => {
      state.open = true;
    },
    close: (state: NavDrawerInitialState) => {
      state.open = false;
    }
  }
});

export const navDrawerActions = actions;
export default reducer;
</code>```

```<code>// reducers.ts

import navDrawer from "./navDrawer";

const reducers = {
  navDrawer
};

export default reducers;
</code>```

```<code>// store.ts

import { configureStore } from "redux-starter-kit";
import reducer from "./reducers";

const store = configureStore({
  reducer
});

export default store;
</code>```

```<code>// Page.tsx

import React, { FC } from "react";
import { Provider } from "react-redux";
import store from "./store";
import ChildComponent from "./ChildComponent";

const StateProvider: FC = () => {
  return <Provider store={store}><ChildComponent /></Provider>;
};

export default StateProvider;
</code>```

```<code>// ChildComponent.tsx

import React, { FC } from "react";
import { useSelector } from "react-redux";

const ChildComponent: FC = () => {
  const navDrawerState = useSelector(state => state.navDrawer); // ERROR OCCURS HERE. "state" is defined as 'unknown' so "state.navDrawer" throws an error.
  return <div>Text</div>
}
</code>```

Edit: I noticed that the type definition for configureStore() contains the state as the first generic type. See screenshot below. If I can get the first generic value from EnhancedStore then I'll be able to use that to define state. Is there any way I can do this in Typescript?

答:
This might not be the answer but I use it like so:

```<code>const isLoggedIn = useSelector<IRootState, boolean>(state => state.user.loggedIn);
</code>```

EDIT: Or use Peter's answer which is shorter/cleaner

```<code>const isLoggedIn = useSelector((state: IRootState) => state.user.loggedIn);
</code>```

Body:
I'm using the useSelector(state => state.SLICE_NAME) hook from React-Redux however I'm having difficulty defining the state parameter. It is set by default as unknown so I get an error when I try to return state.SLICE_NAME (Error: Object is of type 'unknown').

How do I define the state type without having to manually create a separate state type and adding in every new state definition as they're created?

I've tried defining state as typeof store however that doesn't work.

Some code to help explain:

// navDrawer.ts

import { createSlice } from "redux-starter-kit";

// navDrawer initial state
export interface NavDrawerInitialState {
  open: boolean;
}

const navDrawerInitialState: NavDrawerInitialState = {
  open: false
};

// Create state slice
const { actions, reducer } = createSlice({
  slice: "navDrawer",
  initialState: navDrawerInitialState,
  reducers: {
    open: (state: NavDrawerInitialState) => {
      state.open = true;
    },
    close: (state: NavDrawerInitialState) => {
      state.open = false;
    }
  }
});

export const navDrawerActions = actions;
export default reducer;

// reducers.ts

import navDrawer from "./navDrawer";

const reducers = {
  navDrawer
};

export default reducers;

// store.ts

import { configureStore } from "redux-starter-kit";
import reducer from "./reducers";

const store = configureStore({
  reducer
});

export default store;

// Page.tsx

import React, { FC } from "react";
import { Provider } from "react-redux";
import store from "./store";
import ChildComponent from "./ChildComponent";

const StateProvider: FC = () => {
  return <Provider store={store}><ChildComponent /></Provider>;
};

export default StateProvider;

// ChildComponent.tsx

import React, { FC } from "react";
import { useSelector } from "react-redux";

const ChildComponent: FC = () => {
  const navDrawerState = useSelector(state => state.navDrawer); // ERROR OCCURS HERE. "state" is defined as 'unknown' so "state.navDrawer" throws an error.
  return
Text

}

Edit: I noticed that the type definition for configureStore() contains the state as the first generic type. See screenshot below. If I can get the first generic value from EnhancedStore then I'll be able to use that to define state. Is there any way I can do this in Typescript?

Body:
This might not be the answer but I use it like so:

const isLoggedIn = useSelector<IRootState, boolean>(state => state.user.loggedIn);

EDIT: Or use Peter's answer which is shorter/cleaner

const isLoggedIn = useSelector((state: IRootState) => state.user.loggedIn);


问:
How to fix MissingPluginException on Agora video call?
I'm building an App which can make Video calls, I'm using Agora SDK for the feature. I'm having a problem when I want to run the app on my device. Naturally it would ask for Camera and Microphone permission but it doesn't ask me and the video call feature won't start. Here's some of my code:

The Function that gives me the error

```<code>  Future<void> onJoin() async {
    // update input validation
    setState(() {
      _channelController.text.isEmpty
          ? _validateError = true
          : _validateError = false;
    });
    if (_channelController.text.isNotEmpty) {
      // await for camera and mic permissions before pushing video page
      await _handleCameraAndMic(); // doesn't asks for any permissions so the video call won't start
      //await _permissions();
      // push video page with given channel name
      await Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => CallPage(
            channelName: _channelController.text,
          ),
        ),
      );
    }
  }

  Future<void> _handleCameraAndMic() async {
    await PermissionHandler().requestPermissions(
      [PermissionGroup.camera, PermissionGroup.microphone],
    );
  }
</code>```

The Exception I'm getting

Unhandled Exception: MissingPluginException(No implementation found
  for method requestPermissions on channel
  flutter.baseflow.com/permissions/methods)

I'm using this as a reference for bulding the feature

I'm not sure where did I do wrong because I'm very new to flutter development. Any help would be appreciated and if you need more code I will provide it to you, just feel free to ask. Thank you.

答:
There is an open issue on their repo, see this.

Probably the plugin is buggy, so you may try some other plugin.

Body:
I'm building an App which can make Video calls, I'm using Agora SDK for the feature. I'm having a problem when I want to run the app on my device. Naturally it would ask for Camera and Microphone permission but it doesn't ask me and the video call feature won't start. Here's some of my code:

The Function that gives me the error

  Future<void> onJoin() async {
    // update input validation
    setState(() {
      _channelController.text.isEmpty
          ? _validateError = true
          : _validateError = false;
    });
    if (_channelController.text.isNotEmpty) {
      // await for camera and mic permissions before pushing video page
      await _handleCameraAndMic(); // doesn't asks for any permissions so the video call won't start
      //await _permissions();
      // push video page with given channel name
      await Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => CallPage(
            channelName: _channelController.text,
          ),
        ),
      );
    }
  }

  Future<void> _handleCameraAndMic() async {
    await PermissionHandler().requestPermissions(
      [PermissionGroup.camera, PermissionGroup.microphone],
    );
  }

The Exception I'm getting

Unhandled Exception: MissingPluginException(No implementation found
  for method requestPermissions on channel
  flutter.baseflow.com/permissions/methods)

I'm using this as a reference for bulding the feature

I'm not sure where did I do wrong because I'm very new to flutter development. Any help would be appreciated and if you need more code I will provide it to you, just feel free to ask. Thank you.


问:
Write text on spreadsheet cell
I use Farpoint Spread Version 5.0.3514.2008.(Visual Studio 2015, .Net 4.0, C#)

And I want to input long text into spread cell.

But when string length is larger than 15153 then the sheet(Cell) can't show data normally.

I didn't set-up MultiLine Properties.

答:
```<code>FarPoint.Win.Spread.CellType.TextCellType tcell = new FarPoint.Win.Spread.CellType.TextCellType();

 tcell.CharacterCasing = CharacterCasing.Upper; tcell.CharacterSet = FarPoint.Win.Spread.CellType.CharacterSet.Ascii; tcell.MaxLength = 30; tcell.Multiline = true; fpSpread1.ActiveSheet.Cells[0, 0].Text = "This is a text cell. ";

 fpSpread1.ActiveSheet.Cells[0, 0].CellType = tcell;
</code>```

Using Code

Define the text cell by creating an instance of the TextCellType
class.

Create a message to display to the user when the entry is not

valid.

Assign the text cell type to a cell or range of cells by set ting the CellType property for a cell, column, row, or style to the TextCellType object.

Title: Write text on spreadsheet cell

Body:
FarPoint.Win.Spread.CellType.TextCellType tcell = new FarPoint.Win.Spread.CellType.TextCellType();

 tcell.CharacterCasing = CharacterCasing.Upper; tcell.CharacterSet = FarPoint.Win.Spread.CellType.CharacterSet.Ascii; tcell.MaxLength = 30; tcell.Multiline = true; fpSpread1.ActiveSheet.Cells[0, 0].Text = "This is a text cell. ";

 fpSpread1.ActiveSheet.Cells[0, 0].CellType = tcell;

Using Code

Define the text cell by creating an instance of the TextCellType
class.

Create a message to display to the user when the entry is not

valid.

Assign the text cell type to a cell or range of cells by set ting the CellType property for a cell, column, row, or style to the TextCellType object.


问:
Adding Google Maps dynamically in Spring (MVC or Boot)
I am developing an application on rental system in Spring Boot. I need help for adding the google map marker(s) dynamically and displaying it for each rooms I add.<br>
For e.g : While adding room details then also saving google map marker for each into MySQL database and displaying it. </p>

答:
Storing locations for stores is easy, as it is just a class containing latitude and longitude. It could be something like this (for more information, see the guide by Spring):

@Entity
public class Position {

  @Id
  @GeneratedValue(strategy=GenerationType.AUTO)
  private Long id;
  private Long latitude;
  private Long longitude;

  @OneToOne
  private Store store;

  protected Position() {}

  public Position(long latitude, longitude, Store store) {
    this.latitude = latitude;
    this.longitude = longitude;
    this.store = store;
  }

  // Standard Getters and Setters
}
```

<p>Using this object, you can pass the latitude and longitude to the MVC controller, which should inject the values in the following piece of code (from the Google Documentation): </p>

<pre class="lang-html prettyprint-override"><code><div id="map"></div>
<script th:inline="javascript">
  /*<![CDATA[*/
  function initMap() {
    // The location of the map
    var shop = { lat: /*[[${session.shop.latitude}]]*/, lng: /*[[${session.shop.longitude}]]*/ };
    var map = new google.maps.Map(
      document.getElementById('map'), { zoom: 4, center: shop });
    var marker = new google.maps.Marker({ position: shop, map: map });
  }
/*]]>*/
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
</code>```

Body:
I am developing an application on rental system in Spring Boot. I need help for adding the google map marker(s) dynamically and displaying it for each rooms I add.

For e.g : While adding room details then also saving google map marker for each into MySQL database and displaying it.

Body:
Storing locations for stores is easy, as it is just a class containing latitude and longitude. It could be something like this (for more information, see the guide by Spring):

@Entity
public class Position {

  @Id
  @GeneratedValue(strategy=GenerationType.AUTO)
  private Long id;
  private Long latitude;
  private Long longitude;

  @OneToOne
  private Store store;

  protected Position() {}

  public Position(long latitude, longitude, Store store) {
    this.latitude = latitude;
    this.longitude = longitude;
    this.store = store;
  }

  // Standard Getters and Setters
}

Using this object, you can pass the latitude and longitude to the MVC controller, which should inject the values in the following piece of code (from the Google Documentation):

<div id="map"></div>
<script th:inline="javascript">
  /*<![CDATA[*/
  function initMap() {
    // The location of the map
    var shop = { lat: /*[[${session.shop.latitude}]]*/, lng: /*[[${session.shop.longitude}]]*/ };
    var map = new google.maps.Map(
      document.getElementById('map'), { zoom: 4, center: shop });
    var marker = new google.maps.Marker({ position: shop, map: map });
  }
/*]]>*/
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>


问:
laravel Could not open input file: artisan (5.3)
I'm new to Laravel ad i have just created new project using official laravel documentation.

After installing when i run php artisan migrate it will showing

Could not open input file: artisan error in console

Listing of commands that i run

composer create-project --prefer-dist laravel/laravel laravelDemo

which will create new folder laravelDemo

cd laravelDemo

php artisan migrate

I'm using Ubuntu 16.04

I have already checked possible duplicate answer but i have installed it throw composer.

Please help Thanks in Advance :)

答:
The problem is you type the command out of laravelDemo folder.
please go into this folder by running:
cd laravelDemo
and try again.</p>


问:
How to enable or install PHP's mysql_xdevapi extension in WAMPServer to install datatable?
I wanted  to install DataTable in laravel, I used WAMPServer and my

```<code>PHP version is 7.3.5,
Mysql version 5.7.26.
</code>```

I follow many steps on the internet, such as download from pecl.php.net but my problem remain.

When write

```<code>composer require yajra/laravel-datatables-oracle:^9.0
</code>```

in CMD, after wile the below error showed and cause installation stop.
Error: problem1

-The requested PHP extension ext-mysql_xdevapi * is missing from your system. Install or enable PHP's mysql_xdevapi extension.

答:
php_mysql_devapi extension provides access to the MySQL Document Store via the X DevAPI.

The XDevAPI is a common API provided by multiple MySQL Connectors providing easy access to relational tables as well as collections of documents, which are represented in JSON, from a API with CRUD-style operations.

The X DevAPI uses the X Protocol, the new generation client-server protocol of the MySQL 8.0 server.

To install this extension, you need to have mysql 8 on your system.

Wamp

After installing mysql 8 follow these steps to install php_mysql_xdevapi.

```<code>Go to this link https://pecl.php.net/package/mysql_xdevapi to download the .dll for the php_mysql_xdevapi .

After downloading the extension paste in your php installation directory subfolder ext C:\wamp64\bin\php\php7.2.4\ext.

Now you have to add this extension in the php.ini file near the dynamic extensions. extension=php_mysql_xdevapi.dll
</code>```

One important caveat is that in wamp default mysql 8 installation , XDevApi

plugin is disable, you have to enable it by commenting the part which is disabling mysql_xdevapi.

```<code> ;Disabling X Plugin
       ;mysqlx=0
</code>```

Now you successfully have install the php_mysql_xdevapi on wamp, to see it working,

```<code>$session = mysql_xdevapi\getSession('mysqlx://<user>:<password>@host:33060?connect-timeout=5000&ssl-mode=disabled');
</code>```

More Info

Body:
I wanted  to install DataTable in laravel, I used WAMPServer and my

PHP version is 7.3.5,
Mysql version 5.7.26.

I follow many steps on the internet, such as download from pecl.php.net but my problem remain.

When write

composer require yajra/laravel-datatables-oracle:^9.0

in CMD, after wile the below error showed and cause installation stop.
Error: problem1

-The requested PHP extension ext-mysql_xdevapi * is missing from your system. Install or enable PHP's mysql_xdevapi extension.

Body:
php_mysql_devapi extension provides access to the MySQL Document Store via the X DevAPI.

The XDevAPI is a common API provided by multiple MySQL Connectors providing easy access to relational tables as well as collections of documents, which are represented in JSON, from a API with CRUD-style operations.

The X DevAPI uses the X Protocol, the new generation client-server protocol of the MySQL 8.0 server.

To install this extension, you need to have mysql 8 on your system.

Wamp

After installing mysql 8 follow these steps to install php_mysql_xdevapi.

Go to this link https://pecl.php.net/package/mysql_xdevapi to download the .dll for the php_mysql_xdevapi .

After downloading the extension paste in your php installation directory subfolder ext C:\wamp64\bin\php\php7.2.4\ext.

Now you have to add this extension in the php.ini file near the dynamic extensions. extension=php_mysql_xdevapi.dll

One important caveat is that in wamp default mysql 8 installation , XDevApi

plugin is disable, you have to enable it by commenting the part which is disabling mysql_xdevapi.

 ;Disabling X Plugin
       ;mysqlx=0

Now you successfully have install the php_mysql_xdevapi on wamp, to see it working,

$session = mysql_xdevapi\getSession('mysqlx://<user>:<password>@host:33060?connect-timeout=5000&ssl-mode=disabled');

More Info


问:
avoid parsing last separator with `sepBy`
I'm trying to parse a string using megaparsec.

Part of it is a repetition of strings separated by a separator and I'm using sepBy for this.
Consider for example

```<code>sepBy (char 'a') (char 's')
</code>```

This parses correctly "", "a", "asa", ...
The problem appears if I need to continue parsing with another parser which starts with my separator, as in

```<code>(,) <$> sepBy (char 'a') (char 's') <*> string "something"
</code>```

If I try to parse the string "asasomething" with this parser I'd expect to get ("aa", "something"). Instead I get an error because I don't have an a after the second s.

I tried also with sepEndBy but the result is the same

答:
I solved it as follows.

The implementation of sepBy used by megapersec is

```<code>sepBy :: MonadPlus m => m a -> m sep -> m [a]
sepBy p sep = do
  r <- C.optional p
  case r of
    Nothing -> return []
    Just  x -> (x:) <$> many (sep >> p)
</code>```

I modified it to

```<code>sepBy :: Parser a -> Parser sep -> Parser [a]
sepBy p sep = do
  r <- optional p
  case r of
    Nothing -> return []
    Just  x -> (x:) <$> many (try $ sep >> p)
</code>```

to specialise it to Parsec add a try to avoid eager parsing

Body:
I'm trying to parse a string using megaparsec.

Part of it is a repetition of strings separated by a separator and I'm using sepBy for this.
Consider for example

sepBy (char 'a') (char 's')

This parses correctly "", "a", "asa", ...
The problem appears if I need to continue parsing with another parser which starts with my separator, as in

(,) <$> sepBy (char 'a') (char 's') <*> string "something"

If I try to parse the string "asasomething" with this parser I'd expect to get ("aa", "something"). Instead I get an error because I don't have an a after the second s.

I tried also with sepEndBy but the result is the same

Body:
I solved it as follows.

The implementation of sepBy used by megapersec is

sepBy :: MonadPlus m => m a -> m sep -> m [a]
sepBy p sep = do
  r <- C.optional p
  case r of
    Nothing -> return []
    Just  x -> (x:) <$> many (sep >> p)

I modified it to

sepBy :: Parser a -> Parser sep -> Parser [a]
sepBy p sep = do
  r <- optional p
  case r of
    Nothing -> return []
    Just  x -> (x:) <$> many (try $ sep >> p)

to specialise it to Parsec add a try to avoid eager parsing


问:
Replacing values in particular row with another row in R language
I have matrix and i want to replace the fourth row enteries with the 1st row values. Which R command would help me?
I am using replace command but its giving me dimension error.</p>

```<code>> replace(g1,g[1,],g[2,])
     [,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,]    4    2    2    3    4    5    6
[2,]    5    6    0    1    2    3    4
[3,]    6    5    6    0    1    2    3
[4,]    0   NA   NA   NA   NA   NA   NA
[5,]    1   NA   NA   NA   NA   NA   NA
</code>```

答:
You can solve it without use any external functions:

```<code>g1[4,] <- g1[1,]
</code>```

Taking all the columns values for the 4th row and replace it with the first row.

Body:
I have matrix and i want to replace the fourth row enteries with the 1st row values. Which R command would help me?
I am using replace command but its giving me dimension error.

> replace(g1,g[1,],g[2,])
     [,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,]    4    2    2    3    4    5    6
[2,]    5    6    0    1    2    3    4
[3,]    6    5    6    0    1    2    3
[4,]    0   NA   NA   NA   NA   NA   NA
[5,]    1   NA   NA   NA   NA   NA   NA

Body:
You can solve it without use any external functions:

g1[4,] <- g1[1,]

Taking all the columns values for the 4th row and replace it with the first row.


问:
How to update status in DataTable listing page in Laravel
I need without refresh listing page update status of record. I have tried it with full page refresh but I want to an AJAX feature with Laravel rules.</p>

答:
Add Jquery in footer

Add list view page this function

Add your datatables

```<code>$('#table_user').on('click', '.status_clik', function(){
 var sid = $(this).attr("sid");
$.ajax({
    type: "POST",
    url: '/pageController/updateStatus',
    data: {id: sid},
    success: function(response) { // Change elements in the DOM },
});
});
</code>```

In controller page

```<code>class PageController {
    public function status(Request $request){
        $id = $request->get('id');
        if($id!=''){
            $geStatus = DB::table('tablename')->where('id', $id)->first();

            $update_data = array('eStatus'=>GET_OPPOSITE_STATUS[$geStatus->eStatus]);
            $update = DB::table('tablename')->where('id', $id)->update($update_data);
            if($update){

                return response()->json(array("status"=>1,"message"=>'Status updated successfully'));

            }else{ return response()->json(array("status"=>0,"message"=>_FAIL_TO_PROCESS)); }
        }else{return response()->json(array("status"=>0,"message"=>_FAIL_TO_PROCESS));}
    }

}
</code>```

Body:
Add Jquery in footer

Add list view page this function

Add your datatables

$('#table_user').on('click', '.status_clik', function(){
 var sid = $(this).attr("sid");
$.ajax({
    type: "POST",
    url: '/pageController/updateStatus',
    data: {id: sid},
    success: function(response) { // Change elements in the DOM },
});
});

In controller page

class PageController {
    public function status(Request $request){
        $id = $request->get('id');
        if($id!=''){
            $geStatus = DB::table('tablename')->where('id', $id)->first();

            $update_data = array('eStatus'=>GET_OPPOSITE_STATUS[$geStatus->eStatus]);
            $update = DB::table('tablename')->where('id', $id)->update($update_data);
            if($update){

                return response()->json(array("status"=>1,"message"=>'Status updated successfully'));

            }else{ return response()->json(array("status"=>0,"message"=>_FAIL_TO_PROCESS)); }
        }else{return response()->json(array("status"=>0,"message"=>_FAIL_TO_PROCESS));}
    }

}


问:
CSS Dropping For Certain Controls
We have a pretty complex application design with a bunch of telerik controls.  Every now and then, we get issues where the associated CSS to a file are lost, and the controls are not styled.  So for instance, after an async postback (a couple of postbacks into the life of the page), the CSS for the textbox, date picker, combo, and other controls are lost.  It's not complete; some controls still appear as they normally do, I don't think it's all inclusive.

Any idea why and how I can debug, and determine why they get lost?  Anything I can do to work around it?

Thanks.

Brian

答: Have you tried the RadStyleSheetManager?</p>

Title: CSS Dropping For Certain Controls


问:
Why the command to clean is not working in Gradle React native project?
I am trying to clean Gradle files after cd .\android, but it's not working. Please see the below command.

```<code>D:\ReactNativeVS\demo\android>./gradlew clean
</code>```

I get the following error:

'.' is not recognized as an internal or external command, operable
  program or batch file.

答: Please try by running: gradlew clean, without ./

Body:
I am trying to clean Gradle files after cd .\android, but it's not working. Please see the below command.

D:\ReactNativeVS\demo\android>./gradlew clean

I get the following error:

'.' is not recognized as an internal or external command, operable
  program or batch file.


问:
How to terminate continuous thread that detects new file
This is my first foray into both WatchService and multithreading.

I have an application that needs to detect when an external device issues a prompt for the user to do something. The prompt is delivered by way of an XML file dropped into a specific folder. The file is always titled "PRM.xml" and will overwrite previous PRM files if they exist. To prevent re-displaying old prompts, my code deletes the PRM file once displayed.

The application is user-interactive, so it is always listening for a PRM.xml in a background thread while the user is performing other activities on the main thread.

The problem is that when the user wants to end his session in the main thread (by typing sentinel "zzz"), the listening thread won't end, and the application only terminates if another event happens in the folder being monitored.

How do I force the background listening thread to quit when the user directs the main thread to terminate? (I hope I have included enough code to get a good response.)

```<code>// Method 'run' contains code to be executed in the thread
public void run() {

  try {
     // initiate new watch service to watch for new prompts
     WatchService ws = dirToWatch.getFileSystem().newWatchService();
     dirToWatch.register(ws, ENTRY_CREATE);

     // monitor directory continuously until main program thread ends
     while (!SmartTill.stCom.equals("ZZZ")) {

        // get new directory events
        WatchKey wk = ws.take();

        // loop through all retrieved events
        for (WatchEvent<?> event : wk.pollEvents()) {

           if (event.context().toString().endsWith(fileToDetect)) {
              System.out.println("DEBUG: Display Prompt, Delete PRM.");
              // ...call to "displayPrompt" method goes here...
              delFile(Paths.get(dirToWatch + fileToDetect));
           }// end if
        }// end for

     // reset the key (erase list of events)
     System.out.println("Key has been " +
             (wk.reset() ? "reset." : "unregistered."));
     }// end while
  }// end try
  catch(Exception e){}
}// end run
</code>```

答:
I had the same issue and i found this solution to be working,

the solution was to override the interrupt method (your class should extend Thread instead of Runnable) and close the watchService from there, this will throw ClosedWatchServiceException in your take() method, so you have to catch this exception

Override interrupt

```<code>@Override
public void interrupt() {
    super.interrupt();
    System.out.println("Interupt is called");
    try {

            watcher.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
</code>```

Handling exception

```<code>try {
            key = watcher.take();
        } catch (InterruptedException x) {
            System.out.println("take() is interrupted");
            Thread.currentThread().interrupt();
            return;
        } catch (ClosedWatchServiceException e) {
            System.out.println(" take is killed from closedException");
            return;
        }
</code>```

Main Thread

```<code>public static void main(String[] args) throws InterruptedException {
    WatchDir watchDir = new WatchDir(path);
    Thread.currentThread().sleep(1000);
    watchDir.shutDown();
    watchDir.interrupt();
    watchDir.join();
    System.out.println("the WatchDir thread is killed");
}
</code>```

Body:
This is my first foray into both WatchService and multithreading.

I have an application that needs to detect when an external device issues a prompt for the user to do something. The prompt is delivered by way of an XML file dropped into a specific folder. The file is always titled "PRM.xml" and will overwrite previous PRM files if they exist. To prevent re-displaying old prompts, my code deletes the PRM file once displayed.

The application is user-interactive, so it is always listening for a PRM.xml in a background thread while the user is performing other activities on the main thread.

The problem is that when the user wants to end his session in the main thread (by typing sentinel "zzz"), the listening thread won't end, and the application only terminates if another event happens in the folder being monitored.

How do I force the background listening thread to quit when the user directs the main thread to terminate? (I hope I have included enough code to get a good response.)

// Method 'run' contains code to be executed in the thread
public void run() {

  try {
     // initiate new watch service to watch for new prompts
     WatchService ws = dirToWatch.getFileSystem().newWatchService();
     dirToWatch.register(ws, ENTRY_CREATE);

     // monitor directory continuously until main program thread ends
     while (!SmartTill.stCom.equals("ZZZ")) {

        // get new directory events
        WatchKey wk = ws.take();

        // loop through all retrieved events
        for (WatchEvent<?> event : wk.pollEvents()) {

           if (event.context().toString().endsWith(fileToDetect)) {
              System.out.println("DEBUG: Display Prompt, Delete PRM.");
              // ...call to "displayPrompt" method goes here...
              delFile(Paths.get(dirToWatch + fileToDetect));
           }// end if
        }// end for

     // reset the key (erase list of events)
     System.out.println("Key has been " +
             (wk.reset() ? "reset." : "unregistered."));
     }// end while
  }// end try
  catch(Exception e){}
}// end run

Body:
I had the same issue and i found this solution to be working,

the solution was to override the interrupt method (your class should extend Thread instead of Runnable) and close the watchService from there, this will throw ClosedWatchServiceException in your take() method, so you have to catch this exception

Override interrupt

@Override
public void interrupt() {
    super.interrupt();
    System.out.println("Interupt is called");
    try {

            watcher.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Handling exception

try {
            key = watcher.take();
        } catch (InterruptedException x) {
            System.out.println("take() is interrupted");
            Thread.currentThread().interrupt();
            return;
        } catch (ClosedWatchServiceException e) {
            System.out.println(" take is killed from closedException");
            return;
        }

Main Thread

public static void main(String[] args) throws InterruptedException {
    WatchDir watchDir = new WatchDir(path);
    Thread.currentThread().sleep(1000);
    watchDir.shutDown();
    watchDir.interrupt();
    watchDir.join();
    System.out.println("the WatchDir thread is killed");
}


问:
How to insert a character at a certain position in a number without converting it into a string?
I have to insert "/" between 2020 and 0001 in the number 20200001. I know how to do it by converting the number to string, but I am unable to do it by not converting it.</p>

答:
You cannot have a symbol of any kind outside the numeric spectrum inside a number...

Imagine if you were a calculator and a student wanted you to substract the word banana from 400.

That doesn't make sense.

If you need two separate numbers, then store them in a sepatrate variable.


问:
Java string calculator, first number is negative
So i have this code which i took from another question and its never answered, how would i have to change the code if String a = "-5+20-15+8" with the first number being negative, right now it gives an error.</p>

```<code> String a = "5+20-15+8";
    System.out.println(a);
    String operators[]=a.split("[0-9]+");
    String operands[]=a.split("[+-]");
    int agregate = Integer.parseInt(operands[0]);
    for(int i=1;i<operands.length;i++){
        if(operators[i].equals("+"))
            agregate += Integer.parseInt(operands[i]);
        else
            agregate -= Integer.parseInt(operands[i]);
    }
    System.out.println(agregate);
</code>```

答:
The problem is that - and + used as separators so the first - in -5 will interpreted as such wrongly. Quick solution is to expect that those two operator must have spaces around them, thus they differentiate themselfs from the case when they represent the sign.

```<code>public class Main {
     public static void main(String []args){
         String a = "-5 + 20 - 15 + 8";
            System.out.println(a);
            String operators[]=a.split("[0-9]+");
            String operands[]=a.split(" [+-] ");
            int agregate = Integer.parseInt(operands[0]);
            for(int i=1;i<operands.length;i++){
                if(operators[i].equals(" + "))
                    agregate += Integer.parseInt(operands[i]);
                else
                    agregate -= Integer.parseInt(operands[i]);
            }
            System.out.println(agregate);
     }
}
</code>```

Body:
So i have this code which i took from another question and its never answered, how would i have to change the code if String a = "-5+20-15+8" with the first number being negative, right now it gives an error.

 String a = "5+20-15+8";
    System.out.println(a);
    String operators[]=a.split("[0-9]+");
    String operands[]=a.split("[+-]");
    int agregate = Integer.parseInt(operands[0]);
    for(int i=1;i<operands.length;i++){
        if(operators[i].equals("+"))
            agregate += Integer.parseInt(operands[i]);
        else
            agregate -= Integer.parseInt(operands[i]);
    }
    System.out.println(agregate);

Body:
The problem is that - and + used as separators so the first - in -5 will interpreted as such wrongly. Quick solution is to expect that those two operator must have spaces around them, thus they differentiate themselfs from the case when they represent the sign.

public class Main {
     public static void main(String []args){
         String a = "-5 + 20 - 15 + 8";
            System.out.println(a);
            String operators[]=a.split("[0-9]+");
            String operands[]=a.split(" [+-] ");
            int agregate = Integer.parseInt(operands[0]);
            for(int i=1;i<operands.length;i++){
                if(operators[i].equals(" + "))
                    agregate += Integer.parseInt(operands[i]);
                else
                    agregate -= Integer.parseInt(operands[i]);
            }
            System.out.println(agregate);
     }
}


问:
How is memory handled when destroying DOM elements?
If I have click event listener on many dynamically created elements, will they use the memory when remove() is called by removeEventListner is not?

Say I have some code like this:

```<code>for (var i = 0; i < 9999; i++) {
  var $btn = $('<button class="my_button">');
  $('body').append($btn);
  $btn.click(function(){ /* ... */ })
}

$('.my_button').remove();
</code>```

Will the event handlers still use memory? Do I have to call removeEventListner if I want to make sure there's no memory leak risk?

答:
The memory held by that element will be released when it is removed from the DOM and destroyed. This is handled by the browser, so although there in theory shouldn't be any memory leaks you are at the mercy of the garbage collector.

That being said there's a much better approach you can use here. Create a single delegated event handler on a parent element of all the buttons. Then you have one event handler instance which works for all button elements. This will save memory and mean you don't need to worry about the specifics of any garbage collection when removing elements from the DOM. Try this:

```<code>$('#buttonContainer').on('click', '.my_button', function() {
  // button click action here...
});
</code>```

Body:
If I have click event listener on many dynamically created elements, will they use the memory when remove() is called by removeEventListner is not?

Say I have some code like this:

for (var i = 0; i < 9999; i++) {
  var $btn = $('<button class="my_button">');
  $('body').append($btn);
  $btn.click(function(){ /* ... */ })
}

$('.my_button').remove();

Will the event handlers still use memory? Do I have to call removeEventListner if I want to make sure there's no memory leak risk?

Body:
The memory held by that element will be released when it is removed from the DOM and destroyed. This is handled by the browser, so although there in theory shouldn't be any memory leaks you are at the mercy of the garbage collector.

That being said there's a much better approach you can use here. Create a single delegated event handler on a parent element of all the buttons. Then you have one event handler instance which works for all button elements. This will save memory and mean you don't need to worry about the specifics of any garbage collection when removing elements from the DOM. Try this:

$('#buttonContainer').on('click', '.my_button', function() {
  // button click action here...
});