问:
Flutter apk/ipa size vs React Native apk/ipa size
React Native APK size for a hello world example is around 20M (in recent versions) because of support different hardware architectures (ARMv7, ARMv8, X86, etc) while Flutter APK size for same application is around 7M.

What's the reason for the difference in size? Do Flutter support all hardware architecture?

答:
Visit to below mentioned url's and may be they could help you out regarding what you are looking for.

https://nevercode.io/blog/flutter-vs-react-native-a-developers-perspective/

https://android.jlelse.eu/comparing-apk-sizes-a0eb37bb36f

if not it will still give more insights to others on how Flutter is different than others, and whether one should choose flutter over any other hybrid app development technology or not.


来源: stackexchange

问:
Google Indexing API
I have a job portal website (Wordpress + PHP) and I want using Google Indexing API for my website. I don't have any experience on GoogleAPI so I just read their guidance.
According to the guide, to use the Indexing API it has 3 steps:

Complete the prerequisites by enabling the Indexing API, creating a new service account, and verifying ownership in Search Console.

Get an access token to authenticate your API call.

Send requests to notify Google of new, updated, or deleted web pages.

I completed the step 1 but step 2 and 3 it really confuse me. Seem like I need obtain the OAuth token with coding but where do I put these code ? For using API, they show me this example :

```<code>POST https://indexing.googleapis.com/v3/urlNotifications:publish
{
  "url": "https://careers.google.com/jobs/google/technical-writer",
  "type": "URL_UPDATED"
}
</code>```

Again, Im not sure where do I put these block code to using API. Can anyone know about this can explain step by step how to do it for me? Last question : because my website get around 10 - 15 new job post per day. Can I somehow set this Indexing API automatic send request to Google whenever someone post a new job ?
Regards,

答: Rank Math just released free Indexing plugin for WordPress, you can give it a try, it does all the things automatically. More details: https://rankmath.com/blog/google-indexing-api/</p>

ContentLicense: CC BY-SA 4.0

Title: Google Indexing API

Body:
I have a job portal website (Wordpress + PHP) and I want using Google Indexing API for my website. I don't have any experience on GoogleAPI so I just read their guidance.
According to the guide, to use the Indexing API it has 3 steps:

Complete the prerequisites by enabling the Indexing API, creating a new service account, and verifying ownership in Search Console.

Get an access token to authenticate your API call.

Send requests to notify Google of new, updated, or deleted web pages.

I completed the step 1 but step 2 and 3 it really confuse me. Seem like I need obtain the OAuth token with coding but where do I put these code ? For using API, they show me this example :

POST https://indexing.googleapis.com/v3/urlNotifications:publish
{
  "url": "https://careers.google.com/jobs/google/technical-writer",
  "type": "URL_UPDATED"
}

Again, Im not sure where do I put these block code to using API. Can anyone know about this can explain step by step how to do it for me? Last question : because my website get around 10 - 15 new job post per day. Can I somehow set this Indexing API automatic send request to Google whenever someone post a new job ?
Regards,


问:
Dataframe can't fill NaN values in pandas
I have a DataFrame with some NaN values, that I want to fit with the mean of my DataFrame

```<code>data.fillna(data.mean())
</code>```

afterwards, I check to see if there are any NaN or null values left

```<code> print('is nan', data.isna().values.any()) #prints True
 print('is null', data.isnull().values.any()) #prints True
</code>```

before prints to be true, and I don't understand since the NaN values should be filled.

Am I missing something?

答:
Try this to change your dataframe in place:

```<code>data.fillna(data.mean(), inplace=True)
</code>```

Or do this to create a new dataframe with NaNs replaced by data.mean():

```<code>data_new = data.fillna(data.mean())
</code>```

Body:
I have a DataFrame with some NaN values, that I want to fit with the mean of my DataFrame

data.fillna(data.mean())

afterwards, I check to see if there are any NaN or null values left

 print('is nan', data.isna().values.any()) #prints True
 print('is null', data.isnull().values.any()) #prints True

before prints to be true, and I don't understand since the NaN values should be filled.

Am I missing something?

Body:
Try this to change your dataframe in place:

data.fillna(data.mean(), inplace=True)

Or do this to create a new dataframe with NaNs replaced by data.mean():

data_new = data.fillna(data.mean())


问:
Multi Serial Raspberry Pi Python Program
I am using a Raspberry Pi (Revolution Pi by Kunbus) to control multiple arduinos via serial communications (usb). I wanted to know if it was possible to control/communicate with multiple serial ports at once. I know multi serial aruduinos, such as the MultiSerialMega, allow for you to list Serial.begin(9600); and Serial1.begin(9600); to communicate with multiple at once, does this exist on the Raspberry Pi? As it stands I switch ports but the program running on the other arduino stops as soon as I do so.

To summarize: Can I sommunicate with three serial ports in python such as in the MultiSerialMega?

Thanks,
Levi

I've tried just adding a one, like the example for the MultiSerialMega, but that does not work (not surprisingly)

```<code>import serial
import time

while True:
    ser = serial.Serial("/dev/ttyACM0")
    steps = int(input("How many steps?")
    ser.write(b'%d' %steps)
    ser = serial.Serial("/dev/ttyACM1")
    steps = int(input("How many steps?")
    ser.write(b'%d' %steps)
</code>```

I am just playing around with stepper motors at the moment, but as soon as I switch serial ports the program ends/motor stops moving.

答:
From what I understand you want to write to multiple serial ports connected to your Rpi. You should be able to do that with as many ports as you want the same way you do with your Arduinos with multiple hardware UARTs.

Try this:

```<code>import serial
import time
import sys
ser1 = serial.Serial("/dev/ttyACM0")
ser2 = serial.Serial("/dev/ttyACM1")
while True:

    steps = input("How many steps for serial 1? (press q to quit")
    if steps == "q" or steps == "Q":
        ser1.close()
        ser2.close()
        sys.exit()
    else:
        ser1.write(int(steps))

    steps = input("How many steps for serial 2? (press q to quit)")
    if steps == "q" or steps == "Q":
        ser1.close()
        ser2.close()
        sys.exit()
    else:
        ser2.write(int(steps))
</code>```

EDIT: If you happen to have so many Arduinos that you run out of USB ports to connect them you can consider switching to RS485 which is multi-point so you can connect up to 32 serial devices (your Arduinos) to a single serial port on your Rpi. See also this link

Body:
I am using a Raspberry Pi (Revolution Pi by Kunbus) to control multiple arduinos via serial communications (usb). I wanted to know if it was possible to control/communicate with multiple serial ports at once. I know multi serial aruduinos, such as the MultiSerialMega, allow for you to list Serial.begin(9600); and Serial1.begin(9600); to communicate with multiple at once, does this exist on the Raspberry Pi? As it stands I switch ports but the program running on the other arduino stops as soon as I do so.

To summarize: Can I sommunicate with three serial ports in python such as in the MultiSerialMega?

Thanks,
Levi

I've tried just adding a one, like the example for the MultiSerialMega, but that does not work (not surprisingly)

import serial
import time

while True:
    ser = serial.Serial("/dev/ttyACM0")
    steps = int(input("How many steps?")
    ser.write(b'%d' %steps)
    ser = serial.Serial("/dev/ttyACM1")
    steps = int(input("How many steps?")
    ser.write(b'%d' %steps)

I am just playing around with stepper motors at the moment, but as soon as I switch serial ports the program ends/motor stops moving.

Body:
From what I understand you want to write to multiple serial ports connected to your Rpi. You should be able to do that with as many ports as you want the same way you do with your Arduinos with multiple hardware UARTs.

Try this:

import serial
import time
import sys
ser1 = serial.Serial("/dev/ttyACM0")
ser2 = serial.Serial("/dev/ttyACM1")
while True:

    steps = input("How many steps for serial 1? (press q to quit")
    if steps == "q" or steps == "Q":
        ser1.close()
        ser2.close()
        sys.exit()
    else:
        ser1.write(int(steps))

    steps = input("How many steps for serial 2? (press q to quit)")
    if steps == "q" or steps == "Q":
        ser1.close()
        ser2.close()
        sys.exit()
    else:
        ser2.write(int(steps))

EDIT: If you happen to have so many Arduinos that you run out of USB ports to connect them you can consider switching to RS485 which is multi-point so you can connect up to 32 serial devices (your Arduinos) to a single serial port on your Rpi. See also this link


问:
How do you unit test private methods?
I'm building a class library that will have some public & private methods. I want to be able to unit test the private methods (mostly while developing, but also it could be useful for future refactoring).

What is the correct way to do this?

答: Also note that the InternalsVisibleToAtrribute has a requirement that your assembly be strong named, which creates it's own set of problems if you're working in a solution that had not had that requirement before.  I use the accessor to test private methods.  See this question that for an example of this.</p>

OwnerDisplayName: Eric Labashosky

ContentLicense: CC BY-SA 3.0

Title: How do you unit test private methods?

LastEditorDisplayName: Philippe


问:
Git workflow (Reverting a merged branch VS a pushed commit)
I think I generally understand the benefit of using branches in a development workflow. My question is when it comes to reverting small changes, are branches easier or safer to revert in some way than regular commits? For example, if you apply a patch which adds one line of code, is it better to do that in a branch and merge it, or is a pushed commit sufficient?</p>

答:
It really does depend.  Most of the time, it's probably overkill to make branch for a one-line change because those changes are unlikely to be as risky as larger changes.  But if that one line changes everything about a function or which function gets run, etc. you might want to have that on a branch so you can really test it before you pull it into master.

Is that any different after it's been merged?  Well, you'll get a merge commit (unless you rebase instead), but rolling back is effectively the same process.  You might want to read more about how a merge commit differs from a regular commit and about using git revert.


问:
Modify value in the vue app main.js from child component
I need to update a value which is initially set in the main.js for my vue application, from a component.  I am not sure the best way (or even if this is possible)

I have tried setting the value directly form the component, but it does not appear to update.

I would be happy with just having it set properly when the app starts.  I only need this to be set once, but I want it to read the server/host info when the app starts and populate the value.

```<code>Vue.use(Adal, {
// This config gets passed along to Adal, so all settings available to adal can be used here.
  config: {
    // 'common' (multi-tenant gateway) or Azure AD Tenant ID
    tenant: 'xxxxxxxxxxxxxxxxxxxxxxxxx',

    // Application ID
    clientId: 'xxxxxxxxxxxxxxxxxxxxxxx',

    // Host URI
    redirectUri: 'http://localhost:8080',

    cacheLocation: 'localStorage'
  },

  // Set this to true for authentication on startup
  requireAuthOnInitialize: false,

  // Pass a vue-router object in to add route hooks with authentication and role checking
  router
});
</code>```

The redirectUri value I would like to be dynamic based on the URL that the user used to connect to the site.  This is part of the adal-vue library to handle AzureAD Auth for my App.

It appears that this value is only set ONCE and cannot be modified on the fly.  Is there a workaround to allow for this?

答:
I don't know what you do in Adal.install function, I think you can try to declare an option object which is passed to Vue.use(), then you can change the value in option, as it is passed by reference, the value will be changed in Adal...

```<code>const option = {
  config: {
    redirectUri: 'http://localhost:8080',
}
Vue.use(Adal, option);

// then change it in somewhere
option.config.redirectUri = 'http://localhost:9000'
</code>```

Body:
I need to update a value which is initially set in the main.js for my vue application, from a component.  I am not sure the best way (or even if this is possible)

I have tried setting the value directly form the component, but it does not appear to update.

I would be happy with just having it set properly when the app starts.  I only need this to be set once, but I want it to read the server/host info when the app starts and populate the value.

Vue.use(Adal, {
// This config gets passed along to Adal, so all settings available to adal can be used here.
  config: {
    // 'common' (multi-tenant gateway) or Azure AD Tenant ID
    tenant: 'xxxxxxxxxxxxxxxxxxxxxxxxx',

    // Application ID
    clientId: 'xxxxxxxxxxxxxxxxxxxxxxx',

    // Host URI
    redirectUri: 'http://localhost:8080',

    cacheLocation: 'localStorage'
  },

  // Set this to true for authentication on startup
  requireAuthOnInitialize: false,

  // Pass a vue-router object in to add route hooks with authentication and role checking
  router
});

The redirectUri value I would like to be dynamic based on the URL that the user used to connect to the site.  This is part of the adal-vue library to handle AzureAD Auth for my App.

It appears that this value is only set ONCE and cannot be modified on the fly.  Is there a workaround to allow for this?

Body:
I don't know what you do in Adal.install function, I think you can try to declare an option object which is passed to Vue.use(), then you can change the value in option, as it is passed by reference, the value will be changed in Adal...

const option = {
  config: {
    redirectUri: 'http://localhost:8080',
}
Vue.use(Adal, option);

// then change it in somewhere
option.config.redirectUri = 'http://localhost:9000'


问:
Kubernetes node.js container cannot connect to MongoDB Atlas
So I've been struggling with this all afternoon. I can't at all get my NodeJS application running on kubernetes to connect to my MongoDB Atlas database.

In my application I've tried running

```<code>mongoose.connect('mongodb+srv://admin:<password>@<project>.gcp.mongodb.net/project_prod?retryWrites=true&w=majority', { useNewUrlParser: true })
</code>```

but I simply get the error

```<code>UnhandledPromiseRejectionWarning: Error: querySrv ETIMEOUT _mongodb._tcp.<project>.gcp.mongodb.net
    at QueryReqWrap.onresolve [as oncomplete] (dns.js:196:19)
(node:32) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 17)
</code>```

I've tried setting up a ExternalName service too, but using either the URL or the ExternalName results in me not being able to connect to the database.

I've whitelisted my IP on MongoDB Atlas, so I know that isn't the issue.

It also seems to work on my local machine, but not in the kubernetes pod. What am I doing wrong?

答:
I use MongoDB Atlas from Kubernetes but on AWS. Although for testing purposes you can enable all IP addresses and test, here is the approach for a production setup:

MongoDB Atlas supports Network Peering

Under Network Access > New Peering Connection

In the case of AWS, VPC ID, CIDR and Region have to be specified. For GCP it should be the standard procedure used for VPC peering.

Body:
So I've been struggling with this all afternoon. I can't at all get my NodeJS application running on kubernetes to connect to my MongoDB Atlas database.

In my application I've tried running

mongoose.connect('mongodb+srv://admin:<password>@<project>.gcp.mongodb.net/project_prod?retryWrites=true&w=majority', { useNewUrlParser: true })

but I simply get the error

UnhandledPromiseRejectionWarning: Error: querySrv ETIMEOUT _mongodb._tcp.<project>.gcp.mongodb.net
    at QueryReqWrap.onresolve [as oncomplete] (dns.js:196:19)
(node:32) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 17)

I've tried setting up a ExternalName service too, but using either the URL or the ExternalName results in me not being able to connect to the database.

I've whitelisted my IP on MongoDB Atlas, so I know that isn't the issue.

It also seems to work on my local machine, but not in the kubernetes pod. What am I doing wrong?


问:
Printing in Tabular format in TCL/PERL
I have a script in tcl in which a variable gets a collection of data in every loop and appends in a file. Suppose in loop1 ,

```<code>$var = {xy} {ty} {po} {iu} {ii}
</code>```

and in loop2

```<code>$var = {a} {b} {c} {d1} {d2} {e3}
</code>```

Now in a file f.txt the variable in dumped. Like puts $file $var. And in file it comes like this:
Line number 1: {xy} {ty} {po} {iu} {ii}

Line number 2: {a} {b} {c} {d1} {d2}

I want to print them finally in a file in tabular format. Like below:

```<code>xy  a

ty  b

po  c

iu  d1

ii  d2
</code>```

答:
Try this:

```<code>$ perl -anE 'push @{$vars[$_]}, ($F[$_] =~ s/^[{]|[}]$//gr) for 0.. $#F; END {say join "\t", @$_ for @vars}' f.txt
xy  a
ty  b
po  c
iu  d1
ii  d2
</code>```

command line switches:

-a : Turn on autosplit on white space to @F array.

-n : Loop over lines in input file, setting the @F array to the words on the current line.

-E : Execute the following argument as a one-liner

Removing surrounding braces from each words:

$F[$_] =~ s/^[{]|[}]$//gr

g : global substitution (we want to remove both { and })

r : non destructive operation, returns the result of the substitution instead of modifying @F

Title: Printing in Tabular format in TCL/PERL

Body:
I have a script in tcl in which a variable gets a collection of data in every loop and appends in a file. Suppose in loop1 ,

$var = {xy} {ty} {po} {iu} {ii}

and in loop2

$var = {a} {b} {c} {d1} {d2} {e3}

Now in a file f.txt the variable in dumped. Like puts $file $var. And in file it comes like this:
Line number 1: {xy} {ty} {po} {iu} {ii}

Line number 2: {a} {b} {c} {d1} {d2}

I want to print them finally in a file in tabular format. Like below:

xy  a

ty  b

po  c

iu  d1

ii  d2

Body:
Try this:

$ perl -anE 'push @{$vars[$_]}, ($F[$_] =~ s/^[{]|[}]$//gr) for 0.. $#F; END {say join "\t", @$_ for @vars}' f.txt
xy  a
ty  b
po  c
iu  d1
ii  d2

command line switches:

-a : Turn on autosplit on white space to @F array.

-n : Loop over lines in input file, setting the @F array to the words on the current line.

-E : Execute the following argument as a one-liner

Removing surrounding braces from each words:

$F[$_] =~ s/^[{]|[}]$//gr

g : global substitution (we want to remove both { and })

r : non destructive operation, returns the result of the substitution instead of modifying @F


问:
How do I preserve line breaks when using jsoup to convert html to plain text?
I have the following code:

```<code> public class NewClass {
     public String noTags(String str){
         return Jsoup.parse(str).text();
     }

     public static void main(String args[]) {
         String strings="<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN \">" +
         "<HTML> <HEAD> <TITLE></TITLE> <style>body{ font-size: 12px;font-family: verdana, arial, helvetica, sans-serif;}</style> </HEAD> <BODY><p><b>hello world</b></p><p><br><b>yo</b> <a href=\"http://google.com\">googlez</a></p></BODY> </HTML> ";

         NewClass text = new NewClass();
         System.out.println((text.noTags(strings)));
}
</code>```

And I have the result:

```<code>hello world yo googlez
</code>```

But I want to break the line:

```<code>hello world
yo googlez
</code>```

I have looked at jsoup's TextNode#getWholeText() but I can't figure out how to use it.

If there's a
 in the markup I parse, how can I get a line break in my resulting output?

答:
Try this:</p>

```<code>public String noTags(String str){
    Document d = Jsoup.parse(str);
    TextNode tn = new TextNode(d.body().html(), "");
    return tn.getWholeText();
}
</code>```

Body:
I have the following code:

 public class NewClass {
     public String noTags(String str){
         return Jsoup.parse(str).text();
     }

     public static void main(String args[]) {
         String strings="<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN \">" +
         "  <TITLE></TITLE>
hello world

yo googlez
  ";

         NewClass text = new NewClass();
         System.out.println((text.noTags(strings)));
}

And I have the result:

hello world yo googlez

But I want to break the line:

hello world
yo googlez

I have looked at jsoup's TextNode#getWholeText() but I can't figure out how to use it.

If there's a
 in the markup I parse, how can I get a line break in my resulting output?

Body:
Try this:

public String noTags(String str){
    Document d = Jsoup.parse(str);
    TextNode tn = new TextNode(d.body().html(), "");
    return tn.getWholeText();
}


问:
How to force web page to have same scale in all devices?
My web page need to be shown in an app. When it shows in the Android version, it is like 3 times larger than in iOS version.

It is probably due to the settings in each app's webview, but I don't made the app so I can't change anything about it. The only thing I can change is my web page, which is a javascript Google Map, the map marker became super large in the Android app.

So is there a thing that I can force my web page to have same scale regardless of the webview settings or app settings?

答:
If its a web page try adding this to head tag of your HTML</p>

```<code><meta name="viewport" content="initial-scale=1, maximum-scale=1,  width=device-width">
</code>```

Body:
If its a web page try adding this to head tag of your HTML

<meta name="viewport" content="initial-scale=1, maximum-scale=1,  width=device-width">


问:
Detect which `View` was clicked on a `Cell`
i have three UIImageView on a single Cell when i click on any of the UIImageView on the cell i want to detect which one was clicked on onCellSelection, without placing a UITapGestureRecognizer on each UIImageview

```<code>func SocialViewRow(address: SocialMedia)-> ViewRow<SocialMediaViewFile> {

let viewRow = ViewRow<SocialMediaViewFile>() { (row) in

    row.tag = UUID.init().uuidString
    }
    .cellSetup { (cell, row) in
        //  Construct the view
        let bundle = Bundle.main
        let nib = UINib(nibName: "SocialMediaView", bundle: bundle)

        cell.view = nib.instantiate(withOwner: self, options: nil)[0] as? SocialMediaViewFile
        cell.view?.backgroundColor = cell.backgroundColor
        cell.height =  { 50 }
        print("LINK \(address.facebook?[0] ?? "")")

        cell.view?.iconOne.tag = 90090

        //self.itemDetails.activeURL = address

        let openFace = UITapGestureRecognizer(target: self, action: #selector(QuickItemDetailVC.openFace))
        let openT = UITapGestureRecognizer(target: self, action: #selector(QuickItemDetailVC.openTwit))
        let you = UITapGestureRecognizer(target: self, action: #selector(QuickItemDetailVC.openYouYub))

         cell.view?.iconOne.addGestureRecognizer(openFace)

         cell.view?.iconTwo.addGestureRecognizer(openT)
         cell.view?.iconThree.addGestureRecognizer(you)

        cell.frame.insetBy(dx: 5.0, dy: 5.0)
        cell.selectionStyle = .none

    }.onCellSelection() {cell,row in

     //example
    //print(iconTwo was clicked)

}

return viewRow
}
</code>```

答:
Override the touchesbegan function. This method is called every time the user touches the screen. Every time it is called, check to see if the touches began in the same location an image is.

```<code> override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
     let touch = touches.first!
     let location = touch.location(in: self)
     //check here, include code that compares the locations of the image
}
</code>```

Location will be a CGPoint. You should be able to get the CGPoints for the bounds of your images and then determine if the touchBegan in those bounds. If you want to include the entire path the user touched, there are ways to do that too but the beginning touch should be sufficient for what you want.

Body:
i have three UIImageView on a single Cell when i click on any of the UIImageView on the cell i want to detect which one was clicked on onCellSelection, without placing a UITapGestureRecognizer on each UIImageview

func SocialViewRow(address: SocialMedia)-> ViewRow<SocialMediaViewFile> {

let viewRow = ViewRow<SocialMediaViewFile>() { (row) in

    row.tag = UUID.init().uuidString
    }
    .cellSetup { (cell, row) in
        //  Construct the view
        let bundle = Bundle.main
        let nib = UINib(nibName: "SocialMediaView", bundle: bundle)

        cell.view = nib.instantiate(withOwner: self, options: nil)[0] as? SocialMediaViewFile
        cell.view?.backgroundColor = cell.backgroundColor
        cell.height =  { 50 }
        print("LINK \(address.facebook?[0] ?? "")")

        cell.view?.iconOne.tag = 90090

        //self.itemDetails.activeURL = address

        let openFace = UITapGestureRecognizer(target: self, action: #selector(QuickItemDetailVC.openFace))
        let openT = UITapGestureRecognizer(target: self, action: #selector(QuickItemDetailVC.openTwit))
        let you = UITapGestureRecognizer(target: self, action: #selector(QuickItemDetailVC.openYouYub))

         cell.view?.iconOne.addGestureRecognizer(openFace)

         cell.view?.iconTwo.addGestureRecognizer(openT)
         cell.view?.iconThree.addGestureRecognizer(you)

        cell.frame.insetBy(dx: 5.0, dy: 5.0)
        cell.selectionStyle = .none

    }.onCellSelection() {cell,row in

     //example
    //print(iconTwo was clicked)

}

return viewRow
}

Body:
Override the touchesbegan function. This method is called every time the user touches the screen. Every time it is called, check to see if the touches began in the same location an image is.

 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
     let touch = touches.first!
     let location = touch.location(in: self)
     //check here, include code that compares the locations of the image
}

Location will be a CGPoint. You should be able to get the CGPoints for the bounds of your images and then determine if the touchBegan in those bounds. If you want to include the entire path the user touched, there are ways to do that too but the beginning touch should be sufficient for what you want.


问:
How do I make 'forgot password' working in react-aad-msal with Azure AD B2C?
I am using react-aad-msal with Azure AD B2C. I have sign-in and sign-out working. However, when I click 'Forgot your password?', the auth window disappears and nothing happens.

It seems I need to specify name of my 'forgot password' policy, but I do not know where to put it.

Based on Tony's answer added this code to my App's render:

```<code>if (window.location.href.indexOf("error_description=AADB2C90118") >= 0)
    {
      return <AzureAD
      provider={
        new MsalAuthProviderFactory({
          authority: 'https://login.microsoftonline.com/tfp/x5aaas.onmicrosoft.com/B2C_1_PwdReset',
          clientID: 'a1568977-3095-4bf6-a6d6-c10c87658488',
          scopes: ['https://x5aaas.onmicrosoft.com/ui/use'],
          type: LoginType.Redirect,
          postLogoutRedirectUri: window.origin,
        })
      }
      unauthenticatedFunction={this.unauthenticatedFunction}
      userInfoCallback={this.userJustLoggedIn}
      authenticatedFunction={this.authenticatedFunction}
    />;
    }
</code>```

I see that after I click "Forgot password?", the condition is true, and return happens. However, the window for password reset does not show up and I get redirected back to my app URL.

Any suggestions?

答:
What I did was create a Route in my App.js:

```<code>          <Route
            path="/forgot"
            component={() => {
              window.location.href = forgotPasswordUrl;
              return null;
            }}
          />
</code>```

Then, in the constructor

```<code>if (window.location.hash.indexOf('AADB2C90118') >= 0) {
  history.push('/forgot');
}
</code>```

And that works.

Body:
I am using react-aad-msal with Azure AD B2C. I have sign-in and sign-out working. However, when I click 'Forgot your password?', the auth window disappears and nothing happens.

It seems I need to specify name of my 'forgot password' policy, but I do not know where to put it.

Based on Tony's answer added this code to my App's render:

if (window.location.href.indexOf("error_description=AADB2C90118") >= 0)
    {
      return <AzureAD
      provider={
        new MsalAuthProviderFactory({
          authority: 'https://login.microsoftonline.com/tfp/x5aaas.onmicrosoft.com/B2C_1_PwdReset',
          clientID: 'a1568977-3095-4bf6-a6d6-c10c87658488',
          scopes: ['https://x5aaas.onmicrosoft.com/ui/use'],
          type: LoginType.Redirect,
          postLogoutRedirectUri: window.origin,
        })
      }
      unauthenticatedFunction={this.unauthenticatedFunction}
      userInfoCallback={this.userJustLoggedIn}
      authenticatedFunction={this.authenticatedFunction}
    />;
    }

I see that after I click "Forgot password?", the condition is true, and return happens. However, the window for password reset does not show up and I get redirected back to my app URL.

Any suggestions?

Body:
What I did was create a Route in my App.js:

          <Route
            path="/forgot"
            component={() => {
              window.location.href = forgotPasswordUrl;
              return null;
            }}
          />

Then, in the constructor

if (window.location.hash.indexOf('AADB2C90118') >= 0) {
  history.push('/forgot');
}

And that works.


问:
Uniform generation of permutation with repetition at most k times?
We have set {1, 2, 3, ...,n} of numbers. We want to generate permutation of length of m created of those numbers with repetition of each number at most k times.

If we assume n=5, k=2, m=3, then we could receive: {3,3,1}, but not {3, 3, 3} as 3 in the second example happens to be three times in output, which is more than k.

Is there a way of uniform generation of such permutation in a fast way?

I tried two different solutions.

First:

1) generate random permutation with repetition, there is n^m different permutations.

2) check if this is a correct permutation (if it does not contain more than k times the same number

3) if yes, then return, else go to 1)

Python snippet:

```<code>import numba
import numpy as np

@numba.jit(nopython=True)
def gen_sequence1(n, k, m):
    result = np.random.randint(0, n, (1, m))[0]
    while not is_correct(result, k):
        result = np.random.randint(0, n, (1, m))[0]
    return result

@numba.jit(nopython=True)
def most_frequent(iter):
    return np.bincount(iter).max()

@numba.jit(nopython=True)
def is_correct(pruf, k):
    return most_frequent(pruf) <= k
</code>```

Second method:

Generate random integer, add it to sequence only if it didn't show up before k times. Optimized version of these words is below presented (written in Python).
Python snippet:

```<code>def gen_seq(n, d, m):
    choices = list(range(n))
    degrees = [0] * n
    result = []
    k = n - 1
    for i in range(m):
        rand = np.random.randint(0, k)
        result.append(choices[rand])
        degrees[choices[rand]] += 1
        if degrees[choices[rand]] == d:
            choices[rand], choices[k] = choices[k], choices[rand]
            k -= 1
    return result
</code>```

Problem is that the first method is very slow for n=30, m=28, d=1 it needs 10^9 times to generate sequence, which is pretty obvious.

The second one is not generating uniform permutations (some have bigger probabilities than others).

Do you have any ideas how one could generate such sequence fast and uniformly?

答:
This assumes you have enough memory to hold the numbers [1..n] k times.

Set up the array [1..n].

Duplicate the array k times: [1..n, 1..n, 1..n, ... 1..n] into a large array.

Run the first m steps of a Fisher-Yates shuffle on the large duplicated array to get your required permutation.  There is no need to shuffle the entire array since you only need m numbers.

Body:
We have set {1, 2, 3, ...,n} of numbers. We want to generate permutation of length of m created of those numbers with repetition of each number at most k times.

If we assume n=5, k=2, m=3, then we could receive: {3,3,1}, but not {3, 3, 3} as 3 in the second example happens to be three times in output, which is more than k.

Is there a way of uniform generation of such permutation in a fast way?

I tried two different solutions.

First:

1) generate random permutation with repetition, there is n^m different permutations.

2) check if this is a correct permutation (if it does not contain more than k times the same number

3) if yes, then return, else go to 1)

Python snippet:

import numba
import numpy as np

@numba.jit(nopython=True)
def gen_sequence1(n, k, m):
    result = np.random.randint(0, n, (1, m))[0]
    while not is_correct(result, k):
        result = np.random.randint(0, n, (1, m))[0]
    return result

@numba.jit(nopython=True)
def most_frequent(iter):
    return np.bincount(iter).max()

@numba.jit(nopython=True)
def is_correct(pruf, k):
    return most_frequent(pruf) <= k

Second method:

Generate random integer, add it to sequence only if it didn't show up before k times. Optimized version of these words is below presented (written in Python).
Python snippet:

def gen_seq(n, d, m):
    choices = list(range(n))
    degrees = [0] * n
    result = []
    k = n - 1
    for i in range(m):
        rand = np.random.randint(0, k)
        result.append(choices[rand])
        degrees[choices[rand]] += 1
        if degrees[choices[rand]] == d:
            choices[rand], choices[k] = choices[k], choices[rand]
            k -= 1
    return result

Problem is that the first method is very slow for n=30, m=28, d=1 it needs 10^9 times to generate sequence, which is pretty obvious.

The second one is not generating uniform permutations (some have bigger probabilities than others).

Do you have any ideas how one could generate such sequence fast and uniformly?


问:
Import .csv file through SSIS Package without double Quotes
SQL 2005

I am importing .csv file to SQL Table through SSIS Package !! On doing so, I am getting double quotes on every column header or field value !!

How to remove double quotes, while importing .csv file ???

答: Enter " double quotes as the Text Qualifier.</p>


问:
Remove first element of JSON object array
I'm struggling to find a way to cut down this JSON array so I can use the values remaining. Below is what's returned to me from the API I'm fetching and I'm looking to remove the excess so I just have an array with the LGA results. Really unsure where to even start.</p>

```<code>{
  "query": {
    "offence": "Dangerous Operation of a Vehicle",
    "area": "",
    "age": "",
    "year": "",
    "gender": ""
  },
  "result": [
    {
      "LGA": "Aurukun Shire Council",
      "total": 156,
      "lat": -13.354875,
      "lng": 141.729058
    },
    {
      "LGA": "Balonne Shire Council",
      "total": 99,
      "lat": -28.464607,
      "lng": 148.189292
    },
    {
      "LGA": "Yarrabah Shire Council",
      "total": 28,
      "lat": -16.910135,
      "lng": 145.868659
    }
  ]
}
</code>```

答:
You can use Array.prototype.map function to transform your result:

```<code>const response = getYourJsonFromAPI()
response.result.map(result => result.LGA)
</code>```

which returns:

```<code>["Aurukun Shire Council", "Balonne Shire Council", "Yarrabah Shire Council"]
</code>```

Body:
I'm struggling to find a way to cut down this JSON array so I can use the values remaining. Below is what's returned to me from the API I'm fetching and I'm looking to remove the excess so I just have an array with the LGA results. Really unsure where to even start.

{
  "query": {
    "offence": "Dangerous Operation of a Vehicle",
    "area": "",
    "age": "",
    "year": "",
    "gender": ""
  },
  "result": [
    {
      "LGA": "Aurukun Shire Council",
      "total": 156,
      "lat": -13.354875,
      "lng": 141.729058
    },
    {
      "LGA": "Balonne Shire Council",
      "total": 99,
      "lat": -28.464607,
      "lng": 148.189292
    },
    {
      "LGA": "Yarrabah Shire Council",
      "total": 28,
      "lat": -16.910135,
      "lng": 145.868659
    }
  ]
}

Body:
You can use Array.prototype.map function to transform your result:

const response = getYourJsonFromAPI()
response.result.map(result => result.LGA)

which returns:

["Aurukun Shire Council", "Balonne Shire Council", "Yarrabah Shire Council"]


问:
Can't connect to MongoDb 4.0.9 on Windows server with shell
I have MongoDb 4.0.9 running as a service on Windows Server 2016 Standard.

This is my mongod.cfg:

For testing purposes I turned off the server's firewall completely.

I am not using SSH or any other tunnel so far

The Windows service logs on as "Network Service"

I have one user in the "admin" database with roles "userAdminAnyDatabase", "dbAdminAnyDatabase" and "readWriteAnyDatabase"

My local machine is Windows 10 and here I have Mongo 4.0.9 installed as well.  I am trying to connect to my server's database by shell:

When I go on the server (Remote Desktop) I can connect successfully (same user credentials):

I am running out of ideas what I am doing wrong when remote connecting.

What is also confusing: I am doing the exact same thing on another server (different provider, different database, but also Windows Server 2016 Standard, MongoDb 4.0.9 and the same user and roles). And here I CAN connect.

So, I assume it has something to do with the settings of Windows Server (and not Mongo ...)?

Does anybody have an idea?

答:
From what I could gather, it seems your the Windows Machine running the MongoDB service is hosted in the cloud.

If you are certain the windows firewall is turned off (make sure to disable it on Private, Public and Domain - if applicable)

Furthermore, my best guess is that the port might be block by the cloud hosting provider firewall.

Usually they provide the basic port openings (21, 80, 443, 1433, 3389, etc) - and port which are not common for windows (like 27017) are blocked (filtered) by default.

if you wish to verify this, run the following:
nmap <server hostname> to get the default ports checked.
for MongoDB run nmap -p 27017 <server hostname>


问:
Matplotlib Plot showing image as separate r g b images rather than a single RGB image
I have an image represented as a Numpy Array of shape [224, 224, 3]. i am trying to plot this using matplotlib using:
        plt.imshow(img)
But instead of getting a single RGB image, it plots the separated R, G and B images in a single plot. Where am I going wrong?

I have tried looking at the shape of the image and also some examples to plot the image. The "img" variable has the shape of [224, 224, 3] and is a numpy array type.

```<code>        from torchvision import datasets, transforms
        from torch.utils.data import DataLoader
        import matplotlib.pyplot as plt

        # Define Image Transform
        transform = transforms.Compose([transforms.Resize(255),
                                transforms.CenterCrop(224),
                                transforms.ToTensor()])

        # Load Custom Image Dataset
        dataset = datasets.ImageFolder(root="./Cat_Dog_data",
                                          transform=transform)

        # DataLoader
        dataLoader = DataLoader(dataset=dataset, batch_size=32, shuffle=True)

        # Get one batch of Data
        # len(images): 32
        # len(labels): 32
        # shape of images[0]: torch.Size([3, 224, 224])
        images, labels = next(iter(dataLoader))

        # img.shape: [224,224,3]
        img = images[0].numpy().reshape([224, 224, 3])

        plt.imshow(img)
        plt.show()
</code>```

I expect the image to be a single RGB image of a dog or a cat. But the output I am getting is the plot of R,G,B components of that image as columns in a single plot as shown below.

答:
The code finally worked using np.transpose() function instead of the np.reshape() function.</p>

```<code>from torchvision import datasets, transforms
from torch.utils.data import DataLoader
import matplotlib.pyplot as plt

# Define Image Transform
transform = transforms.Compose([transforms.Resize(255),
                                transforms.CenterCrop(224),
                                transforms.ToTensor()])

# Load Custom Image Dataset
dataset = datasets.ImageFolder(root="./Cat_Dog_data", transform=transform)

# DataLoader is a Generator
dataLoader = DataLoader(dataset=dataset, batch_size=32, shuffle=True)

# Get one batch of Data
images, labels = next(iter(dataLoader))

# Use transpose instead of reshape.
img = images[0].numpy().transpose((1, 2, 0))

plt.imshow(img)
plt.show()
</code>```

Body:
I have an image represented as a Numpy Array of shape [224, 224, 3]. i am trying to plot this using matplotlib using:
        plt.imshow(img)
But instead of getting a single RGB image, it plots the separated R, G and B images in a single plot. Where am I going wrong?

I have tried looking at the shape of the image and also some examples to plot the image. The "img" variable has the shape of [224, 224, 3] and is a numpy array type.

        from torchvision import datasets, transforms
        from torch.utils.data import DataLoader
        import matplotlib.pyplot as plt

        # Define Image Transform
        transform = transforms.Compose([transforms.Resize(255),
                                transforms.CenterCrop(224),
                                transforms.ToTensor()])

        # Load Custom Image Dataset
        dataset = datasets.ImageFolder(root="./Cat_Dog_data",
                                          transform=transform)

        # DataLoader
        dataLoader = DataLoader(dataset=dataset, batch_size=32, shuffle=True)

        # Get one batch of Data
        # len(images): 32
        # len(labels): 32
        # shape of images[0]: torch.Size([3, 224, 224])
        images, labels = next(iter(dataLoader))

        # img.shape: [224,224,3]
        img = images[0].numpy().reshape([224, 224, 3])

        plt.imshow(img)
        plt.show()

I expect the image to be a single RGB image of a dog or a cat. But the output I am getting is the plot of R,G,B components of that image as columns in a single plot as shown below.

Body:
The code finally worked using np.transpose() function instead of the np.reshape() function.

from torchvision import datasets, transforms
from torch.utils.data import DataLoader
import matplotlib.pyplot as plt

# Define Image Transform
transform = transforms.Compose([transforms.Resize(255),
                                transforms.CenterCrop(224),
                                transforms.ToTensor()])

# Load Custom Image Dataset
dataset = datasets.ImageFolder(root="./Cat_Dog_data", transform=transform)

# DataLoader is a Generator
dataLoader = DataLoader(dataset=dataset, batch_size=32, shuffle=True)

# Get one batch of Data
images, labels = next(iter(dataLoader))

# Use transpose instead of reshape.
img = images[0].numpy().transpose((1, 2, 0))

plt.imshow(img)
plt.show()


问:
How to find "By Name" in mongoose
I am trying to get database values using a specific name. I want to  get all the books an author written.

This is my code to get the first name of the author and search for all the books he's written in BookDB using Like operator as in mysql

```<code>//get books by author name
router.route('/authorName').get((req, res) => {
    let authorName = req.params.authorName; //how can i pass this value to below regex command
    BookDB.find({"firstName": /authorName/}, (err, books) => {
        if(err) throw err;
        res.status(200).send(books);
    });
});
</code>```

Problem: How can I pass authorName to the {"firstName": /authorName/}.
The way I have written, it is not set the authorName properly.

答:
I did some research and found $regex.

```<code>//get books by author name
router.route('/authorName').get((req, res) => {
    let authorName = req.params.authorName;
    BookDB.find({firstName: {$regex: `${authorName}`}}, (err, books) => {
        if(err) throw err;
        res.status(200).send(books);
    });
});
</code>```

This will find all the results that containing this particular string authorName in BookDB database

Title: How to find "By Name" in mongoose

Body:
I am trying to get database values using a specific name. I want to  get all the books an author written.

This is my code to get the first name of the author and search for all the books he's written in BookDB using Like operator as in mysql

//get books by author name
router.route('/authorName').get((req, res) => {
    let authorName = req.params.authorName; //how can i pass this value to below regex command
    BookDB.find({"firstName": /authorName/}, (err, books) => {
        if(err) throw err;
        res.status(200).send(books);
    });
});

Problem: How can I pass authorName to the {"firstName": /authorName/}.
The way I have written, it is not set the authorName properly.

Body:
I did some research and found $regex.

//get books by author name
router.route('/authorName').get((req, res) => {
    let authorName = req.params.authorName;
    BookDB.find({firstName: {$regex: `${authorName}`}}, (err, books) => {
        if(err) throw err;
        res.status(200).send(books);
    });
});

This will find all the results that containing this particular string authorName in BookDB database


问:
HTML has a margin bigger than body
I'm creating my own personal site using bootstrap.

I've using bootstrap4 with some modifications. However the html margin is bigger than body.

I've already checked other questions and they say that
 or some other tag has a default margin and you need to zero that, however I'm using a reset.css and plus I tried to zero margin of a lot of elements and it didn't work.

the reset css and the link to my web site: https://sitezinho--mateusmsouza.repl.co/

/* http://meyerweb.com/eric/tools/css/reset/
   v2.0 | 20110126
   License: none (public domain)
*/

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font: inherit;
    vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
    display: block;
}
body {
    line-height: 1;
}
ol, ul {
    list-style: none;
}
blockquote, q {
    quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
    content: '';
    content: none;
}
table {
    border-collapse: collapse;
    border-spacing: 0;
}
```

<p>and HTML</p>

<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
    <title>Mateus Machado - Site Pessoal</title>
    <link rel="stylesheet" type="text/css" href="public/css/reset.css">
    <link rel="stylesheet" type="text/css" href="public/css/bootstrap.min.css">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="public/css/custom.css">

    <script type="text/javascript" href="public/js/jquery-3.4.0.min.js">

    </script>
    <script type="text/javascript" src='public/js/bootstrap.bundle.min.js'>

    </script>
</head>

<body>
    <main role="main">
        <nav class="navbar sticky-top navbar-expand-lg navbar-light " style="background-color: black">
            <ul class="navbar-nav mr-auto">
                <li class="nav-item active">Hello World</li>
                <li class="nav-item active">Projetos</li>
                <li class="nav-item active">Material de Estudo</li>

            </ul>

            <ul class="navbar-nav mr-auto>
          <li class=" nav-item active "> <img src="GitHub-Mark-Light-32px.png "> </li>
        </ul>

      </nav>

    <section class="my-4 " >
      <div class="content ">
        <h1 class="h1-responsive font-weight-bold text-center ">printf("Olar ");</h1>

        <p class="lead grey-text text-center w-responsive mx-auto mb-5 ">Me chamo Mateus Machado, trabalho atualmente como Software Tester, graduando em Tecnologia de Banco de Dados. Desenvolvo para projetos pessoais no tempo livre e no tempo mais livre toco violão e faço outras coisas de humano :)</p>

        <div class="container-fluid px-5 py-5 " style="background-color:grey ";>
          <div class="row container-fluid " ">
                <div class="col-5">
                    <img class="img-fluid img-thumbnail" src="img/magogenteboa.jpg">
            </div>

            <div class="col-7 container-fluid">
              <ul>
                <li style="background-color:rgba(0,0,0,.3)" class="px-3 py-3 my-1">
                  <img class="img-fluid" src="img/baseline_school2.png">
                   <p class="text-light">Técnico em Redes de Computadores pela
                     Etec Cônego José Bentos
                    </p>
                  <small class="text-light font-italic">Período: 2016 - 2017</small>

                <li style="background-color:rgba(0,0,0,.3)" class="px-3 py-3 my-1">
                  <img class="img-fluid" src="img/baseline_school2.png">
                  <p class="text-light">Graduando em Tecnologia de Banco de Dados pela Fatec São José dos Campos </p>
                  <small class="text-light font-italic">Período: 2018 - Atualmente</small>
                </li>

                <li style="background-color:rgba(0,0,0,.3)" class="px-3 py-3 my-1">
                  <img class="img-fluid" src="img/baseline_work2.png">
                  <p class="text-light">Tester de Software na
                    DeMaria
                  </p>
                  <small class="text-light font-italic" >Período: 2017 - Atualmente</small>
                </li>
              </ul>

            </div>
          </div>
        </div>
      </div>

    </section>
    </main>
                <style>
              body, p, html , h1, nav, section, main, img{
                margin: 0;

              }
            </style>
  </body>
</html>
</code>```

答:
Try to remove all the tags at the top and replace them with *. An asterisk means all the tags within the html document. I rewrote your code in this manner:

```<code>*{
    margin: 0;
    padding: 0;
    border: 0;
    line-height: 1;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
    display: block;
}
ol, ul {
    list-style: none;
}
blockquote, q {
    quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
    content: '';
    content: none;
}
table {
    border-collapse: collapse;
    border-spacing: 0;
}

</code>```

It would be really helpful to solve this if you can include the html code as well if my code didn't work

Title: HTML has a margin bigger than body

Body:
I'm creating my own personal site using bootstrap.

I've using bootstrap4 with some modifications. However the html margin is bigger than body.

I've already checked other questions and they say that
 or some other tag has a default margin and you need to zero that, however I'm using a reset.css and plus I tried to zero margin of a lot of elements and it didn't work.

the reset css and the link to my web site: https://sitezinho--mateusmsouza.repl.co/

/* http://meyerweb.com/eric/tools/css/reset/
   v2.0 | 20110126
   License: none (public domain)
*/

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font: inherit;
    vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
    display: block;
}
body {
    line-height: 1;
}
ol, ul {
    list-style: none;
}
blockquote, q {
    quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
    content: '';
    content: none;
}
table {
    border-collapse: collapse;
    border-spacing: 0;
}

and HTML

<!DOCTYPE html>

    <title>Mateus Machado - Site Pessoal</title>
    <link rel="stylesheet" type="text/css" href="public/css/reset.css">
    <link rel="stylesheet" type="text/css" href="public/css/bootstrap.min.css">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="public/css/custom.css">

Hello World

Projetos

Material de Estudo

printf("Olar ");

Me chamo Mateus Machado, trabalho atualmente como Software Tester, graduando em Tecnologia de Banco de Dados. Desenvolvo para projetos pessoais no tempo livre e no tempo mais livre toco violão e faço outras coisas de humano :)

Técnico em Redes de Computadores pela
                     Etec Cônego José Bentos

                  Período: 2016 - 2017

Graduando em Tecnologia de Banco de Dados pela Fatec São José dos Campos

                  Período: 2018 - Atualmente

Tester de Software na
                    DeMaria

                  Período: 2017 - Atualmente

Body:
Try to remove all the tags at the top and replace them with *. An asterisk means all the tags within the html document. I rewrote your code in this manner:

*{
    margin: 0;
    padding: 0;
    border: 0;
    line-height: 1;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
    display: block;
}
ol, ul {
    list-style: none;
}
blockquote, q {
    quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
    content: '';
    content: none;
}
table {
    border-collapse: collapse;
    border-spacing: 0;
}

It would be really helpful to solve this if you can include the html code as well if my code didn't work


问:
call a suspend function inside a normal function
I want to call blocking a suspend function in a normal function, but does not block Thread to finishing suspend function and then return Response

```<code>override fun intercept(chain: Interceptor.Chain): Response {

    // getSession is a suspend function
    val session = sessionProvider.getSession()

    return chain.proceed(
        chain
            .request()
            .newBuilder()
            .addHeader("Authorization", "${session.token}")
            .build()
    )
}
</code>```

答:
This looks like you are implementing an OkHttp interceptor, so I am hoping that intercept() is being called on a background thread.

If so, use runBlocking():

```<code>override fun intercept(chain: Interceptor.Chain): Response {

    // getSession is a suspend function
    val session = runBlocking { sessionProvider.getSession() }

    return chain.proceed(
        chain
            .request()
            .newBuilder()
            .addHeader("Authorization", "${session.token}")
            .build()
    )
}
</code>```

runBlocking() will execute the suspend function, blocking the current thread until that work is complete.

Body:
I want to call blocking a suspend function in a normal function, but does not block Thread to finishing suspend function and then return Response

override fun intercept(chain: Interceptor.Chain): Response {

    // getSession is a suspend function
    val session = sessionProvider.getSession()

    return chain.proceed(
        chain
            .request()
            .newBuilder()
            .addHeader("Authorization", "${session.token}")
            .build()
    )
}

Body:
This looks like you are implementing an OkHttp interceptor, so I am hoping that intercept() is being called on a background thread.

If so, use runBlocking():

override fun intercept(chain: Interceptor.Chain): Response {

    // getSession is a suspend function
    val session = runBlocking { sessionProvider.getSession() }

    return chain.proceed(
        chain
            .request()
            .newBuilder()
            .addHeader("Authorization", "${session.token}")
            .build()
    )
}

runBlocking() will execute the suspend function, blocking the current thread until that work is complete.


问:
When to use an extension method with lambda over LINQtoObjects to filter a collection?
I am prototyping some C# 3 collection filters and came across this.
I have a collection of products:

```<code>public class MyProduct
{
    public string Name { get; set; }
    public Double Price { get; set; }
    public string Description { get; set; }
}

var MyProducts = new  List<MyProduct>
{
    new  MyProduct
    {
        Name = "Surfboard",
        Price = 144.99,
        Description = "Most important thing you will ever own."
    },
    new MyProduct
    {
        Name = "Leash",
        Price = 29.28,
        Description = "Keep important things close to you."
    }
    ,
    new MyProduct
    {
        Name = "Sun Screen",
        Price = 15.88,
        Description = "1000 SPF! Who Could ask for more?"
    }
};
</code>```

Now if I use LINQ to filter it works as expected:

```<code>var d = (from mp in MyProducts
             where mp.Price < 50d
             select mp);
</code>```

And if I use the Where extension method combined with a Lambda the filter works as well:

```<code>var f = MyProducts.Where(mp => mp.Price < 50d).ToList();
</code>```

Question: What is the difference, and why use one over the other?

答: Other than the ToList difference, #2 is a lot more readable and natural IMO</p>

Body:
I am prototyping some C# 3 collection filters and came across this.
I have a collection of products:

public class MyProduct
{
    public string Name { get; set; }
    public Double Price { get; set; }
    public string Description { get; set; }
}

var MyProducts = new  List<MyProduct>
{
    new  MyProduct
    {
        Name = "Surfboard",
        Price = 144.99,
        Description = "Most important thing you will ever own."
    },
    new MyProduct
    {
        Name = "Leash",
        Price = 29.28,
        Description = "Keep important things close to you."
    }
    ,
    new MyProduct
    {
        Name = "Sun Screen",
        Price = 15.88,
        Description = "1000 SPF! Who Could ask for more?"
    }
};

Now if I use LINQ to filter it works as expected:

var d = (from mp in MyProducts
             where mp.Price < 50d
             select mp);

And if I use the Where extension method combined with a Lambda the filter works as well:

var f = MyProducts.Where(mp => mp.Price < 50d).ToList();

Question: What is the difference, and why use one over the other?

LastEditorDisplayName: Keith

ContentLicense: CC BY-SA 2.5


问:
Normalize edge weights in igraph for plotting (edge weights too thick)
How can I normalize the plot of a weighted network in igraph where the edges are not too thick according to the edge weight?</p>

答:
In igraph, where g is the graph object, you an access edge weights via E(g)$weight and modify edge weights via assignment: E(g)$weight <- new_values.

To normalize between 0-1 try: E(g)$weight <- E(g)$weight / max(E(g)$weight).

Here's a reproducible example you can copy and paste.

```<code>library(igraph)

set.seed(1) # reproducibility

# generate random graph
g <- sample_k_regular(10, k = 3, directed = FALSE, multiple = FALSE)

# add edge weights
E(g)$weight <- sample(c(1,10,50), length(E(g)), replace = TRUE)

# view the problem
plot(g, edge.width = E(g)$weight)
</code>```

```<code># normalize the edge weights between 0-1
E(g)$weight <- E(g)$weight / max(E(g)$weight)

# play with different values of `k` until you get a reasonable looking graph
k = 9
plot(g, edge.width = E(g)$weight * k)
</code>```

Body:
In igraph, where g is the graph object, you an access edge weights via E(g)$weight and modify edge weights via assignment: E(g)$weight <- new_values.

To normalize between 0-1 try: E(g)$weight <- E(g)$weight / max(E(g)$weight).

Here's a reproducible example you can copy and paste.

library(igraph)

set.seed(1) # reproducibility

# generate random graph
g <- sample_k_regular(10, k = 3, directed = FALSE, multiple = FALSE)

# add edge weights
E(g)$weight <- sample(c(1,10,50), length(E(g)), replace = TRUE)

# view the problem
plot(g, edge.width = E(g)$weight)

# normalize the edge weights between 0-1
E(g)$weight <- E(g)$weight / max(E(g)$weight)

# play with different values of `k` until you get a reasonable looking graph
k = 9
plot(g, edge.width = E(g)$weight * k)


问:
Yank the first word from each line in vim
I'm using vim and I'd like to copy the first word for a range of consecutive lines. The only thing that I could think of is :4,32yw (for lines 4-32), but it didn't work. Any help is appreciated in advance, thanks!

答:
You can do it, but it might be a little bit more complicated than using a simple command as you did.

What you tried to run, is normal mode commands as execute commands. That won't work as you did it. Commands in the normal mode (like pressing yw) won't work  es ex-commands.

To run the normal mode commands in the ex-command mode, you should use the normal command (for more information, you can see :help normal).
However, even if you would change you command to use the normal mode command (something like :4,32 normal! yw) it would still not work, since this would run for every line, each time running over the previous yanked value.

You can do the desired action, using a vim register that would append the word in each loop (for more info about registers you can read :help registers).

To do it, you should change the command to be something like :3,32 normal! ^"Ayw.

To break down this command:

: - enter ex-command mode.

3,32 - The range to run the command over.

normal! - The actual command to run. Run it without any custom mapping, to avoid mappings that run over the wanted action.

^ - Go to the start of the line.

"A - Run the yank into the a register, appending the data to the previously saved data in it.

yw - Yank the current word.

Later, to print the copied values, you should use "ap (in the normal mode) at the desired location.

Drawbacks

Note that the command inserts the new word into the registers, ignoring the first value of the register. It means that if the register wasn't empty once you run this command, all the words would be appended to the current value of the register.

To clear the previous value of the register, you can run the command:

```<code>:let @a=''
</code>```

before running you yank command.

Automation

In case you want to do it many times, you might want to use a simple function that would do it all for you, instead make you run both commands every time.

A simple function that would do this:

```<code>function! CopyFirst(register) range
    execute "let @" . a:register. "=''"
    execute a:firstline . "," . a:lastline . "normal! ^\"" . toupper(a:register) . "yw"
endfunction
</code>```

Usage:

```<code>:3, 32 call Copyfirst('a')
"ap
</code>```

Body:
You can do it, but it might be a little bit more complicated than using a simple command as you did.

What you tried to run, is normal mode commands as execute commands. That won't work as you did it. Commands in the normal mode (like pressing yw) won't work  es ex-commands.

To run the normal mode commands in the ex-command mode, you should use the normal command (for more information, you can see :help normal).
However, even if you would change you command to use the normal mode command (something like :4,32 normal! yw) it would still not work, since this would run for every line, each time running over the previous yanked value.

You can do the desired action, using a vim register that would append the word in each loop (for more info about registers you can read :help registers).

To do it, you should change the command to be something like :3,32 normal! ^"Ayw.

To break down this command:

: - enter ex-command mode.

3,32 - The range to run the command over.

normal! - The actual command to run. Run it without any custom mapping, to avoid mappings that run over the wanted action.

^ - Go to the start of the line.

"A - Run the yank into the a register, appending the data to the previously saved data in it.

yw - Yank the current word.

Later, to print the copied values, you should use "ap (in the normal mode) at the desired location.

Drawbacks

Note that the command inserts the new word into the registers, ignoring the first value of the register. It means that if the register wasn't empty once you run this command, all the words would be appended to the current value of the register.

To clear the previous value of the register, you can run the command:

:let @a=''

before running you yank command.

Automation

In case you want to do it many times, you might want to use a simple function that would do it all for you, instead make you run both commands every time.

A simple function that would do this:

function! CopyFirst(register) range
    execute "let @" . a:register. "=''"
    execute a:firstline . "," . a:lastline . "normal! ^\"" . toupper(a:register) . "yw"
endfunction

Usage:

:3, 32 call Copyfirst('a')
"ap


问:
Get region base URL (HC_HOST) in the SAP Cloud Platform Cloud Foundry environment
In the SAP Cloud Platform Neo environment, there is a system property HC_HOST which contains the base URL of the SAP Cloud Platform region where the application is deployed (see documentation).

Is there something similar for the Cloud Foundry environment? I checked cf env, but I couldn't see anything obvious.

答:
The equivalent to NEO environment variables in CF are VCAP environment variables. I think the closest to HC_HOST in NEO is VCAP_APPLICATION.uris.
Although, you will need to extract base uri from the application uri.


问:
error TS2339: Property 'sendemailverification' does not exist on type 'UserCredential'
I get this error:

```<code>error TS2339: Property 'sendemailverification' does not exist on type 'UserCredential'
</code>```

it's my code
i using firebase email verification

```<code>import { Component, OnInit } from '@angular/core';
import {NgForm} from '@angular/forms';
import * as firebase from 'firebase/app';

@Component({
  selector: 'app-sign-up',
  templateUrl: './sign-up.component.html',
 styleUrls: ['./sign-up.component.css']
})
export class SignUpComponent implements OnInit {

  constructor() { }

  ngOnInit() {
}

onSubmit(form: NgForm) {
const fullname = form.value.fullname;
const email = form.value.email;
const password = form.value.password;

firebase.auth().createUserWithEmailAndPassword(email, password)
  .then(userData => {
    //error
    userData.sendemailverification();
    console.log(userData);
  })
  .catch(err =>{
    console.log(err);
  });
  }

}
</code>```

答: You can use userData.user.sendEmailVerification() to make it work.

Body:
I get this error:

error TS2339: Property 'sendemailverification' does not exist on type 'UserCredential'

it's my code
i using firebase email verification

import { Component, OnInit } from '@angular/core';
import {NgForm} from '@angular/forms';
import * as firebase from 'firebase/app';

@Component({
  selector: 'app-sign-up',
  templateUrl: './sign-up.component.html',
 styleUrls: ['./sign-up.component.css']
})
export class SignUpComponent implements OnInit {

  constructor() { }

  ngOnInit() {
}

onSubmit(form: NgForm) {
const fullname = form.value.fullname;
const email = form.value.email;
const password = form.value.password;

firebase.auth().createUserWithEmailAndPassword(email, password)
  .then(userData => {
    //error
    userData.sendemailverification();
    console.log(userData);
  })
  .catch(err =>{
    console.log(err);
  });
  }

}


问:
How to deserialize json with unknown properties using JMS Serializer?
I'm trying to create DTO which will help me to deserialize nested JSON. I know the structure of JSON but on some nested step I don't know the names/indexes of JSON properties.

JSON looks like:

```<code>{
  "project": {
    "layer": {
      "480x960": [],
      "720x360": [],
      "...": [],
      "...": []
    }
  }
}
</code>```

but I don't know names of properties inside the layer property.

I have some DTOs so far

Project DTO:

```<code>namespace App\DTO;

use JMS\Serializer\Annotation as Serializer;

class Project
{
    /**
     * @var Layer
     *
     * @Serializer\Type("App\DTO\Layer")
     */
    protected $layer;
}
</code>```

Layer DTO: (which I stuck on)

```<code>namespace App\DTO;

use Doctrine\Common\Collections\Collection;
use JMS\Serializer\Annotation as Serializer;

class Layer
{
    // ???
}
</code>```

I seek to achieve something like: $project->getLayer() will return Collection of objects ['480x960', '720x360', '...', etc.]. I don't bother to keep names/indexes of those unknown properties inside layer.

答:
Try this. You don't need class for Layer.

```<code>use JMS\Serializer\Annotation as Serializer;

class Project
{
    /**
     * @Serializer\Type("array<string, array>")
     */
    protected $layer;
}
</code>```

Check http://www.inanzzz.com/index.php/post/vsb9/mapping-random-json-and-xml-request-properties-with-jmsserializerbundle-in-symfony

Body:
I'm trying to create DTO which will help me to deserialize nested JSON. I know the structure of JSON but on some nested step I don't know the names/indexes of JSON properties.

JSON looks like:

{
  "project": {
    "layer": {
      "480x960": [],
      "720x360": [],
      "...": [],
      "...": []
    }
  }
}

but I don't know names of properties inside the layer property.

I have some DTOs so far

Project DTO:

namespace App\DTO;

use JMS\Serializer\Annotation as Serializer;

class Project
{
    /**
     * @var Layer
     *
     * @Serializer\Type("App\DTO\Layer")
     */
    protected $layer;
}

Layer DTO: (which I stuck on)

namespace App\DTO;

use Doctrine\Common\Collections\Collection;
use JMS\Serializer\Annotation as Serializer;

class Layer
{
    // ???
}

I seek to achieve something like: $project->getLayer() will return Collection of objects ['480x960', '720x360', '...', etc.]. I don't bother to keep names/indexes of those unknown properties inside layer.

Body:
Try this. You don't need class for Layer.

use JMS\Serializer\Annotation as Serializer;

class Project
{
    /**
     * @Serializer\Type("array<string, array>")
     */
    protected $layer;
}

Check http://www.inanzzz.com/index.php/post/vsb9/mapping-random-json-and-xml-request-properties-with-jmsserializerbundle-in-symfony


问:
The remove() function is deleting every element I clicked instead of the one recently clicked
I am creating a gallery web app just for fun. I am adding context menu to manipulate images. I added the functionality to delete a certain image by right clicking on it but when a right click on multiple images and click on delete option once, all the previously clicked images also gets removed.

The delete option should delete the recently clicked image only.

$(".image").on("mousedown", function(event) {
  var i = $(this);
  var c = $(".context");
  c.css("display", "none");

  if (event.which == 3) {
    c.css({
      "top": event.pageY + "px",
      "left": event.pageX + "px"
    }).slideDown();

    $("#delete").on("click", function() {
      var p = i.offset();
      i.next().css("margin-left", "290px");
      i.css({
        "position": "absolute",
        "top": p.top - 72,
        "left": p.left - 10
      });

      i.animate({
        top: "-50%",
        opacity: "0"
      });

      setTimeout(function() {
        i.next().animate({
          "marginLeft": "10px"
        });
        i.prev().animate({
          "marginRight": "10px"
        });
        i.remove();
      }, 200);

      c.css("display", "none");
    });
  } else if (event.which == 1 || event.which == 2) {
    c.css("display", "none");
  }
});
```

答:
Assuming the same context menu is been used for all the images, the reason multiple images are been deleted is because your code adds multiple events to the shared #delete button.

One solution to this issue is to add the event for #delete once outside of the mousedown event. Within the mousedown event you then tag the image with a CSS class and target it in the #delete event handler.

Example:

```<code>    $(".image").on("mousedown", function(event) {
      var i = $(this);
      var c = $(".context");
      c.css("display", "none");

      // Deselect any previously selceted images
      $('.image.selected').removeClass('selected');

      if (event.which == 3) {
        c.css({
          "top": event.pageY + "px",
          "left": event.pageX + "px"
        }).slideDown();

        // Tags the image with the `selected` class
        i.addClass('selected');

      } else if (event.which == 1 || event.which == 2) {
        c.css("display", "none");
      }
    });

    $("#delete").on("click", function() {
          // Target selected image
          var i = $('.image.selected');
          var c = $(".context");
          var p = i.offset();
          i.next().css("margin-left", "290px");
          i.css({
            "position": "absolute",
            "top": p.top - 72,
            "left": p.left - 10
          });

          i.animate({
            top: "-50%",
            opacity: "0"
          });

          setTimeout(function() {
            i.next().animate({
              "marginLeft": "10px"
            });
            i.prev().animate({
              "marginRight": "10px"
            });
            i.remove();
          }, 200);

          c.css("display", "none");
        });
</code>```

Body:
Assuming the same context menu is been used for all the images, the reason multiple images are been deleted is because your code adds multiple events to the shared #delete button.

One solution to this issue is to add the event for #delete once outside of the mousedown event. Within the mousedown event you then tag the image with a CSS class and target it in the #delete event handler.

Example:

    $(".image").on("mousedown", function(event) {
      var i = $(this);
      var c = $(".context");
      c.css("display", "none");

      // Deselect any previously selceted images
      $('.image.selected').removeClass('selected');

      if (event.which == 3) {
        c.css({
          "top": event.pageY + "px",
          "left": event.pageX + "px"
        }).slideDown();

        // Tags the image with the `selected` class
        i.addClass('selected');

      } else if (event.which == 1 || event.which == 2) {
        c.css("display", "none");
      }
    });

    $("#delete").on("click", function() {
          // Target selected image
          var i = $('.image.selected');
          var c = $(".context");
          var p = i.offset();
          i.next().css("margin-left", "290px");
          i.css({
            "position": "absolute",
            "top": p.top - 72,
            "left": p.left - 10
          });

          i.animate({
            top: "-50%",
            opacity: "0"
          });

          setTimeout(function() {
            i.next().animate({
              "marginLeft": "10px"
            });
            i.prev().animate({
              "marginRight": "10px"
            });
            i.remove();
          }, 200);

          c.css("display", "none");
        });


问:
What does [] and [_] mean in Prolog
I believe [] means accepting the empty lists while [_] accepting a non empty list that may have anything. But then in some context such as say a function:

```<code>f([]).
f[_]).
f([x|y]):-dostuff.
</code>```

Wouldn't [x|y] and [_] both be called since they essentially mean the same thing?

答:
In Prolog one represents lists as linked lists. A linked list has two "patterns":

the empty list []; and

the "cons" [H|T] with H and T parameters with H the head of the list (the first element), and T the tail of the list (a list with the remaining elements).

So we can present a list with no elements as [], with one element as [H1|[]], with two elements as [H1|[H2|[]]], and so on.

The above notation is a bit verbose, one can use syntactical sugar for lists. For example [H1, H2] is equivalent to [H1|[H2|[]]], the same way [H1,H2|T] is equivalent to [H1|[H2|T]].

The [_] in your code is thus syntactical sugar for [_|[]]. It means that this is a singleton list (a list with exactly one element _), and we do not care here about that value of the list, as long as it unifies with that pattern.

But then in some context such as say a function.

f/1 here is not a function, it is a predicate. It here means that the predicate f/1 is satisfied for an empty list, for a list with one element regardless what that element is, and for a list [X|Y] (I assume that these are uppercase identifiers, since otherwise it is only satisfied if the head is a constant x, and the tail is a constant y, which means it is not really a list).

Title: What does [] and [_] mean in Prolog

Body:
I believe [] means accepting the empty lists while [_] accepting a non empty list that may have anything. But then in some context such as say a function:

f([]).
f[_]).
f([x|y]):-dostuff.

Wouldn't [x|y] and [_] both be called since they essentially mean the same thing?


问:
Make :hover apply to padding as well as main content area
I'm adapting some code from a WordPress theme. I've managed to successfully modify the navigation menu to trigger a CSS rollover on :hover, but I've run into a strange problem where: the hover only seems to properly apply to the main area of the element - rolling over anything inside the padding changes  background-color to black and color to white as expected, but rolling over the  padding itself triggers only background-color, whilst color remains black.

How can I change it so that each menu item's rollover is triggered by rolling over its main area or its padding?

The navigation menu is contained in something like the following:

```<code><nav id="site-navigation" class="main-navigation">
  <ul id="primary-menu" class="primary-menu">
    <li><a href="http://localhost/wordpress/home">Home</a></li>
    <li><a href="http://localhost/wordpress/about/">About</a></li>
    <li><a href="http://localhost/wordpress/services/">Services</a></li>
    <li><a href="http://localhost/wordpress/people/">People</a></li>
    <li><a href="http://localhost/wordpress/mission/">Mission</a></li>
    <li><a href="http://localhost/wordpress/donate/">Donate</a></li>
    <li><a href="http://localhost/wordpress/contact/">Contact</a></li>
  </ul>
</nav>
</code>```

And here's the CSS that applies to it:

```<code>.primary-menu>li {
  font-size: 18px;
  font-weight: bold;
  display: inline-block;
  vertical-align: middle;
  overflow: hidden;
}

.primary-menu>li a {
  padding: 6px 8px 6px 8px;
}

.primary-menu .current-menu-item {
  background-color: #000;
  color: #FFF;
}

.primary-menu>li:hover, .primary-menu>li:focus, .primary-menu>li:active {
  background-color: #000;
  color: #FFF;
}
</code>```

答:
I think this may be the solution you are looking for.

Change the rules with the pseudo-classes to this:

.primary-menu>li:hover a,
.primary-menu>li:focus a,
.primary-menu>li:active a {
  background-color: #000;
  color: #fff;
}
```

It says that when a list-item is hovered on, change the background colour and text colour of the hyperlink, not the list item.

Body:
I'm adapting some code from a WordPress theme. I've managed to successfully modify the navigation menu to trigger a CSS rollover on :hover, but I've run into a strange problem where: the hover only seems to properly apply to the main area of the element - rolling over anything inside the padding changes  background-color to black and color to white as expected, but rolling over the  padding itself triggers only background-color, whilst color remains black.

How can I change it so that each menu item's rollover is triggered by rolling over its main area or its padding?

The navigation menu is contained in something like the following:

Home

About

Services

People

Mission

Donate

Contact

And here's the CSS that applies to it:

.primary-menu>li {
  font-size: 18px;
  font-weight: bold;
  display: inline-block;
  vertical-align: middle;
  overflow: hidden;
}

.primary-menu>li a {
  padding: 6px 8px 6px 8px;
}

.primary-menu .current-menu-item {
  background-color: #000;
  color: #FFF;
}

.primary-menu>li:hover, .primary-menu>li:focus, .primary-menu>li:active {
  background-color: #000;
  color: #FFF;
}

Body:
I think this may be the solution you are looking for.

Change the rules with the pseudo-classes to this:

.primary-menu>li:hover a,
.primary-menu>li:focus a,
.primary-menu>li:active a {
  background-color: #000;
  color: #fff;
}

It says that when a list-item is hovered on, change the background colour and text colour of the hyperlink, not the list item.