问:
Question regarding UIImage -> CVPixelBuffer -> UIImage conversion
I am working on a simple denoising POC in SwiftUI where I want to:

Load an input image

Apply a CoreML model (denoising) to the input image

Display the output image

I have something working based on dozens of source codes I found online. Based on what I've read, a CoreML model (at least the one I'm using) accepts a CVPixelBuffer and outputs also a CVPixelBuffer. So my idea was to do the following:

Convert the input UIImage into a CVPixelBuffer

Apply the CoreML model to the CVPixelBuffer

Convert the newly created CVPixelBuffer into a UIImage

(Note that I've read that using the Vision framework, one can input a CGImage directly into the model. I'll try this approach as soon as I'm familiar with what I'm trying to achieve here as I think it is a good exercise.)

As a start, I wanted to skip the step (2) to focus on the conversion problem. What I tried to achieve in the code bellow is:

Convert the input UIImage into a CVPixelBuffer

Convert the CVPixelBuffer into a UIImage

I'm not a Swift or an Objective-C developer, so I'm pretty sure that I've made at least a few mistakes. I found this code quite complex and I was wondering if there was a better / simpler way to do the same thing?

func convert(input: UIImage) -> UIImage? {

    // Input CGImage
    guard let cgInput = input.cgImage else {
        return nil
    }

    // Image size
    let width = cgInput.width
    let height = cgInput.height
    let region = CGRect(x: 0, y: 0, width: width, height: height)

    // Attributes needed to create the CVPixelBuffer
    let attributes = [kCVPixelBufferCGImageCompatibilityKey: kCFBooleanTrue,
                      kCVPixelBufferCGBitmapContextCompatibilityKey: kCFBooleanTrue]

    // Create the input CVPixelBuffer
    var pbInput:CVPixelBuffer? = nil
    let status = CVPixelBufferCreate(kCFAllocatorDefault,
                                     width,
                                     height,
                                     kCVPixelFormatType_32ARGB,
                                     attributes as CFDictionary,
                                     &pbInput)

    // Sanity check
    if status != kCVReturnSuccess {
        return nil
    }

    // Fill the input CVPixelBuffer with the content of the input CGImage
    CVPixelBufferLockBaseAddress(pbInput!, CVPixelBufferLockFlags(rawValue: 0))
    guard let context = CGContext(data: CVPixelBufferGetBaseAddress(pbInput!),
                                  width: width,
                                  height: height,
                                  bitsPerComponent: cgInput.bitsPerComponent,
                                  bytesPerRow: cgInput.bytesPerRow,
                                  space: cgInput.colorSpace!,
                                  bitmapInfo: CGImageAlphaInfo.noneSkipFirst.rawValue) else {
                                    return nil
    }
    context.draw(cgInput, in: region)
    CVPixelBufferUnlockBaseAddress(pbInput!, CVPixelBufferLockFlags(rawValue: 0))

    // Create the output CGImage
    let ciOutput = CIImage(cvPixelBuffer: pbInput!)
    let temporaryContext = CIContext(options: nil)
    guard let cgOutput = temporaryContext.createCGImage(ciOutput, from: region) else {
        return nil
    }

    // Create and return the output UIImage
    return UIImage(cgImage: cgOutput)
}
```

When I used this code in my SwiftUI project, input and output images looked the same, but there were not identical. I think the input image had a colormap (ColorSync Profile) associated to it that have been lost during the conversion. I assumed I was supposed to use cgInput.colorSpace during the CGContext creation, but it seemed that using CGColorSpace(name: CGColorSpace.sRGB)! was working better. Can somebody please explain that to me?

Thanks for your help.

答:
You can also use CGImage objects with Core ML, but you have to create the MLFeatureValue object by hand and then put it into an MLFeatureProvider to give it to the model. But that only takes care of the model input, not the output.

Another option is to use the code from my CoreMLHelpers repo.

Body:
I am working on a simple denoising POC in SwiftUI where I want to:

Load an input image

Apply a CoreML model (denoising) to the input image

Display the output image

I have something working based on dozens of source codes I found online. Based on what I've read, a CoreML model (at least the one I'm using) accepts a CVPixelBuffer and outputs also a CVPixelBuffer. So my idea was to do the following:

Convert the input UIImage into a CVPixelBuffer

Apply the CoreML model to the CVPixelBuffer

Convert the newly created CVPixelBuffer into a UIImage

(Note that I've read that using the Vision framework, one can input a CGImage directly into the model. I'll try this approach as soon as I'm familiar with what I'm trying to achieve here as I think it is a good exercise.)

As a start, I wanted to skip the step (2) to focus on the conversion problem. What I tried to achieve in the code bellow is:

Convert the input UIImage into a CVPixelBuffer

Convert the CVPixelBuffer into a UIImage

I'm not a Swift or an Objective-C developer, so I'm pretty sure that I've made at least a few mistakes. I found this code quite complex and I was wondering if there was a better / simpler way to do the same thing?

func convert(input: UIImage) -> UIImage? {

    // Input CGImage
    guard let cgInput = input.cgImage else {
        return nil
    }

    // Image size
    let width = cgInput.width
    let height = cgInput.height
    let region = CGRect(x: 0, y: 0, width: width, height: height)

    // Attributes needed to create the CVPixelBuffer
    let attributes = [kCVPixelBufferCGImageCompatibilityKey: kCFBooleanTrue,
                      kCVPixelBufferCGBitmapContextCompatibilityKey: kCFBooleanTrue]

    // Create the input CVPixelBuffer
    var pbInput:CVPixelBuffer? = nil
    let status = CVPixelBufferCreate(kCFAllocatorDefault,
                                     width,
                                     height,
                                     kCVPixelFormatType_32ARGB,
                                     attributes as CFDictionary,
                                     &pbInput)

    // Sanity check
    if status != kCVReturnSuccess {
        return nil
    }

    // Fill the input CVPixelBuffer with the content of the input CGImage
    CVPixelBufferLockBaseAddress(pbInput!, CVPixelBufferLockFlags(rawValue: 0))
    guard let context = CGContext(data: CVPixelBufferGetBaseAddress(pbInput!),
                                  width: width,
                                  height: height,
                                  bitsPerComponent: cgInput.bitsPerComponent,
                                  bytesPerRow: cgInput.bytesPerRow,
                                  space: cgInput.colorSpace!,
                                  bitmapInfo: CGImageAlphaInfo.noneSkipFirst.rawValue) else {
                                    return nil
    }
    context.draw(cgInput, in: region)
    CVPixelBufferUnlockBaseAddress(pbInput!, CVPixelBufferLockFlags(rawValue: 0))

    // Create the output CGImage
    let ciOutput = CIImage(cvPixelBuffer: pbInput!)
    let temporaryContext = CIContext(options: nil)
    guard let cgOutput = temporaryContext.createCGImage(ciOutput, from: region) else {
        return nil
    }

    // Create and return the output UIImage
    return UIImage(cgImage: cgOutput)
}

When I used this code in my SwiftUI project, input and output images looked the same, but there were not identical. I think the input image had a colormap (ColorSync Profile) associated to it that have been lost during the conversion. I assumed I was supposed to use cgInput.colorSpace during the CGContext creation, but it seemed that using CGColorSpace(name: CGColorSpace.sRGB)! was working better. Can somebody please explain that to me?

Thanks for your help.


来源: stackexchange

问:
Replace Value in DataFrame with Regex function return Value
Goal:

In a dataframe containing concatenated Proper Names, split each name at capitalization of name with a space, and replace that value in corresponding dataframe element. Testing on regex function yields correct result when tested on independent values.

Process

```<code>data = {'Full_Name' : ["JackSmithDanielsSmith", "JoeShmoeDoeBoe", "MikeJohnChaoCow"]
        'First_Name': ["JackSmith", "JoeShmoeDoe", "Mike"]
        'Last_Name' : ["DanielsSmith", "Boe", "JohnChaoCow"]}

df = pd.DataFrame(data)

# Regex Function (returns expected results)

def CapitalizeWord(word):
    word = str(word)
    return re.sub("([A-Z])", " \\1", word).strip()

# Procedure
for column in df:
    replace_data = []
    columnObj = df[column]
    for word in columnObj:
        word_split = CapitalizeWord(word)
        replace_data.append(word_split)
    df.replace(columnObj, append_data)
</code>```

Error:

```<code>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-80-b8089f04c8c8> in <module>
----> 9     df.replace(columnObj, replace_data)

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\frame.py in replace(self, to_replace, value, inplace, limit, regex, method)
   4261             limit=limit,
   4262             regex=regex,
-> 4263             method=method,
   4264         )
   4265

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\generic.py in replace(self, to_replace, value, inplace, limit, regex, method)
   6719                         )
   6720                 else:
-> 6721                     raise TypeError("value argument must be scalar, dict, or " "Series")
   6722
   6723             elif is_list_like(to_replace):  # [NA, ''] -> [0, 'missing']

TypeError: value argument must be scalar, dict, or Series
</code>```

Research:

In the df.replace Docs , I noticed my issue is similar to what is referenced in the ending paragraphs. I'm not fully understanding the definition, when used with regex.

答:
Try this:

```<code>df.apply(lambda x: x.str.replace('([A-Z])', " \\1"))
</code>```

Output:

```<code>                   Full_Name      First_Name       Last_Name
0   Jack Smith Daniels Smith      Jack Smith   Daniels Smith
1          Joe Shmoe Doe Boe   Joe Shmoe Doe             Boe
2         Mike John Chao Cow            Mike   John Chao Cow
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Goal:

In a dataframe containing concatenated Proper Names, split each name at capitalization of name with a space, and replace that value in corresponding dataframe element. Testing on regex function yields correct result when tested on independent values.

Process

data = {'Full_Name' : ["JackSmithDanielsSmith", "JoeShmoeDoeBoe", "MikeJohnChaoCow"]
        'First_Name': ["JackSmith", "JoeShmoeDoe", "Mike"]
        'Last_Name' : ["DanielsSmith", "Boe", "JohnChaoCow"]}

df = pd.DataFrame(data)

# Regex Function (returns expected results)

def CapitalizeWord(word):
    word = str(word)
    return re.sub("([A-Z])", " \\1", word).strip()

# Procedure
for column in df:
    replace_data = []
    columnObj = df[column]
    for word in columnObj:
        word_split = CapitalizeWord(word)
        replace_data.append(word_split)
    df.replace(columnObj, append_data)

Error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-80-b8089f04c8c8> in <module>
----> 9     df.replace(columnObj, replace_data)

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\frame.py in replace(self, to_replace, value, inplace, limit, regex, method)
   4261             limit=limit,
   4262             regex=regex,
-> 4263             method=method,
   4264         )
   4265

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\generic.py in replace(self, to_replace, value, inplace, limit, regex, method)
   6719                         )
   6720                 else:
-> 6721                     raise TypeError("value argument must be scalar, dict, or " "Series")
   6722
   6723             elif is_list_like(to_replace):  # [NA, ''] -> [0, 'missing']

TypeError: value argument must be scalar, dict, or Series

Research:

In the df.replace Docs , I noticed my issue is similar to what is referenced in the ending paragraphs. I'm not fully understanding the definition, when used with regex.

Body:
Try this:

df.apply(lambda x: x.str.replace('([A-Z])', " \\1"))

Output:

                   Full_Name      First_Name       Last_Name
0   Jack Smith Daniels Smith      Jack Smith   Daniels Smith
1          Joe Shmoe Doe Boe   Joe Shmoe Doe             Boe
2         Mike John Chao Cow            Mike   John Chao Cow


答:
This might not be the best, but I would stack and unstack:

```<code>(df.stack()
   .str.extractall('([A-Z][a-z]*)')
   .groupby(level=[0,1])
   .agg(' '.join)[0]
   .unstack()
)
</code>```

Output:

```<code>      First_Name                 Full_Name      Last_Name
0     Jack Smith  Jack Smith Daniels Smith  Daniels Smith
1  Joe Shmoe Doe         Joe Shmoe Doe Boe            Boe
2           Mike        Mike John Chao Cow  John Chao Cow
</code>```

Title: Replace Value in DataFrame with Regex function return Value

Body:
This might not be the best, but I would stack and unstack:

(df.stack()
   .str.extractall('([A-Z][a-z]*)')
   .groupby(level=[0,1])
   .agg(' '.join)[0]
   .unstack()
)

Output:

      First_Name                 Full_Name      Last_Name
0     Jack Smith  Jack Smith Daniels Smith  Daniels Smith
1  Joe Shmoe Doe         Joe Shmoe Doe Boe            Boe
2           Mike        Mike John Chao Cow  John Chao Cow


问:
HTML5 php contact form script confirmation
I'm having some trouble with a script confirmation. By standard it's set to hide the contact form and display a confirmation message but it's not working for all browsers. After some tests I realized it doesn't work for most IE versions, which are around 40% of my visitors.

How do I replace the hide-and-show-msg to a "thankyou.html"? I'm guessing this works as most IEs fail to show the confirmation message although they manage to hide the form. The code in 'header' is currently:

```<code><script src="php/js/jquery.validate.js"></script>
<script src="php/js/jquery.placeholder.js"></script>
<script src="php/js/jquery.form.js"></script>
<script>
$(function(){
$('#contact').validate({
submitHandler: function(form) {
    $(form).ajaxSubmit({
    url: 'thankyou.php',
    success: function() {
    $('#contact').hide();
    $('#contact-form').append("<p class='thanks'>Thank you! The message was sent.</center></p>")
    }
    });
    }
});
});
</script>
</code>```

答:
Solved.

Reading http://groups.google.com/group/jquery-en/browse_thread/thread/58a9cbc1068d28c0/eb4bedb2cc36b126?pli=1

I added a conditional script

```<code><head>
<!--[if IE]>
<script >
document.createElement("section");
</script >
<![endif]-->
</code>```

http://plungjan.name/test/testform_validation.html

What you need to do is to append to an element understood by IE.

If you do not want the conditional script, add a div to the end of the page and append to that instead like here:  http://plungjan.name/test/testformvalidation.html

Other issue: I got

```<code>Webpage error details

User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.0.3705; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; InfoPath.1)
Timestamp: Tue, 17 May 2011 13:15:29 UTC

Message: Unexpected call to method or property access.
Line: 5569
Char: 5
Code: 0
URI: http://code.jquery.com/jquery-1.6.1.js
</code>```

Seems the finally is not supported

When I Added catch(e) {} before the finally - error gone

```<code>resolveWith: function( context, args ) {
  if ( !cancelled && !fired && !firing ) {
    // make sure args are available (#8421)
    args = args || [];
    firing = 1;
    try {
      while( callbacks[ 0 ] ) {
        callbacks.shift().apply( context, args );
      }
    }
    catch(e) { /* ADDED BY ME */ }
    finally {
      fired = [ context, args ];
      firing = 0;
    }
  }
  return this;
},
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Solved.

Reading http://groups.google.com/group/jquery-en/browse_thread/thread/58a9cbc1068d28c0/eb4bedb2cc36b126?pli=1

I added a conditional script

<head>
<!--[if IE]>
<script >
document.createElement("section");
</script >
<![endif]-->

http://plungjan.name/test/testform_validation.html

What you need to do is to append to an element understood by IE.

If you do not want the conditional script, add a div to the end of the page and append to that instead like here:  http://plungjan.name/test/testformvalidation.html

Other issue: I got

Webpage error details

User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.0.3705; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; InfoPath.1)
Timestamp: Tue, 17 May 2011 13:15:29 UTC

Message: Unexpected call to method or property access.
Line: 5569
Char: 5
Code: 0
URI: http://code.jquery.com/jquery-1.6.1.js

Seems the finally is not supported

When I Added catch(e) {} before the finally - error gone

resolveWith: function( context, args ) {
  if ( !cancelled && !fired && !firing ) {
    // make sure args are available (#8421)
    args = args || [];
    firing = 1;
    try {
      while( callbacks[ 0 ] ) {
        callbacks.shift().apply( context, args );
      }
    }
    catch(e) { /* ADDED BY ME */ }
    finally {
      fired = [ context, args ];
      firing = 0;
    }
  }
  return this;
},


问:
Why does this function throw an error when using the includes method?
I'm having trouble figuring out why this function throws an error when it reaches the 'includes' method, when console logging whitelist, it shows that it is an array, when i use the includes method, it is throwing an error, cannot read property includes of undefined

```<code>const test = (body, ...whitelists) => {
  const bodies = whitelists.map(({ type = null, whitelist }) => {
    console.log('whitelist ', whitelist)

    const whitelistedBody = Object.entries(body).reduce(
      (newBody, [key, value]) => {
        console.log('KEY ', key)
        console.log('whitelist ', whitelists)

        if (whitelist.includes(key)) {
          newBody[key] = value;
        }

        console.log('newBody ', newBody)
        return newBody;
      },
      {}
    );

    return { type, body: whitelistedBody };
  });

  return (
    bodies.find(({ body }) => Object.keys(body).length) || {
      body: {},
      type: null,
    }
  );
};

test({firstKey: '123'}, ['firstKey']);
</code>```

答:
That's because you are passing an array as second parameter of test, then you try to extract a whitelist property from this array, which makes no sense.

The console.log('whitelist ', whitelist) shows undefined as expected, because ['firstKey'].whitelist is undefined.

Not sure what you are trying to do here.

Body:
I'm having trouble figuring out why this function throws an error when it reaches the 'includes' method, when console logging whitelist, it shows that it is an array, when i use the includes method, it is throwing an error, cannot read property includes of undefined

const test = (body, ...whitelists) => {
  const bodies = whitelists.map(({ type = null, whitelist }) => {
    console.log('whitelist ', whitelist)

    const whitelistedBody = Object.entries(body).reduce(
      (newBody, [key, value]) => {
        console.log('KEY ', key)
        console.log('whitelist ', whitelists)

        if (whitelist.includes(key)) {
          newBody[key] = value;
        }

        console.log('newBody ', newBody)
        return newBody;
      },
      {}
    );

    return { type, body: whitelistedBody };
  });

  return (
    bodies.find(({ body }) => Object.keys(body).length) || {
      body: {},
      type: null,
    }
  );
};

test({firstKey: '123'}, ['firstKey']);


问:
How to install 'win32gui' with `pip`?
Im testing out someones code and I can't import win32gui its really annoying.
I have tried in cmd pip install win32gui and it comes up with

ModuleNotFoundError: No module named 'win32gui'

I am using pycharm, python 3.8 on windows 10

答:
PyCharm can be configured to work in an isolated python environment.
To be sure to install it for the project environment, follow this document from PyCharm editor.</p>

Title: How to install 'win32gui' with `pip`?


问:
Get choices from a DataBase query in wtforms and flask-sqlalchemy
I'm developing a web app using Flask, SQLAlchemy and WTForms. I would like to get my choices in a SelectField from a query through my DB.

With more details.

```<code>my_query = my_table.query.with_entities(My_Entities).all()
</code>```

Result

[(u'1',), (u'2',), (u'3',)]

My class

```<code>class MyForm(Form):
    My_Var = SelectField(choices=RIGHT_HERE)
</code>```

Is there any way ?

答:
Populate QuerySelectField with values from Database</p>
```<code>from wtforms.ext.sqlalchemy.fields import QuerySelectField

from flask_sqlalchemy import SQLAlchemy
name=QuerySelectField('Name',query_factory=lambda:my_table.query,get_label="username")
</code>```

Body:
I'm developing a web app using Flask, SQLAlchemy and WTForms. I would like to get my choices in a SelectField from a query through my DB.

With more details.

my_query = my_table.query.with_entities(My_Entities).all()

Result

[(u'1',), (u'2',), (u'3',)]

My class

class MyForm(Form):
    My_Var = SelectField(choices=RIGHT_HERE)

Is there any way ?

Body:
Populate QuerySelectField with values from Database

from wtforms.ext.sqlalchemy.fields import QuerySelectField

from flask_sqlalchemy import SQLAlchemy
name=QuerySelectField('Name',query_factory=lambda:my_table.query,get_label="username")


问:
How to set Vuetify Navigation Drawer always on top of all other app components
I'd like to know how I could do this.

With some components it appears to be on top, but then other components, such like a Leaflet (Map) component, they overlaps my SideDrawer so I can't use it properly.

How could I set my navigation drawer to be always on top with a higher z-index than the other components?

答:
open up your root component App.vue

make sure your style tag doesn't have the scoped attribute so CSS can apply globally

add the following CSS

.v-navigation-drawer {
z-index: 999999 !important;
}
```


问:
Run python script with args in javascript with exec
I have inputs such as latitude, longitude and frequency.
I would like to run this command on a JS file :

```<code>exec(`python test.py '{"latitude":${latitude},"longitude":${longitude},"frequency":${frequency}}'`, (error, stdout, stderr) => { .... })
</code>```

But when I run I have the following error :

```<code>error: Command failed: python test.py '{"latitude":48.118097,"longitude":-1.636503,"frequency":2.4}'
Traceback (most recent call last):
  File "test.py", line 16, in <module>
    data=json.loads(sys.argv[1])
  File "C:\Users\****\AppData\Local\Programs\Python\Python38\lib\json\__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "C:\Users\****\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\****\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

</code>```

And my python script begin with

```<code>import sys
import json
data=json.loads(sys.argv[1])

</code>```

Moreover if I just run my python script without args, and write random data directly in the python script, it works. So I think it's a problem of the args written in the exec command.

Can you please help me.

答:
Maybe add double quotes?</p>

```<code>python test.py '\"{"latitude":48.118097,"longitude":-1.636503,"frequency":2.4}\"'
</code>```

Body:
I have inputs such as latitude, longitude and frequency.
I would like to run this command on a JS file :

exec(`python test.py '{"latitude":${latitude},"longitude":${longitude},"frequency":${frequency}}'`, (error, stdout, stderr) => { .... })

But when I run I have the following error :

error: Command failed: python test.py '{"latitude":48.118097,"longitude":-1.636503,"frequency":2.4}'
Traceback (most recent call last):
  File "test.py", line 16, in <module>
    data=json.loads(sys.argv[1])
  File "C:\Users\****\AppData\Local\Programs\Python\Python38\lib\json\__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "C:\Users\****\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\****\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

And my python script begin with

import sys
import json
data=json.loads(sys.argv[1])

Moreover if I just run my python script without args, and write random data directly in the python script, it works. So I think it's a problem of the args written in the exec command.

Can you please help me.

Body:
Maybe add double quotes?

python test.py '\"{"latitude":48.118097,"longitude":-1.636503,"frequency":2.4}\"'


问:
Trying to create a callback function to get ID's of 3 different img elements using pure JavaScript
I'm trying to create a callback function that will retrieve the specific id from 1 of 3 different clicked images. The images correlate to either rock, paper, or scissors. I want to be able to grab the id from the clicked image and use it to compare to the computers choice to determine a winner. I will include a codepen and my code bellow.

Thanks in advance!

https://codepen.io/constequalsexcel/pen/MWwjjKa

```<code>HTML
'''
<!DOCTYPE html>

<html lang="en">
    <head>
        <meta charset="utf-8" />

        <title>Rock Paper Scicssors Game</title>

        <link rel="stylesheet" href="styles.css" />
        <link
            href="https://fonts.googleapis.com/css?family=Roboto&display=swap"
            rel="stylesheet"
        />
    </head>

    <body>
        <header>Rock, Paper, Scissors!</header>
        <h4>Choose your weapon!</h4>
        <div class="images">
            <img src="images/rock.png" id="rock" onclick="userChoiceFunction()" />

            <img src="images/paper.png" id="paper" onclick="userChoiceFunction()" />

            <img
                src="images/scissors.png"
                id="scissors"
                onclick="userChoiceFunction()"
            />
        </div>

        <h4 id="computer-message"></h4>
        <div class="outcome-messages"></div>

        <script src="scripts.js"></script>
    </body>
</html>
'''

CSS
'''
header {
    text-align: center;
    margin-top: 50px;
    font-family: 'Roboto';
    font-size: 30px;
    font-weight: bold;
}

h4 {
    text-align: center;
    margin: 100px 0 60px 0;
    font-family: 'Roboto';
}

.images {
    width: 100%;
    display: inline-block;
    text-align: center;
}

.images > button {
    margin-right: 30px;
    -ms-transition: 0.6s ease-in-out;
    -webkit-transition: 0.6s ease-in-out;
    transition: 0.6s ease-in-out;
}

.images > button:hover {
    margin-right: 30px;
    border: 2px solid green;
    -ms-transform: rotate(360deg); /* IE 9 */
    -webkit-transform: rotate(360deg); /* Chrome, Safari, Opera */
    transform: rotate(360deg);
}

.images img {
    max-width: 100px;
    max-height: 100px;
    display: inline-block;
    margin: 10px 30px 0 30px;
}
'''
JS
'''
// click one of three images (rock, paper, or scissors) on screen
// computer randomly chooses one also (rock, paper or scissors)
// compare user selected and computer selected choices
// determine if user or computer wins
// dispaly result to the browser
// start process over so user can play again..

// get the id of clicked img
// set variable equal to img id
// pass variable to function to compare to computers choice

// generate random numbers for computer choice
// set random number equal to rock, paper, or scissors
// set variable equal to computers choice
let computerChoice = Math.ceil(Math.random() * 3);
if (computerChoice === 1) {
    computerChoice = 'rock';
} else if (computerChoice === 2) {
    computerChoice = 'paper';
} else {
    computerChoice = 'scissors';
}
//console.log(computerChoice);

/*
if (computerChoice === userChoice) {
    document.getElementById('computer-message').innerHTML = 'It was a tie!';
} else if (computerChoice === 'paper' && userChoice === 'scissors') {
    document.getElementById('computer-message').innerHTML =
        'The computer chose paper! You win!';
} else if (computerChoice === 'paper' && userChoice === 'rock') {
    document.getElementById('computer-message').innerHTML =
        'Computer chose paper! You lose!';
} else if (computerChoice === 'rock' && userChoice === 'paper') {
    document.getElementById('computer-message').innerHTML =
        'Computer chose rock! You win!';
}
*/
'''
</code>```

答:
You could do something like this...

```<code>let imgChoice = document.querySelectorAll('.images img');
imgChoice.forEach(function(el, index) {
  el.addEventListener('click', compareChoice(el.id));
});
</code>```

So grab the image elements, loop over them and add a click event for all of them that when they click on it, it runs a function. I called mine "compareChoice". This function can then grab what the computer choice is and compare it to the id passed to it.

Body:
I'm trying to create a callback function that will retrieve the specific id from 1 of 3 different clicked images. The images correlate to either rock, paper, or scissors. I want to be able to grab the id from the clicked image and use it to compare to the computers choice to determine a winner. I will include a codepen and my code bellow.

Thanks in advance!

https://codepen.io/constequalsexcel/pen/MWwjjKa

HTML
'''
<!DOCTYPE html>

        <meta charset="utf-8" />

        <title>Rock Paper Scicssors Game</title>

        <link rel="stylesheet" href="styles.css" />
        <link
            href="https://fonts.googleapis.com/css?family=Roboto&display=swap"
            rel="stylesheet"
        />

        Rock, Paper, Scissors!

Choose your weapon!

'''

CSS
'''
header {
    text-align: center;
    margin-top: 50px;
    font-family: 'Roboto';
    font-size: 30px;
    font-weight: bold;
}

h4 {
    text-align: center;
    margin: 100px 0 60px 0;
    font-family: 'Roboto';
}

.images {
    width: 100%;
    display: inline-block;
    text-align: center;
}

.images > button {
    margin-right: 30px;
    -ms-transition: 0.6s ease-in-out;
    -webkit-transition: 0.6s ease-in-out;
    transition: 0.6s ease-in-out;
}

.images > button:hover {
    margin-right: 30px;
    border: 2px solid green;
    -ms-transform: rotate(360deg); /* IE 9 */
    -webkit-transform: rotate(360deg); /* Chrome, Safari, Opera */
    transform: rotate(360deg);
}

.images img {
    max-width: 100px;
    max-height: 100px;
    display: inline-block;
    margin: 10px 30px 0 30px;
}
'''
JS
'''
// click one of three images (rock, paper, or scissors) on screen
// computer randomly chooses one also (rock, paper or scissors)
// compare user selected and computer selected choices
// determine if user or computer wins
// dispaly result to the browser
// start process over so user can play again..

// get the id of clicked img
// set variable equal to img id
// pass variable to function to compare to computers choice

// generate random numbers for computer choice
// set random number equal to rock, paper, or scissors
// set variable equal to computers choice
let computerChoice = Math.ceil(Math.random() * 3);
if (computerChoice === 1) {
    computerChoice = 'rock';
} else if (computerChoice === 2) {
    computerChoice = 'paper';
} else {
    computerChoice = 'scissors';
}
//console.log(computerChoice);

/*
if (computerChoice === userChoice) {
    document.getElementById('computer-message').innerHTML = 'It was a tie!';
} else if (computerChoice === 'paper' && userChoice === 'scissors') {
    document.getElementById('computer-message').innerHTML =
        'The computer chose paper! You win!';
} else if (computerChoice === 'paper' && userChoice === 'rock') {
    document.getElementById('computer-message').innerHTML =
        'Computer chose paper! You lose!';
} else if (computerChoice === 'rock' && userChoice === 'paper') {
    document.getElementById('computer-message').innerHTML =
        'Computer chose rock! You win!';
}
*/
'''

Body:
You could do something like this...

let imgChoice = document.querySelectorAll('.images img');
imgChoice.forEach(function(el, index) {
  el.addEventListener('click', compareChoice(el.id));
});

So grab the image elements, loop over them and add a click event for all of them that when they click on it, it runs a function. I called mine "compareChoice". This function can then grab what the computer choice is and compare it to the id passed to it.


问:
Gensim and Annoy for finding similar sentences
I have a large number of sentences in a database and I want to find the most similar of those sentences to a single sentence that the user types in.

It looks like I may be able to do this with annoy and gensim, but all the examples I can see are using word2vec which I believe is good for finding single similar words, but not for sentences.  However, I note that the AnnoyIndexer() can take a word2vec OR a doc2vec model.

Am I correct that the process is the same, but swapping the word2vec model with a doc2vec model and using a doc2vec vector of the search sentence?

Do I need to use pre-trained word embeddings in any way, or do I literally just train the doc2vec model with the corpus of sentences that I have in my database?

Thank you!

答:
Doc2Vec does not require any pre-trained word-vectors: you just train it on your corpus, and it learns what it needs.

For comparing sentences, you could also try calculating a per-sentence vector that's the sum or average of all its words' word-vectors.

If the sentences aren't too long, you could also consider "Word Mover's Distance", available from gensim word-vectors as the .wmdistance(word_list, word_list). (It's far more expensive to calculate these pairwise distances, than the simple similarity between 2 fixed-length vectors – but it may capture human perception of similarity better.)

Note that ANNOY is just an indexing optimization, which gains speed at the cost of precision. It's only necessary if the brute-force way of finding the .most_similar() – calculating all similarities then sorting to find the top-N – is too slow. It will use more memory for indexing, and accept a risk fo sometimes not finding the exact true nearest-neighbors, for speed.


问:
JQuery - Storing ajax response into global variable
Im still somewhat of a newbie on jQuery and the ajax scene, but I have an $.ajax request performing a GET to retrieve some XML files (~6KB or less), however for the duration the user spends on that page that XML content should not / will not change (this design I cannot change, I also don't have access to change the XML file as I am reading it from somewhere else). Therefore I have a global variable that I store the response data into, and any subsequent look ups on the data are done on this variable so multiple requests don't need to be made.

Given the fact that the XML file can increase, Im not sure this is the best practice, and also coming from a java background my thoughts on global public variables are generally a no-no.

So the question I have is whether there might be a better way to do this, and a question on whether this causes any memory issues if the file expands out to some ridiculous file size?

I figure the data could be passed into a some getter/setter type functions inside the xml object, which would solve my global public variable problems, but still raises the question on whether I should store the response inside the object itself.

For example, what I currently do is:

// top of code
var xml;
// get the file
$.ajax({
  type: "GET",
  url: "test.xml",
  dataType: "xml",
  success : function(data) {
    xml = data;
  }
});
// at a later stage do something with the 'xml' object
var foo = $(xml).find('something').attr('somethingElse');
```

答:
your problem might not be related to any local or global scope for that matter just the server delay between the "success" function executing and the time you are trying to take out data from your variable.

chances are you are trying to print the contents of the variable before the ajax "success" function fires.

OwnerDisplayName: Dom


问:
What is the correct type hinting for COM Objects in python?
I am using COM Objects within python to expose programmable interfaces to 3rd party software. This is achieved through using Dispatch from win32com.client. My project has also been making use of type hinting from python.3.7, however I am unsure as to how you would define the type of these COM objects for the purposes of type hinting. The question relates to all the COM objects I have, with a real example being a Microsoft Direct X Recordset: Dispatch("ADODB.Recordset").

```<code>from win32com.client import Dispatch
def create_my_com_object_instance(input_arg: Dict[str, Union[str, float, int]]) -> <type_of_com_object_here>:
    my_instance = Dispatch("ADODB.Recordset")
    # Set attributes/call methods of this instance here ...
    return my_instance
</code>```

In the above code snippet I would replace 'type_of_com_object_here' with the COM object type.

My first thought was just to call type() on the instance and use the returned type:

```<code>x = Dispatch("ADODB.Recordset")
x
Out[1]: <win32com.gen_py.Microsoft ActiveX Data Objects 6.1 Library._Recordset instance at 0x83848456>
type(x)
Out[2]: win32com.gen_py.B691E011-1797-432E-907A-4D8C69339129x0x6x1._Recordset._Recordset
x.__class__
Out[3]: win32com.gen_py.B691E011-1797-432E-907A-4D8C69339129x0x6x1._Recordset._Recordset
</code>```

This does not return a suitable type for defining the COM Object. I believe that I could create an abstract base class using TypeVar('T') and Generic[], however I am unsure if there is a more pythonic/better alternative available.

Thanks

答:
I'm afraid you're unfortunately running into one of the limits of typing in Python. In particular:

As far as I'm aware, there are no type stubs for the pywin32 library in either Typeshed or as a 3rd party module. This means there is no existing canonical reference for what that type ought to be.

Dynamically dispatching to arbitrary objects is going to strain the limits of what's possible to express using just type hints (assuming that Dispatch really does dispatch to arbitrary objects).

So, I recommend one of the following three approaches:

If you want to assume absolutely nothing about the returned type and treat it as just an opaque blob, have the return type be just object. This is the most restrictive and type safe option, since a PEP 484 compliant type checker will let the caller only use methods that are present in all Python objects, such as __str__ or __eq__.

If you want to assume absolutely nothing about the returned type but also impose no restrictions on its use, have the return type be Any, the dynamic type. This is the most permissive and unsafe operation: you are saying the output is some dynamic type and telling the type checker to let the caller use the returned object however they please.

This is the "default option", so to speak: since there are no type stubs available for pywin32, the type checker will fall back to assuming Dispatch(...) has a return type of Any.

If you know for certain the returned type will always have some specific methods or attributes available, you have the return type be a Protocol. Protocols basically let you do structural subtyping: any class that happens to implement the protocol methods and attributes is considered a subtype of that protocol, even if the class isn't inheriting from the protocol in any way. Protocols are basically like Go's interfaces, if you're familiar with Go.

You may want to create a dedicated create_adodb_recordset(...) function here, so you can more fully customize the return type.

Body:
I am using COM Objects within python to expose programmable interfaces to 3rd party software. This is achieved through using Dispatch from win32com.client. My project has also been making use of type hinting from python.3.7, however I am unsure as to how you would define the type of these COM objects for the purposes of type hinting. The question relates to all the COM objects I have, with a real example being a Microsoft Direct X Recordset: Dispatch("ADODB.Recordset").

from win32com.client import Dispatch
def create_my_com_object_instance(input_arg: Dict[str, Union[str, float, int]]) -> <type_of_com_object_here>:
    my_instance = Dispatch("ADODB.Recordset")
    # Set attributes/call methods of this instance here ...
    return my_instance

In the above code snippet I would replace 'type_of_com_object_here' with the COM object type.

My first thought was just to call type() on the instance and use the returned type:

x = Dispatch("ADODB.Recordset")
x
Out[1]: <win32com.gen_py.Microsoft ActiveX Data Objects 6.1 Library._Recordset instance at 0x83848456>
type(x)
Out[2]: win32com.gen_py.B691E011-1797-432E-907A-4D8C69339129x0x6x1._Recordset._Recordset
x.__class__
Out[3]: win32com.gen_py.B691E011-1797-432E-907A-4D8C69339129x0x6x1._Recordset._Recordset

This does not return a suitable type for defining the COM Object. I believe that I could create an abstract base class using TypeVar('T') and Generic[], however I am unsure if there is a more pythonic/better alternative available.

Thanks


问:
Compare local files to s3 bucket and determine what files (fullpath) are not in the bucket
I have a local file share that was copied to a snowball and imported to an s3 bucket (~70TB; many small files)
Since the import, users have added content to the local share.
Im trying to get a list of all the files that are not present then transfer them to the bucket.

I've tried a sync and an s3cmd sync but it has to iterate through each item, my thoughts are if I export a list then run a copy only items that need to move it would save a lot of time.

Looking for some help on the simplest and fastest way to approach this

答:
Sure you can go this way if you assume your files weren't changed, i.e. if file path is uniquely identifies the content. Additionally you could check if the size remained the same.

To get list of objects in an s3 bucket use list-objects:

```<code>aws s3api list-objects --bucket text-content --query 'Contents[].{Key: Key, Size: Size}')
</code>```

Body:
Sure you can go this way if you assume your files weren't changed, i.e. if file path is uniquely identifies the content. Additionally you could check if the size remained the same.

To get list of objects in an s3 bucket use list-objects:

aws s3api list-objects --bucket text-content --query 'Contents[].{Key: Key, Size: Size}')


问:
PrimeNG P-dialog position is not working with Angular
I am trying this but no luck, using angular 8 and Primeng 9.0.0-rc.4. Thank you so much.

```<code><p-dialog position="right" header="Change Password"  (visible)]="display">
    Content
</p-dialog>
</code>```

https://www.primefaces.org/primeng/#/dialog

答:
I'm having the same issue.  position="left" doesn't work.  If I do [position] I get "ERROR in Can't bind to 'position' since it isn't a known property of 'p-dialog'".  Even looking in the NPM package I can't find "position", just positionOverlay, positionLeft and positionTop.

FYI - If you try to position the dialog yourself, positionLeft and positionTop don't work unless you have both positionLeft AND positionTop. (https://forum.primefaces.org/viewtopic.php?t=51000),

Body:
I am trying this but no luck, using angular 8 and Primeng 9.0.0-rc.4. Thank you so much.

    Content

https://www.primefaces.org/primeng/#/dialog


问:
Android fragment navigation without button click
I am using a "Drawer Navigation" project using fragments and so far this method works:

```<code>button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Navigation.findNavController(view).navigate(R.id.nav_gallery);
        }
    });
</code>```

But I want to use the navigation method inside a fragment class calling a function like this:

```<code>boolean b;
public void fragmentNavigation() {
    if (b) {
        Navigation.findNavController(getView()).navigate(R.id.nav_gallery);
    }
}
</code>```

I am a newbie using the navigation architecture and I still don't know if I need to declare some type of action listener for that function or how to make it work.

答:
You can do that, but be careful of :

using getView() is Nullable; so you must make sure that your fragment has already created the view.

You can solve this by a couple of ways

First: Overriding onViewCreated() which has a nonNull view argument

```<code>@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    fragmentNavigation(view);

}
boolean b;
public void fragmentNavigation(View view) {
    if (b) {
        Navigation.findNavController(view).navigate(R.id.nav_gallery);
    }
}
</code>```

Second: Create a View field in the fragment class, and set it within onCreateView()

```<code>View view;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                         @Nullable Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.main_fragment, container, false);
    return view;
}
</code>```

then always call fragmentNavigation(view); on that view field.

Your fragment is hosted by the NavHostFragment of the Navigation Graph; so that you can avoid potential IllegalStateException

Body:
I am using a "Drawer Navigation" project using fragments and so far this method works:

button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Navigation.findNavController(view).navigate(R.id.nav_gallery);
        }
    });

But I want to use the navigation method inside a fragment class calling a function like this:

boolean b;
public void fragmentNavigation() {
    if (b) {
        Navigation.findNavController(getView()).navigate(R.id.nav_gallery);
    }
}

I am a newbie using the navigation architecture and I still don't know if I need to declare some type of action listener for that function or how to make it work.

Body:
You can do that, but be careful of :

using getView() is Nullable; so you must make sure that your fragment has already created the view.

You can solve this by a couple of ways

First: Overriding onViewCreated() which has a nonNull view argument

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    fragmentNavigation(view);

}
boolean b;
public void fragmentNavigation(View view) {
    if (b) {
        Navigation.findNavController(view).navigate(R.id.nav_gallery);
    }
}

Second: Create a View field in the fragment class, and set it within onCreateView()

View view;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                         @Nullable Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.main_fragment, container, false);
    return view;
}

then always call fragmentNavigation(view); on that view field.

Your fragment is hosted by the NavHostFragment of the Navigation Graph; so that you can avoid potential IllegalStateException


问:
The modSummary function of processR package resturns NULL
I'm trying to learn the Keon-Woong Moon's processR package which you can install by simply:

```<code>install.packages("processR")
</code>```

following some examples from the documentation, I have scraped an example together:

labels=list(X="frame",W="skeptic",Y="donate")
moderator=list(name='skeptic',site=list(c("c")))
model=tripleEquation(labels=labels,moderator=moderator,data=disaster,mode=1)
drawConcept(labels=labels, moderator=moderator, drawbox=TRUE)
semfit=sem(model=model,data=disaster,se="boot",bootstrap=200)
modSummary(semfit)
```
```

```

However the modSummary functions returns NULL. I would appreciate if you could help me understand where is my mistake and how I can solve it.

答:
In your call to model the parameter you want to define is called rangemode not mode.  The following will generate a model, and modSummary will no longer be NULL:

```<code>library(processR)
library(lavaan)

labels = list(X = "frame", W = "skeptic", Y = "donate")
moderator = list(name = 'skeptic', site = list(c("c")))
model = tripleEquation(
  labels = labels,
  moderator = moderator,
  data = disaster,
  rangemode = 1
)
drawConcept(labels = labels,
            moderator = moderator,
            drawbox = TRUE)
semfit = lavaan::sem(
  model = model,
  data = disaster,
  se = "boot",
  bootstrap = 200
)
modSummary(semfit)

Inference for the Moderation Effects
====================================================
                      Moderation Effect
                   c1+c3*W = 0.679-0.171*W
             ---------------------------------------
 skeptic(W)   estimate    95% Bootstrap CI     p
----------------------------------------------------
      1.350       0.449  -0.026 to  0.941    .065
      3.378       0.103  -0.171 to  0.491    .545
      5.406      -0.244  -0.694 to  0.373    .333
====================================================
                             boot.ci.type:bca.simple
</code>```

Body:
I'm trying to learn the Keon-Woong Moon's processR package which you can install by simply:

install.packages("processR")

following some examples from the documentation, I have scraped an example together:

labels=list(X="frame",W="skeptic",Y="donate")
moderator=list(name='skeptic',site=list(c("c")))
model=tripleEquation(labels=labels,moderator=moderator,data=disaster,mode=1)
drawConcept(labels=labels, moderator=moderator, drawbox=TRUE)
semfit=sem(model=model,data=disaster,se="boot",bootstrap=200)
modSummary(semfit)

However the modSummary functions returns NULL. I would appreciate if you could help me understand where is my mistake and how I can solve it.

Body:
In your call to model the parameter you want to define is called rangemode not mode.  The following will generate a model, and modSummary will no longer be NULL:

library(processR)
library(lavaan)

labels = list(X = "frame", W = "skeptic", Y = "donate")
moderator = list(name = 'skeptic', site = list(c("c")))
model = tripleEquation(
  labels = labels,
  moderator = moderator,
  data = disaster,
  rangemode = 1
)
drawConcept(labels = labels,
            moderator = moderator,
            drawbox = TRUE)
semfit = lavaan::sem(
  model = model,
  data = disaster,
  se = "boot",
  bootstrap = 200
)
modSummary(semfit)

Inference for the Moderation Effects
====================================================
                      Moderation Effect
                   c1+c3*W = 0.679-0.171*W
             ---------------------------------------
 skeptic(W)   estimate    95% Bootstrap CI     p
----------------------------------------------------
      1.350       0.449  -0.026 to  0.941    .065
      3.378       0.103  -0.171 to  0.491    .545
      5.406      -0.244  -0.694 to  0.373    .333
====================================================
                             boot.ci.type:bca.simple


问:
Predicate<T> method equals()
I'm using the interface Predicate<T> from com.google.common.base (Google Guava)

But I don't know how to have the equals() method works...

Why do I get false when I type something like this :

```<code>    Predicate<Object> PredicateD = new Predicate<Object>(){
          @Override public boolean apply(Object number) {
                return ((number instanceof Double) && (Math.floor((Double)number) == (Double)number));
            }
    };

    Predicate<Object> PredicateM = new Predicate<Object>(){
          @Override public boolean apply(Object number) {
                return ((number instanceof Double) && (Math.floor((Double)number) == (Double)number));
            }
    };

    System.out.println(PredicateD.equals(PredicateM));
</code>```

Thanks in advance for your Help,

答: I don't think it's necessary to override equals(). Predicate is functional class. The Object.equals(){return (this == obj);} is reasonable.

Title: Predicate<T> method equals()

Body:
I'm using the interface Predicate<T> from com.google.common.base (Google Guava)

But I don't know how to have the equals() method works...

Why do I get false when I type something like this :

    Predicate<Object> PredicateD = new Predicate<Object>(){
          @Override public boolean apply(Object number) {
                return ((number instanceof Double) && (Math.floor((Double)number) == (Double)number));
            }
    };

    Predicate<Object> PredicateM = new Predicate<Object>(){
          @Override public boolean apply(Object number) {
                return ((number instanceof Double) && (Math.floor((Double)number) == (Double)number));
            }
    };

    System.out.println(PredicateD.equals(PredicateM));

Thanks in advance for your Help,


问:
Node.js, require.main === module
In Node.JS document, I found a sentence said

When a file is run directly from Node.js, require.main is set to its
  module. That means that it is possible to determine whether a file has been run directly by testing require.main === module.'

I want to ask what is the main here, I can not find definition of this main in source code, can anyone help, thanks!

答:
When running ECMAScript Modules with Node.js, require.main is not available.  As of Node 13.9.0, there is not a succinct way to determine whether a module was run directly or imported by another module.  It is possible that an import.meta.main value will allow for such a check in the future (comment on the modules issue if you think this makes sense).

As a workaround, it is possible to check if the current ES module was run directly by comparing the import.meta.url value to process.argv[1].  For example:

import { fileURLToPath } from 'url';
import process from 'process';

if (process.argv[1] === fileURLToPath(import.meta.url)) {
  // The script was run directly.
}
```

<p>This does not handle the case where the script is called without the <code>.js</code> extension (e.g. <code>node script</code> instead of <code>node script.js</code>).  To handle this case, any extension could be trimmed from both <code>import.meta.url</code> and <code>process.argv[1]</code>.</p>

<p>The <code>es-main</code> package (caveat: I am the author) provides a way to check if an ES module is run directly, accounting for the different ways it can be run (with or without an extension).</p>

<pre class="lang-js prettyprint-override"><code>import esMain from 'es-main';

if (esMain(import.meta)) {
  // The script was run directly.
}
</code>```

Title: Node.js, require.main === module

Body:
When running ECMAScript Modules with Node.js, require.main is not available.  As of Node 13.9.0, there is not a succinct way to determine whether a module was run directly or imported by another module.  It is possible that an import.meta.main value will allow for such a check in the future (comment on the modules issue if you think this makes sense).

As a workaround, it is possible to check if the current ES module was run directly by comparing the import.meta.url value to process.argv[1].  For example:

import { fileURLToPath } from 'url';
import process from 'process';

if (process.argv[1] === fileURLToPath(import.meta.url)) {
  // The script was run directly.
}

This does not handle the case where the script is called without the .js extension (e.g. node script instead of node script.js).  To handle this case, any extension could be trimmed from both import.meta.url and process.argv[1].

The es-main package (caveat: I am the author) provides a way to check if an ES module is run directly, accounting for the different ways it can be run (with or without an extension).

import esMain from 'es-main';

if (esMain(import.meta)) {
  // The script was run directly.
}


问:
Python UpSert - not enough arguments
This has been a bit frustrating today. I'm sure its something simple that I'm overlooking. See code below (simplified for example sake):

def dbUpsert(sqlQuery, sqlValues):
    # Connect to the database
    connection = pymysql.connect(host='localhost',
                                user='db_user',
                                password='###',
                                db='garden',
                                charset='utf8mb4',
                                cursorclass=pymysql.cursors.DictCursor)
    try:
        with connection.cursor() as cursor:
            # Create a new record
            cursor.execute(sqlQuery, sqlValues)
        # Commit the changes
        connection.commit()
    finally:
        connection.close()

sqlValues = real_plants, datetime.datetime.today().strftime('%Y-%m-%d'),  10
print (sqlValues)
##### Output: ('roses', '2020-02-19', 10)

sqlQuery = """
    INSERT INTO summ_plants_day
        (
            real_plants, d_date, acc_plants
        )
    VALUES (%s, %s, %s)
    ON DUPLICATE KEY UPDATE
        real_plants = %s,
        d_date = %s,
        acc_plants = %s
    """
dbUpsert(sqlQuery, sqlValues)
```

<p>In my database, I have 4 columns. One is an auto-increment primary key, <code>real_plants</code> and <code>d_date</code> together form an index, and <code>acc_plants</code> is the value I want to update / insert.</p>

<p>If an entry for <code>roses</code> exists in table <code>summ_plants_day</code> for the <code>d_date</code> I want to <code>UPDATE</code>, otherwise I want to <code>INSERT</code>.</p>

<p>Here is the error:</p>

<pre class="lang-py prettyprint-override"><code>Traceback (most recent call last):
 in dbUpsert
    cursor.execute(sqlQuery, sqlValues)
 in execute
    query = self.mogrify(query, args)
 in mogrify
    query = query % self._escape_args(args, conn)
TypeError: not enough arguments for format string
</code>```

Also, I used %s based on W3Schools examples. I saw conflicting information online while Googling my issue, is this proper/modern format to protect against SQL injection?

答:
I would suggest using the VALUES() syntax in the ON DUPLICATE KEY UPDATE clause. This avoids the need to pass the same variable twice, so it should work just fine with your existing code:

```<code>INSERT INTO summ_plants_day (real_plants, d_date, acc_plants)
VALUES (%s, %s, %s)
ON DUPLICATE KEY UPDATE
    real_plants = VALUES(real_plants),
    d_date = VALUES(d_date),
    acc_plants = VALUES(acc_plants)
</code>```

Title: Python UpSert - not enough arguments

Body:
This has been a bit frustrating today. I'm sure its something simple that I'm overlooking. See code below (simplified for example sake):

def dbUpsert(sqlQuery, sqlValues):
    # Connect to the database
    connection = pymysql.connect(host='localhost',
                                user='db_user',
                                password='###',
                                db='garden',
                                charset='utf8mb4',
                                cursorclass=pymysql.cursors.DictCursor)
    try:
        with connection.cursor() as cursor:
            # Create a new record
            cursor.execute(sqlQuery, sqlValues)
        # Commit the changes
        connection.commit()
    finally:
        connection.close()

sqlValues = real_plants, datetime.datetime.today().strftime('%Y-%m-%d'),  10
print (sqlValues)
##### Output: ('roses', '2020-02-19', 10)

sqlQuery = """
    INSERT INTO summ_plants_day
        (
            real_plants, d_date, acc_plants
        )
    VALUES (%s, %s, %s)
    ON DUPLICATE KEY UPDATE
        real_plants = %s,
        d_date = %s,
        acc_plants = %s
    """
dbUpsert(sqlQuery, sqlValues)

In my database, I have 4 columns. One is an auto-increment primary key, real_plants and d_date together form an index, and acc_plants is the value I want to update / insert.

If an entry for roses exists in table summ_plants_day for the d_date I want to UPDATE, otherwise I want to INSERT.

Here is the error:

Traceback (most recent call last):
 in dbUpsert
    cursor.execute(sqlQuery, sqlValues)
 in execute
    query = self.mogrify(query, args)
 in mogrify
    query = query % self._escape_args(args, conn)
TypeError: not enough arguments for format string

Also, I used %s based on W3Schools examples. I saw conflicting information online while Googling my issue, is this proper/modern format to protect against SQL injection?

Body:
I would suggest using the VALUES() syntax in the ON DUPLICATE KEY UPDATE clause. This avoids the need to pass the same variable twice, so it should work just fine with your existing code:

INSERT INTO summ_plants_day (real_plants, d_date, acc_plants)
VALUES (%s, %s, %s)
ON DUPLICATE KEY UPDATE
    real_plants = VALUES(real_plants),
    d_date = VALUES(d_date),
    acc_plants = VALUES(acc_plants)


问:
C program terminates without any error after execution of scanf() and taking the input from user
Program terminates automatically after the execution of scanf() and taking input from the user.

This is a program to print perfect number in a given range

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

void main() {
    int i, n, j, sum;
    printf("enter the number \n ");
    scanf("%d", &n);
    for (i = 1; i <= n; i++) {
        sum = 0;
        for (j = 1; j <= i; j++) {
            if (n % j == 0) {
                sum += j;
            }
        }
        if (sum == n) {
            printf("%d", i);
        }
    }
}
</code>```

execution image

答:
There are multiple typos in your code:

you must stop the inner loop before j, not i <= j

you must compute i % j, not n % j

you must test if (sum == i), not if (sum == n)

you should print a newline after the number to separate the perfect numbers.

to search in a range, you must prompt for its boundaries

Here is a corrected version:

#include <stdio.h>

int main() {
    int i, start, end, j, sum;

    printf("enter the range: ");
    if (scanf("%d%d", &start, &end) != 2)
        return 1;
    for (i = start; i <= end; i++) {
        sum = 0;
        for (j = 1; j < i; j++) {
            if (i % j == 0) {
                sum += j;
            }
        }
        if (sum == i) {
            printf("%d\n", i);
        }
    }
    // uncomment this if running from an IDE
    //scanf("%*s");
    return 0;
}
```

If your compiler still terminates after the scanf(), chances you are running your program from within an IDE that does not leave the terminal window open after execution. You can add an extra scanf("%*s"); before the return 0; statement at the end of main() to make the program wait for more input.

Body:
Program terminates automatically after the execution of scanf() and taking input from the user.

This is a program to print perfect number in a given range

#include <stdio.h>

void main() {
    int i, n, j, sum;
    printf("enter the number \n ");
    scanf("%d", &n);
    for (i = 1; i <= n; i++) {
        sum = 0;
        for (j = 1; j <= i; j++) {
            if (n % j == 0) {
                sum += j;
            }
        }
        if (sum == n) {
            printf("%d", i);
        }
    }
}

execution image

Body:
There are multiple typos in your code:

you must stop the inner loop before j, not i <= j

you must compute i % j, not n % j

you must test if (sum == i), not if (sum == n)

you should print a newline after the number to separate the perfect numbers.

to search in a range, you must prompt for its boundaries

Here is a corrected version:

#include <stdio.h>

int main() {
    int i, start, end, j, sum;

    printf("enter the range: ");
    if (scanf("%d%d", &start, &end) != 2)
        return 1;
    for (i = start; i <= end; i++) {
        sum = 0;
        for (j = 1; j < i; j++) {
            if (i % j == 0) {
                sum += j;
            }
        }
        if (sum == i) {
            printf("%d\n", i);
        }
    }
    // uncomment this if running from an IDE
    //scanf("%*s");
    return 0;
}

If your compiler still terminates after the scanf(), chances you are running your program from within an IDE that does not leave the terminal window open after execution. You can add an extra scanf("%*s"); before the return 0; statement at the end of main() to make the program wait for more input.


问:
Is there a way to intercept setters and getters in C#?
In both Ruby and PHP (and I guess other languages as well) there are some utility methods that are called whenever a property is set. ( *instance_variable_set* for Ruby, *__set* for PHP).

So, let's say I have a C# class like this:

```<code>public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}
</code>```

Now, let's say that if any property setter from the Person class is called, I want to call another method first, and then continue with the default behaviour of the setter, and the same applies for the property setters.

Is this possible?

Edit:
I want to do this without defining a backing field.

答:
Yes, of course...

In your example you are using automatic properties, without a backing field.... You just need to create a backing field for your property, and then you can do what you want in the setter and getter.

example:

```<code>private string firstName;

public string FirstName
{
 get { return firstName; }

 set { doMethod(); firstName = value;}
}
</code>```

Body:
In both Ruby and PHP (and I guess other languages as well) there are some utility methods that are called whenever a property is set. ( *instance_variable_set* for Ruby, *__set* for PHP).

So, let's say I have a C# class like this:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Now, let's say that if any property setter from the Person class is called, I want to call another method first, and then continue with the default behaviour of the setter, and the same applies for the property setters.

Is this possible?

Edit:
I want to do this without defining a backing field.

Body:
Yes, of course...

In your example you are using automatic properties, without a backing field.... You just need to create a backing field for your property, and then you can do what you want in the setter and getter.

example:

private string firstName;

public string FirstName
{
 get { return firstName; }

 set { doMethod(); firstName = value;}
}


问:
Why does this function throw an error when using the includes method?
I'm having trouble figuring out why this function throws an error when it reaches the 'includes' method, when console logging whitelist, it shows that it is an array, when i use the includes method, it is throwing an error, cannot read property includes of undefined

```<code>const test = (body, ...whitelists) => {
  const bodies = whitelists.map(({ type = null, whitelist }) => {
    console.log('whitelist ', whitelist)

    const whitelistedBody = Object.entries(body).reduce(
      (newBody, [key, value]) => {
        console.log('KEY ', key)
        console.log('whitelist ', whitelists)

        if (whitelist.includes(key)) {
          newBody[key] = value;
        }

        console.log('newBody ', newBody)
        return newBody;
      },
      {}
    );

    return { type, body: whitelistedBody };
  });

  return (
    bodies.find(({ body }) => Object.keys(body).length) || {
      body: {},
      type: null,
    }
  );
};

test({firstKey: '123'}, ['firstKey']);
</code>```

答:
1) set default = []

```<code>  const bodies = whitelists.map(({ type = null, whitelist = [] }) => {
</code>```

or

2) replaced whitelist to whitelists

```<code>if (whitelists.includes(key)) {
</code>```

Body:
I'm having trouble figuring out why this function throws an error when it reaches the 'includes' method, when console logging whitelist, it shows that it is an array, when i use the includes method, it is throwing an error, cannot read property includes of undefined

const test = (body, ...whitelists) => {
  const bodies = whitelists.map(({ type = null, whitelist }) => {
    console.log('whitelist ', whitelist)

    const whitelistedBody = Object.entries(body).reduce(
      (newBody, [key, value]) => {
        console.log('KEY ', key)
        console.log('whitelist ', whitelists)

        if (whitelist.includes(key)) {
          newBody[key] = value;
        }

        console.log('newBody ', newBody)
        return newBody;
      },
      {}
    );

    return { type, body: whitelistedBody };
  });

  return (
    bodies.find(({ body }) => Object.keys(body).length) || {
      body: {},
      type: null,
    }
  );
};

test({firstKey: '123'}, ['firstKey']);

Body:
1) set default = []

  const bodies = whitelists.map(({ type = null, whitelist = [] }) => {

or

2) replaced whitelist to whitelists

if (whitelists.includes(key)) {


问:
How would i leave out the name jones but display people with the same deptno
```<code>SQL> select empno, ename, deptno
  2  from empcopy
  3  where deptno =
  4      (select deptno
  5       from empcopy
  6       where ename like 'JONES');

 EMPNO ENAME          DEPTNO
------ ---------- ----------
  7369 SMITH              20
  7566 JONES              20
  7788 SCOTT              20
  7876 ADAMS              20
  7902 FORD               20
</code>```

答:
One other option uses self-join including inequality for the values of ename column :

```<code>select e1.empno, e1.ename, e1.deptno
  from employees e1
  join employees e2
    on e1.deptno = e2.deptno
   and e2.ename = 'JONES'
   and e1.ename != e2.ename
</code>```

Demo

Body:
One other option uses self-join including inequality for the values of ename column :

select e1.empno, e1.ename, e1.deptno
  from employees e1
  join employees e2
    on e1.deptno = e2.deptno
   and e2.ename = 'JONES'
   and e1.ename != e2.ename

Demo


问:
Session vs URI multi language identifier
I am working on a multilingual website (php/mysql) and my question is what would be the best solution for language identification - sessions/cookies or URI identification.  I mean in terms of SEO, what would be more accurate.

Thanks

答: URL. You can use something like a '/en/' prefix to all paths. Obviously you'd use mod_rewrite or appropriate framework routing config.</p>


问:
Webpack 4 ts-loader and less-loader not working on certain pc's
I migrated from webpack 1.x to 4.30.
node version : 10.15.3
typescript version : 3.4.5
npm version : 6.9.0

This setup works on 3 (windows) pc's but not on one particular machine, although they all use the same versions of node, webpack, npm, other npm packages.

On the not working machine it is as if Webpack does not use the less-loader and ts-loader defined in the webpack.config.ts..  and gives for example the following errors:

*.less files beginning with id selector

```<code>Unexpected character '#' (1:1)
You may need an appropriate loader to handle this file type
</code>```

*.less files beginning with @import

```<code>Module parse failed: Unexpected character '@' You may need an appropriate loader to handle this file type
</code>```

*.ts file (angular component) containing @Component

```<code>Unexpected character '@' (11:0)
You may need an appropriate loader to handle this file type
</code>```

I already tried reinstalling node.js, clear npm cache, clear node_modules folder and  new npm install, reboot pc several times..
On another pc where we had the same problem but it was "magically"  solved after a reboot..

webpack.config loaders/rules section

```<code>    rules: [
      {
        test: /\.ts$/,
        include: [resolve(__dirname, "Assets")],
        use: [
          "ng-annotate-loader",
          "ts-loader",
          "angular-router-loader"
        ]
      },
      {
        test: /\.less$/,
        include: [resolve(__dirname, "Assets/StyleSheets"), resolve(__dirname, "Assets/NgComponentsNew"), resolve(__dirname, "Assets/WpBundles")],
        use: [
          MiniCssExtractPlugin.loader,
          "css-loader",
          {
            loader: "postcss-loader",
            options: {
              plugins: () => [require('autoprefixer')({
                'browsers': ['> 1%', 'last 2 versions']
              })],
            }
          },
          "less-loader"
        ]
      },
      {
        test: /\.html$/,
        include: [resolve(__dirname, "Assets/NgComponents"), resolve(__dirname, "Assets/NgComponentsNew")],
        use: ["html-loader"]
      },
      {
        test: /\.ico$/,
        include: [resolve(__dirname, "Assets/Images")],
        use: {
          loader: "file-loader",
          options: {
            name: "Images/[name].[ext]"
          }
        }
      },
      {
        test: /\.(png|jpg|gif)$/,
        include: [resolve(__dirname, "Assets/Images"), resolve(__dirname, "Assets/Kendo")],
        use: {
          loader: "file-loader",
          options: {
            name: "Images/[name].[ext]",
            publicPath: "/mvc/static/"
          }
        }
      },
      {
        test: /\.(otf|ttf|eot|svg|woff(2)?)(\?[a-z0-9=&.]+)?$/,
        include: [resolve(__dirname, "Assets"), resolve(__dirname, "./node_modules/@fortawesome/fontawesome-free/webfonts"), resolve(__dirname, "./node_modules/bootstrap/fonts")],
        use: {
          loader: "file-loader",
          options: {
            name: "Fonts/[name].[ext]",
            publicPath: "/mvc/static/"
          }
        }
      },
      {
        test: /jquery.+\.js$/,
        use: [{
          loader: 'expose-loader',
          options: 'jQuery'
        }, {
          loader: 'expose-loader',
          options: '$'
        }]
      },
      //avoid "import" warning
      {
        test: /[\/\\]@angular[\/\\].+\.js$/,
        parser: { system: true }
      }
    ]
  },
</code>```

package.json

```<code>{
  "name": "ourproject",
  "version": "1.1.0",
  "description": "Client Npm Packages",
  "main": "",
  "dependencies": {
    "@angular/animations": "7.2.13",
    "@angular/common": "7.2.13",
    "@angular/compiler": "7.2.13",
    "@angular/core": "7.2.13",
    "@angular/forms": "7.2.13",
    "@angular/http": "7.2.13",
    "@angular/platform-browser": "7.2.13",
    "@angular/platform-browser-dynamic": "7.2.13",
    "@angular/router": "7.2.13",
    "@angular/upgrade": "7.2.13",
    "@fortawesome/fontawesome-free": "5.6.3",
    "@progress/kendo-angular-buttons": "4.4.0",
    "@progress/kendo-angular-l10n": "1.4.0",
    "angular": "1.7.8",
    "angular-animate": "1.7.8",
    "angular-filter": "0.5.17",
    "angular-resource": "1.7.8",
    "angular-sanitize": "1.7.8",
    "angular-translate": "2.18.1",
    "automapper-ts": "1.9.0",
    "bootstrap": "3.3.7",
    "bootstrap-less": "3.3.8",
    "core-js": "3.0.0",
    "eruda": "1.5.0",
    "es5-shim": "4.5.10",
    "golden-layout": "1.5.8",
    "jquery": "3.3.1",
    "jquery-ui-bundle": "1.12.1",
    "jquery-validation-unobtrusive": "3.2.10",
    "json3": "3.3.2",
    "linq": "3.1.0",
    "lodash": "4.17.11",
    "moment": "2.22.2",
    "reflect-metadata": "0.1.13",
    "rxjs": "6.5.1",
    "rxjs-compat": "6.5.1",
    "zone.js": "0.8.26",
    "core.js": "0.4.2"
  },
  "devDependencies": {
    "@angular/language-service": "7.2.13",
    "@types/angular": "1.6.48",
    "@types/angular-resource": "1.5.14",
    "@types/angular-sanitize": "1.3.7",
    "@types/bootstrap": "3.3.39",
    "@types/core-js": "2.5.0",
    "@types/jasmine": "3.3.12",
    "@types/jquery.validation": "1.16.4",
    "@types/kendo-ui": "2018.1.2",
    "@types/lodash": "4.14.110",
    "@types/webpack": "4.4.27",
    "@types/webpack-dev-server": "3.1.5",
    "@types/webpack-env": "1.13.9",
    "@types/node": "11.13.7",
    "angular-router-loader": "0.8.5",
    "autoprefixer": "9.5.1",
    "awesome-typescript-loader": "5.2.1",
    "css-loader": "2.1.1",
    "expose-loader": "0.7.5",
    "file-loader": "3.0.1",
    "html-loader": "0.5.5",
    "imports-loader": "0.8.0",
    "jasmine": "3.4.0",
    "jasmine-spec-reporter": "4.2.1",
    "karma": "4.1.0",
    "karma-chrome-launcher": "2.2.0",
    "karma-cli": "2.0.0",
    "karma-coverage": "1.1.2",
    "istanbul-instrumenter-loader": "3.0.1",
    "karma-remap-coverage": "0.1.5",
    "karma-coverage-istanbul-reporter": "2.0.5",
    "karma-jasmine-html-reporter": "1.4.1",
    "karma-jasmine": "2.0.1",
    "karma-phantomjs-launcher": "1.0.4",
    "karma-sourcemap-loader": "0.3.7",
    "karma-webpack": "3.0.0",
    "less": "3.9.0",
    "less-loader": "4.1.0",
    "mini-css-extract-plugin": "0.5.0",
    "ng-annotate-loader": "0.6.1",
    "optimize-css-assets-webpack-plugin": "5.0.1",
    "postcss-loader": "3.0.0",
    "rimraf": "2.6.3",
    "script-loader": "0.7.2",
    "style-loader": "0.23.1",
    "terser-webpack-plugin": "1.2.3",
    "ts-loader": "5.3.3",
    "ts-node": "8.0.3",
    "typescript": "3.4.5",
    "url-loader": "1.1.2",
    "util": "0.11.1",
    "webpack": "4.30.0",
    "webpack-bundle-analyzer": "3.3.2",
    "webpack-cli": "3.3.0",
    "webpack-dev-server": "3.3.1",
    "webpack-merge": "4.2.1",
    "webpack-node-externals": "1.7.2",
    "webpack-stats-plugin": "0.2.1",
    "protractor": "5.4.2",
    "uglifyjs-webpack-plugin": "2.1.2"
  }
</code>```

I would expect that on every machine with the same node.js and the same npm webpack would handle the files correctly

Is there something else that could influence Webpack so loaders are not used/recognized ?

I repeat, this config works without any problem on other pc's..

Any help would be much apreciated..

答:
In my case, the problem was that we had restructured our repo to have a single, root-level package.json file instead of one in each of several subdirectories. This meant that unless everyone deleted the old node_modules folders, webpack would find one of the stale folders and look there for ts-loader instead of looking in the right place.

This can be avoided by telling webpack exactly where to look for loaders using the resolveLoader configuration option. For example:

  resolveLoader: {
    modules: [path.resolve(__dirname, '../../../node_modules')],
    mainFields: ['ts-loader']
  },
```

Note that the documentation for resolve.modules, which also applies to resolveLoader.modules, states:

Absolute and relative paths can both be used, but be aware that they will behave a bit differently.

A relative path will be scanned similarly to how Node scans for
  node_modules, by looking through the current directory as well as its
  ancestors (i.e. ./node_modules, ../node_modules, and on).

With an absolute path, it will only search in the given directory.

The default behavior seems to correspond to the relative path approach--any node_modules folder in the directory tree between your webpack config file and the folder containing the node_modules folder you expect to be used will be used instead, and in our case this caused the exact issue you describe as soon as we tried to update TypeScript.

Body:
I migrated from webpack 1.x to 4.30.
node version : 10.15.3
typescript version : 3.4.5
npm version : 6.9.0

This setup works on 3 (windows) pc's but not on one particular machine, although they all use the same versions of node, webpack, npm, other npm packages.

On the not working machine it is as if Webpack does not use the less-loader and ts-loader defined in the webpack.config.ts..  and gives for example the following errors:

*.less files beginning with id selector

Unexpected character '#' (1:1)
You may need an appropriate loader to handle this file type

*.less files beginning with @import

Module parse failed: Unexpected character '@' You may need an appropriate loader to handle this file type

*.ts file (angular component) containing @Component

Unexpected character '@' (11:0)
You may need an appropriate loader to handle this file type

I already tried reinstalling node.js, clear npm cache, clear node_modules folder and  new npm install, reboot pc several times..
On another pc where we had the same problem but it was "magically"  solved after a reboot..

webpack.config loaders/rules section

    rules: [
      {
        test: /\.ts$/,
        include: [resolve(__dirname, "Assets")],
        use: [
          "ng-annotate-loader",
          "ts-loader",
          "angular-router-loader"
        ]
      },
      {
        test: /\.less$/,
        include: [resolve(__dirname, "Assets/StyleSheets"), resolve(__dirname, "Assets/NgComponentsNew"), resolve(__dirname, "Assets/WpBundles")],
        use: [
          MiniCssExtractPlugin.loader,
          "css-loader",
          {
            loader: "postcss-loader",
            options: {
              plugins: () => [require('autoprefixer')({
                'browsers': ['> 1%', 'last 2 versions']
              })],
            }
          },
          "less-loader"
        ]
      },
      {
        test: /\.html$/,
        include: [resolve(__dirname, "Assets/NgComponents"), resolve(__dirname, "Assets/NgComponentsNew")],
        use: ["html-loader"]
      },
      {
        test: /\.ico$/,
        include: [resolve(__dirname, "Assets/Images")],
        use: {
          loader: "file-loader",
          options: {
            name: "Images/[name].[ext]"
          }
        }
      },
      {
        test: /\.(png|jpg|gif)$/,
        include: [resolve(__dirname, "Assets/Images"), resolve(__dirname, "Assets/Kendo")],
        use: {
          loader: "file-loader",
          options: {
            name: "Images/[name].[ext]",
            publicPath: "/mvc/static/"
          }
        }
      },
      {
        test: /\.(otf|ttf|eot|svg|woff(2)?)(\?[a-z0-9=&.]+)?$/,
        include: [resolve(__dirname, "Assets"), resolve(__dirname, "./node_modules/@fortawesome/fontawesome-free/webfonts"), resolve(__dirname, "./node_modules/bootstrap/fonts")],
        use: {
          loader: "file-loader",
          options: {
            name: "Fonts/[name].[ext]",
            publicPath: "/mvc/static/"
          }
        }
      },
      {
        test: /jquery.+\.js$/,
        use: [{
          loader: 'expose-loader',
          options: 'jQuery'
        }, {
          loader: 'expose-loader',
          options: '$'
        }]
      },
      //avoid "import" warning
      {
        test: /[\/\\]@angular[\/\\].+\.js$/,
        parser: { system: true }
      }
    ]
  },

package.json

{
  "name": "ourproject",
  "version": "1.1.0",
  "description": "Client Npm Packages",
  "main": "",
  "dependencies": {
    "@angular/animations": "7.2.13",
    "@angular/common": "7.2.13",
    "@angular/compiler": "7.2.13",
    "@angular/core": "7.2.13",
    "@angular/forms": "7.2.13",
    "@angular/http": "7.2.13",
    "@angular/platform-browser": "7.2.13",
    "@angular/platform-browser-dynamic": "7.2.13",
    "@angular/router": "7.2.13",
    "@angular/upgrade": "7.2.13",
    "@fortawesome/fontawesome-free": "5.6.3",
    "@progress/kendo-angular-buttons": "4.4.0",
    "@progress/kendo-angular-l10n": "1.4.0",
    "angular": "1.7.8",
    "angular-animate": "1.7.8",
    "angular-filter": "0.5.17",
    "angular-resource": "1.7.8",
    "angular-sanitize": "1.7.8",
    "angular-translate": "2.18.1",
    "automapper-ts": "1.9.0",
    "bootstrap": "3.3.7",
    "bootstrap-less": "3.3.8",
    "core-js": "3.0.0",
    "eruda": "1.5.0",
    "es5-shim": "4.5.10",
    "golden-layout": "1.5.8",
    "jquery": "3.3.1",
    "jquery-ui-bundle": "1.12.1",
    "jquery-validation-unobtrusive": "3.2.10",
    "json3": "3.3.2",
    "linq": "3.1.0",
    "lodash": "4.17.11",
    "moment": "2.22.2",
    "reflect-metadata": "0.1.13",
    "rxjs": "6.5.1",
    "rxjs-compat": "6.5.1",
    "zone.js": "0.8.26",
    "core.js": "0.4.2"
  },
  "devDependencies": {
    "@angular/language-service": "7.2.13",
    "@types/angular": "1.6.48",
    "@types/angular-resource": "1.5.14",
    "@types/angular-sanitize": "1.3.7",
    "@types/bootstrap": "3.3.39",
    "@types/core-js": "2.5.0",
    "@types/jasmine": "3.3.12",
    "@types/jquery.validation": "1.16.4",
    "@types/kendo-ui": "2018.1.2",
    "@types/lodash": "4.14.110",
    "@types/webpack": "4.4.27",
    "@types/webpack-dev-server": "3.1.5",
    "@types/webpack-env": "1.13.9",
    "@types/node": "11.13.7",
    "angular-router-loader": "0.8.5",
    "autoprefixer": "9.5.1",
    "awesome-typescript-loader": "5.2.1",
    "css-loader": "2.1.1",
    "expose-loader": "0.7.5",
    "file-loader": "3.0.1",
    "html-loader": "0.5.5",
    "imports-loader": "0.8.0",
    "jasmine": "3.4.0",
    "jasmine-spec-reporter": "4.2.1",
    "karma": "4.1.0",
    "karma-chrome-launcher": "2.2.0",
    "karma-cli": "2.0.0",
    "karma-coverage": "1.1.2",
    "istanbul-instrumenter-loader": "3.0.1",
    "karma-remap-coverage": "0.1.5",
    "karma-coverage-istanbul-reporter": "2.0.5",
    "karma-jasmine-html-reporter": "1.4.1",
    "karma-jasmine": "2.0.1",
    "karma-phantomjs-launcher": "1.0.4",
    "karma-sourcemap-loader": "0.3.7",
    "karma-webpack": "3.0.0",
    "less": "3.9.0",
    "less-loader": "4.1.0",
    "mini-css-extract-plugin": "0.5.0",
    "ng-annotate-loader": "0.6.1",
    "optimize-css-assets-webpack-plugin": "5.0.1",
    "postcss-loader": "3.0.0",
    "rimraf": "2.6.3",
    "script-loader": "0.7.2",
    "style-loader": "0.23.1",
    "terser-webpack-plugin": "1.2.3",
    "ts-loader": "5.3.3",
    "ts-node": "8.0.3",
    "typescript": "3.4.5",
    "url-loader": "1.1.2",
    "util": "0.11.1",
    "webpack": "4.30.0",
    "webpack-bundle-analyzer": "3.3.2",
    "webpack-cli": "3.3.0",
    "webpack-dev-server": "3.3.1",
    "webpack-merge": "4.2.1",
    "webpack-node-externals": "1.7.2",
    "webpack-stats-plugin": "0.2.1",
    "protractor": "5.4.2",
    "uglifyjs-webpack-plugin": "2.1.2"
  }

I would expect that on every machine with the same node.js and the same npm webpack would handle the files correctly

Is there something else that could influence Webpack so loaders are not used/recognized ?

I repeat, this config works without any problem on other pc's..

Any help would be much apreciated..

Body:
In my case, the problem was that we had restructured our repo to have a single, root-level package.json file instead of one in each of several subdirectories. This meant that unless everyone deleted the old node_modules folders, webpack would find one of the stale folders and look there for ts-loader instead of looking in the right place.

This can be avoided by telling webpack exactly where to look for loaders using the resolveLoader configuration option. For example:

  resolveLoader: {
    modules: [path.resolve(__dirname, '../../../node_modules')],
    mainFields: ['ts-loader']
  },

Note that the documentation for resolve.modules, which also applies to resolveLoader.modules, states:

Absolute and relative paths can both be used, but be aware that they will behave a bit differently.

A relative path will be scanned similarly to how Node scans for
  node_modules, by looking through the current directory as well as its
  ancestors (i.e. ./node_modules, ../node_modules, and on).

With an absolute path, it will only search in the given directory.

The default behavior seems to correspond to the relative path approach--any node_modules folder in the directory tree between your webpack config file and the folder containing the node_modules folder you expect to be used will be used instead, and in our case this caused the exact issue you describe as soon as we tried to update TypeScript.


问:
How to sum up the duplicated value and keep all the rows on R
I have a dataset like this

```<code>V0  V1  V2
1   A   21
2   A   21
3   B   22
4   C   23
5   C   23
</code>```

So there are duplicated value in V1; and I would like to create a dataset like this, which sum up V2 but keeping the duplicates in V1:

```<code>V0  V1  V2
1   A   42
2   A   42
3   B   22
4   C   46
5   C   46
</code>```

thanks

答:
We can use ave from base R

```<code>df1$V2 <- with(df1, ave(V2, V1, FUN = sum))
</code>```

Or with dplyr

```<code>library(dplyr)
df1 %>%
   group_by(V1) %>%
   mutate(V2 = sum(V2))
</code>```

Body:
I have a dataset like this

V0  V1  V2
1   A   21
2   A   21
3   B   22
4   C   23
5   C   23

So there are duplicated value in V1; and I would like to create a dataset like this, which sum up V2 but keeping the duplicates in V1:

V0  V1  V2
1   A   42
2   A   42
3   B   22
4   C   46
5   C   46

thanks

Body:
We can use ave from base R

df1$V2 <- with(df1, ave(V2, V1, FUN = sum))

Or with dplyr

library(dplyr)
df1 %>%
   group_by(V1) %>%
   mutate(V2 = sum(V2))


问:
How to set Vuetify Navigation Drawer always on top of all other app components
I'd like to know how I could do this.

With some components it appears to be on top, but then other components, such like a Leaflet (Map) component, they overlaps my SideDrawer so I can't use it properly.

How could I set my navigation drawer to be always on top with a higher z-index than the other components?

答:
I had a very similar problem with the v-calendar component. The navigation drawer was working for any other page than the one with v-calendar.

It turns out I was not using the elements v-app, v-content and v-container in the correct way. Could you share your App.vue content so we can check that?

I believe you should look for that structure rather than working on css tricks (not that we can't, but when working with components, we were not supposed to change that deep)

For example, in my app it works now and the structure I have is the following:

```<code><template>
  <v-app>
    <v-navigation-drawer ... />
    <v-content>
      <v-container>
        <router-view />
      </v-container>
    </v-content>
  </v-app>
</template>

</code>```

And the view with the calendar is more or less like:

```<code><template>
  <v-row>
    <v-col>
      <v-sheet>
        <v-calendar />
      </v-sheet>
    </v-col>
  </v-row>
</template>
</code>```

I hope it helps!

Body:
I had a very similar problem with the v-calendar component. The navigation drawer was working for any other page than the one with v-calendar.

It turns out I was not using the elements v-app, v-content and v-container in the correct way. Could you share your App.vue content so we can check that?

I believe you should look for that structure rather than working on css tricks (not that we can't, but when working with components, we were not supposed to change that deep)

For example, in my app it works now and the structure I have is the following:

<template>
  <v-app>
    <v-navigation-drawer ... />
    <v-content>
      <v-container>
        <router-view />
      </v-container>
    </v-content>
  </v-app>
</template>

And the view with the calendar is more or less like:

<template>
  <v-row>
    <v-col>
      <v-sheet>
        <v-calendar />
      </v-sheet>
    </v-col>
  </v-row>
</template>

I hope it helps!


问:
Remove an object from List of dynamic object
```<code>//Data is IList<ExpandoObject>
var result = (from dynamic item in Data
              where item.id== "123"
              select item).FirstOrDefault();
</code>```

Want to achieve below feature but it is erroring out by saying remove not available for dynamic objects.

```<code>Data.Remove(result);
</code>```

Let me know if any suggestions.
thanks

答:
Error: remove not available for dynamic objects

base on Microsoft's docs, The Remove method of IList<T> accepts a parameter with the type of T:

```<code>ICollection<T>.Remove(T)
</code>```

In your example, T is an ExpandoObject, so it means in the Remove method you should pass a parameter with the type of ExpandoObject but you didn't and you are passing a parameter with the type of dynamic. Therefore you facing this error

for resolving this you have two way:

1) Use explicit type instead of var:

```<code>ExpandoObject result = ...
</code>```

2) cast the result when you are passing it to Remove:

```<code>Data.Remove((ExpandoObject) result)
</code>```

I think with doing one of these ways, your problem will resolve. good luck.

Body:
//Data is IList<ExpandoObject>
var result = (from dynamic item in Data
              where item.id== "123"
              select item).FirstOrDefault();

Want to achieve below feature but it is erroring out by saying remove not available for dynamic objects.

Data.Remove(result);

Let me know if any suggestions.
thanks

Body:
Error: remove not available for dynamic objects

base on Microsoft's docs, The Remove method of IList<T> accepts a parameter with the type of T:

ICollection<T>.Remove(T)

In your example, T is an ExpandoObject, so it means in the Remove method you should pass a parameter with the type of ExpandoObject but you didn't and you are passing a parameter with the type of dynamic. Therefore you facing this error

for resolving this you have two way:

1) Use explicit type instead of var:

ExpandoObject result = ...

2) cast the result when you are passing it to Remove:

Data.Remove((ExpandoObject) result)

I think with doing one of these ways, your problem will resolve. good luck.


问:
What should be behind ARPAUTHORIZEDCDFPREFIX?
I've seen that you can specify an "upgrade channel" in MSI files. Is that supposed to be a human readable web page (i.e. all you get is a link in Installed Programs), or should this be a machine readable resource pointing at the latest version somehow?</p>

答:
I checked in the registry on my computer and all entries for this property are empty. It seems the property is used by an obsolete Microsoft technology and the MSDN page states that as of IE7, it should no longer be used: http://msdn.microsoft.com/en-us/library/aa741201(v=vs.85).aspx

Personally I would leave this property undefined unless you get any validation errors on your MSI by doing so. The less you define, the less side effects you generally get. Microsoft is big on hidden compatibility "features", the more you try to deal with this by overriding things yourself the more you bang your head against the method of their madness.