问:
java 8 grouping a map of same key and value and make a key value pair
I have a method fetchConfigsCount() which returns List<Map<String, Object>>.

The result looks like:

{
    "web_id": "abc",
    "count": 1
},
{
    "web_id": "xyz",
    "count": 1
},
{
    "web_id": "pqr",
    "count": 1
}
```
<p>We have another method <code>fetchWebsitesCount()</code> which also returns a response in same format.</p>
<p><code>web_id</code> is the key and its value is owner name.
<code>count</code> is another key and its value is of type <code>int</code>.</p>
<pre class="lang-json prettyprint-override"><code>{
    "web_id": "abc",
    "count": 2
},
{
    "web_id": "xyz",
    "count": 3
},
{
    "web_id": "pqr",
    "count": 4
}
</code>```

We have a list of owners which is of type ArrayList<String>:

List<String> listOfOwners = ["abc","xyz","pqr"];
```
<p>I want to collect all these things and want to create a result like below:</p>
<pre class="lang-json prettyprint-override"><code>result:[
    {"owner": "abc",
    "ownerPresence":{
    "configCount":1,
    "websiteCount":2
    },
    {"owner": "xyz",
    "ownerPresence":{
    "configCount":1,
    "websiteCount":3
    },
    {"owner": "pqr",
    "ownerPresence":{
    "configCount":1,
    "websiteCount":4
    }]
</code>```

I am not sure how I can do this in Java 8.

答:
Here is one way to do it.

first, just remap the counts to a Map<String,List<Integer>>

then simply iterate over than map, building the final map and list.

```<code>List<Map<String, Object>> configCount =
        List.of(Map.of("web_id", "abc", "count", 1),
                Map.of("web_id", "xyz", "count", 1),
                Map.of("web_id", "pqr", "count", 1));

List<Map<String, Object>> webCount =
        List.of(Map.of("web_id", "abc", "count", 2),
                Map.of("web_id", "xyz", "count", 3),
                Map.of("web_id", "pqr", "count", 4));

List<Map<String, Object>> sourceCount =
        List.of(Map.of("web_id", "abc", "count", 22),
                Map.of("web_id", "xyz", "count", 32),
                Map.of("web_id", "pqr", "count", 42));

Map<String, List<Integer>> map = Stream
                .concat(configCount.stream(),
                        Stream.concat(webCount.stream(),
                                sourceCount.stream()))
        .collect(Collectors.groupingBy(
                mp -> (String) mp.get("web_id"),
                Collectors.mapping(
                        mp -> (Integer) mp.get("count"),
                        Collectors.toList())));
</code>```

The above creates the following where the first List values are 'config, website, and source` in that order.

```<code>pqr=[1, 4, 42]
abc=[1, 2, 22]
xyz=[1, 3, 32]
</code>```

Now instantiate a final List to hold all the maps and finish up.

```<code>List<Map<String, Object>> result = new ArrayList<>();

for (Entry<String, List<Integer>> e : map.entrySet()) {
    Map<String, Object> tempMap = new HashMap<>();
    tempMap.put("owner", e.getKey());
    tempMap.put("ownerPresence",
            new HashMap<>(Map.of("configCount",e.getValue().get(0),
                                "webSiteCount",e.getValue().get(1),
                                "sourceCount", e.getValue().get(2))));
    result.add(tempMap);
}

result.forEach(mp -> mp.entrySet()
          .forEach(e -> System.out.println(e.getKey() + ":" + e.getValue())));
</code>```

prints

```<code>owner:pqr
ownerPresence:{sourceCount=42, webSiteCount=4, configCount=1}
owner:abc
ownerPresence:{sourceCount=22, webSiteCount=2, configCount=1}
owner:xyz
ownerPresence:{sourceCount=32, webSiteCount=3, configCount=1}

</code>```

Body:
I have a method fetchConfigsCount() which returns List<Map<String, Object>>.

The result looks like:

{
    "web_id": "abc",
    "count": 1
},
{
    "web_id": "xyz",
    "count": 1
},
{
    "web_id": "pqr",
    "count": 1
}

We have another method fetchWebsitesCount() which also returns a response in same format.

web_id is the key and its value is owner name.
count is another key and its value is of type int.

{
    "web_id": "abc",
    "count": 2
},
{
    "web_id": "xyz",
    "count": 3
},
{
    "web_id": "pqr",
    "count": 4
}

We have a list of owners which is of type ArrayList<String>:

List<String> listOfOwners = ["abc","xyz","pqr"];

I want to collect all these things and want to create a result like below:

result:[
    {"owner": "abc",
    "ownerPresence":{
    "configCount":1,
    "websiteCount":2
    },
    {"owner": "xyz",
    "ownerPresence":{
    "configCount":1,
    "websiteCount":3
    },
    {"owner": "pqr",
    "ownerPresence":{
    "configCount":1,
    "websiteCount":4
    }]

I am not sure how I can do this in Java 8.

Body:
Here is one way to do it.

first, just remap the counts to a Map<String,List<Integer>>

then simply iterate over than map, building the final map and list.

List<Map<String, Object>> configCount =
        List.of(Map.of("web_id", "abc", "count", 1),
                Map.of("web_id", "xyz", "count", 1),
                Map.of("web_id", "pqr", "count", 1));

List<Map<String, Object>> webCount =
        List.of(Map.of("web_id", "abc", "count", 2),
                Map.of("web_id", "xyz", "count", 3),
                Map.of("web_id", "pqr", "count", 4));

List<Map<String, Object>> sourceCount =
        List.of(Map.of("web_id", "abc", "count", 22),
                Map.of("web_id", "xyz", "count", 32),
                Map.of("web_id", "pqr", "count", 42));

Map<String, List<Integer>> map = Stream
                .concat(configCount.stream(),
                        Stream.concat(webCount.stream(),
                                sourceCount.stream()))
        .collect(Collectors.groupingBy(
                mp -> (String) mp.get("web_id"),
                Collectors.mapping(
                        mp -> (Integer) mp.get("count"),
                        Collectors.toList())));

The above creates the following where the first List values are 'config, website, and source` in that order.

pqr=[1, 4, 42]
abc=[1, 2, 22]
xyz=[1, 3, 32]

Now instantiate a final List to hold all the maps and finish up.

List<Map<String, Object>> result = new ArrayList<>();

for (Entry<String, List<Integer>> e : map.entrySet()) {
    Map<String, Object> tempMap = new HashMap<>();
    tempMap.put("owner", e.getKey());
    tempMap.put("ownerPresence",
            new HashMap<>(Map.of("configCount",e.getValue().get(0),
                                "webSiteCount",e.getValue().get(1),
                                "sourceCount", e.getValue().get(2))));
    result.add(tempMap);
}

result.forEach(mp -> mp.entrySet()
          .forEach(e -> System.out.println(e.getKey() + ":" + e.getValue())));

prints

owner:pqr
ownerPresence:{sourceCount=42, webSiteCount=4, configCount=1}
owner:abc
ownerPresence:{sourceCount=22, webSiteCount=2, configCount=1}
owner:xyz
ownerPresence:{sourceCount=32, webSiteCount=3, configCount=1}


来源: stackexchange

问:
IndexError: string index out of range - if function with dataframe
I try to eliminate brackets and unnecessary marks in the dataframe.

Here's what my data look like:

```<code>df["address"]

index  address
0       (#)(△)Kaohsiung City
1       (△)New Taipei City
2       (O)Chiayi City
.
.
</code>```

Currently I'm using this:

```<code>def reshape_address(addr):
    if addr[0] == "(":
        return addr.split(")", 1)[-1]
    else:
        return addr

def run_reshape_addr(text):
    text["address"] = text["address"].apply(reshape_address)
    text["address"] = text["address"].apply(reshape_address)
    text["address"] = text["address"].apply(reshape_address)
#run three times in order to get rid of multiple brackets

run_reshape_addr(df)
</code>```

Somehow I got the IndexError: string index out of range.
However, a partial of data have been executed successfully after this run even the error message pops up.

How can I revise this? And why were some of the data still being executed under this circumstance? Thank you.

答:
You most likely have a record with an empty string, so when you look if it starts with a (, it throws the IndexError.

You can fix this by simply checking if the string is empty first.

def reshape_address(addr):
    if addr and addr[0] == "(": # Check if addr is truthy
        return addr.split(")", 1)[-1]
    else:
        return addr
```

ContentLicense: CC BY-SA 4.0

Body:
I try to eliminate brackets and unnecessary marks in the dataframe.

Here's what my data look like:

df["address"]

index  address
0       (#)(△)Kaohsiung City
1       (△)New Taipei City
2       (O)Chiayi City
.
.

Currently I'm using this:

def reshape_address(addr):
    if addr[0] == "(":
        return addr.split(")", 1)[-1]
    else:
        return addr

def run_reshape_addr(text):
    text["address"] = text["address"].apply(reshape_address)
    text["address"] = text["address"].apply(reshape_address)
    text["address"] = text["address"].apply(reshape_address)
#run three times in order to get rid of multiple brackets

run_reshape_addr(df)

Somehow I got the IndexError: string index out of range.
However, a partial of data have been executed successfully after this run even the error message pops up.

How can I revise this? And why were some of the data still being executed under this circumstance? Thank you.


问:
text processing question: remove rows where one column does not contain a particular value
I have a tab delimited file that looks like this:

```<code>input_sequence  match_sequence  score   receptor_group  epitope antigen organism
ASRPPGGVNEQF    ASRPPGGVNEQF    1.00    25735   EPLPQGQLTAY surface glycoprotein [Severe acute respiratory syndrome coronavirus 2]  SARS-CoV2
ASSYSGGYEQY ASSYSGGYEQY 1.00    33843   KTAYSHLSTSK polymerase  Hepatitis B virus (hepatitis B virus (HBV))
ASSYSGGYEQY ASSYSGGYEQY 1.00    131430  KLSYGIATV   orf1ab polyprotein [Severe acute respiratory syndrome coronavirus 2]    SARS-CoV2
ASSYSGGYEQY ASSFSGGYEQY 0.97    82603   FTISVTTEIL  surface glycoprotein [Severe acute respiratory syndrome coronavirus 2]  SARS-CoV2
ASSYSGGYEQY ASSYAGGYEQY 0.98    133155  FVCNLLLLFVTVYSHLLLV ORF3a protein [Severe acute respiratory syndrome coronavirus 2] SARS-CoV2
ASSLFGSTDTQY    ASSLFGSTDTQY    1.00    92508   FTISVTTEIL  surface glycoprotein [Severe acute respiratory syndrome coronavirus 2]  SARS-CoV2
</code>```

I want to keep 'input_sequence' that only match with 'organism' = SARS-CoV2 and nothing else. So in this example I would keep only line 2 and line 7 and discard lines 3,4,5,6 because here this 'input_sequence' has also a hit with Hepatitis B virus.

In total I have over 20.000 rows in my file.

results required:

```<code>input_sequence  match_sequence  score   receptor_group  epitope antigen organism
ASRPPGGVNEQF    ASRPPGGVNEQF    1.00    25735   EPLPQGQLTAY surface glycoprotein [Severe acute respiratory syndrome coronavirus 2]  SARS-CoV2
ASSLFGSTDTQY    ASSLFGSTDTQY    1.00    92508   FTISVTTEIL  surface glycoprotein [Severe acute respiratory syndrome coronavirus 2]  SARS-CoV2
</code>```

Is there a way to quickly do this using awk or bash (without writing a long script)? Any tips are welcome.

I thought to use awk to count the occurences of each value in column 1 and occurences of SARS-COV2 in column 7, and then only keep those that match... but I don't know how to do this. I only got this far (counting the number of occurrences in column one):

```<code>awk '{for(i=1;i<=NF;i++)if($i ~ /^/)x++;print x;x=0}' file
</code>```

Thanks!

答:
You need to do two passes over the input.

The first pass makes an array whose keys are the input sequences that have an organism other than SARS-CoV2. The second pass checks if the current input sequence is in that array. If not, it prints the line.

```<code>awk -F'\t' 'NR==FNR {if ($7 != "SARS-CoV2") {a[$0]=1}; next}
            !a[$0]' file file
</code>```

Body:
I have a tab delimited file that looks like this:

input_sequence  match_sequence  score   receptor_group  epitope antigen organism
ASRPPGGVNEQF    ASRPPGGVNEQF    1.00    25735   EPLPQGQLTAY surface glycoprotein [Severe acute respiratory syndrome coronavirus 2]  SARS-CoV2
ASSYSGGYEQY ASSYSGGYEQY 1.00    33843   KTAYSHLSTSK polymerase  Hepatitis B virus (hepatitis B virus (HBV))
ASSYSGGYEQY ASSYSGGYEQY 1.00    131430  KLSYGIATV   orf1ab polyprotein [Severe acute respiratory syndrome coronavirus 2]    SARS-CoV2
ASSYSGGYEQY ASSFSGGYEQY 0.97    82603   FTISVTTEIL  surface glycoprotein [Severe acute respiratory syndrome coronavirus 2]  SARS-CoV2
ASSYSGGYEQY ASSYAGGYEQY 0.98    133155  FVCNLLLLFVTVYSHLLLV ORF3a protein [Severe acute respiratory syndrome coronavirus 2] SARS-CoV2
ASSLFGSTDTQY    ASSLFGSTDTQY    1.00    92508   FTISVTTEIL  surface glycoprotein [Severe acute respiratory syndrome coronavirus 2]  SARS-CoV2

I want to keep 'input_sequence' that only match with 'organism' = SARS-CoV2 and nothing else. So in this example I would keep only line 2 and line 7 and discard lines 3,4,5,6 because here this 'input_sequence' has also a hit with Hepatitis B virus.

In total I have over 20.000 rows in my file.

results required:

input_sequence  match_sequence  score   receptor_group  epitope antigen organism
ASRPPGGVNEQF    ASRPPGGVNEQF    1.00    25735   EPLPQGQLTAY surface glycoprotein [Severe acute respiratory syndrome coronavirus 2]  SARS-CoV2
ASSLFGSTDTQY    ASSLFGSTDTQY    1.00    92508   FTISVTTEIL  surface glycoprotein [Severe acute respiratory syndrome coronavirus 2]  SARS-CoV2

Is there a way to quickly do this using awk or bash (without writing a long script)? Any tips are welcome.

I thought to use awk to count the occurences of each value in column 1 and occurences of SARS-COV2 in column 7, and then only keep those that match... but I don't know how to do this. I only got this far (counting the number of occurrences in column one):

awk '{for(i=1;i<=NF;i++)if($i ~ /^/)x++;print x;x=0}' file

Thanks!

Body:
You need to do two passes over the input.

The first pass makes an array whose keys are the input sequences that have an organism other than SARS-CoV2. The second pass checks if the current input sequence is in that array. If not, it prints the line.

awk -F'\t' 'NR==FNR {if ($7 != "SARS-CoV2") {a[$0]=1}; next}
            !a[$0]' file file


问:
How to login to wikipedia using mediawiki API through?
I already have two working bots in Wikipedia, but they use different method.
Currently, I am trying to create a bot using C#. On the API documentation page, they have provided some sample codes in java, PHP, and python. But unfortunately, they haven't provided any sample code in C#. It is the only language I am familiar with.

This is the Wikimedia API:Edit documentation page. Would someone kindly convert the few words from java (or any other language) to C#?

If I could get only this code converted to C#, I can build the rest of the bot by myself.
I asked help on the relevant noticeboard(s) on the wikimedia site(s), but nobody there is familiar with C#. That's why I am now asking this outside of wikipedia.

Thanks a lot in advance

This is the java source-code:

```

/*
edit.js

MediaWiki API Demos
Demo of `Login` module: Sending post request to login

MIT license
*/

var request = require( 'request' ).defaults( { jar: true } ),
url = 'https://test.wikipedia.org/w/api.php';

// Step 1: GET request to fetch login token
function getLoginToken() {
var params = {
    action: 'query',
    meta: 'tokens',
    type: 'login',
    format: 'json'
};

request.get( { url: url, qs: params }, function ( error, res, body ) {
    var data;
    if ( error ) {
        return;
    }
    data = JSON.parse( body );
    loginRequest( data.query.tokens.logintoken );
} );
}

// Step 2: POST request to log in.
// Use of main account for login is not
// supported. Obtain credentials via Special:BotPasswords
// (https://www.mediawiki.org/wiki/Special:BotPasswords) for lgname & lgpassword
function loginRequest( loginToken ) {
var params = {
    action: 'login',
    lgname: 'bot_username',
    lgpassword: 'bot_password',
    lgtoken: loginToken,
    format: 'json'
};

request.post( { url: url, form: params }, function ( error, res, body ) {
    if ( error ) {
        return;
    }
    console.log( body );
} );
}

// Start From Step 1
getLoginToken();</code>```

答:
I can't go so deeply but I hope you can take a look at this page and find out how to do it

https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=net-6.0


问:
Django: Integrity error UNIQUE constraint failed: user_profile.user_id
When I am trying to edit a profile to add info to a UserProfile model, I am getting this strange error:

```<code>IntegrityError at /profiles/edit/
UNIQUE constraint failed: user_profile.user_id
</code>```

What is wrong here,

model:

```<code>class UserProfile(models.Model):

    user = models.OneToOneField(User)
    bio = models.TextField(blank=True)
    phone= models.CharField(max_length=10, blank=True)
    address = models.CharField(max_length=1024)
    age = models.PositiveIntegerField(blank=True,null=True)
    gender = models.IntegerField(choices=GENDER_CHOICES, default=1)
</code>```

form:

```<code>class UserProfileForm(forms.ModelForm):

    class Meta:
        model = UserProfile
        fields = ('phone','age','gender','address','bio')
</code>```

view:

```<code>def edit_profile(request):

    if request.method == 'POST':
        form = UserProfileForm(request.POST)
        print request.POST
        if form.is_valid():

            new_profile = UserProfile(
                            user = request.user,
                            bio = request.POST['bio'],
                            address = request.POST['address'],
                            age = request.POST['age']
                            )

            new_profile.save()

            return HttpResponseRedirect(reverse('user_public_profile', args=(request.user.username,)))
        return render(request,'users/edit_profile.html', {'form': form})

    else:
        form = UserProfileForm()
        return render(request,'users/edit_profile.html',
                          {'form': form})
</code>```

答:
Consider the case: If the same user makes the post request again on URL 'profile/edit' then your code will try to create the new UserProfile using the same user instance, but since this is a one to one field and you have already created one profile using that user hence it will throw integrity error.

So you should check first if the profile associated with that user already exists or not, then if it didn't exist then create it.

ContentLicense: CC BY-SA 3.0

Body:
When I am trying to edit a profile to add info to a UserProfile model, I am getting this strange error:

IntegrityError at /profiles/edit/
UNIQUE constraint failed: user_profile.user_id

What is wrong here,

model:

class UserProfile(models.Model):

    user = models.OneToOneField(User)
    bio = models.TextField(blank=True)
    phone= models.CharField(max_length=10, blank=True)
    address = models.CharField(max_length=1024)
    age = models.PositiveIntegerField(blank=True,null=True)
    gender = models.IntegerField(choices=GENDER_CHOICES, default=1)

form:

class UserProfileForm(forms.ModelForm):

    class Meta:
        model = UserProfile
        fields = ('phone','age','gender','address','bio')

view:

def edit_profile(request):

    if request.method == 'POST':
        form = UserProfileForm(request.POST)
        print request.POST
        if form.is_valid():

            new_profile = UserProfile(
                            user = request.user,
                            bio = request.POST['bio'],
                            address = request.POST['address'],
                            age = request.POST['age']
                            )

            new_profile.save()

            return HttpResponseRedirect(reverse('user_public_profile', args=(request.user.username,)))
        return render(request,'users/edit_profile.html', {'form': form})

    else:
        form = UserProfileForm()
        return render(request,'users/edit_profile.html',
                          {'form': form})


问:
The package org.w3c.dom is accessible from more than one module: <unnamed>, java.xml
I am unable to import org.w3c.dom.NodeList package to Eclipse. It is showing

The package org.w3c.dom is accessible from more than one module: <unnamed>, java.xml" error message in eclipse.

Please let me know how to fix this ?

Eclipse Version:

Eclipse IDE for Enterprise Java Developers.

Version: 2019-06 (4.12.0)

Build id: 20190614-1200

Java version:

java version "12.0.1" 2019-04-16

Java(TM) SE Runtime Environment (build 12.0.1+12)

Java HotSpot(TM) 64-Bit Server VM (build 12.0.1+12, mixed mode, sharing)

答:
You can use this code (for example in a unit test) to determine all JARs that contain a class:

```<code>getClass().getClassLoader().getResources("org/w3c/dom/NodeList.class");
</code>```

This gives you an Enumeration. The easiest way to print this is:

```<code>Collections.list(e).forEach(System.out::println);
</code>```

Body:
You can use this code (for example in a unit test) to determine all JARs that contain a class:

getClass().getClassLoader().getResources("org/w3c/dom/NodeList.class");

This gives you an Enumeration. The easiest way to print this is:

Collections.list(e).forEach(System.out::println);


问:
Add CSS style using className in Material UI component coming from dynamic json object in ReactJS
I have a dynamic json object which contains a button element. I am using createElement and material UI to render the object data.

I wanted to apply customizable CSS using className in the button component, but I couldn't achieve it.
So, how can I apply CSS in runtime to the material UI component?

Here is my code snippet:

```<code>import React, { useState } from "react";
import './App.css';
import { Button, Grid, Checkbox, TextField, Switch, Link } from '@mui/material';

const KeysToComponentMap = {
    button: Button,
    grid: Grid,
    checbox: Checkbox,
    text: TextField,
    switch: Switch,
    link: Link
};

const RenderCard = (props) => {

    const SampleData =
        [
            {
                "type": "button",
                "display": "RELEASE THE BATCH",
                "key": "RS",
                "class": "btn",
                "value": [
                    {
                        "type": "button",
                        "display": "CONFIRM AND SUBMIT",
                        "key": "key1",
                        "value": "post"
                    }
                ]
            },
            {
                "type": "button",
                "display": "RELEASE THE OBSERVATION",
                "key": "RO",
                "value": [
                    {
                        "type": "input",
                        "display": "Observation",
                        "key": "key8",
                        "value": "val1"
                    },
                    {
                        "type": "button",
                        "display": "Done",
                        "key": "key9",
                        "value": [
                            {
                                "type": "button",
                                "display": "CONFIRM AND SUBMIT",
                                "key": "key10",
                                "value": "post"
                            }
                        ]
                    }
                ]
            }
        ]

    }

    return (
        <>{

                {SampleData.map((item, index) => {
                    console.log(item.type);
                    console.log(item.class)

                    if (typeof KeysToComponentMap[item.type] !== "undefined") {

                        return (
                            React.createElement(
                                KeysToComponentMap[item.type],
                                {
                                    onClick: () => { onButtonHandler(item, item.key) },
                                    variant: "contained",
                                    type: "input",
                                    className: KeysToComponentMap[item.class],

                                },

                                item.display &&
                                (typeof item.display === "string"
                                ? item.display
                                : item.value.map(c => ActivityDetail(c)))
                            ))

                    }

                })}

        }

        </>)
}

export default RenderCard;
</code>```

答:
Original Question:

Your problem isn't that the className isn't being applied, it's that the value that you're trying to assign from KeysToComponentMap (KeysToComponentMap[item.class]) is returning undefined.  I had to modify your code, and add a class property to your Sample JSON, to get it to work so you may want to change it however you need it:

```<code>{
  onClick: () => {
    onButtonHandler(item, item.key);
  },
  variant: "contained",
  type: "input",
  className: item.class // Changed from `className: KeysToComponentMap[item.class]`
},
</code>```

Working Code Sandbox: https://codesandbox.io/s/classname-cjlqo?file=/demo.js

Question from Comments:

in case if i want to pass style directly instead of classname then in
what format should be style property be in sample JSON. I was passing
style in json like: [{"style": "color: 'red'"}] but it is a wrong way
that's why not working. So, what is the correct way?

Since you are using MUI 5, the correct prop to pass inline styles is sx.  You may want to make your configuration a bit more flexible by just passing whatever additional properties each component might need straight through and spreading them into the component directly. For example:

```<code>// Sample config:
{
  type: "button",
  display: "RELEASE THE BATCH",
  key: "RS",
  className: "my-button",
  sx: { color: "blue" },
  value: [
    {
      type: "button",
      display: "CONFIRM AND SUBMIT",
      key: "key1",
      value: "post"
    }
  ]
},

// Renderer
    <>
      {SampleData.map(({ type, key, display, value, ...rest }, index) => {
        console.log(type);

        if (typeof KeysToComponentMap[type] !== "undefined") {
          return React.createElement(
            KeysToComponentMap[type],
            {
              onClick: () => {
                onButtonHandler(item, key);
              },
              variant: "contained",
              type: "input",
              ...rest
            },

            display &&
              (typeof display === "string"
                ? display
                : value.map((c) => ActivityDetail(c)))
          );
        }
      })}
    </>
</code>```

Working example with className and style: https://codesandbox.io/s/style-e4inc?file=/demo.js

Body:
I have a dynamic json object which contains a button element. I am using createElement and material UI to render the object data.

I wanted to apply customizable CSS using className in the button component, but I couldn't achieve it.
So, how can I apply CSS in runtime to the material UI component?

Here is my code snippet:

import React, { useState } from "react";
import './App.css';
import { Button, Grid, Checkbox, TextField, Switch, Link } from '@mui/material';

const KeysToComponentMap = {
    button: Button,
    grid: Grid,
    checbox: Checkbox,
    text: TextField,
    switch: Switch,
    link: Link
};

const RenderCard = (props) => {

    const SampleData =
        [
            {
                "type": "button",
                "display": "RELEASE THE BATCH",
                "key": "RS",
                "class": "btn",
                "value": [
                    {
                        "type": "button",
                        "display": "CONFIRM AND SUBMIT",
                        "key": "key1",
                        "value": "post"
                    }
                ]
            },
            {
                "type": "button",
                "display": "RELEASE THE OBSERVATION",
                "key": "RO",
                "value": [
                    {
                        "type": "input",
                        "display": "Observation",
                        "key": "key8",
                        "value": "val1"
                    },
                    {
                        "type": "button",
                        "display": "Done",
                        "key": "key9",
                        "value": [
                            {
                                "type": "button",
                                "display": "CONFIRM AND SUBMIT",
                                "key": "key10",
                                "value": "post"
                            }
                        ]
                    }
                ]
            }
        ]

    }

    return (
        <>{

                {SampleData.map((item, index) => {
                    console.log(item.type);
                    console.log(item.class)

                    if (typeof KeysToComponentMap[item.type] !== "undefined") {

                        return (
                            React.createElement(
                                KeysToComponentMap[item.type],
                                {
                                    onClick: () => { onButtonHandler(item, item.key) },
                                    variant: "contained",
                                    type: "input",
                                    className: KeysToComponentMap[item.class],

                                },

                                item.display &&
                                (typeof item.display === "string"
                                ? item.display
                                : item.value.map(c => ActivityDetail(c)))
                            ))

                    }

                })}

        }

        </>)
}

export default RenderCard;

Body:
Original Question:

Your problem isn't that the className isn't being applied, it's that the value that you're trying to assign from KeysToComponentMap (KeysToComponentMap[item.class]) is returning undefined.  I had to modify your code, and add a class property to your Sample JSON, to get it to work so you may want to change it however you need it:

{
  onClick: () => {
    onButtonHandler(item, item.key);
  },
  variant: "contained",
  type: "input",
  className: item.class // Changed from `className: KeysToComponentMap[item.class]`
},

Working Code Sandbox: https://codesandbox.io/s/classname-cjlqo?file=/demo.js

Question from Comments:

in case if i want to pass style directly instead of classname then in
what format should be style property be in sample JSON. I was passing
style in json like: [{"style": "color: 'red'"}] but it is a wrong way
that's why not working. So, what is the correct way?

Since you are using MUI 5, the correct prop to pass inline styles is sx.  You may want to make your configuration a bit more flexible by just passing whatever additional properties each component might need straight through and spreading them into the component directly. For example:

// Sample config:
{
  type: "button",
  display: "RELEASE THE BATCH",
  key: "RS",
  className: "my-button",
  sx: { color: "blue" },
  value: [
    {
      type: "button",
      display: "CONFIRM AND SUBMIT",
      key: "key1",
      value: "post"
    }
  ]
},

// Renderer
    <>
      {SampleData.map(({ type, key, display, value, ...rest }, index) => {
        console.log(type);

        if (typeof KeysToComponentMap[type] !== "undefined") {
          return React.createElement(
            KeysToComponentMap[type],
            {
              onClick: () => {
                onButtonHandler(item, key);
              },
              variant: "contained",
              type: "input",
              ...rest
            },

            display &&
              (typeof display === "string"
                ? display
                : value.map((c) => ActivityDetail(c)))
          );
        }
      })}
    </>

Working example with className and style: https://codesandbox.io/s/style-e4inc?file=/demo.js


问:
How to solve this error while making training file in python
So I have been making an A.I. program with 0 experience in coding in python just as a hobby. While making the training file, I faced an error and I am not able to solve it.

This is my Training file-

```<code>import numpy as np
import json
import torch
import torch.nn as nn
from torch.utils.data import Dataset,DataLoader
from NeuralNetwork import bag_of_words , tokenize , stem
from Brain import NeuralNet

with open('intents.json','r') as f:
    intents = json.load(f)

all_words = []
tags = []
xy = []

for intent in intents['intents']:
    tag = intent['tag']
    tags.append(tag)

    for pattern in intent['patterns']:
        w = tokenize(pattern)
        all_words.extend(w)
        xy.append((w,tag))

ignore_words = [',','?','/','.','!']
all_words = [stem(w) for w in all_words if w not in ignore_words]
all_words = sorted(set(all_words))
tags = sorted(set(tags))

x_train = []
y_train = []

for (pattern_sentence,tag) in xy:
    bag = bag_of_words(pattern_sentence,all_words)
    x_train.append(bag)

    label = tags.index(tag)
    y_train.append(label)

x_train = np.array(x_train)
y_train = np.array(y_train)

num_epochs = 1000
batch_size = 8
learning_rate = 0.001
input_size = len(x_train[0])
hidden_size = 8
output_size = len(tags)

print("Training the model...")

class ChatDataset(Dataset):

    def __init__(self):
        self.n_samples = len(x_train)
        self.x_data = x_train
        self.y_data = y_train

    def __getitem__(self,index):
        return self.x_data[index],self.y_data[index]

    def __len__(self):
        return self.n_samples

dataset = ChatDataset()

train_loader = DataLoader(dataset=dataset,
                            batch_size=batch_size,
                            shuffle=True,
                            num_workers=0)

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = NeuralNet(input_size,hidden_size,output_size).to(device=device)
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(),lr=learning_rate)

for epoch in range(num_epochs):
    for (words,labels) in train_loader:
        words = words.to(device)
        labels = labels.to(dtype=torch.long).to(device)
        outputs = model(words)
        loss = criterion(outputs,labels)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

    if (epoch+1) % 100 == 0:
        print(f'Epoch [{epoch+1}/{num_epochs}], Loss: {loss.item():.4f}')

print(f'Final Loss : {loss.item():.4f}')

data = {
"model_state":model.state_dict(),
"input_size":input_size,
"hidden_size":hidden_size,
"output_size":output_size,
"all_words":all_words,
"tags":tags
}

FILE = "TrainData.pth"
torch.save(data,FILE)

print(f"Training Completed, File Saved to {FILE}")
</code>```

This is the program which contains all the layers of the neural network which I have named as Brain.py-

```<code>import torch.nn as nn

class NeuralNet(nn.Module):

    def __init__(self,input_size,hidden_size,num_classes):
        super(NeuralNet,self).__init__()
        self.l1 = nn.Linear(input_size,hidden_size)
        self.l2 = nn.Linear(input_size,hidden_size)
        self.l3 = nn.Linear(hidden_size,num_classes)
        self.relu = nn.ReLU()

    def forward(self,x):
        out = self.l1(x)
        out = self.relu(out)
        out = self.l2(out)
        out = self.relu(out)
        out = self.l3(out)
        return out

</code>```

And this is the error which VSCode is sending me-

```<code>File "f:/Aryav files/J.A.R.V.I.S/J.A.R.V.I.S. Mark III/Train.py", line 81, in <module>
    outputs = model(words)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\torch\nn\modules\module.py", line 1102, in _call_impl
    return forward_call(*input, **kwargs)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\torch\nn\modules\linear.py", line 103, in forward
    return F.linear(input, self.weight, self.bias)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\torch\nn\functional.py", line 1848, in linear
    return torch._C._nn.linear(input, weight, bias)
RuntimeError: mat1 and mat2 shapes cannot be multiplied (8x8 and 15x8)
</code>```

I am a very beginner in programming so please tell me the exact line no. and the line which I need to replace it with. Thank You

答:
Refer to PyTorch documentation, nn.Linear has input size and output size as arguments.

So, in your network here:

def __init__(self,input_size,hidden_size,num_classes):
    super(NeuralNet,self).__init__()
    self.l1 = nn.Linear(input_size,hidden_size)
    self.l2 = nn.Linear(input_size,hidden_size)
    self.l3 = nn.Linear(hidden_size,num_classes)
    self.relu = nn.ReLU()
```
<p><code>l1</code> takes <code>input_size</code> of features and outputs <code>hidden_size</code> of features.
<code>l2</code> also takes <code>input_size</code> of features and outputs <code>hidden_size</code> of features.
It will only work if <code>input_size == hidden_size</code>, which I think, in this case, is not the same.</p>
<p>What you want to achieve is to specify all the hidden layers with <code>hidden_size</code> nodes, right?
Then, a simple fix would be</p>
<pre class="lang-py prettyprint-override"><code>self.l1 = nn.Linear(input_size,hidden_size)
self.l2 = nn.Linear(hidden_size,hidden_size)
self.l3 = nn.Linear(hidden_size,num_classes)
</code>```

Then, the inputs and outputs between layers should match.

Sidenote, I think you need another instance of ReLU. This is considered bad, reason is posted here.

Body:
So I have been making an A.I. program with 0 experience in coding in python just as a hobby. While making the training file, I faced an error and I am not able to solve it.

This is my Training file-

import numpy as np
import json
import torch
import torch.nn as nn
from torch.utils.data import Dataset,DataLoader
from NeuralNetwork import bag_of_words , tokenize , stem
from Brain import NeuralNet

with open('intents.json','r') as f:
    intents = json.load(f)

all_words = []
tags = []
xy = []

for intent in intents['intents']:
    tag = intent['tag']
    tags.append(tag)

    for pattern in intent['patterns']:
        w = tokenize(pattern)
        all_words.extend(w)
        xy.append((w,tag))

ignore_words = [',','?','/','.','!']
all_words = [stem(w) for w in all_words if w not in ignore_words]
all_words = sorted(set(all_words))
tags = sorted(set(tags))

x_train = []
y_train = []

for (pattern_sentence,tag) in xy:
    bag = bag_of_words(pattern_sentence,all_words)
    x_train.append(bag)

    label = tags.index(tag)
    y_train.append(label)

x_train = np.array(x_train)
y_train = np.array(y_train)

num_epochs = 1000
batch_size = 8
learning_rate = 0.001
input_size = len(x_train[0])
hidden_size = 8
output_size = len(tags)

print("Training the model...")

class ChatDataset(Dataset):

    def __init__(self):
        self.n_samples = len(x_train)
        self.x_data = x_train
        self.y_data = y_train

    def __getitem__(self,index):
        return self.x_data[index],self.y_data[index]

    def __len__(self):
        return self.n_samples

dataset = ChatDataset()

train_loader = DataLoader(dataset=dataset,
                            batch_size=batch_size,
                            shuffle=True,
                            num_workers=0)

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = NeuralNet(input_size,hidden_size,output_size).to(device=device)
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(),lr=learning_rate)

for epoch in range(num_epochs):
    for (words,labels) in train_loader:
        words = words.to(device)
        labels = labels.to(dtype=torch.long).to(device)
        outputs = model(words)
        loss = criterion(outputs,labels)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

    if (epoch+1) % 100 == 0:
        print(f'Epoch [{epoch+1}/{num_epochs}], Loss: {loss.item():.4f}')

print(f'Final Loss : {loss.item():.4f}')

data = {
"model_state":model.state_dict(),
"input_size":input_size,
"hidden_size":hidden_size,
"output_size":output_size,
"all_words":all_words,
"tags":tags
}

FILE = "TrainData.pth"
torch.save(data,FILE)

print(f"Training Completed, File Saved to {FILE}")

This is the program which contains all the layers of the neural network which I have named as Brain.py-

import torch.nn as nn

class NeuralNet(nn.Module):

    def __init__(self,input_size,hidden_size,num_classes):
        super(NeuralNet,self).__init__()
        self.l1 = nn.Linear(input_size,hidden_size)
        self.l2 = nn.Linear(input_size,hidden_size)
        self.l3 = nn.Linear(hidden_size,num_classes)
        self.relu = nn.ReLU()

    def forward(self,x):
        out = self.l1(x)
        out = self.relu(out)
        out = self.l2(out)
        out = self.relu(out)
        out = self.l3(out)
        return out

And this is the error which VSCode is sending me-

File "f:/Aryav files/J.A.R.V.I.S/J.A.R.V.I.S. Mark III/Train.py", line 81, in <module>
    outputs = model(words)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\torch\nn\modules\module.py", line 1102, in _call_impl
    return forward_call(*input, **kwargs)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\torch\nn\modules\linear.py", line 103, in forward
    return F.linear(input, self.weight, self.bias)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\torch\nn\functional.py", line 1848, in linear
    return torch._C._nn.linear(input, weight, bias)
RuntimeError: mat1 and mat2 shapes cannot be multiplied (8x8 and 15x8)

I am a very beginner in programming so please tell me the exact line no. and the line which I need to replace it with. Thank You

Body:
Refer to PyTorch documentation, nn.Linear has input size and output size as arguments.

So, in your network here:

def __init__(self,input_size,hidden_size,num_classes):
    super(NeuralNet,self).__init__()
    self.l1 = nn.Linear(input_size,hidden_size)
    self.l2 = nn.Linear(input_size,hidden_size)
    self.l3 = nn.Linear(hidden_size,num_classes)
    self.relu = nn.ReLU()

l1 takes input_size of features and outputs hidden_size of features.
l2 also takes input_size of features and outputs hidden_size of features.
It will only work if input_size == hidden_size, which I think, in this case, is not the same.

What you want to achieve is to specify all the hidden layers with hidden_size nodes, right?
Then, a simple fix would be

self.l1 = nn.Linear(input_size,hidden_size)
self.l2 = nn.Linear(hidden_size,hidden_size)
self.l3 = nn.Linear(hidden_size,num_classes)

Then, the inputs and outputs between layers should match.

Sidenote, I think you need another instance of ReLU. This is considered bad, reason is posted here.


问:
How to detect user keyboard is Persian or English when press numeric keys
I want to detect that the user keyboard is English or Persian when it press numeric keys.

I'm using following code for non numeric keys, but it doesn't work on numeric keys!

```<code>  <input type="text" onkeyup="findType(this)">
<script>
  function findType(element) {
    let char = new RegExp("[\u0600-\u06FF]");
    if (char.test(element.value) === true) {
        element.style.direction =  "rtl"
    }
    else {
        element.style.direction =  "ltr"
    }
}
</script>
</code>```

Persian digits 0 to 9 unicode are from &#1776 to &#1785

答:
one way to approach this problem is to take advantage of navigator.language
Here is a reference to the documentation

```<code>let keyboard = () => {
  let lang = navigator.language;
  if (lang === 'ar') {
    return 'arabic';
  }
}
window.onload = keyboard;
</code>```

This worked when I switched my Chrome Browser default language to Arabic, and I was able to detect the language switch. A quick note, it did not work when I enabled the keyboard on my MAC to Arabic.

Once we have detected the keyboard language you can complete the remainder of your tasks.

For older Internet Explorer browsers, I believe you need to use window.navigator.userLanguage depending on the level of support your task requirements.

Another idea, might be to test to data type of the key being pressed, assuming the data types might be different from country to country

```<code>let key_pressed = (e) => {
  let key = e.keyCode;
  return typeof key;
}

window.addEventListener('keydown', (e) => {
  let key = key_pressed(e);
  console.log(key);
})
</code>```

Body:
I want to detect that the user keyboard is English or Persian when it press numeric keys.

I'm using following code for non numeric keys, but it doesn't work on numeric keys!

  <input type="text" onkeyup="findType(this)">

Persian digits 0 to 9 unicode are from &#1776 to &#1785

Body:
one way to approach this problem is to take advantage of navigator.language
Here is a reference to the documentation

let keyboard = () => {
  let lang = navigator.language;
  if (lang === 'ar') {
    return 'arabic';
  }
}
window.onload = keyboard;

This worked when I switched my Chrome Browser default language to Arabic, and I was able to detect the language switch. A quick note, it did not work when I enabled the keyboard on my MAC to Arabic.

Once we have detected the keyboard language you can complete the remainder of your tasks.

For older Internet Explorer browsers, I believe you need to use window.navigator.userLanguage depending on the level of support your task requirements.

Another idea, might be to test to data type of the key being pressed, assuming the data types might be different from country to country

let key_pressed = (e) => {
  let key = e.keyCode;
  return typeof key;
}

window.addEventListener('keydown', (e) => {
  let key = key_pressed(e);
  console.log(key);
})


问:
How to automate commands from the command prompt?
I tried doing this in python and found questions here and here that look relevant, but I couldn't get it working from those answers. I am looking for a way to automate a manual process where I first change the directory and folder from the command prompt as follows.

```<code>d:
</code>```

then

```<code>cd vph
</code>```

then from the command prompt I run the following:

```<code>krr filename.xdf -vph 1,129 -s "StartFrequency: " -StartFrequency -n
</code>```

The last line causes a frequency to be displayed at the command prompt. How can I save to a text file the frequency the last line returns, and how can I automate all the steps above? These steps need to be automated so I can do the same for over a thousand files. I worry nobody reading this has the krr software I need to use. If necessary, you can substitute the last line for something that will run on any windows computer and return a number. The "double-quotes" in the last line might be tricky if the last line needs to be in "double quotes".

答:
```<code>import subprocess
#list of commands to be executed can be given one after another and add && between the commands.
#Only when the first command execution is successful the next command will get executed
lst_cmd = "d && cd  vph && krr filename.xdf -vph 1,129 -s 'StartFrequency: ' -StartFrequency -n"
out,err = subprocess.Popen(lst_cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE).communicate()
print ("the output is {}".format(out))
</code>```

Body:
I tried doing this in python and found questions here and here that look relevant, but I couldn't get it working from those answers. I am looking for a way to automate a manual process where I first change the directory and folder from the command prompt as follows.

d:

then

cd vph

then from the command prompt I run the following:

krr filename.xdf -vph 1,129 -s "StartFrequency: " -StartFrequency -n

The last line causes a frequency to be displayed at the command prompt. How can I save to a text file the frequency the last line returns, and how can I automate all the steps above? These steps need to be automated so I can do the same for over a thousand files. I worry nobody reading this has the krr software I need to use. If necessary, you can substitute the last line for something that will run on any windows computer and return a number. The "double-quotes" in the last line might be tricky if the last line needs to be in "double quotes".


问:
How to get previous day's records in MongodDB?
I am using MongoDB which has a time field in milliseconds. I am trying to get all the records for previous day.
So far I have searched for solutions which show how to get the records for previous 24 hrs. But I need records for previous day only. Please help to write this query.
So something like this

```<code>createdTime: {
     $lt: new Date().getTime(),
     $gt: new Date().getTime() - 1000 * 60 * 60 * 24,
},
</code>```

But like I explained this is not what I want.

答:
```<code>var date = new Date();
date ; //# => today date

var yesterdayDate =  date.setDate(date.getDate() - 1);

createdTime: {
    $lt: date,
    $gt: yesterdayDate,
}
</code>```

Body:
I am using MongoDB which has a time field in milliseconds. I am trying to get all the records for previous day.
So far I have searched for solutions which show how to get the records for previous 24 hrs. But I need records for previous day only. Please help to write this query.
So something like this

createdTime: {
     $lt: new Date().getTime(),
     $gt: new Date().getTime() - 1000 * 60 * 60 * 24,
},

But like I explained this is not what I want.


问:
Printing dynamic content with javascript
Problem

We have page with form.

User fill the form and submit it.

I need to print page with data from form and some other content.

Code #1

```<code>$(document).ready(function($){
 $('input[name=sumb_but]').bind('click', function(e){
  e.preventDefault();
  var print_text = "<p>Test " + $('#form').serialize() + "</p>";
  var newWin = window.open('','printWindow','Toolbar=0,Location=0,Directories=0,Status=0,Menubar=0,Scrollbars=0,Resizable=0');
  newWin.document.body.innerHTML = print_text;
  newWin.print();
  });
});
</code>```

Cool, but:

I need specific css

Print window appear before content was loaded... ooops

Ok!

Code #2

```<code>$(document).ready(function($){
 $('input[name=sumb_but]').bind('click', function(e){
  e.preventDefault();
  var print_text = "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'> <html xmlns='http://www.w3.org/1999/xhtml'> <head> <meta http-equiv='Content-Type' content='text/html; charset=windows-1251' /> <title>Оформление доверенности (простая письменная форма)</title> <link rel='stylesheet' type='text/css' href='/css/print_forms/warrant.css'> </head> <body> <p>Test " + $('#form').serialize() + "</p></body><script type='text/javascript'>window.print();</script></html>";
  var newWin = window.open('','printWindow','Toolbar=0,Location=0,Directories=0,Status=0,Menubar=0,Scrollbars=0,Resizable=0');
  newWin.document.write(print_text);
  });
});
</code>```

document.write - in other case css not loading

At the and of content added "window.print()"

That works fine in all browsers, but not in IE - windows with content loading successfully without printing dialog.
I need help!

p.s.

CSS with media="print" - not good solution for this case for some reason.

答:
```<code>$(document).ready(function($){
 $('input[name=sumb_but]').bind('click', function(e){
  e.preventDefault();
  var print_text = "<p>Test " + $('#form').serialize() + "</p>";
  var newWin = window.open('','printWindow','Toolbar=0,Location=0,Directories=0,Status=0,Menubar=0,Scrollbars=0,Resizable=0');
  newWin.document.body.innerHTML = print_text;
  newWin.document.body.onload = function() { newWin.print(); }

  });
});
</code>```

this could help

Body:
Problem

We have page with form.

User fill the form and submit it.

I need to print page with data from form and some other content.

Code #1

$(document).ready(function($){
 $('input[name=sumb_but]').bind('click', function(e){
  e.preventDefault();
  var print_text = "
Test " + $('#form').serialize() + "
";
  var newWin = window.open('','printWindow','Toolbar=0,Location=0,Directories=0,Status=0,Menubar=0,Scrollbars=0,Resizable=0');
  newWin.document.body.innerHTML = print_text;
  newWin.print();
  });
});

Cool, but:

I need specific css

Print window appear before content was loaded... ooops

Ok!

Code #2

$(document).ready(function($){
 $('input[name=sumb_but]').bind('click', function(e){
  e.preventDefault();
  var print_text = "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>   <meta http-equiv='Content-Type' content='text/html; charset=windows-1251' /> <title>Оформление доверенности (простая письменная форма)</title> <link rel='stylesheet' type='text/css' href='/css/print_forms/warrant.css'>
Test " + $('#form').serialize() + "
";
  var newWin = window.open('','printWindow','Toolbar=0,Location=0,Directories=0,Status=0,Menubar=0,Scrollbars=0,Resizable=0');
  newWin.document.write(print_text);
  });
});

document.write - in other case css not loading

At the and of content added "window.print()"

That works fine in all browsers, but not in IE - windows with content loading successfully without printing dialog.
I need help!

p.s.

CSS with media="print" - not good solution for this case for some reason.

Body:
$(document).ready(function($){
 $('input[name=sumb_but]').bind('click', function(e){
  e.preventDefault();
  var print_text = "<p>Test " + $('#form').serialize() + "</p>";
  var newWin = window.open('','printWindow','Toolbar=0,Location=0,Directories=0,Status=0,Menubar=0,Scrollbars=0,Resizable=0');
  newWin.document.body.innerHTML = print_text;
  newWin.document.body.onload = function() { newWin.print(); }

  });
});

this could help


问:
IntelliJ refuses to setup Gradle JVM: Found invalid Gradle JVM configuration
I have the following problem: I try to setup IntelliJ to use my local Gradle installation but when IDEA starts I get the following error message after importing my project:

```<code>Found invalid Gradle JVM configuration
</code>```

gradle jar works perfectly fine on the command line.

The workaround is to manually do the following:

Find action -> Search -> Gradle -> Then select 'Gradle JVM:' option on the popup

Override 'Use Gradle from:' and choose 'Specificed location' (In my case /home/jose/local/gradle/gradle-4.10.3)

Override 'Gradle JVM:' and choose 'JAVA_HOME' (Shows up correctly as 'version 1.8.0_282')

Click 'Apply' and 'OK'. Restart IntelliJ

But reading the documentation about the Gradle settings and Gradle JVM selection says than IntelliJ will honor the following settings for the gradle wrapper properties (default choice):

JAVA_HOME (Defined to /opt/myjdkhome/1.8.0_282)

GRADLE_USER_HOME (Defined to $HOME/.gradle)

I'm using IntelliJ Idea Community Edition 2021.2.2

And more important, I do have the following overrides on the $HOME/.gradle/gradle.properties

org.gradle.jvmargs=-Xmx2024m -XX:MaxPermSize=512m
org.gradle.daemon=false
org.gradle.java.home=/opt/myjdkhome/1.8.0_282
systemProp.http.proxyHost=proxy.company.com
systemProp.http.proxyPort=8080
systemProp.http.nonProxyHosts=*.company.com
systemProp.https.proxyHost=proxy.company.com
systemProp.https.proxyPort=8080
systemProp.https.nonProxyHosts=*.company.com
systemProp.javax.net.ssl.keyStore=/etc/pki/ca-trust/extracted/java/cacerts
systemProp.javax.net.ssl.keyStorePassword=changeit
systemProp.javax.net.ssl.trustStore=/etc/pki/ca-trust/extracted/java/cacerts
systemProp.javax.net.ssl.trustStorePassword=XXXX
# systemProp.javax.net.debug=ssl:handshake
```
<p>The gradle wrapper property file, gradle/wrapper/gradle-wrapper.properties (generated with <code>gradle wrapper</code>) is pretty vanilla:</p>
<pre class="lang-java prettyprint-override"><code>distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.3-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
</code>```

Any ideas? I was thinking about dropping a XML partial configuration on $PROJECT_ROOT/.idea/gradle.xml but not sure if this will work. There is a way to override that for ALL the projects?

<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="GradleSettings">
    <option name="linkedExternalProjectsSettings">
      <GradleProjectSettings>
        <option name="delegatedBuild" value="true" />
        <option name="testRunner" value="GRADLE" />
        <option name="distributionType" value="LOCAL" />
        <option name="externalProjectPath" value="$PROJECT_DIR$" />
        <option name="gradleHome" value="$USER_HOME$/local/gradle/gradle-4.10.3" />
        <option name="gradleJvm" value="#JAVA_HOME" />
        <option name="modules">
          </set>
        </option>
      </GradleProjectSettings>
    </option>
  </component>
</project>
```

Thanks,

答: It looks like a known bug. Please follow for updates.</p>

Body:
I have the following problem: I try to setup IntelliJ to use my local Gradle installation but when IDEA starts I get the following error message after importing my project:

Found invalid Gradle JVM configuration

gradle jar works perfectly fine on the command line.

The workaround is to manually do the following:

Find action -> Search -> Gradle -> Then select 'Gradle JVM:' option on the popup

Override 'Use Gradle from:' and choose 'Specificed location' (In my case /home/jose/local/gradle/gradle-4.10.3)

Override 'Gradle JVM:' and choose 'JAVA_HOME' (Shows up correctly as 'version 1.8.0_282')

Click 'Apply' and 'OK'. Restart IntelliJ

But reading the documentation about the Gradle settings and Gradle JVM selection says than IntelliJ will honor the following settings for the gradle wrapper properties (default choice):

JAVA_HOME (Defined to /opt/myjdkhome/1.8.0_282)

GRADLE_USER_HOME (Defined to $HOME/.gradle)

I'm using IntelliJ Idea Community Edition 2021.2.2

And more important, I do have the following overrides on the $HOME/.gradle/gradle.properties

org.gradle.jvmargs=-Xmx2024m -XX:MaxPermSize=512m
org.gradle.daemon=false
org.gradle.java.home=/opt/myjdkhome/1.8.0_282
systemProp.http.proxyHost=proxy.company.com
systemProp.http.proxyPort=8080
systemProp.http.nonProxyHosts=*.company.com
systemProp.https.proxyHost=proxy.company.com
systemProp.https.proxyPort=8080
systemProp.https.nonProxyHosts=*.company.com
systemProp.javax.net.ssl.keyStore=/etc/pki/ca-trust/extracted/java/cacerts
systemProp.javax.net.ssl.keyStorePassword=changeit
systemProp.javax.net.ssl.trustStore=/etc/pki/ca-trust/extracted/java/cacerts
systemProp.javax.net.ssl.trustStorePassword=XXXX
# systemProp.javax.net.debug=ssl:handshake

The gradle wrapper property file, gradle/wrapper/gradle-wrapper.properties (generated with gradle wrapper) is pretty vanilla:

distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.3-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

Any ideas? I was thinking about dropping a XML partial configuration on $PROJECT_ROOT/.idea/gradle.xml but not sure if this will work. There is a way to override that for ALL the projects?

<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="GradleSettings">
    <option name="linkedExternalProjectsSettings">
      <GradleProjectSettings>
        <option name="delegatedBuild" value="true" />
        <option name="testRunner" value="GRADLE" />
        <option name="distributionType" value="LOCAL" />
        <option name="externalProjectPath" value="$PROJECT_DIR$" />
        <option name="gradleHome" value="$USER_HOME$/local/gradle/gradle-4.10.3" />
        <option name="gradleJvm" value="#JAVA_HOME" />
        <option name="modules">
          </set>
        </option>
      </GradleProjectSettings>
    </option>
  </component>
</project>

Thanks,


问:
how can i create a grid with java using toStrings
Hi Im new to java and I would like to create a grid using java

I want my output to look like this

```<code>1 2
3 4
</code>```

How can I do it with just the toStrings method? I am thinking of using a constructor where if I put  (int 2) then it will give me this grid, and if it is  (int 3) then it will look like:

```<code>1 2 3
4 5 6
</code>```

答:
Since an answer was already provided, I will post mine:

```<code>public static void main(String[] args) throws Exception {
    int[][] matrix = {{1,2,3}, {4,5,6}, {7,8,9}};
    printGrid(matrix);
}

public static void printGrid(int[][] matrix) {
    for (int[] row : matrix) {
        for (int value : row) {
            System.out.print(value + " ");
        }
        System.out.println();
    }
}
</code>```

If you are really concerned about the extra space next to the value, add a string buffer and trim it out before displaying:

```<code>public static void printGrid(int[][] matrix) {
    for (int[] row : matrix) {
        StringBuilder buffer = new StringBuilder();
        for (int value : row) {
            buffer.append(value + " ");
        }
        System.out.println(buffer.toString().trim());
    }
}
</code>```

By the way, the output of this program is

```<code>1 2 3
4 5 6
7 8 9
</code>```

Body:
Hi Im new to java and I would like to create a grid using java

I want my output to look like this

1 2
3 4

How can I do it with just the toStrings method? I am thinking of using a constructor where if I put  (int 2) then it will give me this grid, and if it is  (int 3) then it will look like:

1 2 3
4 5 6

Body:
Since an answer was already provided, I will post mine:

public static void main(String[] args) throws Exception {
    int[][] matrix = {{1,2,3}, {4,5,6}, {7,8,9}};
    printGrid(matrix);
}

public static void printGrid(int[][] matrix) {
    for (int[] row : matrix) {
        for (int value : row) {
            System.out.print(value + " ");
        }
        System.out.println();
    }
}

If you are really concerned about the extra space next to the value, add a string buffer and trim it out before displaying:

public static void printGrid(int[][] matrix) {
    for (int[] row : matrix) {
        StringBuilder buffer = new StringBuilder();
        for (int value : row) {
            buffer.append(value + " ");
        }
        System.out.println(buffer.toString().trim());
    }
}

By the way, the output of this program is

1 2 3
4 5 6
7 8 9


问:
C++ DLL Not Receiving Passed Variables
I am trying to write a C++ DLL that will receive two long values, sum them, and then return the result. I'm doing this testing as a way to attempt to fix a 20+ year old C++ DLL that needs some fine-tuning to be 64-bit compliant and my skills in C++ are rusty at best. So I'm starting simple with basic math and I can't seem to get it to work. I'm calling the DLL from VBA but I don't think it's my VBA that's the issue.

C++ Header File

```<code>#pragma once

#define DLL_EXPORT _declspec (dllexport)

class __declspec(dllexport) CalculationApi
{
public:
    long Addition(long* value1, long* value2);
};
</code>```

C++ CPP File

```<code>#include "pch.h"
#include "Calculation.h"
#include "windows.h"
#include "string"
#include<iostream>

using namespace std;

long DLL_EXPORT __stdcall CalculationApi::Addition(long* value1, long* value2)
{
    long return_result;
    string MsgBoxMessage;

    string Integer1_Type = typeid(*value1).name();

    string test_integer_text = std::to_string(*value1);

    MsgBoxMessage = "Value1 is: " + to_string(*value1);
    MessageBox(NULL, MsgBoxMessage.c_str(), "Value of Value1", MB_OK);

    MsgBoxMessage = "Value1 Data Type is: " + Integer1_Type;
    MessageBox(NULL, MsgBoxMessage.c_str(), "Data Type of Value1", MB_OK);

    MsgBoxMessage = "Value2 is: " + to_string(*value2);
    MessageBox(NULL, MsgBoxMessage.c_str(), "Value of Value2", MB_OK);

    return_result = *value1 + *value2;

    *value1 = 50;

    MsgBoxMessage = "Value1 is: " + to_string(*value1);
    MessageBox(NULL, MsgBoxMessage.c_str(), "Value of Value1", MB_OK);

    MsgBoxMessage = "Result is: " + to_string(return_result);
    MessageBox(NULL, MsgBoxMessage.c_str(), "Math Results", MB_OK);

    return return_result;

}
</code>```

And just in case I messed up the VBA here's how I call the DLL

```<code>Private Declare PtrSafe Function Addition Lib "C:\Users\micha\source\repos\CalculationDll\x64\Debug\CalculationDll.dll" (value1 As LongPtr, value2 As LongPtr) As LongPtr

Function DLL_Testing()
    Dim value1 As LongPtr
    Dim value2 As LongPtr
    Dim Results As LongPtr

    value1 = 10
    value2 = 20

    Results = Addition(integer1, integer2)

    test = 0

End Function
</code>```

The first messagebox in the C++ comes up blank... I'm sure I'm just not doing something right there but meh doesn't matter much. The second messagebox returns either 0 or some really funky number.  The VBA will return the result "583141696^" which of course is not 10+20.  Also the value1 doesn't get updated to 50, I'm pretty sure I'm not passing the pointer correctly as I've seen value2 update when I changed the value of value1 in the DLL.

This all seems REALLY basic yet it doesn't work. Thoughts?

答:
I think Addition should be static :

```<code>static long Addition(long* value1, long* value2);
</code>```

because if Addition is not static, a third (hidden) parameter (this) exist...

and the class CalculationApi is not really usefull here.

Title: C++ DLL Not Receiving Passed Variables

Body:
I am trying to write a C++ DLL that will receive two long values, sum them, and then return the result. I'm doing this testing as a way to attempt to fix a 20+ year old C++ DLL that needs some fine-tuning to be 64-bit compliant and my skills in C++ are rusty at best. So I'm starting simple with basic math and I can't seem to get it to work. I'm calling the DLL from VBA but I don't think it's my VBA that's the issue.

C++ Header File

#pragma once

#define DLL_EXPORT _declspec (dllexport)

class __declspec(dllexport) CalculationApi
{
public:
    long Addition(long* value1, long* value2);
};

C++ CPP File

#include "pch.h"
#include "Calculation.h"
#include "windows.h"
#include "string"
#include<iostream>

using namespace std;

long DLL_EXPORT __stdcall CalculationApi::Addition(long* value1, long* value2)
{
    long return_result;
    string MsgBoxMessage;

    string Integer1_Type = typeid(*value1).name();

    string test_integer_text = std::to_string(*value1);

    MsgBoxMessage = "Value1 is: " + to_string(*value1);
    MessageBox(NULL, MsgBoxMessage.c_str(), "Value of Value1", MB_OK);

    MsgBoxMessage = "Value1 Data Type is: " + Integer1_Type;
    MessageBox(NULL, MsgBoxMessage.c_str(), "Data Type of Value1", MB_OK);

    MsgBoxMessage = "Value2 is: " + to_string(*value2);
    MessageBox(NULL, MsgBoxMessage.c_str(), "Value of Value2", MB_OK);

    return_result = *value1 + *value2;

    *value1 = 50;

    MsgBoxMessage = "Value1 is: " + to_string(*value1);
    MessageBox(NULL, MsgBoxMessage.c_str(), "Value of Value1", MB_OK);

    MsgBoxMessage = "Result is: " + to_string(return_result);
    MessageBox(NULL, MsgBoxMessage.c_str(), "Math Results", MB_OK);

    return return_result;

}

And just in case I messed up the VBA here's how I call the DLL

Private Declare PtrSafe Function Addition Lib "C:\Users\micha\source\repos\CalculationDll\x64\Debug\CalculationDll.dll" (value1 As LongPtr, value2 As LongPtr) As LongPtr

Function DLL_Testing()
    Dim value1 As LongPtr
    Dim value2 As LongPtr
    Dim Results As LongPtr

    value1 = 10
    value2 = 20

    Results = Addition(integer1, integer2)

    test = 0

End Function

The first messagebox in the C++ comes up blank... I'm sure I'm just not doing something right there but meh doesn't matter much. The second messagebox returns either 0 or some really funky number.  The VBA will return the result "583141696^" which of course is not 10+20.  Also the value1 doesn't get updated to 50, I'm pretty sure I'm not passing the pointer correctly as I've seen value2 update when I changed the value of value1 in the DLL.

This all seems REALLY basic yet it doesn't work. Thoughts?

Body:
I think Addition should be static :

static long Addition(long* value1, long* value2);

because if Addition is not static, a third (hidden) parameter (this) exist...

and the class CalculationApi is not really usefull here.


问:
Are all desktop/laptop monitor's orientation similar to landscape orientation on devices like the iPad?
Are all desktop/laptop monitor's orientation similar to landscape orientation on devices like the iPad?

Is there any difference between?

```<code>body {background:red}

@media only screen and  (orientation : landscape) {
    body {background:blue}
}
</code>```

答:
Are all Desktop/laptop Monitor's orientation similar to Landscape orientation on devices like iPad?

No they are not. The orientation is based on the width and height of the window.

Landscape Mode is when the window width is larger than window height.

Portrait Mode is when the window height is larger than window width.

You can see this using your example: http://jsfiddle.net/tw16/EaHhU/

Adjust the width of the results window to match the above scenarios and you will see the colour change.

Desktop Browser Support: Firefox 3.5+, Google Chrome 5+, Opera 10.6+, Safari 4+

Mobile Browser Support: Android 2+, iOS4, Mobile Firefox.

Body:
Are all desktop/laptop monitor's orientation similar to landscape orientation on devices like the iPad?

Is there any difference between?

body {background:red}

@media only screen and  (orientation : landscape) {
    body {background:blue}
}


答:
You could get rid of all the preceding (...) in one go with rpartition:

def run_reshape_addr(text):
    _, _, text["address"] = text["address"].rpartition(")")
```
<pre class="lang-py prettyprint-override"><code>a = "Correct-Horse-Battery-Staple"
b = "Troubadour"

a.rpartition("-") == ("Correct-Horse-Battery", "-", "Staple")
b.rpartition("-") == ("", "", "Troubadour")
</code>```

Title: IndexError: string index out of range - if function with dataframe

Body:
I try to eliminate brackets and unnecessary marks in the dataframe.

Here's what my data look like:

df["address"]

index  address
0       (#)(△)Kaohsiung City
1       (△)New Taipei City
2       (O)Chiayi City
.
.

Currently I'm using this:

def reshape_address(addr):
    if addr[0] == "(":
        return addr.split(")", 1)[-1]
    else:
        return addr

def run_reshape_addr(text):
    text["address"] = text["address"].apply(reshape_address)
    text["address"] = text["address"].apply(reshape_address)
    text["address"] = text["address"].apply(reshape_address)
#run three times in order to get rid of multiple brackets

run_reshape_addr(df)

Somehow I got the IndexError: string index out of range.
However, a partial of data have been executed successfully after this run even the error message pops up.

How can I revise this? And why were some of the data still being executed under this circumstance? Thank you.

Body:
You could get rid of all the preceding (...) in one go with rpartition:

def run_reshape_addr(text):
    _, _, text["address"] = text["address"].rpartition(")")

a = "Correct-Horse-Battery-Staple"
b = "Troubadour"

a.rpartition("-") == ("Correct-Horse-Battery", "-", "Staple")
b.rpartition("-") == ("", "", "Troubadour")


问:
How do I manage DNS names for a Keycloak deployment on a local docker compose environment?
I have a docker compose with several services:

```<code>version: "3.9"
services:
  mysql:
    image: mysql:8.0
    ...

  auth-service:
    image: mykeycloakimage:latest
    ...

  rest-service:
    image: myrestserviceimage:latest
    ...

  web-ui:
    image: mywebuiimage:latest
    ...

  proxy-service:
    image: mynginximage:latest
    ...
</code>```

I also have /etc/hosts edited on my workstation so everything points to localhost:

```<code>127.0.0.1 auth-service.mylocal.com
127.0.0.1 rest-api.mylocal.com
127.0.0.1 web-ui.mylocal.com
</code>```

The web-ui container is an Angular app, secured with keycloak-angular 9.1.0.  This is working fine - I hit a restricted page, login, and get a JWT bearer token back.  This is then passed back to my REST service with the header Authorization: bearer [token].

The problem then comes however when the REST service (a Spring Boot backend secured with keycloak-spring-boot-starter) goes to authenticate that bearer token.  To match the resource/realm, it needs to reach out to auth-service.mylocal.com, but that only exists in the host's /etc/hosts file.

I've tried:

Using just auth-service in the REST authentication - but then this won't match the incoming bearer token.

Using just auth-service in the /etc/hosts file - but then I can't share cookies between the web-ui and rest-service containers, which I need to do.

Using auth-service.mylocal.com everywhere - the REST service doesn't natively know what this is, and when it reaches out to it's DNS provider it bypasses the host's /etc/host settings, so it can't find this domain name.

Using extra hosts on the REST container - this doesn't really work, because it's inside the docker compose context, and if I set it to 127.0.0.1 it would point at the local container, not the host.

I think I can't use host networking because I'm on macos.

So... How are people setting this up for local testing/development?  How do you manage the auth token in an Angular app (or other front end), pass that back to a back end service, and have the back end service use the token - all from inside a local docker compose (or swarm or probably k8) context?

答:
I'll post what I arrived at here:

#1 - Use network aliases in the compose file.  So something of the form:

```<code>    networks:
      backend:
        aliases:
          - auth-service.mylocal.com
</code>```

This will tell anything on the backend network to route auth-service.mylocal.com to this service.

#2 - Place the network alias on the proxy server, not the actual auth service.  Assuming the auth service isn't running on port 80, you'll still want nginx to do the mapping from 80->8080 or whatever (plus whatever other voodoo you have nginx doing).

#3 - Adjust the proxy service and docker compose so nginx is listening (at least for auth service requests) on port 80.

Body:
I have a docker compose with several services:

version: "3.9"
services:
  mysql:
    image: mysql:8.0
    ...

  auth-service:
    image: mykeycloakimage:latest
    ...

  rest-service:
    image: myrestserviceimage:latest
    ...

  web-ui:
    image: mywebuiimage:latest
    ...

  proxy-service:
    image: mynginximage:latest
    ...

I also have /etc/hosts edited on my workstation so everything points to localhost:

127.0.0.1 auth-service.mylocal.com
127.0.0.1 rest-api.mylocal.com
127.0.0.1 web-ui.mylocal.com

The web-ui container is an Angular app, secured with keycloak-angular 9.1.0.  This is working fine - I hit a restricted page, login, and get a JWT bearer token back.  This is then passed back to my REST service with the header Authorization: bearer [token].

The problem then comes however when the REST service (a Spring Boot backend secured with keycloak-spring-boot-starter) goes to authenticate that bearer token.  To match the resource/realm, it needs to reach out to auth-service.mylocal.com, but that only exists in the host's /etc/hosts file.

I've tried:

Using just auth-service in the REST authentication - but then this won't match the incoming bearer token.

Using just auth-service in the /etc/hosts file - but then I can't share cookies between the web-ui and rest-service containers, which I need to do.

Using auth-service.mylocal.com everywhere - the REST service doesn't natively know what this is, and when it reaches out to it's DNS provider it bypasses the host's /etc/host settings, so it can't find this domain name.

Using extra hosts on the REST container - this doesn't really work, because it's inside the docker compose context, and if I set it to 127.0.0.1 it would point at the local container, not the host.

I think I can't use host networking because I'm on macos.

So... How are people setting this up for local testing/development?  How do you manage the auth token in an Angular app (or other front end), pass that back to a back end service, and have the back end service use the token - all from inside a local docker compose (or swarm or probably k8) context?

Body:
I'll post what I arrived at here:

#1 - Use network aliases in the compose file.  So something of the form:

    networks:
      backend:
        aliases:
          - auth-service.mylocal.com

This will tell anything on the backend network to route auth-service.mylocal.com to this service.

#2 - Place the network alias on the proxy server, not the actual auth service.  Assuming the auth service isn't running on port 80, you'll still want nginx to do the mapping from 80->8080 or whatever (plus whatever other voodoo you have nginx doing).

#3 - Adjust the proxy service and docker compose so nginx is listening (at least for auth service requests) on port 80.


问:
Custom Google Analytics API script is working, but running extremely slow
I am working on a project using the Google Analytics API for PHP.

Here is what I need to do: We have about 320 client websites that we track in our Google Analytics account. We are running into an issue where the Google Analytics code stops tracking (for various reasons) on some sites, and we would like to catch this issue before our clients catch it.

So, what I would like to accomplish is writing a script that checks all of our client sites within Google Analytics and calls the Reporting API and queries for the number of sessions for the last seven days. If there is no data over the last 7 days, the code is more than likely not tracking properly on the website.

I have created a new API project in Google and obtained a client email that I have added as a user with view permissions to each of my accounts within Google Analytics. I have a total of 63 accounts in my Google Analytics organized by state (New York Clients, Virginia Clients, Oregon Clients etc) and each of the accounts have multiple sub-accounts/profiles under each for a total of 320.

I have a script that is working, but it is taking a really long time to run. This script does work, as it gives me each profile in my Google Analytics that hasn’t had data over the last 7 days, but it takes about 65 seconds to run and sometimes I get a timeout error because of how long it is taking to run. I’m certain that this is because of the foreach loops that are making a TON of calls to the API. I feel like if I reduced the number of times I am calling the API, the script would run much faster. However, I’m not sure how I can code my script so that it makes fewer calls to the API.

Is there any way that I could speed up the script below by making fewer calls to the reporting API? Maybe I am going about this the wrong way and there is a more simple way to do what I want to accomplish?

Here is my working code currently:

```<code> // Load the Google API PHP Client Library.
 require_once __DIR__ . '/vendor/autoload.php';
 //initialize analytics
 $analytics = initializeAnalytics();
 //an array that I will be using below in the getProfileIds() function
 $ProfileIDWithDomain = array();
 //Calls a function to obtain all of the profile IDs to query against the Core reporting API
 $profiles = getProfileIds($analytics);
 //for each profile in the $ProfileIDWithDomain array query the reporting API to get data over
 last 7 days:

 foreach ($profiles as $key => $value){
     //$key is profile id $value is domain
     $results = getResults($analytics, $key);
     //print the results
     printResults($results,$key,$value);
 }

 function initializeAnalytics()
 {
   // Creates and returns the Analytics Reporting service object.

   // Use the developers console and download your service account
   // credentials in JSON format. Place them in this directory or
   // change the key file location if necessary.
   $KEY_FILE_LOCATION = __DIR__ . '/{KEY_FILE}';

   // Create and configure a new client object.
   $client = new Google_Client();
   $client->setApplicationName("GA Analytics Reporting");
   $client->setAuthConfig($KEY_FILE_LOCATION);
   $client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
   $analytics = new Google_Service_Analytics($client);

   return $analytics;
 }

 function getResults($analytics, $profileId) {
   // Calls the Core Reporting API and queries for the number of sessions
   // for the last seven days.
   return $analytics->data_ga->get(
        'ga:' . $profileId,
        '7daysAgo',
        'today',
        'ga:sessions');
 }

 function printResults($results, $profile,$domain) {
   // Parses the response from the Core Reporting API and prints
   // the profile name and total sessions.
   if (count($results->getRows()) < 1) {
     echo "<div class='item'>";
     print "No results found for $profile, domain name: $domain";
     echo "</div>";
   }
 }

 function getProfileIds($analytics) {

   // Get the list of accounts for the authorized user.
   $accounts = $analytics->management_accounts->listManagementAccounts();

   if (count($accounts->getItems()) > 0) {
     //get all 63 accounts in GA
     $items = $accounts->getItems();
     //array to store accounts
     $AccountIds = array();
     foreach ($items as $item) {
         //for each of the 63 accounts, store the account ID in an array
         $AccountIds[] = $item->getId();
     }
     //now for each Account ID, we will obtain the properties
     foreach ($AccountIds as $id){

         // Get the list of properties for the authorized user.
         $properties = $analytics->management_webproperties->listManagementWebproperties($id);
         //if there are more than on item in the properties list (multuple profiles under it)
         if (count($properties->getItems()) > 0) {
            $items = $properties->getItems();
            $i = 0;
            if(count($items) > 1){
            foreach($items as $item){
                  //for each item in the property list, get the id
                  $currentPropertyID = $item->getId();
                  //list management profiles for the id
                  $profiles = $analytics->management_profiles->listManagementProfiles($id, $currentPropertyID);
             if (count($profiles->getItems()) > 0) {
                  $user = $profiles->getItems();
                  // Store the ID with an associated URL/domain name
                  $ProfileIDWithDomain[$user[0]->getId()] = str_replace($removeChar, "", $items[$i]["websiteUrl"]);

                  } else {
                     throw new Exception('No views (profiles) found for this user.');
                  }
                  $i++;
              }
           }
           else{
              //only one item in the properties list
              $currentPropertyID = $items[0]->getId();
              //list management profiles for the id
              $profiles = $analytics->management_profiles->listManagementProfiles($id, $currentPropertyID);
              if (count($profiles->getItems()) > 0) {
                 $user = $profiles->getItems();
                 // Store the ID with an associated URL/domain name
                 $ProfileIDWithDomain[$user[0]->getId()] = str_replace($removeChar, "", $items[0]["websiteUrl"]);

              } else {
                 throw new Exception('No views (profiles) found for this user.');
              }
           }

         } else {
           throw new Exception('No properties found for this user.');
         }
     }
   } else {
     throw new Exception('No accounts found for this user.');
   }
   //return an associative array with ID => URL/Domain name for each profile
   return $ProfileIDWithDomain;
 }
</code>```

答:
You are doing a lot of calls there.

List all accounts
List all web properies in each account
List all views in each web propertie.

You can get the same results back with one call to account summaries list

Something like this.

```<code>$service->accountSummaries->ListAccountSummaries($optParams);
</code>```

Body:
I am working on a project using the Google Analytics API for PHP.

Here is what I need to do: We have about 320 client websites that we track in our Google Analytics account. We are running into an issue where the Google Analytics code stops tracking (for various reasons) on some sites, and we would like to catch this issue before our clients catch it.

So, what I would like to accomplish is writing a script that checks all of our client sites within Google Analytics and calls the Reporting API and queries for the number of sessions for the last seven days. If there is no data over the last 7 days, the code is more than likely not tracking properly on the website.

I have created a new API project in Google and obtained a client email that I have added as a user with view permissions to each of my accounts within Google Analytics. I have a total of 63 accounts in my Google Analytics organized by state (New York Clients, Virginia Clients, Oregon Clients etc) and each of the accounts have multiple sub-accounts/profiles under each for a total of 320.

I have a script that is working, but it is taking a really long time to run. This script does work, as it gives me each profile in my Google Analytics that hasn’t had data over the last 7 days, but it takes about 65 seconds to run and sometimes I get a timeout error because of how long it is taking to run. I’m certain that this is because of the foreach loops that are making a TON of calls to the API. I feel like if I reduced the number of times I am calling the API, the script would run much faster. However, I’m not sure how I can code my script so that it makes fewer calls to the API.

Is there any way that I could speed up the script below by making fewer calls to the reporting API? Maybe I am going about this the wrong way and there is a more simple way to do what I want to accomplish?

Here is my working code currently:

 // Load the Google API PHP Client Library.
 require_once __DIR__ . '/vendor/autoload.php';
 //initialize analytics
 $analytics = initializeAnalytics();
 //an array that I will be using below in the getProfileIds() function
 $ProfileIDWithDomain = array();
 //Calls a function to obtain all of the profile IDs to query against the Core reporting API
 $profiles = getProfileIds($analytics);
 //for each profile in the $ProfileIDWithDomain array query the reporting API to get data over
 last 7 days:

 foreach ($profiles as $key => $value){
     //$key is profile id $value is domain
     $results = getResults($analytics, $key);
     //print the results
     printResults($results,$key,$value);
 }

 function initializeAnalytics()
 {
   // Creates and returns the Analytics Reporting service object.

   // Use the developers console and download your service account
   // credentials in JSON format. Place them in this directory or
   // change the key file location if necessary.
   $KEY_FILE_LOCATION = __DIR__ . '/{KEY_FILE}';

   // Create and configure a new client object.
   $client = new Google_Client();
   $client->setApplicationName("GA Analytics Reporting");
   $client->setAuthConfig($KEY_FILE_LOCATION);
   $client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
   $analytics = new Google_Service_Analytics($client);

   return $analytics;
 }

 function getResults($analytics, $profileId) {
   // Calls the Core Reporting API and queries for the number of sessions
   // for the last seven days.
   return $analytics->data_ga->get(
        'ga:' . $profileId,
        '7daysAgo',
        'today',
        'ga:sessions');
 }

 function printResults($results, $profile,$domain) {
   // Parses the response from the Core Reporting API and prints
   // the profile name and total sessions.
   if (count($results->getRows()) < 1) {
     echo "
";
     print "No results found for $profile, domain name: $domain";
     echo "
";
   }
 }

 function getProfileIds($analytics) {

   // Get the list of accounts for the authorized user.
   $accounts = $analytics->management_accounts->listManagementAccounts();

   if (count($accounts->getItems()) > 0) {
     //get all 63 accounts in GA
     $items = $accounts->getItems();
     //array to store accounts
     $AccountIds = array();
     foreach ($items as $item) {
         //for each of the 63 accounts, store the account ID in an array
         $AccountIds[] = $item->getId();
     }
     //now for each Account ID, we will obtain the properties
     foreach ($AccountIds as $id){

         // Get the list of properties for the authorized user.
         $properties = $analytics->management_webproperties->listManagementWebproperties($id);
         //if there are more than on item in the properties list (multuple profiles under it)
         if (count($properties->getItems()) > 0) {
            $items = $properties->getItems();
            $i = 0;
            if(count($items) > 1){
            foreach($items as $item){
                  //for each item in the property list, get the id
                  $currentPropertyID = $item->getId();
                  //list management profiles for the id
                  $profiles = $analytics->management_profiles->listManagementProfiles($id, $currentPropertyID);
             if (count($profiles->getItems()) > 0) {
                  $user = $profiles->getItems();
                  // Store the ID with an associated URL/domain name
                  $ProfileIDWithDomain[$user[0]->getId()] = str_replace($removeChar, "", $items[$i]["websiteUrl"]);

                  } else {
                     throw new Exception('No views (profiles) found for this user.');
                  }
                  $i++;
              }
           }
           else{
              //only one item in the properties list
              $currentPropertyID = $items[0]->getId();
              //list management profiles for the id
              $profiles = $analytics->management_profiles->listManagementProfiles($id, $currentPropertyID);
              if (count($profiles->getItems()) > 0) {
                 $user = $profiles->getItems();
                 // Store the ID with an associated URL/domain name
                 $ProfileIDWithDomain[$user[0]->getId()] = str_replace($removeChar, "", $items[0]["websiteUrl"]);

              } else {
                 throw new Exception('No views (profiles) found for this user.');
              }
           }

         } else {
           throw new Exception('No properties found for this user.');
         }
     }
   } else {
     throw new Exception('No accounts found for this user.');
   }
   //return an associative array with ID => URL/Domain name for each profile
   return $ProfileIDWithDomain;
 }

Body:
You are doing a lot of calls there.

List all accounts
List all web properies in each account
List all views in each web propertie.

You can get the same results back with one call to account summaries list

Something like this.

$service->accountSummaries->ListAccountSummaries($optParams);


问:
Use of eval in a target recipe
In a Makefile I'm writing I had an interest in cleaning up some of the CC prints and centralizing some of the build preparations (like creating directories in the build tree). I figured macros would be a good fit for this task. This is effectively what im trying to do, used all over various Makefiles:

```<code>define func
    @mkdir -p $$(dir $(1))
    @printf "%-5s $(2)\n" $(3)
endef

test:
    @echo Run
    $(eval $(call func,a,b,c))
</code>```

My thought was that after first expansion I'd get something like (less any tabs maybe, I'm not exactly sure how the expansion works within eval):

```<code>test:
    @echo Run
    $(eval @mkdir -p $(dir a)\n@printf "%-5s b\n" c
</code>```

and of course finally the commands would be executed. However, what I get is this:

```<code># make
Makefile:7: *** recipe commences before first target.  Stop.
</code>```

I changed eval to info and got this:

```<code>        @mkdir -p $(dir a)
        @printf "%-5s b\n" c
Run
</code>```

So I thought maybe my explicit tabs in the macro definition were causing trouble, so I removed them and tried again:

```<code># make
Makefile:7: *** missing separator.  Stop.
</code>```

So it still does not quite work. If it is indeed possible at all, it seems some function of indentions in the macro, or maybe I'm defining the macros incorrectly. I thought perhaps the two commands in the macro was causing trouble (since the complaint is regarding a separator), but reducing the macro to a single line did not help either.

答:
You don't want eval here.  Eval is used to evaluate makefile syntax.  That is, the thing you're evaluation has to be a valid, complete makefile.  You can see that what info prints is not a valid makefile.  If you put that into a file and ran make -f <file>, you'd get a syntax error.

You are just trying to expand a variable for shell syntax.  Just remove the eval.

Title: Use of eval in a target recipe

Body:
In a Makefile I'm writing I had an interest in cleaning up some of the CC prints and centralizing some of the build preparations (like creating directories in the build tree). I figured macros would be a good fit for this task. This is effectively what im trying to do, used all over various Makefiles:

define func
    @mkdir -p $$(dir $(1))
    @printf "%-5s $(2)\n" $(3)
endef

test:
    @echo Run
    $(eval $(call func,a,b,c))

My thought was that after first expansion I'd get something like (less any tabs maybe, I'm not exactly sure how the expansion works within eval):

test:
    @echo Run
    $(eval @mkdir -p $(dir a)\n@printf "%-5s b\n" c

and of course finally the commands would be executed. However, what I get is this:

# make
Makefile:7: *** recipe commences before first target.  Stop.

I changed eval to info and got this:

        @mkdir -p $(dir a)
        @printf "%-5s b\n" c
Run

So I thought maybe my explicit tabs in the macro definition were causing trouble, so I removed them and tried again:

# make
Makefile:7: *** missing separator.  Stop.

So it still does not quite work. If it is indeed possible at all, it seems some function of indentions in the macro, or maybe I'm defining the macros incorrectly. I thought perhaps the two commands in the macro was causing trouble (since the complaint is regarding a separator), but reducing the macro to a single line did not help either.


问:
Why does extracting a specific git tag to a /tmp directory mess up the working tree?
Because I wanted to look at the files in the last release, tagged v2.1, to run it in isolation from my working directory, I created a tmp directory

```<code>mkdir /tmp/lastRelease
</code>```

and extracted the last release in that directory

```<code>git --work-tree=/tmp/lastRelease checkout tags/v2.1 -- .
</code>```

The files are indeed extracted just fine to /tmp/lastRelease.

But now when I run git status in the working directory I find that very many files (all the files modified since tag v2.1?) appear as staged for commit, and another long list of files (that are in HEAD) appears as not staged for commit.

Was this last command the right way to extract a specific tag? How do I reset to HEAD? (The obvious git checkout HEAD doesn't modify what git status says, even though the files are there.)

答:
This is only a partial answer. I don't know why the working directory gets messed up when extracting to an unrelated directory, but it's possible to return to a sane state—the one where the repo was just before the git --work-tree... command—by running:

```<code>git reset --hard HEAD
</code>```

Body:
Because I wanted to look at the files in the last release, tagged v2.1, to run it in isolation from my working directory, I created a tmp directory

mkdir /tmp/lastRelease

and extracted the last release in that directory

git --work-tree=/tmp/lastRelease checkout tags/v2.1 -- .

The files are indeed extracted just fine to /tmp/lastRelease.

But now when I run git status in the working directory I find that very many files (all the files modified since tag v2.1?) appear as staged for commit, and another long list of files (that are in HEAD) appears as not staged for commit.

Was this last command the right way to extract a specific tag? How do I reset to HEAD? (The obvious git checkout HEAD doesn't modify what git status says, even though the files are there.)

Body:
This is only a partial answer. I don't know why the working directory gets messed up when extracting to an unrelated directory, but it's possible to return to a sane state—the one where the repo was just before the git --work-tree... command—by running:

git reset --hard HEAD


问:
bestway to parse xml services in javascript?
I am new to javascript.I wanted to parse xml and displayed in javascript.I used the following code.it did not give output?any help please? what is advantage if we use jQuery  and difference between normal javascript and jQuery?`

```<code>  <script type="text/javascript" src="jquery.js"></script>
  <script type="text/javascript">
    $(document).ready(function(){
     $.get("http://www.hindu.com/rss/01hdline.xml", function(response){
     var response = $.paseXML(response);
      var $xml = $(response);

   //Now you can find any xml node with $xml using various methods of jQuery
  //E.g
   alert($xml.find( "title" ));
  });
  });
</code>```

答:
If you used jQuery you dont have to write all the code which you have written, jQuery will do it for you and it works across all the browsers. Also it has built in utility to parse xml using which you can easily traverse through the xml document and write you logic. Try this

```<code>$.get("http://www.hindu.com/rss/01hdline.xml", function(response){
   var response = $.paseXML(response);
   var $xml = $(response);

   //Now you can find any xml node with $xml using various methods of jQuery
   //E.g
   alert($xml.find( "title" ));
});
</code>```

The reason your code is not working because

You cannot do cross-domain XMLHttpRequests.

You might instead consider either XMLHttp-request your own server to fetch the remote XML content for you (php script, for example)

Body:
If you used jQuery you dont have to write all the code which you have written, jQuery will do it for you and it works across all the browsers. Also it has built in utility to parse xml using which you can easily traverse through the xml document and write you logic. Try this

$.get("http://www.hindu.com/rss/01hdline.xml", function(response){
   var response = $.paseXML(response);
   var $xml = $(response);

   //Now you can find any xml node with $xml using various methods of jQuery
   //E.g
   alert($xml.find( "title" ));
});

The reason your code is not working because

You cannot do cross-domain XMLHttpRequests.

You might instead consider either XMLHttp-request your own server to fetch the remote XML content for you (php script, for example)