问:
Eclipse error: The type org.eclipse.emf.edit.domain.EditingDomain cannot be resolved. It is indirectly referenced from required .class files
I've got an error message in Eclipse:

```<code>The type org.eclipse.emf.edit.domain.EditingDomain cannot be resolved.
It is indirectly referenced from required .class files
</code>```

I've got it when I tried to use the EMF DiffMerge plugin on my EMF model project. I loaded an instance model of my project from an EMF persisted XMI file to a Resource and tried to gave it to EMF DiffMerge like this (the error is given on the last line):

```<code>ResourceSet resSet = new ResourceSetImpl();

Resource resource = resSet.getResource(URI.createURI("grafok/MyGraph.xmi"),true);
IEditableModelScope targetScope = new FragmentedModelScope(resource);
</code>```

Can you help guys what's the problem?

Anyway I tried cleaning the project and remove the JRE library and add it again in the properties/Java build path, as advised in another similar post but these didnt help.

答:
You need to add org.eclipse.emf.transaction to the dependencies of your project.
That will solve you problem.

Body:
I've got an error message in Eclipse:

The type org.eclipse.emf.edit.domain.EditingDomain cannot be resolved.
It is indirectly referenced from required .class files

I've got it when I tried to use the EMF DiffMerge plugin on my EMF model project. I loaded an instance model of my project from an EMF persisted XMI file to a Resource and tried to gave it to EMF DiffMerge like this (the error is given on the last line):

ResourceSet resSet = new ResourceSetImpl();

Resource resource = resSet.getResource(URI.createURI("grafok/MyGraph.xmi"),true);
IEditableModelScope targetScope = new FragmentedModelScope(resource);

Can you help guys what's the problem?

Anyway I tried cleaning the project and remove the JRE library and add it again in the properties/Java build path, as advised in another similar post but these didnt help.


来源: stackexchange

问:
When sorting a Angular Material table can you view the data without modifying it?
Angular Material table utilizes a MatTableDataSource method called sortData() to sort the table's data source. (https://material.angular.io/components/table/api#MatTableDataSource). It is an arrow function:

```<code>sortData: ((data: T[], sort: MatSort) => T[])
</code>```

I need to view the sorted data without actually changing the sort. For example,

```<code>this.dataSource.sortData = (sortData) => {
    console.log(sortData);
    return sortData;
};
</code>```

The problem here is that I am overriding the native sort functionality. return sortData returns the original data, without any sorting. All I want to do is observe the sorted data without modifying it. Is it possible to do this?

答:
I hope I understood your question correctly.

So, you need to sort data without modifying it.

You should create a copy of your data and sort it. You can use a global variable or a property.

```<code>let sortedData;
this.dataSource.sortData = (sortData) => {
    this.sortedData = {...sortData};
    // Any kind of sorting
    console.log(sortedData);
    return sortData;
};
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Angular Material table utilizes a MatTableDataSource method called sortData() to sort the table's data source. (https://material.angular.io/components/table/api#MatTableDataSource). It is an arrow function:

sortData: ((data: T[], sort: MatSort) => T[])

I need to view the sorted data without actually changing the sort. For example,

this.dataSource.sortData = (sortData) => {
    console.log(sortData);
    return sortData;
};

The problem here is that I am overriding the native sort functionality. return sortData returns the original data, without any sorting. All I want to do is observe the sorted data without modifying it. Is it possible to do this?

Body:
I hope I understood your question correctly.

So, you need to sort data without modifying it.

You should create a copy of your data and sort it. You can use a global variable or a property.

let sortedData;
this.dataSource.sortData = (sortData) => {
    this.sortedData = {...sortData};
    // Any kind of sorting
    console.log(sortedData);
    return sortData;
};


问:
jQuery bind click
I have the following situation:

In a html page i have a dynamically generated button, similar to:

```<code><div id='myButton'></div>
</code>```

This html page includes a script (e.g., A.js), that handles most of the functionality of the site, and in this script the button is being bound to an handler:

```<code>$("#myButton").bind("click", function(){
foo();
});
</code>```

So far its simple. Now, only in a particular situation, i need the same button to execute a second function. This has to be done through another script, dynamically generated and injected inside the html site. So the html will look similar to this:

```<code><script type=text/javascript src=A.js></script>
<script type=text/javascript>
//Dynamically generated script
</script>
</code>```

I do not want to override the previous function, i still need that to be executed, but also i need this function to be executed before the first one. And the way scripts are included on the site cannot be changed.

So, I have written the following (inside the second script tag):

```<code>    $("#myButton").bind("click",
     function(){
          bar(); // I still want foo() to be executed but after this is executed first.
});
</code>```

Is it possible to do something like this? Note that i do not have control on how scripts  are included on my site. Altering that order is not possible.

答:
why not just combine bolt foo,bar into that function..

```<code>$("#myButton").bind("click", function(){
 bar();
 foo();
});
</code>```

or you may implement the foo() as callback function.

ContentLicense: CC BY-SA 3.0

Title: jQuery bind click

Body:
I have the following situation:

In a html page i have a dynamically generated button, similar to:

This html page includes a script (e.g., A.js), that handles most of the functionality of the site, and in this script the button is being bound to an handler:

$("#myButton").bind("click", function(){
foo();
});

So far its simple. Now, only in a particular situation, i need the same button to execute a second function. This has to be done through another script, dynamically generated and injected inside the html site. So the html will look similar to this:

I do not want to override the previous function, i still need that to be executed, but also i need this function to be executed before the first one. And the way scripts are included on the site cannot be changed.

So, I have written the following (inside the second script tag):

    $("#myButton").bind("click",
     function(){
          bar(); // I still want foo() to be executed but after this is executed first.
});

Is it possible to do something like this? Note that i do not have control on how scripts  are included on my site. Altering that order is not possible.

Body:
why not just combine bolt foo,bar into that function..

$("#myButton").bind("click", function(){
 bar();
 foo();
});

or you may implement the foo() as callback function.


问:
Use 'navigation' and 'route' inside header present in class - React-navigation v5
I'm stuck as I want to switch to the V5 version of react-navigation.
With v4, I used to pass my params and use them with :

Set :

this.props.navigation.navigate('MyDestination', {myParam: 'value'})

Get :

this.props.navigation.getParam('myParam')

With v5, some things changed and I now can't use the this.props.navigation since it's not seemed to be known by the app.

My code is splitted so I have my App.js that only refer to the Navigation class :

```<code>import React from 'react';
import { StyleSheet, Text, View } from 'react-native'
import Navigation from './navigation/Navigation'

export default function App() {
  return (
      <Navigation/>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});
</code>```

Then my Navigation file contains all the navigation mechanism (I did not added my TabBar yet, since I want to fix the base navigation first) :

```<code>import { NavigationContainer } from '@react-navigation/native'
import { createStackNavigator } from '@react-navigation/stack'
import { createBottomTabNavigator } from 'react-navigation-tabs'
import { StyleSheet, Image } from 'react-native'
import React from 'react'
import Home from '../components/Home'
import LendList from '../components/LendList'
import AddMoney from '../components/AddMoney'
import AddStuff from '../components/AddStuff'
import Settings from '../components/Settings'
import Test from '../components/Test'

function HomeScreen() {
    return(
        <Home/>
    )
}

function LendListScreen() {
    return(
        <LendList/>
    )
}

const Stack = createStackNavigator()

function App() {
    return(
        <NavigationContainer>
            <Stack.Navigator initialRouteName="Home">
                <Stack.Screen name="Home"
                component={Home}
                options={{ title: "Home Page"}}
                />
                <Stack.Screen name="LendList"
                component={LendList}
                options={{ title: 'Liste' }}
                />
                <Stack.Screen name="AddMoney"
                component={AddMoney}
                options={{ title: "Ajout Money"}}
                />
                <Stack.Screen name="AddStuff"
                component={AddStuff}
                options={{ title: "Ajout Stuff"}}
                />
                <Stack.Screen name="Settings"
                component={Settings}
                options={{ title: "Settings"}}
                />
                <Stack.Screen name="Test"
                component={Test}
                options={{ title: "Test"}}
                />
            </Stack.Navigator>
        </NavigationContainer>
    )
}

export default App
</code>```

And then come each of my pages (coded with classes), and here is one example, Home.js (I removed all the Style part to shorten the code displayed here) :

```<code>import React from 'react'
import { StyleSheet, Text, Image, View, Button, TouchableOpacity } from 'react-native'
import Moment from 'react-moment'
import { CommonActions } from '@react-navigation/native'
import { useNavigation } from '@react-navigation/native'

class Home extends React.Component {

    static navigationOptions = () => {

        return {
            headerRight: () => <TouchableOpacity style={styles.settings_touchable_headerrightbutton}
                            onPress={() => this.goToSettings()}>
                            <Image style={styles.settings_image}
                            source={require('../assets/ic_settings.png')} />
            </TouchableOpacity>
        }
    }

    constructor(props) {
        super(props)
        this._goToSettings = this._goToSettings.bind(this)
    }

    _updateNavigationParams() {
        navigation.setParams({
          goToSettings: this._goToSettings
        })
    }

    componentDidMount(){
        console.log("navigation")
        this._updateNavigationParams()

    }

    _checkMoneyDetails(navigation){
        navigation.navigate('LendList', {type: 'Money'})
    }

    _checkStuffDetails(navigation){
        navigation.navigate('LendList', {type: 'Stuff'})
    }

    _checkPeopleDetails(navigation){
        navigation.navigate('LendList', {type: 'People'})
    }

    _goToSettings = () => {
        navigation.navigate('Settings')
    }

    render(){
        const date = new Date();
        const { navigation } = this.props;

        return(
            <View style={styles.main_container}>
                <View style={styles.header_view}>
                    <Text style={styles.header_text}>GiViToMe</Text>
                    <Text style={styles.header_text}>Nous sommes le :{' '}
                    {/* TODO: Penser à gérer ensuite les formats de date étrangers */}
                        <Moment element={Text} format="DD/MM/YYYY" date={date}/>
                    </Text>
                </View>
                <View style={styles.lend_view}>
                    <Text style={styles.title_lend_text}>Vos prêts :</Text>
                    <View style={styles.money_stuff_view}>
                        <View style={styles.money_view}>
                            <View style={styles.money_data_view}>
                                <Image source={require('../assets/ic_money.png')} style={styles.home_img} />
                                <Text>XXX $</Text>
                            </View>
                            <Button title='Money' onPress={() => {this._checkMoneyDetails(navigation)}}/>
                        </View>
                        <View style={styles.stuff_view}>
                            <View style={styles.stuff_data_view}>
                                <Image source={require('../assets/ic_box.png')} style={styles.home_img} />
                                <Text>XXX objets</Text>
                            </View>
                            <Button title='Stuff' onPress={() => {this._checkStuffDetails(navigation)}}/>
                        </View>
                    </View>
                    <View style={styles.people_view}>
                        <View style={styles.people_data_view}>
                            <Image source={require('../assets/ic_people.png')} style={styles.home_img} />
                            <Text>XXX people</Text>
                        </View>
                        <Button title='People' onPress={() => {this._checkPeopleDetails(navigation)}}/>
                    </View>
                </View>
                <View style={styles.footer_view}>
                    <Text style={styles.text_footer_view}>a.vescera inc.</Text>
                </View>
            </View>
        )
    }
}

export default Home
</code>```

My problem is that, per the online documentation, I saw that to use "navigation" or "route" within a class, I should use the const navigation = { this.props } after the render() function.

This problem is that, to use one specific function within the header, I have to bind it after the componentDidMount() function, but the value present under render() is not yet known.

How could I solve this ? (sure that in the given example, having all the code in the navigation part allow to use navigation and route easily but you understand that I have to split my code.

Thanks.

答:
Ok, so each time the same, I try many days solving my problem, and when I finally decide to post on stack, I find a solution :).

So, if there's some performance issue or other you may see by looking at my code, do not hesitate to correct me. I just found that this solution solved my problem.

So within my Navigation.js file, I just passed the navigation and route objects to make them usable thanks to the props into my classes, like this :

```<code>function App() {
    return(
        <NavigationContainer>
            <Stack.Navigator initialRouteName="Home">
                <Stack.Screen name="Home"
                component={Home}
                options={({route, navigation}) => (
                    {headerTitle: 'Home Page',
                    route: {route},
                    navigation: {navigation}}
                )}
                />
            </Stack.Navigator>
        </NavigatorContainer>
)}
</code>```

then within my classes I just call to this.props.navigation or this.props.route and gather form these objects what I need.

Other thing is that, for those who would use this code to build something similar, I also had to change the way I display the header button.
I do not use the static navigationOptions = () => {} anymore. I just add directly the navigation.setOptions piece of code within the ComponentDidMount function like this:

```<code>navigation.setOptions({
            headerRight: () => <TouchableOpacity style={styles.settings_touchable_headerrightbutton}
                            onPress={() => route.params.goToSettings()}>
                            <Image style={styles.settings_image}
                            source={require('../assets/ic_settings.png')} />
            </TouchableOpacity>
        })
</code>```

I have to do it this way since I'm using a function declared in my class, so I have to bind it in the constructor like this this._goToSettings = this._goToSettings.bind(this) and then add it to the navigation.setParams function.

Body:
I'm stuck as I want to switch to the V5 version of react-navigation.
With v4, I used to pass my params and use them with :

Set :

this.props.navigation.navigate('MyDestination', {myParam: 'value'})

Get :

this.props.navigation.getParam('myParam')

With v5, some things changed and I now can't use the this.props.navigation since it's not seemed to be known by the app.

My code is splitted so I have my App.js that only refer to the Navigation class :

import React from 'react';
import { StyleSheet, Text, View } from 'react-native'
import Navigation from './navigation/Navigation'

export default function App() {
  return (
      <Navigation/>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

Then my Navigation file contains all the navigation mechanism (I did not added my TabBar yet, since I want to fix the base navigation first) :

import { NavigationContainer } from '@react-navigation/native'
import { createStackNavigator } from '@react-navigation/stack'
import { createBottomTabNavigator } from 'react-navigation-tabs'
import { StyleSheet, Image } from 'react-native'
import React from 'react'
import Home from '../components/Home'
import LendList from '../components/LendList'
import AddMoney from '../components/AddMoney'
import AddStuff from '../components/AddStuff'
import Settings from '../components/Settings'
import Test from '../components/Test'

function HomeScreen() {
    return(
        <Home/>
    )
}

function LendListScreen() {
    return(
        <LendList/>
    )
}

const Stack = createStackNavigator()

function App() {
    return(
        <NavigationContainer>
            <Stack.Navigator initialRouteName="Home">
                <Stack.Screen name="Home"
                component={Home}
                options={{ title: "Home Page"}}
                />
                <Stack.Screen name="LendList"
                component={LendList}
                options={{ title: 'Liste' }}
                />
                <Stack.Screen name="AddMoney"
                component={AddMoney}
                options={{ title: "Ajout Money"}}
                />
                <Stack.Screen name="AddStuff"
                component={AddStuff}
                options={{ title: "Ajout Stuff"}}
                />
                <Stack.Screen name="Settings"
                component={Settings}
                options={{ title: "Settings"}}
                />
                <Stack.Screen name="Test"
                component={Test}
                options={{ title: "Test"}}
                />
            </Stack.Navigator>
        </NavigationContainer>
    )
}

export default App

And then come each of my pages (coded with classes), and here is one example, Home.js (I removed all the Style part to shorten the code displayed here) :

import React from 'react'
import { StyleSheet, Text, Image, View, Button, TouchableOpacity } from 'react-native'
import Moment from 'react-moment'
import { CommonActions } from '@react-navigation/native'
import { useNavigation } from '@react-navigation/native'

class Home extends React.Component {

    static navigationOptions = () => {

        return {
            headerRight: () => <TouchableOpacity style={styles.settings_touchable_headerrightbutton}
                            onPress={() => this.goToSettings()}>
                            <Image style={styles.settings_image}
                            source={require('../assets/ic_settings.png')} />
            </TouchableOpacity>
        }
    }

    constructor(props) {
        super(props)
        this._goToSettings = this._goToSettings.bind(this)
    }

    _updateNavigationParams() {
        navigation.setParams({
          goToSettings: this._goToSettings
        })
    }

    componentDidMount(){
        console.log("navigation")
        this._updateNavigationParams()

    }

    _checkMoneyDetails(navigation){
        navigation.navigate('LendList', {type: 'Money'})
    }

    _checkStuffDetails(navigation){
        navigation.navigate('LendList', {type: 'Stuff'})
    }

    _checkPeopleDetails(navigation){
        navigation.navigate('LendList', {type: 'People'})
    }

    _goToSettings = () => {
        navigation.navigate('Settings')
    }

    render(){
        const date = new Date();
        const { navigation } = this.props;

        return(
            <View style={styles.main_container}>
                <View style={styles.header_view}>
                    <Text style={styles.header_text}>GiViToMe</Text>
                    <Text style={styles.header_text}>Nous sommes le :{' '}
                    {/* TODO: Penser à gérer ensuite les formats de date étrangers */}
                        <Moment element={Text} format="DD/MM/YYYY" date={date}/>
                    </Text>
                </View>
                <View style={styles.lend_view}>
                    <Text style={styles.title_lend_text}>Vos prêts :</Text>
                    <View style={styles.money_stuff_view}>
                        <View style={styles.money_view}>
                            <View style={styles.money_data_view}>
                                <Image source={require('../assets/ic_money.png')} style={styles.home_img} />
                                <Text>XXX $</Text>
                            </View>
                            <Button title='Money' onPress={() => {this._checkMoneyDetails(navigation)}}/>
                        </View>
                        <View style={styles.stuff_view}>
                            <View style={styles.stuff_data_view}>
                                <Image source={require('../assets/ic_box.png')} style={styles.home_img} />
                                <Text>XXX objets</Text>
                            </View>
                            <Button title='Stuff' onPress={() => {this._checkStuffDetails(navigation)}}/>
                        </View>
                    </View>
                    <View style={styles.people_view}>
                        <View style={styles.people_data_view}>
                            <Image source={require('../assets/ic_people.png')} style={styles.home_img} />
                            <Text>XXX people</Text>
                        </View>
                        <Button title='People' onPress={() => {this._checkPeopleDetails(navigation)}}/>
                    </View>
                </View>
                <View style={styles.footer_view}>
                    <Text style={styles.text_footer_view}>a.vescera inc.</Text>
                </View>
            </View>
        )
    }
}

export default Home

My problem is that, per the online documentation, I saw that to use "navigation" or "route" within a class, I should use the const navigation = { this.props } after the render() function.

This problem is that, to use one specific function within the header, I have to bind it after the componentDidMount() function, but the value present under render() is not yet known.

How could I solve this ? (sure that in the given example, having all the code in the navigation part allow to use navigation and route easily but you understand that I have to split my code.

Thanks.

Body:
Ok, so each time the same, I try many days solving my problem, and when I finally decide to post on stack, I find a solution :).

So, if there's some performance issue or other you may see by looking at my code, do not hesitate to correct me. I just found that this solution solved my problem.

So within my Navigation.js file, I just passed the navigation and route objects to make them usable thanks to the props into my classes, like this :

function App() {
    return(
        <NavigationContainer>
            <Stack.Navigator initialRouteName="Home">
                <Stack.Screen name="Home"
                component={Home}
                options={({route, navigation}) => (
                    {headerTitle: 'Home Page',
                    route: {route},
                    navigation: {navigation}}
                )}
                />
            </Stack.Navigator>
        </NavigatorContainer>
)}

then within my classes I just call to this.props.navigation or this.props.route and gather form these objects what I need.

Other thing is that, for those who would use this code to build something similar, I also had to change the way I display the header button.
I do not use the static navigationOptions = () => {} anymore. I just add directly the navigation.setOptions piece of code within the ComponentDidMount function like this:

navigation.setOptions({
            headerRight: () => <TouchableOpacity style={styles.settings_touchable_headerrightbutton}
                            onPress={() => route.params.goToSettings()}>
                            <Image style={styles.settings_image}
                            source={require('../assets/ic_settings.png')} />
            </TouchableOpacity>
        })

I have to do it this way since I'm using a function declared in my class, so I have to bind it in the constructor like this this._goToSettings = this._goToSettings.bind(this) and then add it to the navigation.setParams function.


问:
pip-18.0 has 'logging module not found' error
Having just upgraded to  pip-18.0

all uses of pip produce this error:

```<code>...\site-packages\pip\_internal\__init__.py", line 5, in <module>
    import logging
ModuleNotFoundError: No module named 'logging'

logging.py exists in \site-packages\pip\_internal\utils\
(and also contains an 'import logging' statement!)
</code>```

I suppose I could move it up a directory level or update _init to 'import utils.logging'
In fact lots of my programs' packages eg numpy are now failing with no logging module.   I have now identified the problem:

import logging

Traceback (most recent call last):
  File "", line 1, in
    import logging
ModuleNotFoundError: No module named 'logging'

import lib2to3.logging

lib2to3 is a subdir of Lib, containing the logging module,
but is no longer found in the module search.

答:
In my case, running OpenWrt/LEDE 17.01.4 on the client, I had installed most of Python3 via:

```<code>opkg install python3-light
</code>```

when I received the ImportError: No module named logging. I needed to separately install the logging package:

```<code>opkg install python3-logging
</code>```

The above is enough to run the Ansible ping module. To run the setup module you also need:

```<code>opkg install python3-multiprocessing python3-distutils
</code>```

Body:
Having just upgraded to  pip-18.0

all uses of pip produce this error:

...\site-packages\pip\_internal\__init__.py", line 5, in <module>
    import logging
ModuleNotFoundError: No module named 'logging'

logging.py exists in \site-packages\pip\_internal\utils\
(and also contains an 'import logging' statement!)

I suppose I could move it up a directory level or update _init to 'import utils.logging'
In fact lots of my programs' packages eg numpy are now failing with no logging module.   I have now identified the problem:

import logging

Traceback (most recent call last):
  File "", line 1, in
    import logging
ModuleNotFoundError: No module named 'logging'

import lib2to3.logging

lib2to3 is a subdir of Lib, containing the logging module,
but is no longer found in the module search.

Body:
In my case, running OpenWrt/LEDE 17.01.4 on the client, I had installed most of Python3 via:

opkg install python3-light

when I received the ImportError: No module named logging. I needed to separately install the logging package:

opkg install python3-logging

The above is enough to run the Ansible ping module. To run the setup module you also need:

opkg install python3-multiprocessing python3-distutils


问:
Laravel paginate 'Allowed memory exhausted'
I got the problem when i was trying to paginate results of big query with several joins and groupBy inside. Part of my code here:

```<code>$lots = Lot::select('lots.id', 'lots.name', 'lots.slug', 'lots.description', 'lots.customer as lot_customer',
            'lots.created_at', 'lots.measure', 'lots.delivery_place', 'lots.amount as real_amount', 'lots.amount')
            ->leftJoin('tenders', 'tenders.id', '=', 'lots.tender_id')
            ->leftJoin('customers', 'lots.customer_id', '=', 'customers.id')
            ->groupBy('lots.id')
            ->paginate(25);
</code>```

I had 420650 - total records in database, but for pagination i wanted to show only 25 records per page. I got message:

Allowed memory size exhausted (tried to allocate 16777224 bytes)...

If you have way to resolve such problem, please share. Thank you!

答:
You can increase the memory limit php.ini</p>

```<code>ini_set('memory_limit','160M'); or memory_limit = 2024M
</code>```

Body:
I got the problem when i was trying to paginate results of big query with several joins and groupBy inside. Part of my code here:

$lots = Lot::select('lots.id', 'lots.name', 'lots.slug', 'lots.description', 'lots.customer as lot_customer',
            'lots.created_at', 'lots.measure', 'lots.delivery_place', 'lots.amount as real_amount', 'lots.amount')
            ->leftJoin('tenders', 'tenders.id', '=', 'lots.tender_id')
            ->leftJoin('customers', 'lots.customer_id', '=', 'customers.id')
            ->groupBy('lots.id')
            ->paginate(25);

I had 420650 - total records in database, but for pagination i wanted to show only 25 records per page. I got message:

Allowed memory size exhausted (tried to allocate 16777224 bytes)...

If you have way to resolve such problem, please share. Thank you!

Body:
You can increase the memory limit php.ini

ini_set('memory_limit','160M'); or memory_limit = 2024M


问:
Powershell newcomer
I am a total new comer to powershell so please forgive me if my question sounds stupid. I found the script below from Yuri Posidelov which I tweaked to activate a process and show the window and send keystrokes to shut down the process which works great. However it fails if there are two process with the same name can anyone help me with this.

Orignal code by Yuriy Posidelov

```<code>param([string] $proc="SBDDesktop", [string]$adm)

cls

Add-Type @"

  using System;

  using System.Runtime.InteropServices;

  public class WinAp {

     [DllImport("user32.dll")]

     [return: MarshalAs(UnmanagedType.Bool)]

     public static extern bool SetForegroundWindow(IntPtr hWnd);

     [DllImport("user32.dll")]

     [return: MarshalAs(UnmanagedType.Bool)]

     public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

  }

"@

$p = Get-Process |where {$_.mainWindowTItle }|where {$_.Name -like "$proc"}

if (($p -eq $null) -and ($adm -ne ""))

{

    Start-Process "$proc" -Verb runAs

}

elseif (($p -eq $null) -and ($adm -eq ""))

{

    Start-Process "$proc" #-Verb runAs

}

else

{

    $h = $p.MainWindowHandle

    [void] [WinAp]::SetForegroundWindow($h)

    [void] [WinAp]::ShowWindow($h,3);

    $wshell = New-Object -ComObject wscript.shell;

    #$wshell.SendKeys('~')

    $wshell.SendKeys('%fx')

    sleep 1

    $wshell.SendKeys('N')

}

#|format-table id,name,mainwindowtitle –AutoSize

# static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

# powershell.exe -windowstyle hidden -file *.ps1 -adm "a"
</code>```

答:
If more than one windowhandle, do a loop:</p>

```<code>$processList = [object[]]@( Get-Process |where {$_.mainWindowTItle }|where {$_.Name -like "$proc"} )

foreach( $p in $processList ) {

    if (($p -eq $null) -and ($adm -ne "")) {
        Start-Process "$proc" -Verb runAs
    }
    elseif (($p -eq $null) -and ($adm -eq "")) {
        Start-Process "$proc" #-Verb runAs
    }
    else {

        $h = $p.MainWindowHandle

        [WinAp]::SetForegroundWindow($h) | Out-Null

        [WinAp]::ShowWindow($h,3) | Out-Null

        $wshell = New-Object -ComObject wscript.shell;

        #[void]$wshell.SendKeys('~')

        [void]$wshell.SendKeys('%fx')

        sleep 1 | Out-Null

        [void]$wshell.SendKeys('N')
    }
}
</code>```

Title: Powershell newcomer

Body:
I am a total new comer to powershell so please forgive me if my question sounds stupid. I found the script below from Yuri Posidelov which I tweaked to activate a process and show the window and send keystrokes to shut down the process which works great. However it fails if there are two process with the same name can anyone help me with this.

Orignal code by Yuriy Posidelov

param([string] $proc="SBDDesktop", [string]$adm)

cls

Add-Type @"

  using System;

  using System.Runtime.InteropServices;

  public class WinAp {

     [DllImport("user32.dll")]

     [return: MarshalAs(UnmanagedType.Bool)]

     public static extern bool SetForegroundWindow(IntPtr hWnd);

     [DllImport("user32.dll")]

     [return: MarshalAs(UnmanagedType.Bool)]

     public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

  }

"@

$p = Get-Process |where {$_.mainWindowTItle }|where {$_.Name -like "$proc"}

if (($p -eq $null) -and ($adm -ne ""))

{

    Start-Process "$proc" -Verb runAs

}

elseif (($p -eq $null) -and ($adm -eq ""))

{

    Start-Process "$proc" #-Verb runAs

}

else

{

    $h = $p.MainWindowHandle

    [void] [WinAp]::SetForegroundWindow($h)

    [void] [WinAp]::ShowWindow($h,3);

    $wshell = New-Object -ComObject wscript.shell;

    #$wshell.SendKeys('~')

    $wshell.SendKeys('%fx')

    sleep 1

    $wshell.SendKeys('N')

}

#|format-table id,name,mainwindowtitle –AutoSize

# static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

# powershell.exe -windowstyle hidden -file *.ps1 -adm "a"

Body:
If more than one windowhandle, do a loop:

$processList = [object[]]@( Get-Process |where {$_.mainWindowTItle }|where {$_.Name -like "$proc"} )

foreach( $p in $processList ) {

    if (($p -eq $null) -and ($adm -ne "")) {
        Start-Process "$proc" -Verb runAs
    }
    elseif (($p -eq $null) -and ($adm -eq "")) {
        Start-Process "$proc" #-Verb runAs
    }
    else {

        $h = $p.MainWindowHandle

        [WinAp]::SetForegroundWindow($h) | Out-Null

        [WinAp]::ShowWindow($h,3) | Out-Null

        $wshell = New-Object -ComObject wscript.shell;

        #[void]$wshell.SendKeys('~')

        [void]$wshell.SendKeys('%fx')

        sleep 1 | Out-Null

        [void]$wshell.SendKeys('N')
    }
}


问:
Maximum Size List in Java
It's useful to me to have a data structure in Java that has all the functionality of a List, but has a maximum storage capacity, and drops older data when newer data is added. Conceivably at some point I might want to implement a fixed size Queue which keeps a more general ordering of the data, and drops the old data lowest in that ordering, but that's the for the future.

At the moment I'm implementing it like this:

```<code>public class FixedSizeList<T> {

  private final int maxSize;
  private final LinkedList<T> list = new LinkedList<T>();

  public FixedSizeQueue(int maxSize) {
    this.maxSize = maxSize < 0 ? 0 : maxSize;
  }

  public T add(T t) {
    list.add(t);
    return list.size() > maxSize ? list.remove() : null;
  }

  // add remaining methods...

}
</code>```

Is there either (a) an existing data structure that serves my needs, or (b) a better way of implementing this data structure?

答: I would use array and 2 indexes for head and tail of the list.Make sure that head is always < tail and you're safe.</p>

Title: Maximum Size List in Java

Body:
It's useful to me to have a data structure in Java that has all the functionality of a List, but has a maximum storage capacity, and drops older data when newer data is added. Conceivably at some point I might want to implement a fixed size Queue which keeps a more general ordering of the data, and drops the old data lowest in that ordering, but that's the for the future.

At the moment I'm implementing it like this:

public class FixedSizeList<T> {

  private final int maxSize;
  private final LinkedList<T> list = new LinkedList<T>();

  public FixedSizeQueue(int maxSize) {
    this.maxSize = maxSize < 0 ? 0 : maxSize;
  }

  public T add(T t) {
    list.add(t);
    return list.size() > maxSize ? list.remove() : null;
  }

  // add remaining methods...

}

Is there either (a) an existing data structure that serves my needs, or (b) a better way of implementing this data structure?


问:
How to get x and two y axis values of chart
I would like to get the value of X, and the values of the two axes Y and display them in MarkerViev. How can I do this? My markerview code and the desired result are presented below.

public class MyMarkerView extends MarkerView {

    private final TextView tvContent;
    private final TextView tvTime;

    public MyMarkerView(Context context, int layoutResource) {
        super(context, layoutResource);

        tvContent = findViewById(R.id.tvFuel);
        tvTime = findViewById(R.id.time_chart);
    }

    // runs every time the MarkerView is redrawn, can be used to update the
    // content (user-interface)
    @Override
    public void refreshContent(Entry e, Highlight highlight) {

        if (e instanceof CandleEntry) {

            CandleEntry ce = (CandleEntry) e;

            tvContent.setText(Utils.formatNumber(ce.getHigh(), 0, true));
        } else {

            String fuelText = "Топливо: " + Utils.formatNumber(e.getY(), 0, true) + " л.";
            tvContent.setText(fuelText);
            //here get x string and second Y axis values...

        }

        super.refreshContent(e, highlight);
    }

    @Override
    public MPPointF getOffset() {
        return new MPPointF(-(getWidth() / 2), -getHeight());
    }
}
```

Desired Result

答:
Thanks for the comment, Manu. I solved the problem as follows.

```<code>public class MyMarkerView extends MarkerView {

private final TextView tvFuel;
private final TextView tvTime;
private final TextView tvSpeed;

private Float[] mFuelSet;
private Float[] mSpeedSet;
private String[] mTimeSet;

public MyMarkerView(Context context, int layoutResource, Float[] fuelSet, Float[] speedSet, String[] timeSet) {
    super(context, layoutResource);

    tvFuel = findViewById(R.id.tvFuel);
    tvSpeed = findViewById(R.id.tvSpeed);
    tvTime = findViewById(R.id.time_chart);

    mFuelSet = fuelSet;
    mSpeedSet = speedSet;
    mTimeSet = timeSet;
}

@Override
public void refreshContent(Entry e, Highlight highlight) {

    if (e instanceof CandleEntry) {
        CandleEntry ce = (CandleEntry) e;
        tvFuel.setText(Utils.formatNumber(ce.getHigh(), 0, true));
    } else {

        int index = (int) e.getX();

        String fuelText = "Топливо: " + mFuelSet[index] + " л.";
        tvFuel.setText(fuelText);
        String speedText = "Скорость: " + mSpeedSet[index] + " км/ч";
        tvSpeed.setText(speedText);
        String timeText = mTimeSet[index];
        tvTime.setText(timeText);
    }

    super.refreshContent(e, highlight);
}
</code>```

}

Body:
I would like to get the value of X, and the values of the two axes Y and display them in MarkerViev. How can I do this? My markerview code and the desired result are presented below.

public class MyMarkerView extends MarkerView {

    private final TextView tvContent;
    private final TextView tvTime;

    public MyMarkerView(Context context, int layoutResource) {
        super(context, layoutResource);

        tvContent = findViewById(R.id.tvFuel);
        tvTime = findViewById(R.id.time_chart);
    }

    // runs every time the MarkerView is redrawn, can be used to update the
    // content (user-interface)
    @Override
    public void refreshContent(Entry e, Highlight highlight) {

        if (e instanceof CandleEntry) {

            CandleEntry ce = (CandleEntry) e;

            tvContent.setText(Utils.formatNumber(ce.getHigh(), 0, true));
        } else {

            String fuelText = "Топливо: " + Utils.formatNumber(e.getY(), 0, true) + " л.";
            tvContent.setText(fuelText);
            //here get x string and second Y axis values...

        }

        super.refreshContent(e, highlight);
    }

    @Override
    public MPPointF getOffset() {
        return new MPPointF(-(getWidth() / 2), -getHeight());
    }
}

Desired Result

Body:
Thanks for the comment, Manu. I solved the problem as follows.

public class MyMarkerView extends MarkerView {

private final TextView tvFuel;
private final TextView tvTime;
private final TextView tvSpeed;

private Float[] mFuelSet;
private Float[] mSpeedSet;
private String[] mTimeSet;

public MyMarkerView(Context context, int layoutResource, Float[] fuelSet, Float[] speedSet, String[] timeSet) {
    super(context, layoutResource);

    tvFuel = findViewById(R.id.tvFuel);
    tvSpeed = findViewById(R.id.tvSpeed);
    tvTime = findViewById(R.id.time_chart);

    mFuelSet = fuelSet;
    mSpeedSet = speedSet;
    mTimeSet = timeSet;
}

@Override
public void refreshContent(Entry e, Highlight highlight) {

    if (e instanceof CandleEntry) {
        CandleEntry ce = (CandleEntry) e;
        tvFuel.setText(Utils.formatNumber(ce.getHigh(), 0, true));
    } else {

        int index = (int) e.getX();

        String fuelText = "Топливо: " + mFuelSet[index] + " л.";
        tvFuel.setText(fuelText);
        String speedText = "Скорость: " + mSpeedSet[index] + " км/ч";
        tvSpeed.setText(speedText);
        String timeText = mTimeSet[index];
        tvTime.setText(timeText);
    }

    super.refreshContent(e, highlight);
}

}


问:
Laravel api authenticates POST requests but returns 'Unauthenticated' with GET
I have setup a Route group to authenticate my API calls with a token.

POST requests work fine, valid token passes authentication and an invalid one returns "Unauthenticated" as expected.

When making a GET request I get "Unauthenticated" every time.

I'm making GET requests with the same api_token that I made the POST requests with and still get "Unauthenticated"

This is my route group

```<code>Route::group(['middleware' => ['auth:api', 'api']], function () {
    Route::post('/', 'ApiPostController@store');
    Route::get('/', 'ApiPostController@fetch');
});

</code>```

I tried removing the POST route from the group, that didn't work. Tried changing the route (from / to /get) that didn't do anything either.

What is causing the GET requests to fail even though I'm sending a valid token?

答:
If you are in Apache server you can try adding those line in .htaccess

```<code>RewriteEngine On
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]
</code>```

you can also clear config and try

```<code>php artisan config:clear
</code>```

you can add @csrf as well.

Body:
I have setup a Route group to authenticate my API calls with a token.

POST requests work fine, valid token passes authentication and an invalid one returns "Unauthenticated" as expected.

When making a GET request I get "Unauthenticated" every time.

I'm making GET requests with the same api_token that I made the POST requests with and still get "Unauthenticated"

This is my route group

Route::group(['middleware' => ['auth:api', 'api']], function () {
    Route::post('/', 'ApiPostController@store');
    Route::get('/', 'ApiPostController@fetch');
});

I tried removing the POST route from the group, that didn't work. Tried changing the route (from / to /get) that didn't do anything either.

What is causing the GET requests to fail even though I'm sending a valid token?

Body:
If you are in Apache server you can try adding those line in .htaccess

RewriteEngine On
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]

you can also clear config and try

php artisan config:clear

you can add @csrf as well.


问:
C++ runtime type switching with multiple enums
This is a magic switch problem, the solution was described here. However, I was wondering if it was possible to make it 3-dimensional, i.e. let it switch based on three given enums. In the ideal case, n-dimensional would be preferred of course. I tried first to make it 2-dimensional as shown below, but I run into double variadic unpacking, and I cannot find out how that would work.

template<class Enum, class Enum2, template<Enum, Enum2>class Z>
struct magic_switch {
  // return value of a call to magic_switch(Args...)
  template<class...Args>
  using R = std::result_of_t<Z<Enum(0), Enum2(0)>(Args...)>;
  // A function pointer for a jump table:
  template<class...Args>
  using F = R<Args...>(*)(Args&&...);
  // Produces a single function pointer for index I and args Args...
  template<size_t I, size_t I2, class...Args>
  F<Args...> f() const {
    using ret = R<Args...>;
    return +[](Args&&...args)->ret{
      using Invoke=Z<Enum(I), Enum(I2)>;
      return Invoke{}(std::forward<Args>(args)...);
    };
  }
  // builds a jump table:
  template<class...Args, size_t...Is, size_t ...Is2>
  std::array<F<Args...>,size_t(Enum::COUNT)>
  table( std::index_sequence<Is...>, std::index_sequence<Is2...> ) const {
    return {{
      f<Is, Is2, Args...>()... ... // << -- 2d expansion not working
    }};
  }
  template<class...Args>
  R<Args...> operator()(Enum n, Enum2 n2, Args&&...args) {
    // a static jump table for this case of Args...:
    static auto jump=table<Args...>(std::make_index_sequence<size_t(Enum::COUNT)>{}, std::make_index_sequence<size_t(Enum2::COUNT)>{});
    // Look up the nth entry in the jump table, and invoke it:
    return jump[size_t(n) + size_t(Enum::COUNT) * size_t(n2)](std::forward<Args>(args)...);
  }
};
```

<p>Calling this code would be as follows </p>

<pre class="lang-cpp prettyprint-override"><code>enum class abc_enum { a, b, c, COUNT };
enum class defg_enum { d, e, f, g, COUNT };

template<abc_enum e, defg_enum f>
struct stuff {
  void operator()() const {
    std::cout << (int)e << '\n';
    std::cout << (int)f << '\n';
  }
};
magic_switch<abc_enum, defg_enum, stuff>{}(abc_enum::b, defg_enum::f);
</code>```

However, above does not compile due to the double variadic pack expansion. For more dimensions, even more variadic packs would have to be unpacked. Is there a solution for the n-dimensional magic switch problem?

答:
You might do it by step,

First transform each runtime enum into std::variant of the possible std::integral_constant:

```<code>template <typename Enum, typename Seq> struct EnumVariantHelper;

template <typename Enum, std::size_t ... Is>
struct EnumVariantHelper<Enum, std::index_sequence<Is...>>
{
    using type = std::variant<std::integral_constant<Enum, Enum(Is)>...>;
};

template <typename Enum, std::size_t Count>
using EnumVariant = typename EnumVariantHelper<Enum, std::make_index_sequence<Count>>::type;

template <typename Enum, std::size_t Count>
struct AsVariant
{
    template <Enum E>
    struct F
    {
        EnumVariant<Enum, Count> operator()() const
        {
            return std::integral_constant<Enum, E>{};
        }
    };
};
</code>```

Then, let the combination stuff to std::visit, you might do something like:

```<code>auto v1 = magic_switch<abc_enum, abc_enum::COUNT,
                       AsVariant<abc_enum, std::size_t(abc_enum::COUNT)>::F>{}(abc_enum::b);
auto v2 = magic_switch<defg_enum, defg_enum::COUNT,
                       AsVariant<defg_enum, std::size_t(defg_enum::COUNT)>::F>{}(defg_enum::f);

std::visit([](auto e1, auto e2){ return stuff<e1(), e2()>{}(); }, v1, v2);
</code>```

Demo

Body:
This is a magic switch problem, the solution was described here. However, I was wondering if it was possible to make it 3-dimensional, i.e. let it switch based on three given enums. In the ideal case, n-dimensional would be preferred of course. I tried first to make it 2-dimensional as shown below, but I run into double variadic unpacking, and I cannot find out how that would work.

template<class Enum, class Enum2, template<Enum, Enum2>class Z>
struct magic_switch {
  // return value of a call to magic_switch(Args...)
  template<class...Args>
  using R = std::result_of_t<Z<Enum(0), Enum2(0)>(Args...)>;
  // A function pointer for a jump table:
  template<class...Args>
  using F = R<Args...>(*)(Args&&...);
  // Produces a single function pointer for index I and args Args...
  template<size_t I, size_t I2, class...Args>
  F<Args...> f() const {
    using ret = R<Args...>;
    return +[](Args&&...args)->ret{
      using Invoke=Z<Enum(I), Enum(I2)>;
      return Invoke{}(std::forward<Args>(args)...);
    };
  }
  // builds a jump table:
  template<class...Args, size_t...Is, size_t ...Is2>
  std::array<F<Args...>,size_t(Enum::COUNT)>
  table( std::index_sequence<Is...>, std::index_sequence<Is2...> ) const {
    return {{
      f<Is, Is2, Args...>()... ... // << -- 2d expansion not working
    }};
  }
  template<class...Args>
  R<Args...> operator()(Enum n, Enum2 n2, Args&&...args) {
    // a static jump table for this case of Args...:
    static auto jump=table<Args...>(std::make_index_sequence<size_t(Enum::COUNT)>{}, std::make_index_sequence<size_t(Enum2::COUNT)>{});
    // Look up the nth entry in the jump table, and invoke it:
    return jump[size_t(n) + size_t(Enum::COUNT) * size_t(n2)](std::forward<Args>(args)...);
  }
};

Calling this code would be as follows

enum class abc_enum { a, b, c, COUNT };
enum class defg_enum { d, e, f, g, COUNT };

template<abc_enum e, defg_enum f>
struct stuff {
  void operator()() const {
    std::cout << (int)e << '\n';
    std::cout << (int)f << '\n';
  }
};
magic_switch<abc_enum, defg_enum, stuff>{}(abc_enum::b, defg_enum::f);

However, above does not compile due to the double variadic pack expansion. For more dimensions, even more variadic packs would have to be unpacked. Is there a solution for the n-dimensional magic switch problem?

Body:
You might do it by step,

First transform each runtime enum into std::variant of the possible std::integral_constant:

template <typename Enum, typename Seq> struct EnumVariantHelper;

template <typename Enum, std::size_t ... Is>
struct EnumVariantHelper<Enum, std::index_sequence<Is...>>
{
    using type = std::variant<std::integral_constant<Enum, Enum(Is)>...>;
};

template <typename Enum, std::size_t Count>
using EnumVariant = typename EnumVariantHelper<Enum, std::make_index_sequence<Count>>::type;

template <typename Enum, std::size_t Count>
struct AsVariant
{
    template <Enum E>
    struct F
    {
        EnumVariant<Enum, Count> operator()() const
        {
            return std::integral_constant<Enum, E>{};
        }
    };
};

Then, let the combination stuff to std::visit, you might do something like:

auto v1 = magic_switch<abc_enum, abc_enum::COUNT,
                       AsVariant<abc_enum, std::size_t(abc_enum::COUNT)>::F>{}(abc_enum::b);
auto v2 = magic_switch<defg_enum, defg_enum::COUNT,
                       AsVariant<defg_enum, std::size_t(defg_enum::COUNT)>::F>{}(defg_enum::f);

std::visit([](auto e1, auto e2){ return stuff<e1(), e2()>{}(); }, v1, v2);

Demo


问:
Android Apache POI error when reading Microsoft Word document: org.apache.xmlbeans.SchemaTypeLoaderException Cannot resolve type for handle
I am trying to use Apache POI in my Android application so that I can read Microsoft Word files. I am integrating the POIA library which enables Apache POI usage on Android (https://github.com/SUPERCILEX/poi-android). However, when I run my code and read in a Word file, I receive the following error:

Exception: org.apache.xmlbeans.SchemaTypeLoaderException: Cannot
  resolve type for handle _XY_Q=space|R=space

Below is my code (I am receiving error on the first line):

```<code>var document = XWPFDocument(uri?.let { contentResolver.openInputStream(it) });
var extractor = XWPFWordExtractor(document);
var documentText = extractor.text; // Retrieve the document's text
</code>```

At runtime I have the following code:

```<code>super.onCreate(savedInstanceState)
System.setProperty("org.apache.poi.javax.xml.stream.XMLInputFactory", "com.fasterxml.aalto.stax.InputFactoryImpl")
System.setProperty("org.apache.poi.javax.xml.stream.XMLOutputFactory", "com.fasterxml.aalto.stax.OutputFactoryImpl")
System.setProperty("org.apache.poi.javax.xml.stream.XMLEventFactory", "com.fasterxml.aalto.stax.EventFactoryImpl")
</code>```

Below is my gradle (project-level):

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.3.60'
    repositories {
        google()
        jcenter()

    }
    ext {
        poiVersion = '3.17'
    }
    dependencies {
        classpath 'com.android.tools:r8:1.4.93'
        classpath 'com.android.tools.build:gradle:3.4.2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        maven { url 'https://jitpack.io' }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

Below is my gradle (app-level):

```<code>apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "com.example.diffchecker"
        minSdkVersion 21
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    // For developers using the Android Support Library
    implementation 'pub.devrel:easypermissions:2.0.1'
    implementation 'com.google.android.gms:play-services-ads:18.3.0'
    implementation ("com.github.SUPERCILEX.poi-android:poi:$poiVersion") {
        exclude group: 'stax', module: 'stax-api'
    }
}
</code>```

Below is the full stack trace:

```<code>I/System.out: Exception: org.apache.xmlbeans.SchemaTypeLoaderException: Cannot resolve type for handle _XY_Q=space|R=space@http://www.w3.org/XML/1998/namespace (schemaorg_apache_xmlbeans.system.sF1327CCA741569E70F9CA8C9AF9B44B2.cttext7f5btype) - code 13
</code>```

IMPORTANT: I am trying to read in the contents of a Word file the USER SELECTED, not a Word file from a hardcoded path.

Please include ALL the relevant code in your answer, and your code should work on Android API 22.

答:
Did you add proper packagingOptions in build.gradle ?

```<code>packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
    }
</code>```

Also enable multiDexEnabled

Body:
I am trying to use Apache POI in my Android application so that I can read Microsoft Word files. I am integrating the POIA library which enables Apache POI usage on Android (https://github.com/SUPERCILEX/poi-android). However, when I run my code and read in a Word file, I receive the following error:

Exception: org.apache.xmlbeans.SchemaTypeLoaderException: Cannot
  resolve type for handle _XY_Q=space|R=space

Below is my code (I am receiving error on the first line):

var document = XWPFDocument(uri?.let { contentResolver.openInputStream(it) });
var extractor = XWPFWordExtractor(document);
var documentText = extractor.text; // Retrieve the document's text

At runtime I have the following code:

super.onCreate(savedInstanceState)
System.setProperty("org.apache.poi.javax.xml.stream.XMLInputFactory", "com.fasterxml.aalto.stax.InputFactoryImpl")
System.setProperty("org.apache.poi.javax.xml.stream.XMLOutputFactory", "com.fasterxml.aalto.stax.OutputFactoryImpl")
System.setProperty("org.apache.poi.javax.xml.stream.XMLEventFactory", "com.fasterxml.aalto.stax.EventFactoryImpl")

Below is my gradle (project-level):

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.3.60'
    repositories {
        google()
        jcenter()

    }
    ext {
        poiVersion = '3.17'
    }
    dependencies {
        classpath 'com.android.tools:r8:1.4.93'
        classpath 'com.android.tools.build:gradle:3.4.2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        maven { url 'https://jitpack.io' }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Below is my gradle (app-level):

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "com.example.diffchecker"
        minSdkVersion 21
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    // For developers using the Android Support Library
    implementation 'pub.devrel:easypermissions:2.0.1'
    implementation 'com.google.android.gms:play-services-ads:18.3.0'
    implementation ("com.github.SUPERCILEX.poi-android:poi:$poiVersion") {
        exclude group: 'stax', module: 'stax-api'
    }
}

Below is the full stack trace:

I/System.out: Exception: org.apache.xmlbeans.SchemaTypeLoaderException: Cannot resolve type for handle _XY_Q=space|R=space@http://www.w3.org/XML/1998/namespace (schemaorg_apache_xmlbeans.system.sF1327CCA741569E70F9CA8C9AF9B44B2.cttext7f5btype) - code 13

IMPORTANT: I am trying to read in the contents of a Word file the USER SELECTED, not a Word file from a hardcoded path.

Please include ALL the relevant code in your answer, and your code should work on Android API 22.

Body:
Did you add proper packagingOptions in build.gradle ?

packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
    }

Also enable multiDexEnabled


问:
Java and Hyper-V
I am trying to learn something about JAVA and the best way to do this is creating something I would actually use and know what the purpose of it is.
I am trying to communicate with HyperV (WMI Library).

For example I found the following, my question is: how to use it? I am using Netbeans to create the GUI.

http://www.paulneve.com/wlab/javadoc/org/paulneve/wlab/virtualisation/VirtualisationAccessHyperVImpl.html

Also, how to load jInterop into my project so I can use it?

Thank you.

答:
You can use JInterop for managing all operations of HyperV.

Download JInterop from here.

Add all JInterop jar files to your project build path.

Following is an example of getting all VMs of Hyper server:

```<code>public class ManageHyperV {
    static final int RETURN_IMMEDIATE = 0x10;
    static final int FORWARD_ONLY = 0x20;
    private static final int STOP = 0;
    private static final int START = 1;
    static IJIDispatch msvmServices = null;

    private static IJIDispatch createCOMServer(String namespace) { //root//virtualization
        JIComServer comServer;
        try {
            JISystem.getLogger().setLevel(Level.WARNING);
            JISystem.setAutoRegisteration(true);

            JISession session = JISession.createSession(domainName,userName,password);
            session.useSessionSecurity(false);
            comServer = new JIComServer(valueOf("WbemScripting.SWbemLocator"),hostIP,session);

            IJIDispatch wbemLocator = (IJIDispatch) narrowObject(comServer.createInstance().queryInterface(IID));
            //parameters to connect to WbemScripting.SWbemLocator
            Object[] params = new Object[] {
                    new JIString(hostIP),//strServer
                    new JIString(namespace),//strNamespace
                    //                  new JIString("ROOT\\CIMV2"),
                    JIVariant.OPTIONAL_PARAM(),//strUser
                    JIVariant.OPTIONAL_PARAM(),//strPassword
                    JIVariant.OPTIONAL_PARAM(),//strLocale
                    JIVariant.OPTIONAL_PARAM(),//strAuthority
                    new Integer(0),//iSecurityFlags
                    JIVariant.OPTIONAL_PARAM()//objwbemNamedValueSet
            };
            JIVariant results[] = wbemLocator.callMethodA("ConnectServer", params);
            IJIDispatch wbemServices = (IJIDispatch) narrowObject(results[0].getObjectAsComObject());
            return wbemServices;
        } catch (JIException jie) {
            System.out.println(jie.getMessage());
            jie.printStackTrace();
        } catch (JIRuntimeException jire) {
            jire.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static void getVMList() throws JIException {

            String temp = "select * from Msvm_ComputerSystem";
            String[] arrQuery = new String[]{temp};

            for (int k=0;k<arrQuery.length;k++) {

                Object[] params = new Object[] {
                        new JIString(arrQuery[k]),
                        JIVariant.OPTIONAL_PARAM(),
                        new JIVariant(new Integer(RETURN_IMMEDIATE + FORWARD_ONLY))
                };

                JIVariant[] servicesSet = msvmServices.callMethodA("ExecQuery", params);
                iterateEnum(servicesSet);

            }
    }

    private  static void iterateEnum(JIVariant[] servicesSet) {
        try {
            IJIDispatch wbemObjectSet = (IJIDispatch) narrowObject(servicesSet[0].getObjectAsComObject());
            JIVariant newEnumvariant = wbemObjectSet.get("_NewEnum");
            IJIComObject enumComObject = newEnumvariant.getObjectAsComObject();
            IJIEnumVariant enumVariant = (IJIEnumVariant) narrowObject(enumComObject.queryInterface(IJIEnumVariant.IID));
            List<Object[]> respArr = getEnumIterations(enumVariant);

            for (Object[] elements : respArr) {
                JIArray aJIArray = (JIArray) elements[0];
                JIVariant[] array = (JIVariant[]) aJIArray.getArrayInstance();

                for (JIVariant variant : array) {
                    IJIDispatch wbemObjectDispatch = (IJIDispatch) narrowObject(variant.getObjectAsComObject());

                    JIVariant[] v = wbemObjectDispatch.callMethodA("GetObjectText_", new Object[] {});
                    System.out.println("----------------------------------------------------------------------");
                    System.out.println(v[0].getObjectAsString().getString());
                    System.out.println("----------------------------------------------------------------------");
                }
            }
        } catch (JIRuntimeException e) {
            e.printStackTrace();
        } catch (JIException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        msvmServices = createCOMServer("root\\virtualization");
        getVMList();
    }

}

private static List<Object[]> getEnumIterations(IJIEnumVariant enumVariant) {
    List<Object[]> list = new ArrayList<Object[]>();
    int i=0;

    for (i=0;i<100;i++) {
        try {
            list.add(enumVariant.next(1));
        }catch (JIRuntimeException jre) {
            break;
        }
        catch (JIException jie) {
            break;
        }
        catch (Exception e) {
            break;
        }
    }
    return list;
}
</code>```

Also, provide administrator username and password.

It should work.

Thanks.

Title: Java and Hyper-V

Body:
You can use JInterop for managing all operations of HyperV.

Download JInterop from here.

Add all JInterop jar files to your project build path.

Following is an example of getting all VMs of Hyper server:

public class ManageHyperV {
    static final int RETURN_IMMEDIATE = 0x10;
    static final int FORWARD_ONLY = 0x20;
    private static final int STOP = 0;
    private static final int START = 1;
    static IJIDispatch msvmServices = null;

    private static IJIDispatch createCOMServer(String namespace) { //root//virtualization
        JIComServer comServer;
        try {
            JISystem.getLogger().setLevel(Level.WARNING);
            JISystem.setAutoRegisteration(true);

            JISession session = JISession.createSession(domainName,userName,password);
            session.useSessionSecurity(false);
            comServer = new JIComServer(valueOf("WbemScripting.SWbemLocator"),hostIP,session);

            IJIDispatch wbemLocator = (IJIDispatch) narrowObject(comServer.createInstance().queryInterface(IID));
            //parameters to connect to WbemScripting.SWbemLocator
            Object[] params = new Object[] {
                    new JIString(hostIP),//strServer
                    new JIString(namespace),//strNamespace
                    //                  new JIString("ROOT\\CIMV2"),
                    JIVariant.OPTIONAL_PARAM(),//strUser
                    JIVariant.OPTIONAL_PARAM(),//strPassword
                    JIVariant.OPTIONAL_PARAM(),//strLocale
                    JIVariant.OPTIONAL_PARAM(),//strAuthority
                    new Integer(0),//iSecurityFlags
                    JIVariant.OPTIONAL_PARAM()//objwbemNamedValueSet
            };
            JIVariant results[] = wbemLocator.callMethodA("ConnectServer", params);
            IJIDispatch wbemServices = (IJIDispatch) narrowObject(results[0].getObjectAsComObject());
            return wbemServices;
        } catch (JIException jie) {
            System.out.println(jie.getMessage());
            jie.printStackTrace();
        } catch (JIRuntimeException jire) {
            jire.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static void getVMList() throws JIException {

            String temp = "select * from Msvm_ComputerSystem";
            String[] arrQuery = new String[]{temp};

            for (int k=0;k<arrQuery.length;k++) {

                Object[] params = new Object[] {
                        new JIString(arrQuery[k]),
                        JIVariant.OPTIONAL_PARAM(),
                        new JIVariant(new Integer(RETURN_IMMEDIATE + FORWARD_ONLY))
                };

                JIVariant[] servicesSet = msvmServices.callMethodA("ExecQuery", params);
                iterateEnum(servicesSet);

            }
    }

    private  static void iterateEnum(JIVariant[] servicesSet) {
        try {
            IJIDispatch wbemObjectSet = (IJIDispatch) narrowObject(servicesSet[0].getObjectAsComObject());
            JIVariant newEnumvariant = wbemObjectSet.get("_NewEnum");
            IJIComObject enumComObject = newEnumvariant.getObjectAsComObject();
            IJIEnumVariant enumVariant = (IJIEnumVariant) narrowObject(enumComObject.queryInterface(IJIEnumVariant.IID));
            List<Object[]> respArr = getEnumIterations(enumVariant);

            for (Object[] elements : respArr) {
                JIArray aJIArray = (JIArray) elements[0];
                JIVariant[] array = (JIVariant[]) aJIArray.getArrayInstance();

                for (JIVariant variant : array) {
                    IJIDispatch wbemObjectDispatch = (IJIDispatch) narrowObject(variant.getObjectAsComObject());

                    JIVariant[] v = wbemObjectDispatch.callMethodA("GetObjectText_", new Object[] {});
                    System.out.println("----------------------------------------------------------------------");
                    System.out.println(v[0].getObjectAsString().getString());
                    System.out.println("----------------------------------------------------------------------");
                }
            }
        } catch (JIRuntimeException e) {
            e.printStackTrace();
        } catch (JIException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        msvmServices = createCOMServer("root\\virtualization");
        getVMList();
    }

}

private static List<Object[]> getEnumIterations(IJIEnumVariant enumVariant) {
    List<Object[]> list = new ArrayList<Object[]>();
    int i=0;

    for (i=0;i<100;i++) {
        try {
            list.add(enumVariant.next(1));
        }catch (JIRuntimeException jre) {
            break;
        }
        catch (JIException jie) {
            break;
        }
        catch (Exception e) {
            break;
        }
    }
    return list;
}

Also, provide administrator username and password.

It should work.

Thanks.


问:
Python recursive function to create generic tree
I'm trying to create a tree with n children for each node.
Problem is, when I try to implement this using a recursive function, I ends up with multiple recursive calls so I can't have a single return statement, hence having None as a final result.

Here is my piece of code :

def recursive_func(tree, n):
    if n == 0:
        return tree
    else:
        permutations = get_permutations()
        for permutation in permutations:
            child_tree = recursive_func(Tree(permutation), n-1)
            tree.addChild(child_tree)

```

<p><code>get_permutations()</code> gives a list of child trees to create. I also have a <code>Tree</code> class with a node value and a list of children.</p>

<p>Here is the Tree class:</p>

<pre class="lang-py prettyprint-override"><code>class Tree:
    def __init__(self, result):
        self.node = node
        self.children = []

    def addChild(self, tree):
        self.children.append(tree)
</code>```

This is probably a rookie error in the design of my problem, but I would be glad to get some help.

答:
TLDR: Since you use the result of recursive_func, it should always return its tree.

The recursive_func has three important points for this problem:

```<code>def recursive_func(tree, n):
    if n == 0:
        return tree  # 1.
    else:
        permutations = get_permutations()
        for permutation in permutations:
            child_tree = recursive_func(Tree(permutation), n-1)  # 2.
            tree.addChild(child_tree)
    # 3.
</code>```

Now, 1. defines that the function sometimes returns a Tree. This matches 2. which always expects the function to return a Tree. However, both conflict with 3., which implicitly returns None when the second branch is done.

Since the first branch is empty aside from the return, both 1. and 3. can be collapsed to one path that always  returns a Tree.

```<code>def recursive_func(tree, n):
    if n > 0:
        permutations = get_permutations()
        for permutation in permutations:
            child_tree = recursive_func(Tree(permutation), n-1)
            tree.addChild(child_tree)
    return tree
</code>```

Body:
I'm trying to create a tree with n children for each node.
Problem is, when I try to implement this using a recursive function, I ends up with multiple recursive calls so I can't have a single return statement, hence having None as a final result.

Here is my piece of code :

def recursive_func(tree, n):
    if n == 0:
        return tree
    else:
        permutations = get_permutations()
        for permutation in permutations:
            child_tree = recursive_func(Tree(permutation), n-1)
            tree.addChild(child_tree)

get_permutations() gives a list of child trees to create. I also have a Tree class with a node value and a list of children.

Here is the Tree class:

class Tree:
    def __init__(self, result):
        self.node = node
        self.children = []

    def addChild(self, tree):
        self.children.append(tree)

This is probably a rookie error in the design of my problem, but I would be glad to get some help.

Body:
TLDR: Since you use the result of recursive_func, it should always return its tree.

The recursive_func has three important points for this problem:

def recursive_func(tree, n):
    if n == 0:
        return tree  # 1.
    else:
        permutations = get_permutations()
        for permutation in permutations:
            child_tree = recursive_func(Tree(permutation), n-1)  # 2.
            tree.addChild(child_tree)
    # 3.

Now, 1. defines that the function sometimes returns a Tree. This matches 2. which always expects the function to return a Tree. However, both conflict with 3., which implicitly returns None when the second branch is done.

Since the first branch is empty aside from the return, both 1. and 3. can be collapsed to one path that always  returns a Tree.

def recursive_func(tree, n):
    if n > 0:
        permutations = get_permutations()
        for permutation in permutations:
            child_tree = recursive_func(Tree(permutation), n-1)
            tree.addChild(child_tree)
    return tree


问:
Google protobuf 3: deprecated a field, but cannot remove the dependencies?
I have a proto A that depends on proto B. Then I deprecated the field protoB:

```<code>import "protoB.proto";

message ProtoA {
  string assignmentStatus = 1;
  protoB proto_b = 2 [deprecated = true];
}
</code>```

I'd think in this case I should be able to remove the import statement right? But when I did that, the compiler complains about the dependency not being imported.

What's the deal here?

答:
Marking something as deprecated just ... marks it as deprecated; for example, in C# the proto_b member would be declared but marked as [Obsolete]. Since it still exists, it needs to know what to describe it as. The data is still accessible in your application, for example.

If you want to remove it: remove it:

message ProtoA {
  string assignmentStatus = 1;
  // field 2 *was* protoB proto_b = 2, now removed
}
```

(leaving a comment is important to avoid people accidentally reusing the field number, which could cause problems with pre-existing data).

Body:
I have a proto A that depends on proto B. Then I deprecated the field protoB:

import "protoB.proto";

message ProtoA {
  string assignmentStatus = 1;
  protoB proto_b = 2 [deprecated = true];
}

I'd think in this case I should be able to remove the import statement right? But when I did that, the compiler complains about the dependency not being imported.

What's the deal here?

Body:
Marking something as deprecated just ... marks it as deprecated; for example, in C# the proto_b member would be declared but marked as [Obsolete]. Since it still exists, it needs to know what to describe it as. The data is still accessible in your application, for example.

If you want to remove it: remove it:

message ProtoA {
  string assignmentStatus = 1;
  // field 2 *was* protoB proto_b = 2, now removed
}

(leaving a comment is important to avoid people accidentally reusing the field number, which could cause problems with pre-existing data).


问:
Request goes through each line in dictionary: how to fix
```<code>geomap = {
    "UK": ["London", "Manchester", "Liverpool"],
    "Czech Republic": ["Prague", "Brno", "Ostrava"],
    "Slovak Republic": ["Bratislava", "Košice"],
    "USA": ["Washington", "New York", "Detroit"],
    "Germany": ["Berlin", "Hamburg", "Munich"]
}

search = input("Tell me city and I'll tell you country: ")

for country, cities in geomap.items():
  if search in cities:
    print(search, "found in", country)
  else:
    print(search, "not found")
</code>```

outcome:

```<code>London found in UK
London not found
London not found
London not found
London not found
</code>```

Looks like it goes through each line in geomap dictionary. Do you have some ideas how to fix this? Thank you!

desired outcome:

```<code>London -> London found in UK (when IN dictionary)
Paris -> Paris not found (when not)
</code>```

and no extra sentences

答:
It sounds like you are using your dictionary wrong. If you want to read a city and return a country you should try this snippet:

geomap = {"London": "UK",
          "Manchester": "UK",
          "Prague": "Czech Republic"
          # all the other cities you need...
         }

search = input("Tell me city and I'll tell you country: ")

if search in geomap.keys():
    print(f"{search} found in {geomap[search]}")
else:
    print(f"{search} not found")

```

Body:
geomap = {
    "UK": ["London", "Manchester", "Liverpool"],
    "Czech Republic": ["Prague", "Brno", "Ostrava"],
    "Slovak Republic": ["Bratislava", "Košice"],
    "USA": ["Washington", "New York", "Detroit"],
    "Germany": ["Berlin", "Hamburg", "Munich"]
}

search = input("Tell me city and I'll tell you country: ")

for country, cities in geomap.items():
  if search in cities:
    print(search, "found in", country)
  else:
    print(search, "not found")

outcome:

London found in UK
London not found
London not found
London not found
London not found

Looks like it goes through each line in geomap dictionary. Do you have some ideas how to fix this? Thank you!

desired outcome:

London -> London found in UK (when IN dictionary)
Paris -> Paris not found (when not)

and no extra sentences


问:
Unable to terminate simultaneously running scripts at once in bash
I am trying to run 2 files, namely a python script called PaperCapture.py, and a bash script PrinterAutomation.sh simultaneously, since my task requires them to start at the same time. The python script is used to click pictures using a camera, and the bash script is used to send an echo signal to a printer, in order to print something and feed forward the paper.

I wrote another bash script called ScriptStart.sh which can start both these scripts simultaneously, but when I press Ctrl + C, or even try to kill the processes, the PrinterAutomation.sh script keeps running in the background, even when the terminal has been closed.

The code of ScriptStart.sh is below:

```<code>#!/bin/bash

#=============================================================================
# INITIAL SCRIPT FOR STARTING CAMERA & PRINTER SCRIPTS
#=============================================================================

python3 PaperCapture.py &  PIDIOS=$!
sudo sh ./PrinterAutomation.sh &  PIDMIX=$!
wait $PIDIOS

PID=pidof ./PrinterAutomation.sh
echo $PID
kill -INT $PID
</code>```

If anyone can help me to figure this out, it would be great. All I need is for both the scripts to start simultaneously, and for PrinterAutomation.sh to stop running when PaperCapture.py has stopped running.

=======================================

UPDATE:

Removing pidof and using sudo kill -INT "$PIDMIX" terminates the scripts in the terminal foreground, but PrinterAutomation.sh still keeps running in the background.

This was fixed by adding the line

```<code>trap "kill 0" EXIT
</code>```

at the top

答:
You don't have permission to kill a process which isn't yours. Try

```<code>sudo kill -INT "$PIDMIX"
</code>```

and probably get rid of the pointless and somewhat error-prone extra call to pidof (which also has a syntax error anyway; you probably meant

```<code>PID=$(pidof ./PrinterAutomation.sh)
</code>```

or even better, prefer lower case for your private variables.)

Body:
I am trying to run 2 files, namely a python script called PaperCapture.py, and a bash script PrinterAutomation.sh simultaneously, since my task requires them to start at the same time. The python script is used to click pictures using a camera, and the bash script is used to send an echo signal to a printer, in order to print something and feed forward the paper.

I wrote another bash script called ScriptStart.sh which can start both these scripts simultaneously, but when I press Ctrl + C, or even try to kill the processes, the PrinterAutomation.sh script keeps running in the background, even when the terminal has been closed.

The code of ScriptStart.sh is below:

#!/bin/bash

#=============================================================================
# INITIAL SCRIPT FOR STARTING CAMERA & PRINTER SCRIPTS
#=============================================================================

python3 PaperCapture.py &  PIDIOS=$!
sudo sh ./PrinterAutomation.sh &  PIDMIX=$!
wait $PIDIOS

PID=pidof ./PrinterAutomation.sh
echo $PID
kill -INT $PID

If anyone can help me to figure this out, it would be great. All I need is for both the scripts to start simultaneously, and for PrinterAutomation.sh to stop running when PaperCapture.py has stopped running.

=======================================

UPDATE:

Removing pidof and using sudo kill -INT "$PIDMIX" terminates the scripts in the terminal foreground, but PrinterAutomation.sh still keeps running in the background.

This was fixed by adding the line

trap "kill 0" EXIT

at the top

Body:
You don't have permission to kill a process which isn't yours. Try

sudo kill -INT "$PIDMIX"

and probably get rid of the pointless and somewhat error-prone extra call to pidof (which also has a syntax error anyway; you probably meant

PID=$(pidof ./PrinterAutomation.sh)

or even better, prefer lower case for your private variables.)


问:
NullPointerException in PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
```<code> //obtain the active page
 IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
</code>```

returns Exception in thread "Thread-3" java.lang.NullPointerExceptionµ.
What shall i do?

答:
If the thread does not run in the active window, PlatformUI.getWorkbench().getActiveWorkbenchWindow() will return "null".
You must wrap your code in a Display, e.g.:</p>

```<code>Display.getDefault().asyncExec(new Runnable() {
    @Override
    public void run() {
        IWorkbenchWindow iw = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
    }
});
</code>```

OwnerDisplayName: DAHI Nouha

ContentLicense: CC BY-SA 2.5

Body:
 //obtain the active page
 IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();

returns Exception in thread "Thread-3" java.lang.NullPointerExceptionµ.
What shall i do?

Body:
If the thread does not run in the active window, PlatformUI.getWorkbench().getActiveWorkbenchWindow() will return "null".
You must wrap your code in a Display, e.g.:

Display.getDefault().asyncExec(new Runnable() {
    @Override
    public void run() {
        IWorkbenchWindow iw = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
    }
});


问:
Numpy: What is the most Pythonic way of taking a "rolling" matrix from array?
Let's say I have a np.array such as:

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

Given a window of size 5, I want to and get:

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

It's an easy problem any rookie can solve, just wanted to know what is the most Pythonic numpy implementation.

答:
Depends on how badly you want to avoid copying that data. If badly enough, use np.lib.stride_tricks.as_strided:

```<code>arr = np.arange(11)
window = 7
as_strided(arr, shape=(window, arr.size - window + 1), strides=arr.strides * 2, writeable=False)
</code>```

This will make an array that has views of the same element in multiple places, so I've set writable=False. You can always make an expanded copy if you like.

Body:
Let's say I have a np.array such as:

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

Given a window of size 5, I want to and get:

0, 1, 2, 3, 4
1, 2, 3, 4, 5
2, 3, 4, 5, 6
3, 4, 5, 6, 7
4, 5, 6, 7, 8
5, 6, 7, 8, 9
6, 7, 8, 9, 10

It's an easy problem any rookie can solve, just wanted to know what is the most Pythonic numpy implementation.

Body:
Depends on how badly you want to avoid copying that data. If badly enough, use np.lib.stride_tricks.as_strided:

arr = np.arange(11)
window = 7
as_strided(arr, shape=(window, arr.size - window + 1), strides=arr.strides * 2, writeable=False)

This will make an array that has views of the same element in multiple places, so I've set writable=False. You can always make an expanded copy if you like.


答:
The Get-Process will return all the processes that match your criteria which means it will return multiple objects to the variable $p.

So you need to iterate over them you can simply use foreach loop

```<code>foreach($process in $p){
    if (($process -eq $null) -and ($adm -ne ""))

    {

        Start-Process "$proc" -Verb runAs

    }

    elseif (($$process -eq $null) -and ($adm -eq ""))

    {

        Start-Process "$proc" #-Verb runAs

    }

    else

    {

        $h = $process.MainWindowHandle

        [void] [WinAp]::SetForegroundWindow($h)

        [void] [WinAp]::ShowWindow($h,3);

        $wshell = New-Object -ComObject wscript.shell;

        #$wshell.SendKeys('~')

        $wshell.SendKeys('%fx')

        sleep 1

        $wshell.SendKeys('N')

    }
}
</code>```

Title: Powershell newcomer

Body:
I am a total new comer to powershell so please forgive me if my question sounds stupid. I found the script below from Yuri Posidelov which I tweaked to activate a process and show the window and send keystrokes to shut down the process which works great. However it fails if there are two process with the same name can anyone help me with this.

Orignal code by Yuriy Posidelov

param([string] $proc="SBDDesktop", [string]$adm)

cls

Add-Type @"

  using System;

  using System.Runtime.InteropServices;

  public class WinAp {

     [DllImport("user32.dll")]

     [return: MarshalAs(UnmanagedType.Bool)]

     public static extern bool SetForegroundWindow(IntPtr hWnd);

     [DllImport("user32.dll")]

     [return: MarshalAs(UnmanagedType.Bool)]

     public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

  }

"@

$p = Get-Process |where {$_.mainWindowTItle }|where {$_.Name -like "$proc"}

if (($p -eq $null) -and ($adm -ne ""))

{

    Start-Process "$proc" -Verb runAs

}

elseif (($p -eq $null) -and ($adm -eq ""))

{

    Start-Process "$proc" #-Verb runAs

}

else

{

    $h = $p.MainWindowHandle

    [void] [WinAp]::SetForegroundWindow($h)

    [void] [WinAp]::ShowWindow($h,3);

    $wshell = New-Object -ComObject wscript.shell;

    #$wshell.SendKeys('~')

    $wshell.SendKeys('%fx')

    sleep 1

    $wshell.SendKeys('N')

}

#|format-table id,name,mainwindowtitle –AutoSize

# static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

# powershell.exe -windowstyle hidden -file *.ps1 -adm "a"

Body:
The Get-Process will return all the processes that match your criteria which means it will return multiple objects to the variable $p.

So you need to iterate over them you can simply use foreach loop

foreach($process in $p){
    if (($process -eq $null) -and ($adm -ne ""))

    {

        Start-Process "$proc" -Verb runAs

    }

    elseif (($$process -eq $null) -and ($adm -eq ""))

    {

        Start-Process "$proc" #-Verb runAs

    }

    else

    {

        $h = $process.MainWindowHandle

        [void] [WinAp]::SetForegroundWindow($h)

        [void] [WinAp]::ShowWindow($h,3);

        $wshell = New-Object -ComObject wscript.shell;

        #$wshell.SendKeys('~')

        $wshell.SendKeys('%fx')

        sleep 1

        $wshell.SendKeys('N')

    }
}


问:
React-router-dom: Nested routes is not working but routes instead from within the root component App
I am following this tutorial to implement Nested routing.

Here's the relevant code:

App.js

```<code>   <PrivateRoute
                exact
                name="Home"
                path="/home"
                component={DefaultLayout}
              />
</code>```

DefaultLayout.js

```<code>const Users = React.lazy(() => import("../../views/Users/Users"));

          <Route path="/home/users" component={Users} />
</code>```

PrivateRoute.js

```<code>import React from "react";
import { Route, Redirect } from "react-router-dom";
import { connect } from "react-redux";
import PropTypes from "prop-types";
const PrivateRoute = ({ component: Component, auth, ...rest }) => (
  <Route
    {...rest}
    render={props =>
      auth.isAuthenticated === true ? (
        <Component {...props} />
      ) : (
        <Redirect to="/" />
      )
    }
  />
);

PrivateRoute.propTypes = {
  auth: PropTypes.object.isRequired
};

const mapStateToProps = state => ({
  auth: state.auth
});

export default connect(mapStateToProps)(PrivateRoute);
</code>```

So as you may have guessed, I am protecting the /home route with the PrivateRoute component.

The /home routes is associated with DefaultLayout component.

The DefaultLayout component contains a NestedRoute that is /home/users which leads to the component Users.

The private route functions properly and it routes the user after he logs-in to the default layout:

However when I click on a button that routes me to /home/users, I get this blank screen:

Any idea what I've done wrong?

EDIT 1: When I add this to App.js:

```<code>   const Users = React.lazy(() => import("../../views/Users/Users"));

              <Route path="/home/users" component={Users} />
</code>```

I do get routed to the Users component. However, not as a nested route but as a component in the root routes. In other words, the Users component does not appear inside the defaultLayout component but appears as a root component. I hope that makes sense. Here's a screenshot:

EDIT 1 Conclusion: The Nested routing implementation doesn't work. The app still routes from inside App.js instead from inside DefaultLayout.js.

EDIT 2: I realized that even without the PrivateRoute component and using the normal Route component, the nested routing still doesn't work:

```<code>      <Route exact path="/home" name="Home" component={DefaultLayout} />
</code>```

答:
Looks like you need to remove the exact prop from your Home Route:

```<code><Route path="/home" name="Home" component={DefaultLayout} />
</code>```

With exact, your DefaultLayout component will only be rendered when the url is exactly /home. Since /home/users isn't equal to /home, when you navigate to /home/users, neither your DefaultLayout component nor the nested Users route will be rendered.

Here are the docs that describe the exact prop: https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/Route.md#exact-bool

Body:
I am following this tutorial to implement Nested routing.

Here's the relevant code:

App.js

   <PrivateRoute
                exact
                name="Home"
                path="/home"
                component={DefaultLayout}
              />

DefaultLayout.js

const Users = React.lazy(() => import("../../views/Users/Users"));

          <Route path="/home/users" component={Users} />

PrivateRoute.js

import React from "react";
import { Route, Redirect } from "react-router-dom";
import { connect } from "react-redux";
import PropTypes from "prop-types";
const PrivateRoute = ({ component: Component, auth, ...rest }) => (
  <Route
    {...rest}
    render={props =>
      auth.isAuthenticated === true ? (
        <Component {...props} />
      ) : (
        <Redirect to="/" />
      )
    }
  />
);

PrivateRoute.propTypes = {
  auth: PropTypes.object.isRequired
};

const mapStateToProps = state => ({
  auth: state.auth
});

export default connect(mapStateToProps)(PrivateRoute);

So as you may have guessed, I am protecting the /home route with the PrivateRoute component.

The /home routes is associated with DefaultLayout component.

The DefaultLayout component contains a NestedRoute that is /home/users which leads to the component Users.

The private route functions properly and it routes the user after he logs-in to the default layout:

However when I click on a button that routes me to /home/users, I get this blank screen:

Any idea what I've done wrong?

EDIT 1: When I add this to App.js:

   const Users = React.lazy(() => import("../../views/Users/Users"));

              <Route path="/home/users" component={Users} />

I do get routed to the Users component. However, not as a nested route but as a component in the root routes. In other words, the Users component does not appear inside the defaultLayout component but appears as a root component. I hope that makes sense. Here's a screenshot:

EDIT 1 Conclusion: The Nested routing implementation doesn't work. The app still routes from inside App.js instead from inside DefaultLayout.js.

EDIT 2: I realized that even without the PrivateRoute component and using the normal Route component, the nested routing still doesn't work:

      <Route exact path="/home" name="Home" component={DefaultLayout} />

Body:
Looks like you need to remove the exact prop from your Home Route:

<Route path="/home" name="Home" component={DefaultLayout} />

With exact, your DefaultLayout component will only be rendered when the url is exactly /home. Since /home/users isn't equal to /home, when you navigate to /home/users, neither your DefaultLayout component nor the nested Users route will be rendered.

Here are the docs that describe the exact prop: https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/Route.md#exact-bool


问:
Unable to copy 350 GB data from one bucket to another in google cloud
I'm trying to move data from one bucket to another bucket within same project on Google Cloud.
It has plain images and documents, like .png, .jpg & .pdf files. I tried several times, but the results remain same.

Below is the command i'm using,
gsutil -m cp -r -n gs://bucket1/folder1/subfolder/* gs://bucket2/folder1/subfolder/ 2>&1 | tee ./result.txt

It runs for few hours, after some time the screen goes to hung state, i'm not seeing any logs running on google console.

My doubt as follows, Is there any setting on GCP that, if the network traffic flows for several hours, it will block the traffic, something like that ?
Is there any size cap in the bucket level ? If yes, How can i check that ?

Do i have to add any additional parameter to the above command ?
Do you have any other suggestions to complete this task ?

答:
I would suggest to try using Storage Transfer Service to complete the task.

Storage Transfer Service is a product that enables you to:

1.Move or backup data to a Cloud Storage bucket either from other cloud storage providers or from your on-premises storage.

> 2.Move data from one Cloud Storage bucket to another, so that it is available to different groups of users or applications.

3.Periodically move data as part of a data processing pipeline or analytical workflow.

Creating and managing data transfers with the Console

EDIT

You could run the command perfdiag - Run performance diagnostic

The perfdiag command runs a suite of diagnostic tests for a given
  Google Storage bucket.

```<code>gsutil perfdiag gs://your-bucket
</code>```

If the Availability is not 100% and/or HTTP errors are detected, then there is an indication of a Service/Network Problem

Body:
I would suggest to try using Storage Transfer Service to complete the task.

Storage Transfer Service is a product that enables you to:

1.Move or backup data to a Cloud Storage bucket either from other cloud storage providers or from your on-premises storage.

> 2.Move data from one Cloud Storage bucket to another, so that it is available to different groups of users or applications.

3.Periodically move data as part of a data processing pipeline or analytical workflow.

Creating and managing data transfers with the Console

EDIT

You could run the command perfdiag - Run performance diagnostic

The perfdiag command runs a suite of diagnostic tests for a given
  Google Storage bucket.

gsutil perfdiag gs://your-bucket

If the Availability is not 100% and/or HTTP errors are detected, then there is an indication of a Service/Network Problem