问:
printing of xml
I want to print the array into xml format but i am unable to print it.
Here is the code

```<code>if(!empty($recordsArray)){
print("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n>");
print("<joblist>\n");
foreach ($recordsArray as $data){
</code>```

print("".$data['user_id']."".$data['$task_id']."\n");

```<code>}
print("</joblist>\n");

}
}
</code>```

even i am unable to see

```<code><?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n>
</code>```

when i am doing view source its showing

```<code><?xml version="1.0" encoding="UTF-8" ?>
<joblist>
<job><id>123</id><taskid>14</taskid></job>
</joblist>
</code>```

now what to be done to display on the web page

答:
If you want it to be viewed in the browser, instead of what is most likely your server's default, "text/html", you need to serve the file as "text/xml" or "application/xml".

You might not be able to see the tags because they are treated as bogus HTML (though they are no doubt in the source code if you view source)--though admittedly you should see any text inside the elements.

In any case, you will want to create a header (before you do any printing, including printing whitespace) anyways, to ensure it is displayed and treated as XML by the user's browser, by adding:

```<code>header('Content-type:application/xml;charset=utf8');
</code>```

ContentLicense: CC BY-SA 3.0

Title: printing of xml

Body:
I want to print the array into xml format but i am unable to print it.
Here is the code

if(!empty($recordsArray)){
print("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n>");
print("<joblist>\n");
foreach ($recordsArray as $data){

print("".$data['user_id']."".$data['$task_id']."\n");

}
print("</joblist>\n");

}
}

even i am unable to see

<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n>

when i am doing view source its showing

<?xml version="1.0" encoding="UTF-8" ?>
<joblist>
<job><id>123</id><taskid>14</taskid></job>
</joblist>

now what to be done to display on the web page

Body:
If you want it to be viewed in the browser, instead of what is most likely your server's default, "text/html", you need to serve the file as "text/xml" or "application/xml".

You might not be able to see the tags because they are treated as bogus HTML (though they are no doubt in the source code if you view source)--though admittedly you should see any text inside the elements.

In any case, you will want to create a header (before you do any printing, including printing whitespace) anyways, to ensure it is displayed and treated as XML by the user's browser, by adding:

header('Content-type:application/xml;charset=utf8');


来源: stackexchange

问:
Azure Data Factory Lookup and For Each
I have a Data Factory Pipeline that I want to have iterate through the rows of a SQL Lookup activity. I have narrowed the query down to three columns and 500 rows.

I understand that to reference a value in the table I use:

```<code>@{activity('lookupActivity').output.value[row#].colname}
</code>```

However, the for each needs to have something to iterate over. My first guess is to set some array variable to the rows of the returned sql query. So what do I set that variable to?

```<code>@{activity('lookupActivity').output.value?
</code>```

Lastly, it looks like almost all data is represented as a json in ADF, is this true? And how could I view the output of this look up as a json so I can understand what my dynamic content needs to look like?

答:
You're right that everything (nearly) is JSON.  (Exception: Azure Data Factory v2: Activity execute pipeline output

So you can put your @activity('lookupActivity').output.value which is an array into the foreach activity on the settings tab, like this

Then inside your foreach loop, you reference the current value of one of the columns as @item().colname.

ContentLicense: CC BY-SA 4.0

Title: Azure Data Factory Lookup and For Each

Body:
I have a Data Factory Pipeline that I want to have iterate through the rows of a SQL Lookup activity. I have narrowed the query down to three columns and 500 rows.

I understand that to reference a value in the table I use:

@{activity('lookupActivity').output.value[row#].colname}

However, the for each needs to have something to iterate over. My first guess is to set some array variable to the rows of the returned sql query. So what do I set that variable to?

@{activity('lookupActivity').output.value?

Lastly, it looks like almost all data is represented as a json in ADF, is this true? And how could I view the output of this look up as a json so I can understand what my dynamic content needs to look like?


问:
How to find window ID in a REMOTE linuix
I connect to a remote linux using ssh and I need to get only a window with x11vnc, i.e., I need to execute:

x11vnc -id  -display :0

Every command I try in the ssh session (xprop, wmcrtl, etc.) returns info about the local xwindows system, not about the remote one, so I don't know how to get information of the windows running in the remote machine.

I can't get the while desktop with x11vnc because it is locked and I get only a black screen. I would try the '-id pick' option if had access to the desktop.

答:
Every command I try in the ssh session (xprop, wmcrtl, etc.) returns info about the local xwindows system, not about the remote one

I assume this is because you connect using ssh -X or something similar. That way ssh sets DISPLAY to point to a tunnel it created to your local X server so that remote commands can display output on your screen. Try to override this variable, examples: DISPLAY=:0 xwininfo -tree -root or DISPLAY=:0 xprop -root|grep ^_NET_CLIENT_LIST.


问:
Data Frame - changing of the nested variable
We are discussing data that is imported from excel

```<code>ene2 = pd.read_excel('Energy Indicators.xls', index=False)
</code>```

recently I asked in post, where answers were clear, straightforward and brought success.

Changing Values of elements in Pandas Datastructure

However I went steps further, and I have similar (sic!) problem, where assigning variable does not change anything.

Lets consider Data Structure

```<code>print(ene2.head())
</code>```

               Country Energy Supply Energy Supply per Capita % Renewable's
    15             NaN    Gigajoules               Gigajoules             %
    16     Afghanistan     321000000                       10       78.6693
    17         Albania     102000000                       35           100
    18        Algeria1    1959000000                       51       0.55101
    19  American Samoa           ...                      ...      0.641026

238                            Viet Nam    2554000000                       28       45.3215
239           Wallis and Futuna Islands             0                       26             0
240                               Yemen     344000000                       13             0
241                              Zambia     400000000                       26       99.7147
242                            Zimbabwe     480000000                       32       52.5361
243                                 NaN           NaN                      NaN           NaN
244                                 NaN           NaN                      NaN           NaN
```

<p>where some countries have index (like Algieria1 or Australia12)
I want to change those names to become just Algieria, Australia and so on.</p>

<p>There is in total 20 entries that suppose to be changed.
I developed a method to do it, which at the last step fails..</p>

```for value in ene2['Country']:
    if type(value) == float: # to cover NaN values
        continue

    x = re.findall("\D+\d", value) # to find those countries/elements which are with number

    while len(x) > 0: # this shows elements with number, otherwise answer is [], which is 0
        for letters in x: # to touch letters
            right = letters[:-1] # and get rid of the last number
            ene2.loc[ene2['Country'] == value, 'Country'] = right # THIS IS ELEMENT WHICH FAILS <= it does not chagne the value
        x = re.findall("\D+\d", value) # to bring the new value to the while loop
```

Code above should make the task, to finally remove all the indexes from the names,
however the code - ene2.loc[...] which used to work previously, here, where is nested, just do nothing.

What could be the case that this exchange does not work, how can I overcome the problem a) in a old style way b) in the Panda way?

答:
The code suggest you already use pandas, so why not use the built-in replace method with regex?

```<code>df = pd.DataFrame(data=["Afghanistan","Albania", "Algeria1", "Algeria9999"], columns=["Country"])
df["Country_clean"] = df["Country"].str.replace(r'\d+$', '')
</code>```

output:

```<code>print(df["Country_clean"])

0    Afghanistan
1        Albania
2        Algeria
3        Algeria
Name: Country, dtype: object
</code>```

Body:
We are discussing data that is imported from excel

ene2 = pd.read_excel('Energy Indicators.xls', index=False)

recently I asked in post, where answers were clear, straightforward and brought success.

Changing Values of elements in Pandas Datastructure

However I went steps further, and I have similar (sic!) problem, where assigning variable does not change anything.

Lets consider Data Structure

print(ene2.head())

               Country Energy Supply Energy Supply per Capita % Renewable's
    15             NaN    Gigajoules               Gigajoules             %
    16     Afghanistan     321000000                       10       78.6693
    17         Albania     102000000                       35           100
    18        Algeria1    1959000000                       51       0.55101
    19  American Samoa           ...                      ...      0.641026

238                            Viet Nam    2554000000                       28       45.3215
239           Wallis and Futuna Islands             0                       26             0
240                               Yemen     344000000                       13             0
241                              Zambia     400000000                       26       99.7147
242                            Zimbabwe     480000000                       32       52.5361
243                                 NaN           NaN                      NaN           NaN
244                                 NaN           NaN                      NaN           NaN

where some countries have index (like Algieria1 or Australia12)
I want to change those names to become just Algieria, Australia and so on.

There is in total 20 entries that suppose to be changed.
I developed a method to do it, which at the last step fails..

for value in ene2['Country']:
    if type(value) == float: # to cover NaN values
        continue

    x = re.findall("\D+\d", value) # to find those countries/elements which are with number

    while len(x) > 0: # this shows elements with number, otherwise answer is [], which is 0
        for letters in x: # to touch letters
            right = letters[:-1] # and get rid of the last number
            ene2.loc[ene2['Country'] == value, 'Country'] = right # THIS IS ELEMENT WHICH FAILS <= it does not chagne the value
        x = re.findall("\D+\d", value) # to bring the new value to the while loop

Code above should make the task, to finally remove all the indexes from the names,
however the code - ene2.loc[...] which used to work previously, here, where is nested, just do nothing.

What could be the case that this exchange does not work, how can I overcome the problem a) in a old style way b) in the Panda way?

Body:
The code suggest you already use pandas, so why not use the built-in replace method with regex?

df = pd.DataFrame(data=["Afghanistan","Albania", "Algeria1", "Algeria9999"], columns=["Country"])
df["Country_clean"] = df["Country"].str.replace(r'\d+$', '')

output:

print(df["Country_clean"])

0    Afghanistan
1        Albania
2        Algeria
3        Algeria
Name: Country, dtype: object


问:
jquery, submit form after google maps geocoding
I have a form which collects a persons address.  When they click submit I want to geocode their address, and use that to fill lat and lng fields.  Here is what I am doing now which is based on the 2nd answer here submit form does not stop in jquery ajax call

```<code><script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
    $(document).ready(function() {
        var geocoder;
        var address;
        $('#theform').submit(function() {
            geocoder = new google.maps.Geocoder();
            address = $('#id_street').val() + " " + $('#id_street2').val() + " " + $('#id_city').val() + ", " + $('#id_state').val() + " " + $('#id_zip').val();
            geocoder.geocode( { 'address': address}, function(results, status) {
              if (status == google.maps.GeocoderStatus.OK) {
                $('#id_lat').val(results[0].geometry.location.lat().toFixed(6));
                $('#id_lng').val(results[0].geometry.location.lng().toFixed(6));
                $('#theform').unbind('submit');
                $('#theform').submit();
              } else {
                $('#theform').unbind('submit');
                $('#theform').submit();
              }
            });
            return false;
        });
    });
</script>
</code>```

and the form

```<code><form method="POST" id="theform" action="">
    <li><label for="id_street">Street</label> <input id="id_street" type="text" name="street" value="3520 Lebon Dr." maxlength="100" /></li>
    <li><label for="id_street2">Street2 (optional)</label> <input id="id_street2" type="text" name="street2" maxlength="100" /></li>
    <li><label for="id_city">City</label> <input id="id_city" type="text" name="city" value="San Diego" maxlength="50" /></li>
    <li><label for="id_state">State</label> <select name="state" id="id_state">
    ...a bunch of state options...
    <li><label for="id_zip">Zip Code</label> <input id="id_zip" type="text" name="zip" value="92122" maxlength="30" /></li>
    <label for="id_lat">Latitude</label><input type="text" name="lat" value="0.000000" id="id_lat" />
    <label for="id_lng">Longitude</label><input type="text" name="lng" value="0.000000" id="id_lng" />
</form>
</code>```

The lat and lng fields get filled fine, but the form does not actually get submitted by $('#theform').submit().  To actually submit the form you have to click submit again.

Any ideas about what I am doing wrong?
And in case anyone asks I do want to submit the form even if geocoding is unsuccessful as in that case I will be using geopy to geocode the address server side.

edit:
Ok so I made a really simple example and can't get submit to work at all:

```<code><html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>

<script type="text/javascript">
$(function() {
    $('#subby').click(function() {
        $('#theform').submit();
    });
});

</script>

</head>
<body>
<a href="#" id="subby">Submit</a>
<form id="#theform" action="javascript:alert('success!');">
      <input type="submit" />
</form>
</body>
</html>
</code>```

I would expect that when clicking the link Submit you would get an alertbox just like when you click the submit button, but this is not the case.  What am I doing wrong with submit?

答: I just figured it out.  I accidentally omitted my submit button from the form I posted.  It was named submit.  Apparently that mucks things up for jquery (thanks here: jQuery doesn't submit a form).  The simple example I posted still isn't working and I'm not sure why but my actual problem is solved.</p>

Body:
I have a form which collects a persons address.  When they click submit I want to geocode their address, and use that to fill lat and lng fields.  Here is what I am doing now which is based on the 2nd answer here submit form does not stop in jquery ajax call

and the form

<form method="POST" id="theform" action="">

Street <input id="id_street" type="text" name="street" value="3520 Lebon Dr." maxlength="100" />

Street2 (optional) <input id="id_street2" type="text" name="street2" maxlength="100" />

City <input id="id_city" type="text" name="city" value="San Diego" maxlength="50" />

State <select name="state" id="id_state">
    ...a bunch of state options...

Zip Code <input id="id_zip" type="text" name="zip" value="92122" maxlength="30" />

    Latitude<input type="text" name="lat" value="0.000000" id="id_lat" />
    Longitude<input type="text" name="lng" value="0.000000" id="id_lng" />
</form>

The lat and lng fields get filled fine, but the form does not actually get submitted by $('#theform').submit().  To actually submit the form you have to click submit again.

Any ideas about what I am doing wrong?
And in case anyone asks I do want to submit the form even if geocoding is unsuccessful as in that case I will be using geopy to geocode the address server side.

edit:
Ok so I made a really simple example and can't get submit to work at all:

Submit
<form id="#theform" action="javascript:alert('success!');">
      <input type="submit" />
</form>

I would expect that when clicking the link Submit you would get an alertbox just like when you click the submit button, but this is not the case.  What am I doing wrong with submit?


问:
things I don't get in python. bounded method acting like an alien
I don't understang this behaviour, I changed 'r' on the class 'f' and it is reflected back
on 'q' as you can see 'q.r' indicates that it is now referencing a 'lambda' function but at the same time the adress is always '0x037591F0' so why 'q.r()' is failling?</p>

```<code>class f:
    def r(self):
        print('bla bla bla')

>>> q=f()
>>> f.r
<function f.r at 0x0378F4B0>
>>> q.r
<bound method f.r of <__main__.f object at 0x037591F0>>
>>> f.r=lambda : 'google'
>>> f.r
<function <lambda> at 0x015F9348>
>>> q.r
<bound method <lambda> of <__main__.f object at 0x037591F0>>
>>> q.r()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: <lambda>() takes 0 positional arguments but 1 was given
</code>```

答:
In your case, r doesn't even start out as a static method, but even if it did, when you assign a lambda to r on the class, you're replacing it and it will no longer be a static method. So, when Python calls it, it will pass self as the first parameter.

```<code>import inspect

class C:
    @staticmethod
    def r():
        return 'x'

print(isinstance(inspect.getmro(C)[0].__dict__['r'], staticmethod))
C.r = lambda: 'y'
print(isinstance(inspect.getmro(C)[0].__dict__['r'], staticmethod))
</code>```

Result:

```<code>True
False
</code>```

Body:
I don't understang this behaviour, I changed 'r' on the class 'f' and it is reflected back
on 'q' as you can see 'q.r' indicates that it is now referencing a 'lambda' function but at the same time the adress is always '0x037591F0' so why 'q.r()' is failling?

class f:
    def r(self):
        print('bla bla bla')

>>> q=f()
>>> f.r
<function f.r at 0x0378F4B0>
>>> q.r
<bound method f.r of <__main__.f object at 0x037591F0>>
>>> f.r=lambda : 'google'
>>> f.r
<function <lambda> at 0x015F9348>
>>> q.r
<bound method <lambda> of <__main__.f object at 0x037591F0>>
>>> q.r()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: <lambda>() takes 0 positional arguments but 1 was given

Body:
In your case, r doesn't even start out as a static method, but even if it did, when you assign a lambda to r on the class, you're replacing it and it will no longer be a static method. So, when Python calls it, it will pass self as the first parameter.

import inspect

class C:
    @staticmethod
    def r():
        return 'x'

print(isinstance(inspect.getmro(C)[0].__dict__['r'], staticmethod))
C.r = lambda: 'y'
print(isinstance(inspect.getmro(C)[0].__dict__['r'], staticmethod))

Result:

True
False


问:
Selection aware keyBindingFn in draftjs
I'm experimenting with Draft.js, and I'm trying to emulate a little bit of markdown keybindings.

My thought is that if the cursor is at the start of a line (and there is no selection), I'd like the # key to increase the header level.

Now, I have code that works for this, but it seems a bit fragile.  The keyBindingFn(e) doesn't have access to the editor state, so I can only check if e.key === '#', and return 'increase-header-level'.  Then, in the handleKeyCommand, I can check the state to see if the user is at the beginning of the line. The unfortunate thing is that if they aren't, I have to manually update the content to add a # character.

It would make sense to me to make the keyBindingFn check the state, but I'm not sure if it would be safe to access the EditorState there, since it isn't being passed in.

```<code>    keyBindingFunction(e) {
        if (e.key === '#') {
            console.log('increase-header-level')
            return 'increase-header-level'
        }
        let defaultKeyBinding = Draft.getDefaultKeyBinding(e)
        console.log(defaultKeyBinding)
        return defaultKeyBinding

    }

    handleKeyCommand(command, editorState) {
        if (command === 'increase-header-level') {
            let selection = editorState.getSelection()
            if (selection.getStartKey() === selection.getEndKey()) {
                if (selection.getStartOffset() === 0) {
                    this.increaseHeaderLevel(editorState, selection);
                    return false
                }
            }
            const contentState = Draft.Modifier.replaceText(editorState.getCurrentContent(), editorState.getSelection(), "#")
            this.onChange(EditorState.push(editorState, contentState, 'insert-characters'))
            return true
        }
        let newState = RichUtils.handleKeyCommand(editorState, command)
        if (newState) {
            this.onChange(newState)
            return true
        }
        return false
    }

    render() {
        return (
            <div className="rich-editor-container">
                <Editor
                    editorState={this.state.editorState}
                    onChange={this.onChange}
                    handleKeyCommand={this.handleKeyCommand}
                    keyBindingFn={this.keyBindingFunction}
                />
            </div>
        )
    }

</code>```

答:
I think I figured out the way to do it:

```<code>    render() {
        let keyBindFunction;
        if (this.state.editorState.getSelection().getStartOffset() === 0) {
            keyBindFunction = (e) => { return e.key === '#' ? 'increase-header-level' : Draft.getDefaultKeyBinding(e)}
        }
        return (
            <div className="rich-editor-container">
                <Editor
                    editorState={this.state.editorState}
                    onChange={this.onChange}
                    handleKeyCommand={this.handleKeyCommand}
                    keyBindingFn={keyBindFunction}
                />
            </div>
        )
    }
</code>```

I'll clean it up with an isAtStartOfBlock function, and a mapping for key commands at the start of block, but this is good enough for a PoC.

If this could lead to some unexpected race condition, please let me know.  I don't want to have to hunt down strange failures in the future ;-)

Title: Selection aware keyBindingFn in draftjs

Body:
I'm experimenting with Draft.js, and I'm trying to emulate a little bit of markdown keybindings.

My thought is that if the cursor is at the start of a line (and there is no selection), I'd like the # key to increase the header level.

Now, I have code that works for this, but it seems a bit fragile.  The keyBindingFn(e) doesn't have access to the editor state, so I can only check if e.key === '#', and return 'increase-header-level'.  Then, in the handleKeyCommand, I can check the state to see if the user is at the beginning of the line. The unfortunate thing is that if they aren't, I have to manually update the content to add a # character.

It would make sense to me to make the keyBindingFn check the state, but I'm not sure if it would be safe to access the EditorState there, since it isn't being passed in.

    keyBindingFunction(e) {
        if (e.key === '#') {
            console.log('increase-header-level')
            return 'increase-header-level'
        }
        let defaultKeyBinding = Draft.getDefaultKeyBinding(e)
        console.log(defaultKeyBinding)
        return defaultKeyBinding

    }

    handleKeyCommand(command, editorState) {
        if (command === 'increase-header-level') {
            let selection = editorState.getSelection()
            if (selection.getStartKey() === selection.getEndKey()) {
                if (selection.getStartOffset() === 0) {
                    this.increaseHeaderLevel(editorState, selection);
                    return false
                }
            }
            const contentState = Draft.Modifier.replaceText(editorState.getCurrentContent(), editorState.getSelection(), "#")
            this.onChange(EditorState.push(editorState, contentState, 'insert-characters'))
            return true
        }
        let newState = RichUtils.handleKeyCommand(editorState, command)
        if (newState) {
            this.onChange(newState)
            return true
        }
        return false
    }

    render() {
        return (

                <Editor
                    editorState={this.state.editorState}
                    onChange={this.onChange}
                    handleKeyCommand={this.handleKeyCommand}
                    keyBindingFn={this.keyBindingFunction}
                />

        )
    }

Body:
I think I figured out the way to do it:

    render() {
        let keyBindFunction;
        if (this.state.editorState.getSelection().getStartOffset() === 0) {
            keyBindFunction = (e) => { return e.key === '#' ? 'increase-header-level' : Draft.getDefaultKeyBinding(e)}
        }
        return (
            <div className="rich-editor-container">
                <Editor
                    editorState={this.state.editorState}
                    onChange={this.onChange}
                    handleKeyCommand={this.handleKeyCommand}
                    keyBindingFn={keyBindFunction}
                />
            </div>
        )
    }

I'll clean it up with an isAtStartOfBlock function, and a mapping for key commands at the start of block, but this is good enough for a PoC.

If this could lead to some unexpected race condition, please let me know.  I don't want to have to hunt down strange failures in the future ;-)


问:
How can I combine these two async functions?
I'm looping thru a teams array getting team data and players for each team...

I have 2 async functions that pull the same data but I can't figure out how to combine them.

As it works currently, each loop adds the teamPlayers array to a players array in the first async function. On completion I have 1450 player objects in my players array. The second async function adds the team object to a teams array. On completion I have 32 team objects in my teams array.

I've tried changing the first async function to get data and then have the dispatch return a value of results.teamPlayers but I end up with a players array with 32 arrays each with x number of player objects.

```<code>async function loadRosters(endPoints, teams, authKey) {
    axios.defaults.headers.common['Authorization'] = authKey;

    const requests = teams.map(teamId => {
        try {
            return axios.get(endPoints.roster + teamId).then(r => r.data.teamPlayers);
        } catch (e) {
            console.log(e);
        }
        return [];
    });

    const results = (await Promise.all(requests)).flat();
    dispatch({ type: 'SET_PLAYERS', value: results });

    return results;
}

async function loadTeamData(endPoints, teams, authKey) {
    axios.defaults.headers.common['Authorization'] = authKey;

    const requests = teams.map(teamId => {
        try {
            return axios.get(endPoints.roster + teamId).then(r => r.data.team);
        } catch (e) {
            //
        }
        return [];
    });

    const results = (await Promise.all(requests)).flat();
    dispatch({ type: 'SET_TEAM_LOGOS', value: results });

    return results;
}
</code>```

Here is the structure of the data I'm getting:

```<code>{
  "team": {
    "teamId": "string",
    "abbr": "string",
    "logo": "string"
  },
  "teamPlayers": [
    {
      "firstName": "string",
      "lastName": "string",
      "esbId": "string",
      "position": "string",
      "jerseyNumber": 0,
      "teamAbbr": "string",
      "headshot": "string"
    }
  ]
}
</code>```

It may be simpler if I get the team.logo and add it to each player in teamPlayers.

答:
Just as a suggestion, why don't you create an endpoint that accepts multiple team IDs so you don't need to send multiple requests to the server, it can return all the data at once in an array? Also, having both a team and a teamPlayers key returning from that endpoint is slightly dubious design, at least semantically. Anyway, here's my best attempt:

async function loadTeams(endPoints, teams, authKey) {
    axios.defaults.headers.common['Authorization'] = authKey;

    const requests = teams.map(teamId =>
      axios.get(endPoints.roster + teamId).then(res => res.data, e => {
        console.error(e);
        return { teamPlayers: [], team: [] };
      })
    );

    const allTeamData = await Promise.all(requests);
    // Following variables will aggregate ALL players from ALL teams and
    // ALL logos (? it seems your logos are arrays, but that's a bit weird)
    const allTeamPlayers = [], allTeamLogos = [];

    for (const { teamPlayers, team } of allTeamData) {
      allTeamPlayers.push(...teamPlayers); // spread optional
      allTeamLogos.push(...team); // again, spread optional
    }

    dispatch({ type: 'SET_PLAYERS', value: allTeamPlayers });
    dispatch({ type: 'SET_TEAM_LOGOS', value: allTeamLogos });

    return { teamPlayers: allTeamPlayers, team: allTeamLogos };
}
```

Now you can call the function and get the teamPlayers or team keys of the result to get whatever you need.

Body:
I'm looping thru a teams array getting team data and players for each team...

I have 2 async functions that pull the same data but I can't figure out how to combine them.

As it works currently, each loop adds the teamPlayers array to a players array in the first async function. On completion I have 1450 player objects in my players array. The second async function adds the team object to a teams array. On completion I have 32 team objects in my teams array.

I've tried changing the first async function to get data and then have the dispatch return a value of results.teamPlayers but I end up with a players array with 32 arrays each with x number of player objects.

async function loadRosters(endPoints, teams, authKey) {
    axios.defaults.headers.common['Authorization'] = authKey;

    const requests = teams.map(teamId => {
        try {
            return axios.get(endPoints.roster + teamId).then(r => r.data.teamPlayers);
        } catch (e) {
            console.log(e);
        }
        return [];
    });

    const results = (await Promise.all(requests)).flat();
    dispatch({ type: 'SET_PLAYERS', value: results });

    return results;
}

async function loadTeamData(endPoints, teams, authKey) {
    axios.defaults.headers.common['Authorization'] = authKey;

    const requests = teams.map(teamId => {
        try {
            return axios.get(endPoints.roster + teamId).then(r => r.data.team);
        } catch (e) {
            //
        }
        return [];
    });

    const results = (await Promise.all(requests)).flat();
    dispatch({ type: 'SET_TEAM_LOGOS', value: results });

    return results;
}

Here is the structure of the data I'm getting:

{
  "team": {
    "teamId": "string",
    "abbr": "string",
    "logo": "string"
  },
  "teamPlayers": [
    {
      "firstName": "string",
      "lastName": "string",
      "esbId": "string",
      "position": "string",
      "jerseyNumber": 0,
      "teamAbbr": "string",
      "headshot": "string"
    }
  ]
}

It may be simpler if I get the team.logo and add it to each player in teamPlayers.

Body:
Just as a suggestion, why don't you create an endpoint that accepts multiple team IDs so you don't need to send multiple requests to the server, it can return all the data at once in an array? Also, having both a team and a teamPlayers key returning from that endpoint is slightly dubious design, at least semantically. Anyway, here's my best attempt:

async function loadTeams(endPoints, teams, authKey) {
    axios.defaults.headers.common['Authorization'] = authKey;

    const requests = teams.map(teamId =>
      axios.get(endPoints.roster + teamId).then(res => res.data, e => {
        console.error(e);
        return { teamPlayers: [], team: [] };
      })
    );

    const allTeamData = await Promise.all(requests);
    // Following variables will aggregate ALL players from ALL teams and
    // ALL logos (? it seems your logos are arrays, but that's a bit weird)
    const allTeamPlayers = [], allTeamLogos = [];

    for (const { teamPlayers, team } of allTeamData) {
      allTeamPlayers.push(...teamPlayers); // spread optional
      allTeamLogos.push(...team); // again, spread optional
    }

    dispatch({ type: 'SET_PLAYERS', value: allTeamPlayers });
    dispatch({ type: 'SET_TEAM_LOGOS', value: allTeamLogos });

    return { teamPlayers: allTeamPlayers, team: allTeamLogos };
}

Now you can call the function and get the teamPlayers or team keys of the result to get whatever you need.


问:
I simply want to upload a new build to an existing version. Keep getting ERROR ITMS-90062
I am trying to understand why I keep getting this error.

ERROR ITMS-90062: "This bundle is invalid. The value for key CFBundleShortVersionString [0.0.2] in the Info.plist file must contain a higher version than that of the previously approved version [3.11]. Please find more information about CFBundleShortVersionString at https://developer.apple.com/documentation/bundleresources/information_property_list/cfbundleshortversionstring"

Although we are building our app using Ionic / Cordova, the actual app is built using Xcode.

In Xcode 11.5, it is clearly marked as:
 - Version: 3.11
 - Build: 0.0.1

and when I go to AppStore Connect -> Activity, the current version that is marked as "Ready for Sale" is:
 - Version 3.11
 - Build 0.0.1

To me, it should be a simple process.  It I have a small fix, I want this to be Version 3.11, Build 0.0.2

'Version' is for major fixes/new features, and 'Build' is for minor fixes (typos, color changes, other aesthetics).

Yes, when I try to upload Version 3.11, Build 0.0.2 to the Appstore Connect, I get the ERROR ITMS-90062.

Any advice? I really don't know what I am doing wrong.

Derek

答:
Resolved!  The lightbulb went off :)

Each approved app must have a new, increasing Version Number.
We can upload multiple builds to App Store Connect (and TestFlight), each with an increasing Build Number, for any Version Number.  Only when testing is complete, then we submit one of those Builds for approval..and hence a new version bump.


问:
WF4, Promoted Properties, and Collections
What's the recommendation when needing to query an WF4 instance store for a collection of data?

For example, my workflow has a collection of Step objects that will be used to display to end users where at in the overall workflow they are.

How should I expose this data? I don't think property promotion is a good fit for collections. Should I just store this data in my own tables or is there a better way?

答: You are right, the property promotion is more geared towards simple values. There is a possibility to store more complex data in a serialized form in there but as that would make it very hard to query that is usually not very helpful. Your best bet would be to store the data in your own tables. If you want to ensure your data is always consistent with the workflow state stores you can use an PersistenceIOParticipant and update your tables as part of the same transaction that stores the workflow state. </p>


问:
Python/NumPy: find the first index of zero, then replace all elements with zero after that for each row
I have an numpy array like this:

```<code>a = np.array([[1, 0, 1, 1, 1],
              [1, 1, 1, 1, 0],
              [1, 0, 0, 1, 1],
              [1, 0, 1, 0, 1]])
</code>```

Question 1:
As shown in the title, I want to replace all elements with zero after the first zero appeared. The result should be like this :

```<code>a = np.array([[1, 0, 0, 0, 0],
              [1, 1, 1, 1, 0],
              [1, 0, 0, 0, 0],
              [1, 0, 0, 0, 0]])
</code>```

Question 2: how to slice different columns for each row like this example?
As I am dealing with an array with large size. If any one could find an efficient way to solve this please. Thank you very much.

答:
Question 1: An efficient way to do this would be the following.

import numpy as np

a = np.array([[1, 0, 1, 1, 1],
              [1, 1, 1, 1, 0],
              [1, 0, 0, 1, 1],
              [1, 0, 1, 0, 1]])

for row in a:
    zeros = np.where(row == 0)[0]
    if (len(zeros)):# Check if zero exists
        row[zeros[0]:] = 0

print(a)
```

<p>Output:</p>

```[[1 0 0 0 0]
 [1 1 1 1 0]
 [1 0 0 0 0]
 [1 0 0 0 0]]
```

<p><strong>Question 2</strong>: Using the same array, for each row <code>rowIdx</code>, you can have a array of columns <code>colIdxs</code> that you want to extract from.</p>

<pre class="lang-py prettyprint-override"><code>rowIdx = 2
colIdxs = [1, 3, 4]
print(a[rowIdx, colIdxs])
</code>```

Output:

```<code>[0 1 1]
</code>```

Body:
I have an numpy array like this:

a = np.array([[1, 0, 1, 1, 1],
              [1, 1, 1, 1, 0],
              [1, 0, 0, 1, 1],
              [1, 0, 1, 0, 1]])

Question 1:
As shown in the title, I want to replace all elements with zero after the first zero appeared. The result should be like this :

a = np.array([[1, 0, 0, 0, 0],
              [1, 1, 1, 1, 0],
              [1, 0, 0, 0, 0],
              [1, 0, 0, 0, 0]])

Question 2: how to slice different columns for each row like this example?
As I am dealing with an array with large size. If any one could find an efficient way to solve this please. Thank you very much.

Body:
Question 1: An efficient way to do this would be the following.

import numpy as np

a = np.array([[1, 0, 1, 1, 1],
              [1, 1, 1, 1, 0],
              [1, 0, 0, 1, 1],
              [1, 0, 1, 0, 1]])

for row in a:
    zeros = np.where(row == 0)[0]
    if (len(zeros)):# Check if zero exists
        row[zeros[0]:] = 0

print(a)

Output:

[[1 0 0 0 0]
 [1 1 1 1 0]
 [1 0 0 0 0]
 [1 0 0 0 0]]

Question 2: Using the same array, for each row rowIdx, you can have a array of columns colIdxs that you want to extract from.

rowIdx = 2
colIdxs = [1, 3, 4]
print(a[rowIdx, colIdxs])

Output:

[0 1 1]


问:
Creating eBooks using Affinity Publisher
I started using Affinity Publisher and then realized that it doesn't export to .mobi or .epub files.
So, I exported to PDF and then tried to convert it to an eBook format using Kindle Create. It gives me an output in .kpf format...
My question is whether I should use .kpf format? Will it even be supported in old devices? I'm surprised that Kindle Create is not converting to .mobi anymore. Any advice please? I cannot afford InDesign at the moment and I'm on Mac. </p>

答:
The bigger issue is that exporting as PDF fixes page boundaries, but eReaders strongly prefer not to have the document paginated, since the device size varies so much.  So I would say the whole approach is misguided.

I assume you're using Affinity Publisher rather than, say, Adobe InDesign due to Adobe's "rental software" policy.  I've made the same choice and am facing the same "no ebook support" issue.  People are recommending Jutoh, and for US$45, I just may try it.  If anyone else has experience with Jutoh, I'd be interested to hear about it.


问:
IONIC 4 ion-menu Menu ERROR when opening closing
I hope you are all doing well.

I am facing an issue with MENU Controller on IONIC 4 App.

When the user clicks on the MENU and opens it and closes it several times i get errors, also when it logs out and logs back in, and it crashes the app:

```<code>helpers-46f4a262.js:44 ASSERT: _before() should be called while animating

Uncaught (in promise) Error: ASSERT: _before() should be called while animating
    at assert (helpers-46f4a262.js:46)
    at Menu.afterAnimation (ion-menu_4-md.entry.js:340)
    at Menu._setOpen (ion-menu_4-md.entry.js:200)

beforeAnimation(shouldOpen) {
        assert(!this.isAnimating, '_before() should not be called while animating');
        // this places the menu into the correct location before it animates in
        // this css class doesn't actually kick off any animations
        this.el.classList.add(SHOW_MENU);
        if (this.backdropEl) {
            this.backdropEl.classList.add(SHOW_BACKDROP);
        }
        this.blocker.block();
        this.isAnimating = true;
        if (shouldOpen) {
            this.ionWillOpen.emit();
        }
        else {
            this.ionWillClose.emit();
        }
    }
    afterAnimation(isOpen) {
        assert(this.isAnimating, '_before() should be called while animating');
        // keep opening/closing the menu disabled for a touch more yet
        // only add listeners/css if it's enabled and isOpen
        // and only remove listeners/css if it's not open
        // emit opened/closed events
        this._isOpen = isOpen;
        this.isAnimating = false;
        if (!this._isOpen) {
            this.blocker.unblock();
        }
        if (isOpen) {
            // add css class
            if (this.contentEl) {
                this.contentEl.classList.add(MENU_CONTENT_OPEN);
            }
            // emit open event
            this.ionDidOpen.emit();
        }
        else {
            // remove css classes
            this.el.classList.remove(SHOW_MENU);
            if (this.contentEl) {
                this.contentEl.classList.remove(MENU_CONTENT_OPEN);
            }
            if (this.backdropEl) {
                this.backdropEl.classList.remove(SHOW_BACKDROP);
            }
            if (this.animation) {
                this.animation.stop();
            }
            // emit close event
            this.ionDidClose.emit();
        }
    }
</code>```

Click here for STREAMABLE Link Video

what is causing this?
any solution?

i have placed MENU to app.component.html

this is code:

```<code><ion-app>
  <ion-menu [disabled]="this.profileService.profile.length === 0 || selectedRouter.includes('subscriptions-and-packages')" (ionDidOpen)="openMenu($event)" (ionDidClose)="closeMenu($event)" side="end" menuId="first" contentId="content1">
        <ion-header>
          <ion-toolbar>
            <ion-title>{{ 'menu' | translate }}</ion-title>
          </ion-toolbar>
        </ion-header>
        <ion-content>
          <ion-list>
          <ion-menu-toggle auto-hide="true">
            <ion-item lines="none" (click)="goToEditprprofileFromMenu()">
              <ion-avatar slot="start" style="width: 30px; height: 30px; margin-right: 25px;">
                <img *ngIf="profileService.profile.profile_pic !== null; else noProfilePicFound" src="{{profileImageAPILink}}{{profileService.profile.id}}/{{profileService.profile.profile_pic}}">
                <ng-template #noProfilePicFound>
                  <img src="/assets/new-admify-icons/usersingle.svg">
                </ng-template>
                </ion-avatar>
                <ion-label>{{ 'my_profile' | translate }}</ion-label>
            </ion-item>
            <ion-item (click)="goToSubsciptions()" lines="none">
                <ion-icon slot="start" src="assets/new-admify-icons/subscriptions-active.svg"></ion-icon>
                <ion-label>{{ 'subscriptions' | translate }}</ion-label>
            </ion-item>
            <ion-item lines="none"  (click)="addAFeedback($event)">
              <ion-icon slot="start" color="primary" src="assets/new-admify-icons/feedback.svg"></ion-icon>
              <ion-label>{{ 'feedback' | translate }}</ion-label>
            </ion-item>
        <ion-item lines="none"  (click)="logout()" style="color: black ">
          <ion-icon slot="start" color="danger" src="assets/new-admify-icons/logout-active.svg"></ion-icon>
          <ion-label>{{ 'logout' | translate }}</ion-label>
        </ion-item>
          </ion-menu-toggle>
          </ion-list>
        </ion-content>
      </ion-menu>
  <ion-router-outlet id="content1"></ion-router-outlet>
</ion-app>
</code>```

答:
I got this error and finally found what's causing. Just post here for anybody else. I was trying to modify open/close the menu after disabling it.

My case was similar to this post. After logout I was redirecting to login page and disabling menu (to prevent open it with swipe gesture). Then, when I login again, I was forgetting to enable it. So, I got this error when I was trying to open the menu.

Body:
I hope you are all doing well.

I am facing an issue with MENU Controller on IONIC 4 App.

When the user clicks on the MENU and opens it and closes it several times i get errors, also when it logs out and logs back in, and it crashes the app:

helpers-46f4a262.js:44 ASSERT: _before() should be called while animating

Uncaught (in promise) Error: ASSERT: _before() should be called while animating
    at assert (helpers-46f4a262.js:46)
    at Menu.afterAnimation (ion-menu_4-md.entry.js:340)
    at Menu._setOpen (ion-menu_4-md.entry.js:200)

beforeAnimation(shouldOpen) {
        assert(!this.isAnimating, '_before() should not be called while animating');
        // this places the menu into the correct location before it animates in
        // this css class doesn't actually kick off any animations
        this.el.classList.add(SHOW_MENU);
        if (this.backdropEl) {
            this.backdropEl.classList.add(SHOW_BACKDROP);
        }
        this.blocker.block();
        this.isAnimating = true;
        if (shouldOpen) {
            this.ionWillOpen.emit();
        }
        else {
            this.ionWillClose.emit();
        }
    }
    afterAnimation(isOpen) {
        assert(this.isAnimating, '_before() should be called while animating');
        // keep opening/closing the menu disabled for a touch more yet
        // only add listeners/css if it's enabled and isOpen
        // and only remove listeners/css if it's not open
        // emit opened/closed events
        this._isOpen = isOpen;
        this.isAnimating = false;
        if (!this._isOpen) {
            this.blocker.unblock();
        }
        if (isOpen) {
            // add css class
            if (this.contentEl) {
                this.contentEl.classList.add(MENU_CONTENT_OPEN);
            }
            // emit open event
            this.ionDidOpen.emit();
        }
        else {
            // remove css classes
            this.el.classList.remove(SHOW_MENU);
            if (this.contentEl) {
                this.contentEl.classList.remove(MENU_CONTENT_OPEN);
            }
            if (this.backdropEl) {
                this.backdropEl.classList.remove(SHOW_BACKDROP);
            }
            if (this.animation) {
                this.animation.stop();
            }
            // emit close event
            this.ionDidClose.emit();
        }
    }

Click here for STREAMABLE Link Video

what is causing this?
any solution?

i have placed MENU to app.component.html

this is code:

<ion-app>
  <ion-menu [disabled]="this.profileService.profile.length === 0 || selectedRouter.includes('subscriptions-and-packages')" (ionDidOpen)="openMenu($event)" (ionDidClose)="closeMenu($event)" side="end" menuId="first" contentId="content1">
        <ion-header>
          <ion-toolbar>
            <ion-title>{{ 'menu' | translate }}</ion-title>
          </ion-toolbar>
        </ion-header>
        <ion-content>
          <ion-list>
          <ion-menu-toggle auto-hide="true">
            <ion-item lines="none" (click)="goToEditprprofileFromMenu()">
              <ion-avatar slot="start" style="width: 30px; height: 30px; margin-right: 25px;">

                <ng-template #noProfilePicFound>

                </ng-template>
                </ion-avatar>
                <ion-label>{{ 'my_profile' | translate }}</ion-label>
            </ion-item>
            <ion-item (click)="goToSubsciptions()" lines="none">
                <ion-icon slot="start" src="assets/new-admify-icons/subscriptions-active.svg"></ion-icon>
                <ion-label>{{ 'subscriptions' | translate }}</ion-label>
            </ion-item>
            <ion-item lines="none"  (click)="addAFeedback($event)">
              <ion-icon slot="start" color="primary" src="assets/new-admify-icons/feedback.svg"></ion-icon>
              <ion-label>{{ 'feedback' | translate }}</ion-label>
            </ion-item>
        <ion-item lines="none"  (click)="logout()" style="color: black ">
          <ion-icon slot="start" color="danger" src="assets/new-admify-icons/logout-active.svg"></ion-icon>
          <ion-label>{{ 'logout' | translate }}</ion-label>
        </ion-item>
          </ion-menu-toggle>
          </ion-list>
        </ion-content>
      </ion-menu>
  <ion-router-outlet id="content1"></ion-router-outlet>
</ion-app>


问:
Notification Api System Correct Process
I built a small notification api system that has id, user_id, subject, text, status, created_at columns in the data base.

My current process is that when a user requests for her notifications i get the most recent 100 unread messages and send to the user, then wait for the front end to send me a list of ids of those that have been read by the user so that i can change their status to read.

but sometimes this does not happen meaning the when the user requests for another set of messages they will get back their already read messages.

So i am thinking of marking the messages as read once i retrieve them for the user rather than wait for update from the frontend.

but i am not sure if this is the best way to handle this! is there a better process for api notification systems please advice me. Thanks.

答:
I would think about it like this: What is that listing of unread items depicting? What the state understands to have been left unread. Is pulling a listing of unread items really meant to denote all those items were read? I think not. You may allow a bulk mark read, but reading the list is just a stateful representation, of fact. Read the list, and authoritatively mark read when touched by a visible interface component by sending a per-item request to thing/mark-read.

If you're having issues with the (central) store not representing state accurately because you think they should be read, debug your interface. I would not mark read on pulling the list, though. That would be a flawed approach.

If you do directly insert all 100 into the display where you consider them read, create an endpoint in your api for thing/mark-items-read and pass it those 100 item ID's.

Title: Notification Api System Correct Process


问:
Creating a list of 6 every possible combination
How would I create a list of 6 columns from a dataframe of 21 columns. I need to create every single combination possible and store these combinations is a dataframe.

Suppose

```<code>lst = ['c1', 'c2', 'c3', 'c4','c5', 'c6', 'c7','c8', 'c9', 'c10', 'c11','c12', 'c13', 'c14','c15', 'c16', 'c17', 'c18','c19', 'c20', 'c21']

# Calling DataFrame constructor on list
df = pd.DataFrame(lst)

Some list generator
adds new list to cdf dataframe

final df should be something like this not sure if i wrote this in the right syntax but a dataframe with 1 column haveing a list of 6 elements
cdf = [[c1', 'c2', 'c3', 'c4','c5', 'c6'],['c7','c8', 'c9', 'c10', 'c11','c12'], ['c13', 'c14','c15', 'c16', 'c17', 'c18']...]
</code>```

Thank you!

答:
I would do the combinations work in pure python, using the itertools.combinations function, documentation here. You can then import that list of tuples into pandas if desired.

Example code, which generates the combinations (combos are in sorted order, no repeated elements), prints how many combinations there are, and shows the first 2 and last 2 as examples:

```<code>import itertools
lst = ['c1', 'c2', 'c3', 'c4','c5', 'c6', 'c7','c8', 'c9', 'c10', 'c11','c12', 'c13', 'c14','c15', 'c16', 'c17', 'c18','c19', 'c20', 'c21']

combos = itertools.combinations(lst, 6)
combos_list = list(combos)
print(f'{len(combos_list)} Combinations')
print(combos_list[0])
print(combos_list[1])
print(combos_list[-2])
print(combos_list[-1])
</code>```

This generates output:

```<code>54264 Combinations
('c1', 'c2', 'c3', 'c4', 'c5', 'c6')
('c1', 'c2', 'c3', 'c4', 'c5', 'c7')
('c15', 'c17', 'c18', 'c19', 'c20', 'c21')
('c16', 'c17', 'c18', 'c19', 'c20', 'c21')
</code>```

Happy Coding!

Body:
How would I create a list of 6 columns from a dataframe of 21 columns. I need to create every single combination possible and store these combinations is a dataframe.

Suppose

lst = ['c1', 'c2', 'c3', 'c4','c5', 'c6', 'c7','c8', 'c9', 'c10', 'c11','c12', 'c13', 'c14','c15', 'c16', 'c17', 'c18','c19', 'c20', 'c21']

# Calling DataFrame constructor on list
df = pd.DataFrame(lst)

Some list generator
adds new list to cdf dataframe

final df should be something like this not sure if i wrote this in the right syntax but a dataframe with 1 column haveing a list of 6 elements
cdf = [[c1', 'c2', 'c3', 'c4','c5', 'c6'],['c7','c8', 'c9', 'c10', 'c11','c12'], ['c13', 'c14','c15', 'c16', 'c17', 'c18']...]

Thank you!

Body:
I would do the combinations work in pure python, using the itertools.combinations function, documentation here. You can then import that list of tuples into pandas if desired.

Example code, which generates the combinations (combos are in sorted order, no repeated elements), prints how many combinations there are, and shows the first 2 and last 2 as examples:

import itertools
lst = ['c1', 'c2', 'c3', 'c4','c5', 'c6', 'c7','c8', 'c9', 'c10', 'c11','c12', 'c13', 'c14','c15', 'c16', 'c17', 'c18','c19', 'c20', 'c21']

combos = itertools.combinations(lst, 6)
combos_list = list(combos)
print(f'{len(combos_list)} Combinations')
print(combos_list[0])
print(combos_list[1])
print(combos_list[-2])
print(combos_list[-1])

This generates output:

54264 Combinations
('c1', 'c2', 'c3', 'c4', 'c5', 'c6')
('c1', 'c2', 'c3', 'c4', 'c5', 'c7')
('c15', 'c17', 'c18', 'c19', 'c20', 'c21')
('c16', 'c17', 'c18', 'c19', 'c20', 'c21')

Happy Coding!


问:
Multiple Html Files sent at the same server for multiple people
i'm making a sort of a game on a website, and the game has players ( of course) and when they open a new room, each one gets assigned to a role basically
each role has a " power "
what i want to know is, how can i make each role for each player, because some players wait for other players input
And there's some html files that won't get shown to other players, hence "power",
so how can i get multiple html files to get shown for some people but not others ?</p>

答:
What you are describing sounds like a job for websockets.

https://javascript.info/websocket


问:
Databricks - Creating output file
I'm pretty new to databricks, so excuse my ignorance.
I have a databricks notebook that creates a table to hold data. I'm trying to output the data to a pipe delimited file using another notebook which is using python. If I use the 'Order By' clause each record is created in a seperate file. If I leave the clause out of the code I get 1 file, but it's not in order

The code from the notebook is as follows

```<code>%python

try:

  dfsql = spark.sql("select field_1, field_2, field_3, field_4, field_5, field_6, field_7, field_8, field_9, field_10, field_11, field_12,  field_13, field_14, field_15, field_16 from dbsmets1mig02_technical_build.tbl_tech_output_bsmart_update ORDER BY MSN,Sort_Order") #Replace with your SQL

except:

  print("Exception occurred")

if dfsql.count() == 0:

  print("No data rows")

else:

  dfsql.write.format("com.databricks.spark.csv").option("header","false").option("delimiter", "|").mode("overwrite").save("/mnt/publisheddatasmets1mig/smetsmig1/mmt/bsmart")
</code>```

答:
To accomplish this I have done something similar to what simon_dmorias suggested. I am not sure if there is a better way to do so, as this doesn't scale very well but if you are working with a small dataset it will work.

simon_dmorias suggested: df.coalesce(1).write.format("com.databricks.spark.csv").option("header","false").option("delimiter", "|").mode("overwrite").save("/mnt/mountone/data/")

This will write a single partition in a directory /mnt/mountone/data/data-<guid>-.csv, which I believe is not what you are looking for, right? You just want /mnt/mountone/data.csv, similar to the pandas .to_csv function.

Therefore, I will write it to a temporary location on the cluster (not on the mount).

df.coalesce(1).write.format("com.databricks.spark.csv").option("header","false").option("delimiter", "|").mode("overwrite").save("/tmpdir/data")

I will then use the dbutils.fs.ls("/tmpdir/data") command to list the directory contents and identify the name of the csv file that was written in the directory i.e. /tmpdir/data/data-<guid>-.csv.

Once you have the CSV file name, I will use the dbutils.fs.cp function to copy the file to a mount location and rename the file. This allows you to have a single file without the directory, which is what I believe you were looking for.

dbutils.fs.cp("/tmpdir/data/data-<guid>-.csv", "/mnt/mountone/data.csv")

Title: Databricks - Creating output file

Body:
I'm pretty new to databricks, so excuse my ignorance.
I have a databricks notebook that creates a table to hold data. I'm trying to output the data to a pipe delimited file using another notebook which is using python. If I use the 'Order By' clause each record is created in a seperate file. If I leave the clause out of the code I get 1 file, but it's not in order

The code from the notebook is as follows

%python

try:

  dfsql = spark.sql("select field_1, field_2, field_3, field_4, field_5, field_6, field_7, field_8, field_9, field_10, field_11, field_12,  field_13, field_14, field_15, field_16 from dbsmets1mig02_technical_build.tbl_tech_output_bsmart_update ORDER BY MSN,Sort_Order") #Replace with your SQL

except:

  print("Exception occurred")

if dfsql.count() == 0:

  print("No data rows")

else:

  dfsql.write.format("com.databricks.spark.csv").option("header","false").option("delimiter", "|").mode("overwrite").save("/mnt/publisheddatasmets1mig/smetsmig1/mmt/bsmart")


问:
binding window to popstate event triggered twice
Simply binding the window (in jQuery) to popstate, the event is always triggered twice.

```<code>$( window ).bind( 'popstate', myFunction );
</code>```

There's nothing in myFunction() to cause this - I've tried stripping out this function to a simple:

```<code>console.log( 'triggered' );
</code>```

And the result is the same. It's always triggered twice (tested in Safari, Chrome & Firefox).

I know there are issues with the HTML5 history API, but any advice other than 'try History.js' would be gratefully received!

答:
This does not answer the question directly, but it might be of help to others who find this question. Because I only needed to listen for the popstate once, and remove the listener immediately.

If you want to dispose of the listener after it has been triggered (only once), you can add the following object to the third parameter of addEventListener:

```<code>window.addEventListener('popstate', myFunction, {once: true});
</code>```

once

A Boolean indicating that the listener should be invoked at most once after being added. If true, the listener would be automatically removed when invoked.

Here is the documentation: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

Body:
Simply binding the window (in jQuery) to popstate, the event is always triggered twice.

$( window ).bind( 'popstate', myFunction );

There's nothing in myFunction() to cause this - I've tried stripping out this function to a simple:

console.log( 'triggered' );

And the result is the same. It's always triggered twice (tested in Safari, Chrome & Firefox).

I know there are issues with the HTML5 history API, but any advice other than 'try History.js' would be gratefully received!

Body:
This does not answer the question directly, but it might be of help to others who find this question. Because I only needed to listen for the popstate once, and remove the listener immediately.

If you want to dispose of the listener after it has been triggered (only once), you can add the following object to the third parameter of addEventListener:

window.addEventListener('popstate', myFunction, {once: true});

once

A Boolean indicating that the listener should be invoked at most once after being added. If true, the listener would be automatically removed when invoked.

Here is the documentation: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener


问:
Undefined reference to MasterController::StaticMetaObject
I'm just starting learning Qt and currently I'm reading the book Learn Qt 5 by Nicolas Sheriff. Where I am, in chapter 2, I'm following all the instructions and I'M understanding what I am doing but i getting stuck on one thing: when i compile the following program along with others, I'm getting this list of errors:image shwowing the error messages

Here's the project structure

and the files I find worth showing are:

cm.pro file

```<code>QT       -= gui

TARGET = cm-lib
TEMPLATE = lib

CONFIG += c++17
DEFINES += CMLIB_LIBRARY
INCLUDEPATH += source

SOURCES += source/models/client.cpp \
           source/controllers/master-controller.cpp \

HEADERS += source/cm-lib_global.h \
           source/controllers/master-controller.h \
           source/models/client.h \
</code>```

cm-lib.pro

```<code>QT       -= gui

TARGET = cm-lib
TEMPLATE = lib
CONFIG += c++17
DEFINES += CMLIB_LIBRARY
INCLUDEPATH += source

SOURCES += source/models/client.cpp \
           source/controllers/master-controller.cpp \

HEADERS += source/cm-lib_global.h \
           source/controllers/master-controller.h \
           source/models/client.h \
</code>```

cm-ui.pro

```<code>QT += qml quick

TEMPLATE = app
CONFIG += c++17
INCLUDEPATH += source \
        ../cm-lib/source

SOURCES += source/main.cpp

RESOURCES += views.qrc
LIBS += -L$$PWD/../../build-cm-kit1-Debug/cm-lib/ -lcm-lib
</code>```

MasterController.h

```<code>#ifndef MASTERCONTROLLER_H
#define MASTERCONTROLLER_H
#include <QObject>
#include <QString>
#include <cm-lib_global.h>

namespace cm::controllers {
class CMLIBSHARED_EXPORT MasterController : public QObject
{
    Q_OBJECT
    QString welcomeMessage = "This is MasterController to Major Tom";
    Q_PROPERTY( QString ui_welcomeMessage MEMBER welcomeMessage CONSTANT )
    public:
    explicit MasterController(QObject* parent = nullptr);
};
}
</code>```

main.cpp

```<code>#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>

#include <controllers/master-controller.h>

int main(int argc, char *argv[])
{
    #if defined(Q_OS_WIN)
        QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    #endif

    QGuiApplication app(argc, argv);

    qmlRegisterType<cm::controllers::MasterController>("CM", 1, 0, "MasterController");

    cm::controllers::MasterController masterController{};

    QQmlApplicationEngine engine{};
    engine.rootContext()->setContextProperty("masterController", &masterController);
    engine.load(QUrl(QStringLiteral("qrc:/views/MasterView.qml")));

    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}
</code>```

It' long like that because I used the MVC design pattern here like in the book.

I think the problem is caused by the inclusion of the Q_OBJECT macro in MasterController.h because when I remove it, the project compile well without any issue.

After googling about the issue, on almost all the places I visited, the error was caused by the fact that the classes including Q_OBJECT macro would be declared in their own header file or qmake was not rerunned on these files including Q_OBJECT but It's not true in my case.

System tools used:

Qt creator

Qt 5.11
-Kubuntu 18.04

答:
Simply change MEMBER to READ in the Q_PROPERTY solved this problem
for me tho.

Took me hours :) You're welcome.

MasterController.h

    #ifndef MASTERCONTROLLER_H
    #define MASTERCONTROLLER_H
    #include <QObject>
    #include <QString>
    #include <cm-lib_global.h>

    namespace cm::controllers {
    class CMLIBSHARED_EXPORT MasterController : public QObject
    {
        Q_OBJECT
        QString welcomeMessage = "This is MasterController to Major Tom";
        Q_PROPERTY( QString ui_welcomeMessage READ welcomeMessage CONSTANT ) //<-----MEMBER to READ
        public:
        explicit MasterController(QObject* parent = nullptr);
    };
    }
```

Btw.: In the error message (of the screenshot you included in the question) you can right click and expand the message Show Output in the qt creator. Normally the error has a zickzackely underlining in there.

Body:
I'm just starting learning Qt and currently I'm reading the book Learn Qt 5 by Nicolas Sheriff. Where I am, in chapter 2, I'm following all the instructions and I'M understanding what I am doing but i getting stuck on one thing: when i compile the following program along with others, I'm getting this list of errors:image shwowing the error messages

Here's the project structure

and the files I find worth showing are:

cm.pro file

QT       -= gui

TARGET = cm-lib
TEMPLATE = lib

CONFIG += c++17
DEFINES += CMLIB_LIBRARY
INCLUDEPATH += source

SOURCES += source/models/client.cpp \
           source/controllers/master-controller.cpp \

HEADERS += source/cm-lib_global.h \
           source/controllers/master-controller.h \
           source/models/client.h \

cm-lib.pro

QT       -= gui

TARGET = cm-lib
TEMPLATE = lib
CONFIG += c++17
DEFINES += CMLIB_LIBRARY
INCLUDEPATH += source

SOURCES += source/models/client.cpp \
           source/controllers/master-controller.cpp \

HEADERS += source/cm-lib_global.h \
           source/controllers/master-controller.h \
           source/models/client.h \

cm-ui.pro

QT += qml quick

TEMPLATE = app
CONFIG += c++17
INCLUDEPATH += source \
        ../cm-lib/source

SOURCES += source/main.cpp

RESOURCES += views.qrc
LIBS += -L$$PWD/../../build-cm-kit1-Debug/cm-lib/ -lcm-lib

MasterController.h

#ifndef MASTERCONTROLLER_H
#define MASTERCONTROLLER_H
#include <QObject>
#include <QString>
#include <cm-lib_global.h>

namespace cm::controllers {
class CMLIBSHARED_EXPORT MasterController : public QObject
{
    Q_OBJECT
    QString welcomeMessage = "This is MasterController to Major Tom";
    Q_PROPERTY( QString ui_welcomeMessage MEMBER welcomeMessage CONSTANT )
    public:
    explicit MasterController(QObject* parent = nullptr);
};
}

main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>

#include <controllers/master-controller.h>

int main(int argc, char *argv[])
{
    #if defined(Q_OS_WIN)
        QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    #endif

    QGuiApplication app(argc, argv);

    qmlRegisterType<cm::controllers::MasterController>("CM", 1, 0, "MasterController");

    cm::controllers::MasterController masterController{};

    QQmlApplicationEngine engine{};
    engine.rootContext()->setContextProperty("masterController", &masterController);
    engine.load(QUrl(QStringLiteral("qrc:/views/MasterView.qml")));

    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}

It' long like that because I used the MVC design pattern here like in the book.

I think the problem is caused by the inclusion of the Q_OBJECT macro in MasterController.h because when I remove it, the project compile well without any issue.

After googling about the issue, on almost all the places I visited, the error was caused by the fact that the classes including Q_OBJECT macro would be declared in their own header file or qmake was not rerunned on these files including Q_OBJECT but It's not true in my case.

System tools used:

Qt creator

Qt 5.11
-Kubuntu 18.04

Body:
Simply change MEMBER to READ in the Q_PROPERTY solved this problem
for me tho.

Took me hours :) You're welcome.

MasterController.h

    #ifndef MASTERCONTROLLER_H
    #define MASTERCONTROLLER_H
    #include <QObject>
    #include <QString>
    #include <cm-lib_global.h>

    namespace cm::controllers {
    class CMLIBSHARED_EXPORT MasterController : public QObject
    {
        Q_OBJECT
        QString welcomeMessage = "This is MasterController to Major Tom";
        Q_PROPERTY( QString ui_welcomeMessage READ welcomeMessage CONSTANT ) //<-----MEMBER to READ
        public:
        explicit MasterController(QObject* parent = nullptr);
    };
    }

Btw.: In the error message (of the screenshot you included in the question) you can right click and expand the message Show Output in the qt creator. Normally the error has a zickzackely underlining in there.


问:
Iterate over two list and set element from first list
I have two ArrayList as below -

```<code>certificates=[CERT1, CERT2]
promotions=[{type}, {type, promotionCode}, {type, promotionCode}]
</code>```

promotions list size is not confirm but certificates list size is confirmed. So consider first list size is 2 and second list size is 3

I want to set promotionCode in second list from certificates but in second list some time promotionCode is not present.

```<code>for (int i = 0; i < getCertificateNumber().size(); i++) {
   if (!promotions().isEmpty()) {
       promotions().get(i).setPromotionCode(getCertificateNumber().get(i));
   }
}
</code>```

as in above for loop it set only first two promotions in promotion list because certificate list size two

How can I avoid any element from second list which don't have promotionCode and set CERT to element which has promotionCode

答:
You can add an if statement to check if the promotion code is not null , in this way to avoid getting beyong CERT1 :</p>

```<code>int i = 0;
for ( Promotion prom : promotions ) {
    // check if promotioncode is not null
    if( prom.getPromotionCode() != null ) {
       prom.setPromotionCode(getCertificateNumber().get(i));
       i++; // increments only if not null
 }
}
</code>```

Body:
I have two ArrayList as below -

certificates=[CERT1, CERT2]
promotions=[{type}, {type, promotionCode}, {type, promotionCode}]

promotions list size is not confirm but certificates list size is confirmed. So consider first list size is 2 and second list size is 3

I want to set promotionCode in second list from certificates but in second list some time promotionCode is not present.

for (int i = 0; i < getCertificateNumber().size(); i++) {
   if (!promotions().isEmpty()) {
       promotions().get(i).setPromotionCode(getCertificateNumber().get(i));
   }
}

as in above for loop it set only first two promotions in promotion list because certificate list size two

How can I avoid any element from second list which don't have promotionCode and set CERT to element which has promotionCode

Body:
You can add an if statement to check if the promotion code is not null , in this way to avoid getting beyong CERT1 :

int i = 0;
for ( Promotion prom : promotions ) {
    // check if promotioncode is not null
    if( prom.getPromotionCode() != null ) {
       prom.setPromotionCode(getCertificateNumber().get(i));
       i++; // increments only if not null
 }
}


问:
SwingWorker: when exactly is called done method?
Javadoc of the done() method of SwingWorker:

Executed on the Event Dispatch Thread after the doInBackground method
  is finished.

I've clues that it is not true in the case of canceled worker.

Done is called in each case (normal termination or cancellation) but when cancelled it is not enqueued to the EDT, as it happens for normal termination.

Is there some more precise analisis on when done is called in the case that a SwingWorker is cancelled?

Clarification:
this question is NOT on how to cancel a SwingWorker. Here it is assumed that the SwingWorker is cancelled in the right way.

And it is NOT about thread still working when they are supposed to be finished.

答:
something is possible, other could be illusion

really nice outPut

```<code>run:
***removed***
java.lang.RuntimeException: I want to produce a stack trace!
        at help.SwingWorker05$W.done(SwingWorker05.java:71)
        at javax.swing.SwingWorker$5.run(SwingWorker.java:717)
        at javax.swing.SwingWorker.doneEDT(SwingWorker.java:721)
        at javax.swing.SwingWorker.access$100(SwingWorker.java:207)
        at javax.swing.SwingWorker$2.done(SwingWorker.java:284)
        at java.util.concurrent.FutureTask$Sync.innerCancel(FutureTask.java:293)
        at java.util.concurrent.FutureTask.cancel(FutureTask.java:76)
        at javax.swing.SwingWorker.cancel(SwingWorker.java:526)
        at help.SwingWorker05$1.run(SwingWorker05.java:25)
        at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
        at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
        at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
        at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
        at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
I'm still alive
Thread Status with Name :SwingWorker1, SwingWorker Status is STARTED
SwingWorker by tutorial's background process has completed
Thread Status with Name :SwingWorker1, SwingWorker Status is DONE
Thread Status with Name :look here what's possible with SwingWorker, SwingWorker Status is STARTED
BUILD SUCCESSFUL (total time: 10 seconds)
</code>```

from

```<code>import java.awt.EventQueue;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.SwingWorker;

public class SwingWorker05 {

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            public void run() {
                try {
                    W w = new W();
                    w.addPropertyChangeListener(
                            new SwingWorkerCompletionWaiter("look here what's possible with SwingWorker"));
                    w.execute();
                    Thread.sleep(1000);
                    try {
                        w.cancel(false);
                    } catch (RuntimeException rte) {
                        rte.printStackTrace();
                    }
                    Thread.sleep(6000);
                } catch (InterruptedException ignored_in_testing) {
                }
            }
        });

        final MySwingWorker mySW = new MySwingWorker();
        mySW.addPropertyChangeListener(new SwingWorkerCompletionWaiter("SwingWorker1"));
        mySW.execute();
    }

    private static class MySwingWorker extends SwingWorker<Void, Void> {

        private static final long SLEEP_TIME = 250;

        @Override
        protected Void doInBackground() throws Exception {
            Thread.sleep(SLEEP_TIME);
            return null;
        }

        @Override
        protected void done() {
            System.out.println("SwingWorker by tutorial's background process has completed");
        }
    }

    public static class W extends SwingWorker {

        @Override
        protected Object doInBackground() throws Exception {
            while (!isCancelled()) {
                Thread.sleep(5000);
            }

            System.out.println("I'm still alive");
            return null;
        }

        @Override
        protected void done() {
            System.out.println("***remove***");
            throw new RuntimeException("I want to produce a stack trace!");
        }
    }

    private static class SwingWorkerCompletionWaiter implements PropertyChangeListener {

        private String str;

        SwingWorkerCompletionWaiter(String str) {
            this.str = str;
        }

        @Override
        public void propertyChange(PropertyChangeEvent event) {
            if ("state".equals(event.getPropertyName()) && SwingWorker.StateValue.DONE == event.getNewValue()) {
                System.out.println("Thread Status with Name :" + str + ", SwingWorker Status is " + event.getNewValue());
            } else if ("state".equals(event.getPropertyName()) && SwingWorker.StateValue.PENDING == event.getNewValue()) {
                System.out.println("Thread Status with Mame :" + str + ", SwingWorker Status is " + event.getNewValue());
            } else if ("state".equals(event.getPropertyName()) && SwingWorker.StateValue.STARTED == event.getNewValue()) {
                System.out.println("Thread Status with Name :" + str + ", SwingWorker Status is " + event.getNewValue());
            } else {
                System.out.println("Thread Status with Name :" + str + ", Something wrong happends ");
            }
        }
    }
}
</code>```

Body:
something is possible, other could be illusion

really nice outPut

run:
***removed***
java.lang.RuntimeException: I want to produce a stack trace!
        at help.SwingWorker05$W.done(SwingWorker05.java:71)
        at javax.swing.SwingWorker$5.run(SwingWorker.java:717)
        at javax.swing.SwingWorker.doneEDT(SwingWorker.java:721)
        at javax.swing.SwingWorker.access$100(SwingWorker.java:207)
        at javax.swing.SwingWorker$2.done(SwingWorker.java:284)
        at java.util.concurrent.FutureTask$Sync.innerCancel(FutureTask.java:293)
        at java.util.concurrent.FutureTask.cancel(FutureTask.java:76)
        at javax.swing.SwingWorker.cancel(SwingWorker.java:526)
        at help.SwingWorker05$1.run(SwingWorker05.java:25)
        at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
        at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
        at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
        at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
        at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
I'm still alive
Thread Status with Name :SwingWorker1, SwingWorker Status is STARTED
SwingWorker by tutorial's background process has completed
Thread Status with Name :SwingWorker1, SwingWorker Status is DONE
Thread Status with Name :look here what's possible with SwingWorker, SwingWorker Status is STARTED
BUILD SUCCESSFUL (total time: 10 seconds)

from

import java.awt.EventQueue;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.SwingWorker;

public class SwingWorker05 {

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            public void run() {
                try {
                    W w = new W();
                    w.addPropertyChangeListener(
                            new SwingWorkerCompletionWaiter("look here what's possible with SwingWorker"));
                    w.execute();
                    Thread.sleep(1000);
                    try {
                        w.cancel(false);
                    } catch (RuntimeException rte) {
                        rte.printStackTrace();
                    }
                    Thread.sleep(6000);
                } catch (InterruptedException ignored_in_testing) {
                }
            }
        });

        final MySwingWorker mySW = new MySwingWorker();
        mySW.addPropertyChangeListener(new SwingWorkerCompletionWaiter("SwingWorker1"));
        mySW.execute();
    }

    private static class MySwingWorker extends SwingWorker<Void, Void> {

        private static final long SLEEP_TIME = 250;

        @Override
        protected Void doInBackground() throws Exception {
            Thread.sleep(SLEEP_TIME);
            return null;
        }

        @Override
        protected void done() {
            System.out.println("SwingWorker by tutorial's background process has completed");
        }
    }

    public static class W extends SwingWorker {

        @Override
        protected Object doInBackground() throws Exception {
            while (!isCancelled()) {
                Thread.sleep(5000);
            }

            System.out.println("I'm still alive");
            return null;
        }

        @Override
        protected void done() {
            System.out.println("***remove***");
            throw new RuntimeException("I want to produce a stack trace!");
        }
    }

    private static class SwingWorkerCompletionWaiter implements PropertyChangeListener {

        private String str;

        SwingWorkerCompletionWaiter(String str) {
            this.str = str;
        }

        @Override
        public void propertyChange(PropertyChangeEvent event) {
            if ("state".equals(event.getPropertyName()) && SwingWorker.StateValue.DONE == event.getNewValue()) {
                System.out.println("Thread Status with Name :" + str + ", SwingWorker Status is " + event.getNewValue());
            } else if ("state".equals(event.getPropertyName()) && SwingWorker.StateValue.PENDING == event.getNewValue()) {
                System.out.println("Thread Status with Mame :" + str + ", SwingWorker Status is " + event.getNewValue());
            } else if ("state".equals(event.getPropertyName()) && SwingWorker.StateValue.STARTED == event.getNewValue()) {
                System.out.println("Thread Status with Name :" + str + ", SwingWorker Status is " + event.getNewValue());
            } else {
                System.out.println("Thread Status with Name :" + str + ", Something wrong happends ");
            }
        }
    }
}


问:
Can I get the path of the currently running java executable?
Suppose I want to run a java program from the command line and I use this command:

```<code>myExes\java\java.exe AJavaProgram
</code>```

As you can see, java.exe is not in my path, so I am running it manually rather than simply using the command java AJavaProgram.

I would like the program to return/print the first entry in the command, in this case, that entry is myExes\java. (Including java.exe at the end of this is also fine).

Is there a way to do this?

Initially, I thought it would be simple. args[0] would return the path, but that is not the case.

答:
You can't get the string "myExes\java\java.exe", but you can get the location of the Java installation.

The following are results for running with OpenJDK 14 on Windows 10:

System.out.println(System.getProperty("java.home"));
System.out.println(System.getProperty("sun.boot.library.path"));
```

<p><em>Output</em></p>

<pre class="lang-none prettyprint-override"><code>C:\prog\Java64\jdk-14
C:\prog\Java64\jdk-14\bin
</code>```

For reference, the full path of java.exe is:

C:\prog\Java64\jdk-14\bin\java.exe
```

Body:
Suppose I want to run a java program from the command line and I use this command:

myExes\java\java.exe AJavaProgram

As you can see, java.exe is not in my path, so I am running it manually rather than simply using the command java AJavaProgram.

I would like the program to return/print the first entry in the command, in this case, that entry is myExes\java. (Including java.exe at the end of this is also fine).

Is there a way to do this?

Initially, I thought it would be simple. args[0] would return the path, but that is not the case.

Body:
You can't get the string "myExes\java\java.exe", but you can get the location of the Java installation.

The following are results for running with OpenJDK 14 on Windows 10:

System.out.println(System.getProperty("java.home"));
System.out.println(System.getProperty("sun.boot.library.path"));

Output

C:\prog\Java64\jdk-14
C:\prog\Java64\jdk-14\bin

For reference, the full path of java.exe is:

C:\prog\Java64\jdk-14\bin\java.exe


问:
Try/Except for ...AttributeError: Can only use .str accessor with string values
I am running a function that grabs some data from a website and writes it into a pandas database. I am using selenium and geckodriver.

```<code>...code...

first_names = driver.find_elements_by_class_name('first-name')
first_names = [name.text for name in first_names]

last_names = driver.find_elements_by_class_name('last-name')
last_names = [name.text for name in last_names]

commit_status = driver.find_elements_by_class_name('school-name')
commit_status = [commit.text for commit in commit_status]

#error is happening below

athlete['commit_school'] = athlete['commit'].str.replace('\d+', '').str.replace('/',
'').str.replace('VERBAL', '').str.replace('SIGNED', '')

athlete['first'] = athlete['first'].str.title()
athlete['last'] = athlete['last'].str.title()

...code...
</code>```

I then loop through this function to go through similar data on different states webpages. Sometimes it returns the data on the page normally and continues to the next state, while other times, I get:
AttributeError: Can only use .str accessor with string values!
...and the code breaks. The part that is confusing me is that the times I get the error seem to be arbitrary. Sometimes I will make it through 1/4 of the loop and sometimes 3/4 of the loop.

My first attempt to fix was a try/except, but I am not sure if I am doing it right or if that is the best approach:

```<code>athlete['state'] = state_all[:length:]
athlete['hs'] = hs_all[:length:]
athlete['commit'] = commit_status[:length:]

try:
    athlete['commit_school'] = athlete['commit'].str.replace('\d+', '').str.replace('/',
    '').str.replace('VERBAL', '').str.replace('SIGNED', '')
    athlete['first'] = athlete['first'].str.title()
    athlete['last'] = athlete['last'].str.title()
except AttributeError:
    pass

athlete['list'] = 'Rivals_' + year + '_' + list_state
athlete['home'] = profile_page[:length:]
</code>```

The error is happening within that try/except statement, but I think it just skips all of it if it finds an error.

答:
Does the below code where I add .astype('str') to the middle for each column solve? You probably have column with mixed data type of strings and objects.

```<code>athlete['commit_school'] = athlete['commit'].astype('str').str.replace('\d+', '').str.replace('/', '').str.replace('VERBAL', '').str.replace('SIGNED', '')

athlete['first'] = athlete['first'].astype('str').str.title()
athlete['last'] = athlete['last'].astype('str').str.title()
</code>```

Body:
I am running a function that grabs some data from a website and writes it into a pandas database. I am using selenium and geckodriver.

...code...

first_names = driver.find_elements_by_class_name('first-name')
first_names = [name.text for name in first_names]

last_names = driver.find_elements_by_class_name('last-name')
last_names = [name.text for name in last_names]

commit_status = driver.find_elements_by_class_name('school-name')
commit_status = [commit.text for commit in commit_status]

#error is happening below

athlete['commit_school'] = athlete['commit'].str.replace('\d+', '').str.replace('/',
'').str.replace('VERBAL', '').str.replace('SIGNED', '')

athlete['first'] = athlete['first'].str.title()
athlete['last'] = athlete['last'].str.title()

...code...

I then loop through this function to go through similar data on different states webpages. Sometimes it returns the data on the page normally and continues to the next state, while other times, I get:
AttributeError: Can only use .str accessor with string values!
...and the code breaks. The part that is confusing me is that the times I get the error seem to be arbitrary. Sometimes I will make it through 1/4 of the loop and sometimes 3/4 of the loop.

My first attempt to fix was a try/except, but I am not sure if I am doing it right or if that is the best approach:

athlete['state'] = state_all[:length:]
athlete['hs'] = hs_all[:length:]
athlete['commit'] = commit_status[:length:]

try:
    athlete['commit_school'] = athlete['commit'].str.replace('\d+', '').str.replace('/',
    '').str.replace('VERBAL', '').str.replace('SIGNED', '')
    athlete['first'] = athlete['first'].str.title()
    athlete['last'] = athlete['last'].str.title()
except AttributeError:
    pass

athlete['list'] = 'Rivals_' + year + '_' + list_state
athlete['home'] = profile_page[:length:]

The error is happening within that try/except statement, but I think it just skips all of it if it finds an error.

Body:
Does the below code where I add .astype('str') to the middle for each column solve? You probably have column with mixed data type of strings and objects.

athlete['commit_school'] = athlete['commit'].astype('str').str.replace('\d+', '').str.replace('/', '').str.replace('VERBAL', '').str.replace('SIGNED', '')

athlete['first'] = athlete['first'].astype('str').str.title()
athlete['last'] = athlete['last'].astype('str').str.title()


问:
Anyone knows what is in Skimage TIfffile save, unknown error "type b".?
I am getting a strange error saving a tiff file (stack grayscale), any idea?:

File
  "C:\Users\ptyimg_np.MT00200169\Anaconda3\lib\site-packages\tifffile\tifffile.py",
  line 1241, in save
      sampleformat = {'u': 1, 'i': 2, 'f': 3, 'c': 6}[datadtype.kind] KeyError: 'b'

my code is

```<code> #!/usr/bin/env python
# -*- coding: utf-8 -*-
from skimage.morphology import watershed
from skimage.feature import peak_local_max
from scipy import ndimage
from skimage import img_as_float
from skimage import exposure,io
from skimage import external
from skimage.color import rgb2gray
from skimage.filters import threshold_local  , threshold_niblack
import numpy as np
import  tifffile
from joblib import Parallel, delayed
import sys

# Load an example image
input_namefile = sys.argv[1]
output_namefile = 'seg_'+ input_namefile

#Settings
block_size = 25 #Size block of the local thresholding

img = io.imread(input_namefile, plugin='tifffile')
thresh =  threshold_niblack(img, window_size=block_size , k=0.8) #
res = img > thresh
res = np.asanyarray(res)
print("saving segmentation")
tifffile.imsave(output_namefile, res , photometric='minisblack' )
</code>```

答:
Some analysis first. The offending line:

```<code>sampleformat = {'u': 1, 'i': 2, 'f': 3, 'c': 6}[datadtype.kind]
</code>```

is causing a KeyError exception because the value of datadtype.kind (the NumPy datatype) is set to b and there is no b in that dictionary. It only caters for types i, u, f, and c (respectively, signed integer, unsigned integer, floating-point, and complex floating-point). Type b is boolean.

This looks like a bug in the code that you're using. If it's something that's not supported, the code should really catch the exception and report on it in a more user-friendly manner rather than just dumping an exception for you to figure out.

My advice is to raise this as a bug with the author.

In terms of the root cause of the issue (this is speculation based on analysis, so could be wrong, I'm just providing it as a possible cause), an examination of your code shows:

```<code>img = io.imread(input_namefile, plugin='tifffile')
thresh =  threshold_niblack(img, window_size=block_size , k=0.8) #
res = img > thresh
res = np.asanyarray(res)
tifffile.imsave(output_namefile, res , photometric='minisblack' )
</code>```

That third line above will set res to a either a boolean value or a boolean array that depends on the respective values of each pixel in img and thresh (I don't know enough about NumPy to pontificate on this).

However, regardless of that, they are one or more booleans so, when you try to write them with the imsave() call, it complains about the type being used (as mentioned above, it appears to not cater for boolean values correrctly).

Based on some sample code found elsewhere:

```<code>image = data.coins()
mask = image > 128
masked_image = image * mask
</code>```

I suspect that you should use something similar to that last line to apply the mask to the image, then write the resultant value:

```<code>img = io.imread(input_namefile, plugin='tifffile')
thresh =  threshold_niblack(img, window_size=block_size , k=0.8)

mask = image > 128  # <-- unsure if this is needed.
res = img * thresh  # <-- add this line.

res = np.asanyarray(res)
tifffile.imsave(output_namefile, res , photometric='minisblack' )
</code>```

Applying the mask to the original image should give you an array of usable values that you can write back out to an image file. Note that I'm unsure whether you need the res > thresh line since it appears to me that the threshold already gives you a mask. I could be wrong on that point so my advice is still to raise it with the author.

Body:
I am getting a strange error saving a tiff file (stack grayscale), any idea?:

File
  "C:\Users\ptyimg_np.MT00200169\Anaconda3\lib\site-packages\tifffile\tifffile.py",
  line 1241, in save
      sampleformat = {'u': 1, 'i': 2, 'f': 3, 'c': 6}[datadtype.kind] KeyError: 'b'

my code is

 #!/usr/bin/env python
# -*- coding: utf-8 -*-
from skimage.morphology import watershed
from skimage.feature import peak_local_max
from scipy import ndimage
from skimage import img_as_float
from skimage import exposure,io
from skimage import external
from skimage.color import rgb2gray
from skimage.filters import threshold_local  , threshold_niblack
import numpy as np
import  tifffile
from joblib import Parallel, delayed
import sys

# Load an example image
input_namefile = sys.argv[1]
output_namefile = 'seg_'+ input_namefile

#Settings
block_size = 25 #Size block of the local thresholding

img = io.imread(input_namefile, plugin='tifffile')
thresh =  threshold_niblack(img, window_size=block_size , k=0.8) #
res = img > thresh
res = np.asanyarray(res)
print("saving segmentation")
tifffile.imsave(output_namefile, res , photometric='minisblack' )

Body:
Some analysis first. The offending line:

sampleformat = {'u': 1, 'i': 2, 'f': 3, 'c': 6}[datadtype.kind]

is causing a KeyError exception because the value of datadtype.kind (the NumPy datatype) is set to b and there is no b in that dictionary. It only caters for types i, u, f, and c (respectively, signed integer, unsigned integer, floating-point, and complex floating-point). Type b is boolean.

This looks like a bug in the code that you're using. If it's something that's not supported, the code should really catch the exception and report on it in a more user-friendly manner rather than just dumping an exception for you to figure out.

My advice is to raise this as a bug with the author.

In terms of the root cause of the issue (this is speculation based on analysis, so could be wrong, I'm just providing it as a possible cause), an examination of your code shows:

img = io.imread(input_namefile, plugin='tifffile')
thresh =  threshold_niblack(img, window_size=block_size , k=0.8) #
res = img > thresh
res = np.asanyarray(res)
tifffile.imsave(output_namefile, res , photometric='minisblack' )

That third line above will set res to a either a boolean value or a boolean array that depends on the respective values of each pixel in img and thresh (I don't know enough about NumPy to pontificate on this).

However, regardless of that, they are one or more booleans so, when you try to write them with the imsave() call, it complains about the type being used (as mentioned above, it appears to not cater for boolean values correrctly).

Based on some sample code found elsewhere:

image = data.coins()
mask = image > 128
masked_image = image * mask

I suspect that you should use something similar to that last line to apply the mask to the image, then write the resultant value:

img = io.imread(input_namefile, plugin='tifffile')
thresh =  threshold_niblack(img, window_size=block_size , k=0.8)

mask = image > 128  # <-- unsure if this is needed.
res = img * thresh  # <-- add this line.

res = np.asanyarray(res)
tifffile.imsave(output_namefile, res , photometric='minisblack' )

Applying the mask to the original image should give you an array of usable values that you can write back out to an image file. Note that I'm unsure whether you need the res > thresh line since it appears to me that the threshold already gives you a mask. I could be wrong on that point so my advice is still to raise it with the author.


问:
things I don't get in python. bounded method acting like an alien
I don't understang this behaviour, I changed 'r' on the class 'f' and it is reflected back
on 'q' as you can see 'q.r' indicates that it is now referencing a 'lambda' function but at the same time the adress is always '0x037591F0' so why 'q.r()' is failling?</p>

```<code>class f:
    def r(self):
        print('bla bla bla')

>>> q=f()
>>> f.r
<function f.r at 0x0378F4B0>
>>> q.r
<bound method f.r of <__main__.f object at 0x037591F0>>
>>> f.r=lambda : 'google'
>>> f.r
<function <lambda> at 0x015F9348>
>>> q.r
<bound method <lambda> of <__main__.f object at 0x037591F0>>
>>> q.r()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: <lambda>() takes 0 positional arguments but 1 was given
</code>```

答: r is a class attribute whose value is a function. When you access it from an instance of the class, you don't actually get the function object back: you get back the result of the function's __get__ method, which is a new method object. Further, every such access creates a new method object, but because that object is short-lived (basically, it exists long enough to be called, then it is garbage-collected), each new object can use the same memory as the previous one.

Body:
I don't understang this behaviour, I changed 'r' on the class 'f' and it is reflected back
on 'q' as you can see 'q.r' indicates that it is now referencing a 'lambda' function but at the same time the adress is always '0x037591F0' so why 'q.r()' is failling?

class f:
    def r(self):
        print('bla bla bla')

>>> q=f()
>>> f.r
<function f.r at 0x0378F4B0>
>>> q.r
<bound method f.r of <__main__.f object at 0x037591F0>>
>>> f.r=lambda : 'google'
>>> f.r
<function <lambda> at 0x015F9348>
>>> q.r
<bound method <lambda> of <__main__.f object at 0x037591F0>>
>>> q.r()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: <lambda>() takes 0 positional arguments but 1 was given