问:
React-Native react-navigation from another file
I have problem with navigation in RN, so I thought you could help me. I can't find any way to navigate from my "settings" tab to my "SignedOut", this is my repo, code is not complicated, all you have to look is in "navigation" and "screens" folder. Thing is my "settings" file is in one file "MainTabNavigator" and SignedOut is in "RootNavigation", and when i try something like this:

```<code>this.props.navigation.navigate("SignedOut");
</code>```

nothing happend, here is my function for this:

```<code>onSignOut()
.then(() => {
    console.log('Logout!');
    this.props.navigation.navigate("SignedOut");
})
.catch(e => {
    console.log(e);
})
</code>```

I do get this log printed out so it should call this navigation method successfully. Do you have any ideas why? I mean, I think that this is the reason maybe I am missing something here?

This is what my MainTabNavigator looks like:

```<code>import React from 'react';
import { Platform } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { TabNavigator, TabBarBottom, DrawerNavigator } from 'react-navigation';

import Colors from '../constants/Colors';

import HomeScreen from '../screens/HomeScreen';
import ListScreen from '../screens/ListScreen';
import SettingsScreen from '../screens/SettingsScreen';
import WordDetails from '../screens/WordDetails';
import DrawerMenu from './drawerDesign/Drawer';

export default DrawerNavigator(
  {
    Home: {
      screen: HomeScreen,
    },
    List: {
      screen: ListScreen,
    },
    Settings: {
      screen: SettingsScreen,
    },
    WordDetails: {
      screen: WordDetails,
    },
  }, {
    contentComponent: DrawerMenu,
    drawerWidth: 200,
    drawerPosition: "right",
    contentOptions: {
      activeTintColor: '#e91e63',
      itemsContainerStyle: {
        marginVertical: 0,
        opacity: 0.6

      },
      iconContainerStyle: {
        opacity: 0.6
      },
      style: {
        flex: 1,
        paddingTop: 35,
      },
    }
  }
);
</code>```

SingedOutNavigator:

```<code>import React from 'react';
import { Platform, StatusBar, Easing, Animated } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { StackNavigator } from 'react-navigation';

import Colors from '../constants/Colors';

import SignIn from '../screens/SignInScreen';
import Register from '../screens/RegisterScreen';

const headerStyle = {
    marginTop: Platform.OS === "android" ? StatusBar.currentHeight : 0,
    backgroundColor: '#2b303b',
};

export default StackNavigator(
    {
        SignIn: {
            screen: SignIn,
            navigationOptions: {
                title: "Prijavi se",
                headerStyle,
                headerTitleStyle: {
                    color: '#f5f5f5'
                },
            },
        },
        Register: {
            screen: Register,
            navigationOptions: {
                title: "Prijavi se",
                headerStyle,
                headerTitleStyle: {
                    color: '#f5f5f5'
                },
            },
        }
    },
    {
        headerMode: "none",
        transitionConfig: () => ({
            transitionSpec: {
                duration: 1000,
                easing: Easing.step0,
                timing: Animated.timing,
            },
            screenInterpolator: sceneProps => {
                const { layout, position, scene } = sceneProps
                const { index } = scene

                const height = layout.initHeight
                const translateY = position.interpolate({
                    inputRange: [index - 1, index, index + 1],
                    outputRange: [height, 0, 0],
                })

                const opacity = position.interpolate({
                    inputRange: [index - 1, index - 0.99, index],
                    outputRange: [0, 1, 1],
                })

                return { opacity, transform: [{ translateY }] }
            },
        }),
    }
);
</code>```

And from this "Settings" Screen i want to go on this "SignIn" from "SignedOutNavigator"..

答:
I Believe u need to declare the screens in app.js.

```<code>import YOURSCREENfrom './src/screens/YOURSCREEN'

const Routes = {
    YOURSCREEN: { screen: YOURSCREEN}
}
</code>```

Then u can call this.props.navigation.navigate("YOURSCREEN");

Body:
I have problem with navigation in RN, so I thought you could help me. I can't find any way to navigate from my "settings" tab to my "SignedOut", this is my repo, code is not complicated, all you have to look is in "navigation" and "screens" folder. Thing is my "settings" file is in one file "MainTabNavigator" and SignedOut is in "RootNavigation", and when i try something like this:

this.props.navigation.navigate("SignedOut");

nothing happend, here is my function for this:

onSignOut()
.then(() => {
    console.log('Logout!');
    this.props.navigation.navigate("SignedOut");
})
.catch(e => {
    console.log(e);
})

I do get this log printed out so it should call this navigation method successfully. Do you have any ideas why? I mean, I think that this is the reason maybe I am missing something here?

This is what my MainTabNavigator looks like:

import React from 'react';
import { Platform } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { TabNavigator, TabBarBottom, DrawerNavigator } from 'react-navigation';

import Colors from '../constants/Colors';

import HomeScreen from '../screens/HomeScreen';
import ListScreen from '../screens/ListScreen';
import SettingsScreen from '../screens/SettingsScreen';
import WordDetails from '../screens/WordDetails';
import DrawerMenu from './drawerDesign/Drawer';

export default DrawerNavigator(
  {
    Home: {
      screen: HomeScreen,
    },
    List: {
      screen: ListScreen,
    },
    Settings: {
      screen: SettingsScreen,
    },
    WordDetails: {
      screen: WordDetails,
    },
  }, {
    contentComponent: DrawerMenu,
    drawerWidth: 200,
    drawerPosition: "right",
    contentOptions: {
      activeTintColor: '#e91e63',
      itemsContainerStyle: {
        marginVertical: 0,
        opacity: 0.6

      },
      iconContainerStyle: {
        opacity: 0.6
      },
      style: {
        flex: 1,
        paddingTop: 35,
      },
    }
  }
);

SingedOutNavigator:

import React from 'react';
import { Platform, StatusBar, Easing, Animated } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { StackNavigator } from 'react-navigation';

import Colors from '../constants/Colors';

import SignIn from '../screens/SignInScreen';
import Register from '../screens/RegisterScreen';

const headerStyle = {
    marginTop: Platform.OS === "android" ? StatusBar.currentHeight : 0,
    backgroundColor: '#2b303b',
};

export default StackNavigator(
    {
        SignIn: {
            screen: SignIn,
            navigationOptions: {
                title: "Prijavi se",
                headerStyle,
                headerTitleStyle: {
                    color: '#f5f5f5'
                },
            },
        },
        Register: {
            screen: Register,
            navigationOptions: {
                title: "Prijavi se",
                headerStyle,
                headerTitleStyle: {
                    color: '#f5f5f5'
                },
            },
        }
    },
    {
        headerMode: "none",
        transitionConfig: () => ({
            transitionSpec: {
                duration: 1000,
                easing: Easing.step0,
                timing: Animated.timing,
            },
            screenInterpolator: sceneProps => {
                const { layout, position, scene } = sceneProps
                const { index } = scene

                const height = layout.initHeight
                const translateY = position.interpolate({
                    inputRange: [index - 1, index, index + 1],
                    outputRange: [height, 0, 0],
                })

                const opacity = position.interpolate({
                    inputRange: [index - 1, index - 0.99, index],
                    outputRange: [0, 1, 1],
                })

                return { opacity, transform: [{ translateY }] }
            },
        }),
    }
);

And from this "Settings" Screen i want to go on this "SignIn" from "SignedOutNavigator"..

Body:
I Believe u need to declare the screens in app.js.

import YOURSCREENfrom './src/screens/YOURSCREEN'

const Routes = {
    YOURSCREEN: { screen: YOURSCREEN}
}

Then u can call this.props.navigation.navigate("YOURSCREEN");


来源: stackexchange

问:
int max = ~0; What does it mean?
int max = ~0;

What does it mean?

答: The ~ operator is a bit inverse, so ~0 gives you an integer value with all ones (in binary). </p>

ContentLicense: CC BY-SA 2.5

Title: int max = ~0; What does it mean?

Body:
int max = ~0;

What does it mean?


问:
I can't create server application in RakNet ( C++ )
I'm trying create server application in C++ using RakNet.
When i try following code :

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

#define MAX_CLIENTS 10
#define SERVER_PORT 60000

int main(void)
{
    char str[512];
    RakNet::RakPeerInterface *peer = RakNet::RakPeerInterface::GetInstance();
    bool isServer;

    printf("(C) or (S)erver?\n");
    gets(str);
    if ((str[0] == 'c') || (str[0] == 'C'))
    {
        SocketDescriptor sd;
        peer->Startup(1, &sd, 1);
        isServer = false;
    }
    else {
        SocketDescriptor sd(SERVER_PORT, 0);
        peer->Startup(MAX_CLIENTS, &sd, 1);
        isServer = true;
    }

    // TODO - Add code body here

    RakNet::RakPeerInterface::DestroyInstance(peer);

    return 0;
}
</code>```

Compiler giving this errors :

I guess i set up RakNet successfully What is missing ?

答:
Well, one that that seems to be missing - if you are using the RakNet SocketDescriptor object is the "RakNet::" part to elt it know which namespace to use?

You have it on the PeerInterface section, but then have not used it on the SocketDescriptor

Also the RakNet socket descriptors are part of the "#include "RakNetTypes.h"" as far as I remember.. which also seems to be missing.. so unless youre using other SocketDescriptors .. that may also be needed :o

Missed the "Gets" part too - there is header for that under "#include "Gets.h"" within Raknet as well

ContentLicense: CC BY-SA 3.0

Body:
I'm trying create server application in C++ using RakNet.
When i try following code :

#include <stdio.h>
#include "RakPeerInterface.h"

#define MAX_CLIENTS 10
#define SERVER_PORT 60000

int main(void)
{
    char str[512];
    RakNet::RakPeerInterface *peer = RakNet::RakPeerInterface::GetInstance();
    bool isServer;

    printf("(C) or (S)erver?\n");
    gets(str);
    if ((str[0] == 'c') || (str[0] == 'C'))
    {
        SocketDescriptor sd;
        peer->Startup(1, &sd, 1);
        isServer = false;
    }
    else {
        SocketDescriptor sd(SERVER_PORT, 0);
        peer->Startup(MAX_CLIENTS, &sd, 1);
        isServer = true;
    }

    // TODO - Add code body here

    RakNet::RakPeerInterface::DestroyInstance(peer);

    return 0;
}

Compiler giving this errors :

I guess i set up RakNet successfully What is missing ?


问:
TeamCity SVN agent-side checkout fails with error svn: E200030: There are unfinished transactions detected in folder
After upgrading to TeamCity 2017.2 my SVN checkout began failing on my build agent with this error:

svn: E200030: There are unfinished transactions detected in '[... folder ...]'

The agent is running on Windows Server 2012 R2 and TeamCity Professional 2017.2 (build 50574)

Initial Googling and browsing on Stack Overflow didn't find an answer yet.

答:
After further Googling I found this bug on the TeamCity YouTrack:

https://youtrack.jetbrains.com/issue/TW-49325 specifically this comment https://youtrack.jetbrains.com/issue/TW-49325#comment=27-2472122

I had TortoiseSVN 1.9 installed on the build agent.

Disabling the Tortoise icon overlays for my build agent folders under Settings -> Icon Overlays -> Exclude Paths allowed my checkout to continue successfully again.

Looks like the problem is caused by a TortoiseSVN client when it monitors SVN folders,


问:
how to get all LatLng points between two end points in a polyline
I am working on GMap customization. I want a floating circle to move across a a Polyline. My question is that can we get all LatLng points in a Polyline after a specific interval for eg, all LatLng at interval of 100meters. My polyline code is:

```<code>/** polyline **/
            var tpath = [
                    new google.maps.LatLng(15.508718,73.839337),
                    new google.maps.LatLng(15.511457,73.839165)
                ];
            var travelPath = new google.maps.Polyline({
                path : tpath,
                map : map,
                geodesic : true,
                strokeColor : '#000',
                strokeOpacity : 0.7,
                strokeWeight : 1
            });
</code>```

i get only the end LatLng values. I want the values across the Polyline.

Thanks in advance.

答:
You can set On click listener on Polyline by using GoogleMap.OnPolylineClickListener, after it returns the polyline you click on.

```<code>List<LatLng> mPoints=polyline.getPoints();
</code>```

be sure to make your polyline clickable by setting.

lineOptions.clickable(true);

Body:
I am working on GMap customization. I want a floating circle to move across a a Polyline. My question is that can we get all LatLng points in a Polyline after a specific interval for eg, all LatLng at interval of 100meters. My polyline code is:

/** polyline **/
            var tpath = [
                    new google.maps.LatLng(15.508718,73.839337),
                    new google.maps.LatLng(15.511457,73.839165)
                ];
            var travelPath = new google.maps.Polyline({
                path : tpath,
                map : map,
                geodesic : true,
                strokeColor : '#000',
                strokeOpacity : 0.7,
                strokeWeight : 1
            });

i get only the end LatLng values. I want the values across the Polyline.

Thanks in advance.

Body:
You can set On click listener on Polyline by using GoogleMap.OnPolylineClickListener, after it returns the polyline you click on.

List<LatLng> mPoints=polyline.getPoints();

be sure to make your polyline clickable by setting.

lineOptions.clickable(true);


问:
Looping through a real spiral on a discrete grid
The goal is to find a closest pixel with a certain value. To do that, I want to loop over the pixel, starting from the closest, with increasing distance, untill I reach a pixel which matches my requirements (edge of the grid or the desired value).

I believe this is not a duplicate, although very similar question have appeared before.

Looping in a spiral or another spiral answer are useful, but they won't result in the points ordered by distance to the center.

Justin L. actually mentions his application to find the closest point, but overlook the actual distance.

For example the algorithm in this image would find [1, 1] before [0, 1] although [0, 1] is much closer (distance of 1) compared to [1, 1] (distance of √2).

I'd like to get the points ordered by distance
[1, 0]    [0, 1]    [-1, 0]    [0, -1]    [1, 1]    ...
otherwise it wouldn't be a real spiral.

This answer suggests spiraling with a very small step size, but since I don't know how far I need to spiral, this sounds very inefficient.

I hope this graphic makes the order clearer.

答:
I wouldn't name it a spiral loop what you are describing. A spiral is a (connected) path. What you are looking for is not a path. Anyways, I would do the following:

In a pre-process step, add all coordinates of the grid including their distance to the center to an e.g. std::vector and have it sorted by the distance to the center. Then build an index table by storing the offset in the grid for each coordinate.

At runtime use the index table to walk through the grid.

I am not sure though, if this pragmatic approach is what you are looking for. The runtime relevant step 2 is fast for sure.


问:
Files in Collate field missing from package when installing from Github
Note: I cross-posted this question here: https://github.com/hadley/devtools/issues/245

Update: @hadley just closed the issue since he can install now. I have tested it just now and install_github works on Windows too. Apparently I need wait for some time for Github archive to include the new committed changes. For people encounter the same problem, @hadley pointed out that I have .R and .r files in R/ and all the files in DESCRIPTION collate have .r extensions.

I am writing an R package and put it on Github. I can build and load on my own computer. However, after running install_github("KineticEval",username="zhenglei-gao"), I got the following error:

```<code>* installing *source* package 'KineticEval' ...
** R
Error in .install_package_code_files(".", instdir) :
files in 'Collate' field missing from 'C:/Users/z.gao/AppData/Local/Temp/RtmpUzWWYn    /R.INSTALLd3c17515a0/KineticEval/R':
  kingraph.r
  kinplot.r
  FOCUS2006A.r
  FOCUS2006B.r
  FOCUS2006C.r
  FOCUS2006D.r
  modFit1.r
  IRLSkinfit.full.r
  mkinfit.full.r
ERROR: unable to collate and parse R files for package 'KineticEval'
* removing 'C:/Users/z.gao/R-dev/KineticEval'
</code>```

A related question is here: Files in Collate field missing from package after build from incorrect .Rbuildignore file

But I can't figure out whether the error is also related to my .Rbuildignore file.

答: I had the exact same problem. I had a silly mistake in my .Rbuildignore. The file I was missing was named something like OutputPlotGenerator.R, and my .Rbuildignore file included the line output, thus removing / ignoring my R file.

Body:
Note: I cross-posted this question here: https://github.com/hadley/devtools/issues/245

Update: @hadley just closed the issue since he can install now. I have tested it just now and install_github works on Windows too. Apparently I need wait for some time for Github archive to include the new committed changes. For people encounter the same problem, @hadley pointed out that I have .R and .r files in R/ and all the files in DESCRIPTION collate have .r extensions.

I am writing an R package and put it on Github. I can build and load on my own computer. However, after running install_github("KineticEval",username="zhenglei-gao"), I got the following error:

* installing *source* package 'KineticEval' ...
** R
Error in .install_package_code_files(".", instdir) :
files in 'Collate' field missing from 'C:/Users/z.gao/AppData/Local/Temp/RtmpUzWWYn    /R.INSTALLd3c17515a0/KineticEval/R':
  kingraph.r
  kinplot.r
  FOCUS2006A.r
  FOCUS2006B.r
  FOCUS2006C.r
  FOCUS2006D.r
  modFit1.r
  IRLSkinfit.full.r
  mkinfit.full.r
ERROR: unable to collate and parse R files for package 'KineticEval'
* removing 'C:/Users/z.gao/R-dev/KineticEval'

A related question is here: Files in Collate field missing from package after build from incorrect .Rbuildignore file

But I can't figure out whether the error is also related to my .Rbuildignore file.


问:
Stop Mongoose to create auto index
I am trying to create schema in mongoose it create new index in mongodb named _id?

```<code> const modelSchema = new Schema({
    uid: { type: Number, required: true },
    content: {
        text: { type: String },
        attachments: [{
            type: { type: String, enum: ['IMAGE', 'VIDEO', 'POLL', 'GOAL', 'POST', 'MILESTONE', 'ARTICLE', 'DOCUMENT', 'AUDIO', 'QUOTE', 'USER', 'TIP', 'URL'] },
            object_id: { type: Number }
        }]
    },
    created: { type: String }
});
</code>```

I am expecting this result:

```<code>"content" : {
"text" : "hello",
"attachments" : [
    {
        "type" : "IMAGE",
        "object_id" : 1
    }
]
</code>```

I am getting this result:

```<code>"content" : {
"text" : "hello",
"attachments" : [
    {
        "type" : "IMAGE",
        "object_id" : 1,
        "_id" : ObjectId("5a2664fd6db6672ac43f1823")
    }
]
</code>```

答:
You can set _id to false to disable auto _id when defining a schema

```<code>var childSchema = new Schema({ name: String }, { _id: false });
</code>```

check http://mongoosejs.com/docs/guide.html#_id

Title: Stop Mongoose to create auto index

Body:
I am trying to create schema in mongoose it create new index in mongodb named _id?

 const modelSchema = new Schema({
    uid: { type: Number, required: true },
    content: {
        text: { type: String },
        attachments: [{
            type: { type: String, enum: ['IMAGE', 'VIDEO', 'POLL', 'GOAL', 'POST', 'MILESTONE', 'ARTICLE', 'DOCUMENT', 'AUDIO', 'QUOTE', 'USER', 'TIP', 'URL'] },
            object_id: { type: Number }
        }]
    },
    created: { type: String }
});

I am expecting this result:

"content" : {
"text" : "hello",
"attachments" : [
    {
        "type" : "IMAGE",
        "object_id" : 1
    }
]

I am getting this result:

"content" : {
"text" : "hello",
"attachments" : [
    {
        "type" : "IMAGE",
        "object_id" : 1,
        "_id" : ObjectId("5a2664fd6db6672ac43f1823")
    }
]

Body:
You can set _id to false to disable auto _id when defining a schema

var childSchema = new Schema({ name: String }, { _id: false });

check http://mongoosejs.com/docs/guide.html#_id


问:
Updating the state in a react component with canvas object fails
We have a few regions on a world map that will highlight when the user puts their mouse over that region. My approach to the problem is to use the canvas element and draw rough polygons around the regions and using some MIT code detect whether the user has their mouse inside the polygon. If they do then the image will switch to the appropriate graphic that shows the highlighted and labeled region.

Everything seemed to be going okay, but when I try to change the state it bombs out. I'm figuring it has something to do with the vitual dom somewhere.

Here is the component

```<code>class HomeMap extends Component {
    constructor(props) {
        super(props);
        this.onMouseMove = this.onMouseMove.bind(this);
        this.state = {
            placeName: 'default',
        };
    }

    onMouseMove(canvas, eX, eY) {
        const { top, left } = canvas.getBoundingClientRect();
        const [x, y] = [eX - left, eY - top];
        const mouseOver = mapImages.map(image => ({
            ...image,
            isInside: inside([x, y], image.polygon),
        }))
            .filter(({ isInside }) => isInside);

        const stateChange = {
            placeName: mouseOver.length === 0
                ? 'default'
                : mouseOver[0].name,
        };
        console.log(stateChange);
        this.setState(stateChange);
    }

    componentDidMount() {
        this.ctx.drawImage(getImage('default').image, 0, 0, 656, 327);
    }

    componentDidUpdate() {
        console.log(getImage('default'))
        console.log(this.state);
        this.ctx.drawImage(getImage(this.state.placeName).image, 0, 0, 656, 327);
    }

    render() {
        return (
            <div>
                <canvas
                    onMouseMove={(e) => { this.onMouseMove(this.canvas, e.clientX, e.clientY); } }
                    width={626}
                    height={327}
                    ref={(ref) => {
                        this.ctx = ref.getContext('2d');
                        this.canvas = ref;
                    } }
                />
            </div>
        );
    }
};
</code>```

here is a fairly minimal reproduction running on codesandbox

When I run it in production when the component updates the canvas ref becomes null, I believe that is what throws the error.

答:
I found the cause of the problem: caching the 2d context.

```<code><canvas
    onMouseMove={(e) => { this.onMouseMove(this.canvas, e.clientX, e.clientY); } }
    width={626}
    height={327}
    ref={(ref) => {
        this.ctx = ref.getContext('2d'); // <=== remove this
        this.canvas = ref;
    } }
/>
</code>```

So rather than saving the reference to the getContext, I just cached the canvas element and called canvas.getContext('2d') when I needed to access the drawing functions.

Body:
We have a few regions on a world map that will highlight when the user puts their mouse over that region. My approach to the problem is to use the canvas element and draw rough polygons around the regions and using some MIT code detect whether the user has their mouse inside the polygon. If they do then the image will switch to the appropriate graphic that shows the highlighted and labeled region.

Everything seemed to be going okay, but when I try to change the state it bombs out. I'm figuring it has something to do with the vitual dom somewhere.

Here is the component

class HomeMap extends Component {
    constructor(props) {
        super(props);
        this.onMouseMove = this.onMouseMove.bind(this);
        this.state = {
            placeName: 'default',
        };
    }

    onMouseMove(canvas, eX, eY) {
        const { top, left } = canvas.getBoundingClientRect();
        const [x, y] = [eX - left, eY - top];
        const mouseOver = mapImages.map(image => ({
            ...image,
            isInside: inside([x, y], image.polygon),
        }))
            .filter(({ isInside }) => isInside);

        const stateChange = {
            placeName: mouseOver.length === 0
                ? 'default'
                : mouseOver[0].name,
        };
        console.log(stateChange);
        this.setState(stateChange);
    }

    componentDidMount() {
        this.ctx.drawImage(getImage('default').image, 0, 0, 656, 327);
    }

    componentDidUpdate() {
        console.log(getImage('default'))
        console.log(this.state);
        this.ctx.drawImage(getImage(this.state.placeName).image, 0, 0, 656, 327);
    }

    render() {
        return (

                <canvas
                    onMouseMove={(e) => { this.onMouseMove(this.canvas, e.clientX, e.clientY); } }
                    width={626}
                    height={327}
                    ref={(ref) => {
                        this.ctx = ref.getContext('2d');
                        this.canvas = ref;
                    } }
                />

        );
    }
};

here is a fairly minimal reproduction running on codesandbox

When I run it in production when the component updates the canvas ref becomes null, I believe that is what throws the error.

Body:
I found the cause of the problem: caching the 2d context.

<canvas
    onMouseMove={(e) => { this.onMouseMove(this.canvas, e.clientX, e.clientY); } }
    width={626}
    height={327}
    ref={(ref) => {
        this.ctx = ref.getContext('2d'); // <=== remove this
        this.canvas = ref;
    } }
/>

So rather than saving the reference to the getContext, I just cached the canvas element and called canvas.getContext('2d') when I needed to access the drawing functions.


问:
React Dropzone : change style when you're dragging and drop
I'm a junior developer, and react is new for me
So i use dropzone-react, and i search how to change the style when you're dragging a file in the zone ?
Dropzone react purposes a basic style for that, but i don't find how can i change this ?
Do you have an example ?
Thank you !</p>

答:
An exmple for refrence

```<code>const { Component } = React
const { render } = ReactDOM
const Dropzone = reactDropzone

const handleDropRejected = (...args) => console.log('reject', args)

class ImageUpload extends Component {
  constructor(props) {
    super(props)

    this.state = { preview: null }
    this.handleDrop = this.handleDrop.bind(this)
  }

  handleDrop([{ preview }]) {
    this.setState({ preview })
  }

  render() {
    const { preview } = this.state

    const dropzoneStyle = {
    width  : "20%",
    height : "150px",
    border : "1px solid black"
};
const dropzoneStyleActive = {
    width  : "20%",
    height : "150px",
    border : "5px solid green"
};

    return (
      <section>
        <Dropzone
          //onDrop={ this.handleDrop }
          style={dropzoneStyle}
          activeStyle={dropzoneStyleActive}
          accept="image/jpeg,image/jpg,image/tiff,image/gif" multiple={ false } onDropRejected={ handleDropRejected }>
          Drag a file here or click to upload.
        </Dropzone>
        { preview &&
        <img src={ preview } alt="image preview" />
        }
      </section>
    )
  }
}

render(<ImageUpload />, document.getElementById('main'))
</code>```

You can use the activeClassName and className properties to apply different  styling when you drag the file in dropzone.

Body:
An exmple for refrence

const { Component } = React
const { render } = ReactDOM
const Dropzone = reactDropzone

const handleDropRejected = (...args) => console.log('reject', args)

class ImageUpload extends Component {
  constructor(props) {
    super(props)

    this.state = { preview: null }
    this.handleDrop = this.handleDrop.bind(this)
  }

  handleDrop([{ preview }]) {
    this.setState({ preview })
  }

  render() {
    const { preview } = this.state

    const dropzoneStyle = {
    width  : "20%",
    height : "150px",
    border : "1px solid black"
};
const dropzoneStyleActive = {
    width  : "20%",
    height : "150px",
    border : "5px solid green"
};

    return (
      <section>
        <Dropzone
          //onDrop={ this.handleDrop }
          style={dropzoneStyle}
          activeStyle={dropzoneStyleActive}
          accept="image/jpeg,image/jpg,image/tiff,image/gif" multiple={ false } onDropRejected={ handleDropRejected }>
          Drag a file here or click to upload.
        </Dropzone>
        { preview &&
        <img src={ preview } alt="image preview" />
        }
      </section>
    )
  }
}

render(<ImageUpload />, document.getElementById('main'))

You can use the activeClassName and className properties to apply different  styling when you drag the file in dropzone.


问:
Include PHP inside JavaScript (.js) files
I have a JavaScript file (extension .js, not .html) containing several JavaScript functions.

I want to call one of the PHP functions in a PHP file containing only several PHP functions from within one of the JavaScript functions.

Is that possible?

Would I need to "include" the .php file containing the PHP function in the .js file?

How would I do that?
 For example, say I had a file called myLib.php containing a function called myFunc that takes two parameters (param1 and param2). Then I have a .js file containing a function called myJsFunc.  How would a call the myFunc (PHP) from within the myJsFunc (JavaScript function)?  Wouldn't I need to include the PHP file somehow in the .js file?

答:
There is not any safe way to include php file into js.

One thing you can do as define your php file data as javascript global variable in php file. for example i have three variable which i want to use as js.

abc.php

```<code><?php
$abc = "Abc";
$number = 052;
$mydata = array("val1","val2","val3");
?>
<script type="text/javascript">
var abc = '<?php echo $abc?>';
var number = '<?php echo $number ?>';
var mydata = <?php echo json_encode($mydata); ?>;
</script>
</code>```

After use it directly in your js file wherever you want to use.

abc.js

```<code>function test(){
   alert('Print php variable : '+ abc +', '+number);
}

function printArrVar(){
  alert('print php array variable : '+ JSON.stringify(mydata));
}
</code>```

Beside If you have any critical data which you don't want to show publicly then you can encrypt data with js. and also get original value of it's from js so no one can get it's original value. if they show into publicly.

this is the standard way you can call php script data into js file without including js into php code or php script into js.

Body:
There is not any safe way to include php file into js.

One thing you can do as define your php file data as javascript global variable in php file. for example i have three variable which i want to use as js.

abc.php

<?php
$abc = "Abc";
$number = 052;
$mydata = array("val1","val2","val3");
?>
<script type="text/javascript">
var abc = '<?php echo $abc?>';
var number = '<?php echo $number ?>';
var mydata = <?php echo json_encode($mydata); ?>;
</script>

After use it directly in your js file wherever you want to use.

abc.js

function test(){
   alert('Print php variable : '+ abc +', '+number);
}

function printArrVar(){
  alert('print php array variable : '+ JSON.stringify(mydata));
}

Beside If you have any critical data which you don't want to show publicly then you can encrypt data with js. and also get original value of it's from js so no one can get it's original value. if they show into publicly.

this is the standard way you can call php script data into js file without including js into php code or php script into js.


问:
pytest-html add custom test results to report
I'm using pytest0html to generate my html report. my test record tested values and I need to show a table of this values with prettytable in case of success.
I think that i need to implement this hook:

```<code>@pytest.mark.optionalhook
def pytest_html_results_table_html(report, data):
    if report.passed:
        del data[:]
        data.append(my_pretty_table_string)
        # or data.append(report.extra.text)
</code>```

But how to pass my_pretty_table_string to the hook function or how to edit report.extra.text from my test function ?
Thank you for your help

答:
Where is your my_pretty_table_string stored and generated?

Please give more details to your question so we can help :)

pytest_html_results_table_html gets report object from pytest_runtest_makereport hook. So you need to implement pytest_runtest_makereport to add your data to the result at 'call' step.

```<code>@pytest.mark.hookwrapper
def pytest_runtest_makereport(item, call):
   outcome = yield # get makereport outcome
   if call.when == 'call':
      outcome.result.my_data = <your data object goes here>
</code>```

then you can access report.my_data in pytest_html_results_table_html hook.

Alex

Body:
I'm using pytest0html to generate my html report. my test record tested values and I need to show a table of this values with prettytable in case of success.
I think that i need to implement this hook:

@pytest.mark.optionalhook
def pytest_html_results_table_html(report, data):
    if report.passed:
        del data[:]
        data.append(my_pretty_table_string)
        # or data.append(report.extra.text)

But how to pass my_pretty_table_string to the hook function or how to edit report.extra.text from my test function ?
Thank you for your help

Body:
Where is your my_pretty_table_string stored and generated?

Please give more details to your question so we can help :)

pytest_html_results_table_html gets report object from pytest_runtest_makereport hook. So you need to implement pytest_runtest_makereport to add your data to the result at 'call' step.

@pytest.mark.hookwrapper
def pytest_runtest_makereport(item, call):
   outcome = yield # get makereport outcome
   if call.when == 'call':
      outcome.result.my_data = <your data object goes here>

then you can access report.my_data in pytest_html_results_table_html hook.

Alex


问:
Loop background music in SpriteKit
I'm finishing a game for iOS done with the SpriteKit framework. I want to know if there is any way to loop background music while the user is playing. SpriteKit includes a simple music player but it does not allow looping music... So I want to know how could I accomplish this. Thanks!</p>

答:
In your scene class add:

Method 1:

```<code>self.run(SKAction.repeatForever(SKAction.playSoundFileNamed("music.mp3", waitForCompletion: true)))
</code>```

Method 2:

```<code>self.addChild(SKAudioNode(fileNamed: "music.mp3"))
</code>```

Title: Loop background music in SpriteKit

Body:
In your scene class add:

Method 1:

self.run(SKAction.repeatForever(SKAction.playSoundFileNamed("music.mp3", waitForCompletion: true)))

Method 2:

self.addChild(SKAudioNode(fileNamed: "music.mp3"))


问:
AWS Dynamodb ContinuousBackupsUnavailableException
I'm trying to backup my DynamoDB table that was originally created over a year ago using DynamoDBs new "backup" feature.  However when I go to create the backup, I get the following error message:

```<code>Backups are being enabled for the table: prod-supercoolsoftware-stuff. Please
retry later (Service: AmazonDynamoDBv2; Status Code: 400; Error Code:
ContinuousBackupsUnavailableException; Request ID:
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx)
</code>```

However, when I backup a table made just yesterday on the same account in the same region, it works.

Will my table eventually be able to be backed up?  Or do I need to figure out how to create a new table and migrate the data over to it (yuck!)?

Edit:  backups are now enabled for my tables 12/26/17

答:
I think its worth just waiting a while and trying again in the next few days and weeks. According to the AWS docs the exception means Backups have not yet been enabled for this table. So it sounds like an expected situation rather than a functional exception.

AWS have indicated the backup feature is being rolled out incrementally

On-Demand Backup is being rolled out to US East (N. Virginia), US East
  (Ohio), US West (Oregon), EU (Ireland) regions starting today, and
  will be completed for all tables in the coming weeks.

The above announcement is not dated but im pretty sure it was from last week (late Nov 2017).

Although the statement doesn't specify any details, it sounds like even within those regions, individual tables may get the feature at different times.

Body:
I'm trying to backup my DynamoDB table that was originally created over a year ago using DynamoDBs new "backup" feature.  However when I go to create the backup, I get the following error message:

Backups are being enabled for the table: prod-supercoolsoftware-stuff. Please
retry later (Service: AmazonDynamoDBv2; Status Code: 400; Error Code:
ContinuousBackupsUnavailableException; Request ID:
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx)

However, when I backup a table made just yesterday on the same account in the same region, it works.

Will my table eventually be able to be backed up?  Or do I need to figure out how to create a new table and migrate the data over to it (yuck!)?

Edit:  backups are now enabled for my tables 12/26/17


问:
Iteration over the dictionary and extracting values
I have a dictionary (result_dict) as follows.

```<code>{'11333216@N05': {'person': {'can_buy_pro': 0,
   'description': {'_content': ''},
   'has_stats': '1',
   'iconfarm': 3,
   'iconserver': '2214',
   'id': '11333216@N05',
   'ispro': 0,
   'location': {'_content': ''},
   'mbox_sha1sum': {'_content': '8eb2e248cbad94e2b4a5aae75eb653c7e061a90c'},
   'mobileurl': {'_content': 'https://m.flickr.com/photostream.gne?id=11327876'},
   'nsid': '11333216@N05',
   'path_alias': 'kishansamarasinghe',
   'photos': {'count': {'_content': 442},
    'firstdate': {'_content': '1193073180'},
    'firstdatetaken': {'_content': '2000-01-01 00:49:17'}},
   'photosurl': {'_content': 'https://www.flickr.com/photos/kishansamarasinghe/'},
   'profileurl': {'_content': 'https://www.flickr.com/people/kishansamarasinghe/'},
   'realname': {'_content': 'Kishan Samarasinghe'},
   'timezone': {'label': 'Sri Jayawardenepura',
    'offset': '+06:00',
    'timezone_id': 'Asia/Colombo'},
   'username': {'_content': 'Three Sixty Five Degrees'}},
  'stat': 'ok'},
 '117692977@N08': {'person': {'can_buy_pro': 0,
   'description': {'_content': ''},
   'has_stats': '0',
   'iconfarm': 1,
   'iconserver': '404',
   'id': '117692977@N08',
   'ispro': 0,
   'location': {'_content': 'Almere, The Nederlands'},
   'mobileurl': {'_content': 'https://m.flickr.com/photostream.gne?id=117600164'},
   'nsid': '117692977@N08',
   'path_alias': 'meijsvo',
   'photos': {'count': {'_content': 3237},
    'firstdate': {'_content': '1392469161'},
    'firstdatetaken': {'_content': '2013-06-23 14:39:30'}},
   'photosurl': {'_content': 'https://www.flickr.com/photos/meijsvo/'},
   'profileurl': {'_content': 'https://www.flickr.com/people/meijsvo/'},
   'realname': {'_content': 'Markéta Eijsvogelová'},
   'timezone': {'label': 'Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna',
    'offset': '+01:00',
    'timezone_id': 'Europe/Amsterdam'},
   'username': {'_content': 'meijsvo'}},
  'stat': 'ok'},
 '21539776@N02': {'person': {'can_buy_pro': 0,
   'description': {'_content': ''},
   'has_stats': '1',
   'iconfarm': 0,
   'iconserver': '0',
</code>```

This contains more than 150 usernames (e.g. 11333216@N05) . I want to extract 'mobileurl' for each user and create a dataframe containing username and mobileurl columns. I couldn't find a way to iterate each user and extract his mobileurl as indexing is impossible. However, I have extract the mobileurl for one of the users as follows.

```<code>result_dict['76617062@N08']["person"]["mobileurl"]['_content']

'https://m.flickr.com/photostream.gne?id=76524249'
</code>```

Would be grateful if someone can help, as I'm a bit new to python.

答:
```<code>result_dict = {'11333216@N05': {'person': {'can_buy_pro': 0,
   'description': {'_content': ''},
   'has_stats': '1',
   'iconfarm': 3,
   'iconserver': '2214',
   'id': '11333216@N05',
   'ispro': 0,
   'location': {'_content': ''},
   'mbox_sha1sum': {'_content': '8eb2e248cbad94e2b4a5aae75eb653c7e061a90c'},
   'mobileurl': {'_content': 'https://m.flickr.com/photostream.gne?id=11327876'},
   'nsid': '11333216@N05',
   'path_alias': 'kishansamarasinghe',
   'photos': {'count': {'_content': 442},
    'firstdate': {'_content': '1193073180'},
    'firstdatetaken': {'_content': '2000-01-01 00:49:17'}},
   'photosurl': {'_content': 'https://www.flickr.com/photos/kishansamarasinghe/'},
   'profileurl': {'_content': 'https://www.flickr.com/people/kishansamarasinghe/'},
   'realname': {'_content': 'Kishan Samarasinghe'},
   'timezone': {'label': 'Sri Jayawardenepura',
    'offset': '+06:00',
    'timezone_id': 'Asia/Colombo'},
   'username': {'_content': 'Three Sixty Five Degrees'}},
  'stat': 'ok'},
 '117692977@N08': {'person': {'can_buy_pro': 0,
   'description': {'_content': ''},
   'has_stats': '0',
   'iconfarm': 1,
   'iconserver': '404',
   'id': '117692977@N08',
   'ispro': 0,
   'location': {'_content': 'Almere, The Nederlands'},
   'mobileurl': {'_content': 'https://m.flickr.com/photostream.gne?id=117600164'},
   'nsid': '117692977@N08',
   'path_alias': 'meijsvo',
   'photos': {'count': {'_content': 3237},
    'firstdate': {'_content': '1392469161'},
    'firstdatetaken': {'_content': '2013-06-23 14:39:30'}},
   'photosurl': {'_content': 'https://www.flickr.com/photos/meijsvo/'},
   'profileurl': {'_content': 'https://www.flickr.com/people/meijsvo/'},
   'realname': {'_content': 'Markéta Eijsvogelová'},
   'timezone': {'label': 'Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna',
    'offset': '+01:00',
    'timezone_id': 'Europe/Amsterdam'},
   'username': {'_content': 'meijsvo'}},
  'stat': 'ok'},
 '21539776@N02': {'person': {'can_buy_pro': 0,
   'description': {'_content': ''},
   'has_stats': '1',
   'iconfarm': 0,
   'iconserver': '0'}
}
}
</code>```

For your use case better use iteritems() of dictionary:

```<code>for key, value in result_dict.iteritems():
    print value.get("person", {}).get("mobileurl", {}).get("_content")
</code>```

OUTPUT

```<code>https://m.flickr.com/photostream.gne?id=117600164
https://m.flickr.com/photostream.gne?id=11327876
</code>```

Body:
I have a dictionary (result_dict) as follows.

{'11333216@N05': {'person': {'can_buy_pro': 0,
   'description': {'_content': ''},
   'has_stats': '1',
   'iconfarm': 3,
   'iconserver': '2214',
   'id': '11333216@N05',
   'ispro': 0,
   'location': {'_content': ''},
   'mbox_sha1sum': {'_content': '8eb2e248cbad94e2b4a5aae75eb653c7e061a90c'},
   'mobileurl': {'_content': 'https://m.flickr.com/photostream.gne?id=11327876'},
   'nsid': '11333216@N05',
   'path_alias': 'kishansamarasinghe',
   'photos': {'count': {'_content': 442},
    'firstdate': {'_content': '1193073180'},
    'firstdatetaken': {'_content': '2000-01-01 00:49:17'}},
   'photosurl': {'_content': 'https://www.flickr.com/photos/kishansamarasinghe/'},
   'profileurl': {'_content': 'https://www.flickr.com/people/kishansamarasinghe/'},
   'realname': {'_content': 'Kishan Samarasinghe'},
   'timezone': {'label': 'Sri Jayawardenepura',
    'offset': '+06:00',
    'timezone_id': 'Asia/Colombo'},
   'username': {'_content': 'Three Sixty Five Degrees'}},
  'stat': 'ok'},
 '117692977@N08': {'person': {'can_buy_pro': 0,
   'description': {'_content': ''},
   'has_stats': '0',
   'iconfarm': 1,
   'iconserver': '404',
   'id': '117692977@N08',
   'ispro': 0,
   'location': {'_content': 'Almere, The Nederlands'},
   'mobileurl': {'_content': 'https://m.flickr.com/photostream.gne?id=117600164'},
   'nsid': '117692977@N08',
   'path_alias': 'meijsvo',
   'photos': {'count': {'_content': 3237},
    'firstdate': {'_content': '1392469161'},
    'firstdatetaken': {'_content': '2013-06-23 14:39:30'}},
   'photosurl': {'_content': 'https://www.flickr.com/photos/meijsvo/'},
   'profileurl': {'_content': 'https://www.flickr.com/people/meijsvo/'},
   'realname': {'_content': 'Markéta Eijsvogelová'},
   'timezone': {'label': 'Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna',
    'offset': '+01:00',
    'timezone_id': 'Europe/Amsterdam'},
   'username': {'_content': 'meijsvo'}},
  'stat': 'ok'},
 '21539776@N02': {'person': {'can_buy_pro': 0,
   'description': {'_content': ''},
   'has_stats': '1',
   'iconfarm': 0,
   'iconserver': '0',

This contains more than 150 usernames (e.g. 11333216@N05) . I want to extract 'mobileurl' for each user and create a dataframe containing username and mobileurl columns. I couldn't find a way to iterate each user and extract his mobileurl as indexing is impossible. However, I have extract the mobileurl for one of the users as follows.

result_dict['76617062@N08']["person"]["mobileurl"]['_content']

'https://m.flickr.com/photostream.gne?id=76524249'

Would be grateful if someone can help, as I'm a bit new to python.

Body:
result_dict = {'11333216@N05': {'person': {'can_buy_pro': 0,
   'description': {'_content': ''},
   'has_stats': '1',
   'iconfarm': 3,
   'iconserver': '2214',
   'id': '11333216@N05',
   'ispro': 0,
   'location': {'_content': ''},
   'mbox_sha1sum': {'_content': '8eb2e248cbad94e2b4a5aae75eb653c7e061a90c'},
   'mobileurl': {'_content': 'https://m.flickr.com/photostream.gne?id=11327876'},
   'nsid': '11333216@N05',
   'path_alias': 'kishansamarasinghe',
   'photos': {'count': {'_content': 442},
    'firstdate': {'_content': '1193073180'},
    'firstdatetaken': {'_content': '2000-01-01 00:49:17'}},
   'photosurl': {'_content': 'https://www.flickr.com/photos/kishansamarasinghe/'},
   'profileurl': {'_content': 'https://www.flickr.com/people/kishansamarasinghe/'},
   'realname': {'_content': 'Kishan Samarasinghe'},
   'timezone': {'label': 'Sri Jayawardenepura',
    'offset': '+06:00',
    'timezone_id': 'Asia/Colombo'},
   'username': {'_content': 'Three Sixty Five Degrees'}},
  'stat': 'ok'},
 '117692977@N08': {'person': {'can_buy_pro': 0,
   'description': {'_content': ''},
   'has_stats': '0',
   'iconfarm': 1,
   'iconserver': '404',
   'id': '117692977@N08',
   'ispro': 0,
   'location': {'_content': 'Almere, The Nederlands'},
   'mobileurl': {'_content': 'https://m.flickr.com/photostream.gne?id=117600164'},
   'nsid': '117692977@N08',
   'path_alias': 'meijsvo',
   'photos': {'count': {'_content': 3237},
    'firstdate': {'_content': '1392469161'},
    'firstdatetaken': {'_content': '2013-06-23 14:39:30'}},
   'photosurl': {'_content': 'https://www.flickr.com/photos/meijsvo/'},
   'profileurl': {'_content': 'https://www.flickr.com/people/meijsvo/'},
   'realname': {'_content': 'Markéta Eijsvogelová'},
   'timezone': {'label': 'Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna',
    'offset': '+01:00',
    'timezone_id': 'Europe/Amsterdam'},
   'username': {'_content': 'meijsvo'}},
  'stat': 'ok'},
 '21539776@N02': {'person': {'can_buy_pro': 0,
   'description': {'_content': ''},
   'has_stats': '1',
   'iconfarm': 0,
   'iconserver': '0'}
}
}

For your use case better use iteritems() of dictionary:

for key, value in result_dict.iteritems():
    print value.get("person", {}).get("mobileurl", {}).get("_content")

OUTPUT

https://m.flickr.com/photostream.gne?id=117600164
https://m.flickr.com/photostream.gne?id=11327876


问:
Segfault when using *this
I'm getting a segfault when I try to access a member of a class from within a method of that same class, which does not make sense to me at all.

I have the Tree class:

```<code>class Tree
{

public:

Coord* root;

Tree(int x, int y)
{
    root = new Coord(x, y);
    populateTree();
}

void populateTree()
{
    queue<Coord*> nodes;
    nodes.push(root);

    while (nodes.size() > 0)
    {
        Coord* currnode = nodes.front();
        nodes.pop();

        if ( !(currnode->getValidMoves()) )
        {
            return;
        }

        else
        {
            for (int i = 0; i < MAX_CHILDREN_PER_COORD; i++)
            {
                if (currnode->children[i] != NULL)
                {
                    nodes.push(currnode->children[i]);
                }
            }
        }
    }
}
</code>```

...and the Coord class...

```<code>class Coord : public Loc
{
    public:

    Coord(int xPos, int yPos);

    Coord* children[MAX_CHILDREN_PER_COORD];

    bool getValidMoves();

    bool operator==(Coord coord);
    bool operator==(Loc loc);

};

Coord::Coord(int xPos, int yPos) : Loc(xPos, yPos) {}

bool Coord::getValidMoves()
{
    //This line segfaults
    Coord test = *this;

    //Global boolean method. Checks found
    if (!foundTrue())
    {
        for (int i = 0; i < MAX_CHILDREN_PER_COORD; i++)
        {
            //If the above segfaulting line is commented out, this is the first place that segfaults
            int newX = x + knightPositions[i].x;
            int newY = y + knightPositions[i].y;

            if ( !(newX > GRID_X || newX < 0 || newY > GRID_Y || newY < 0) )
            {
                //knightPositions is a Loc array of length MAX_CHILDREN_PER_COORD
                children[i] = new Coord(x + knightPositions[i].x, y + knightPositions[i].y);
                //Global 2d array of ints. Gets checked by foundTrue()
                found[x + knightPositions[i].x][y + knightPositions[i].y] = true;
            }
        }

        return true;
    }

    else
    {
        return false;
    }

    //Otherwise, just leave it as a blank array
}

bool Coord::operator==(Coord coord)
{
    return coord.x == x && coord.y == y;
}

bool Coord::operator==(Loc loc)
{
    return loc.x == x && loc.y == y;
}
</code>```

... and the Loc class, from which Coord inheirits...

```<code>class Loc
{
    public:
        int x, y;

        //Constructor
        Loc(int xPos, int yPos) : x(xPos), y(yPos) {}
};
</code>```

The segfault occurs in Coord::getValidMoves() as indicated by the comments. If step through the code to that point, then make a watch for *this or x or this->x, I get a "Cannot access memory at 0xbaadf00d"

Why is this happening? Where have I messed up? I just don't understand how trying to access *this in a method could possibly result in a segfault.

答:
If you make your constructor look like this:

```<code>Coord::Coord(int xPos, int yPos) : Loc(xPos, yPos)
{
    for (int i = 0; i < MAX_CHILDREN_PER_COORD; ++i) {
        children[i] = NULL;
    }
}
</code>```

your problem will go away. You should initialize all your data members in the constructor.

The problem is that children will contain random data.  It won't be initialized to NULL, and so the test currnode->children[i] != NULL will not be true even for non-existent children.  You will then call member functions on these non-existent children and when those member functions run they will have an invalid this pointer.

Title: Segfault when using *this

Body:
I'm getting a segfault when I try to access a member of a class from within a method of that same class, which does not make sense to me at all.

I have the Tree class:

class Tree
{

public:

Coord* root;

Tree(int x, int y)
{
    root = new Coord(x, y);
    populateTree();
}

void populateTree()
{
    queue<Coord*> nodes;
    nodes.push(root);

    while (nodes.size() > 0)
    {
        Coord* currnode = nodes.front();
        nodes.pop();

        if ( !(currnode->getValidMoves()) )
        {
            return;
        }

        else
        {
            for (int i = 0; i < MAX_CHILDREN_PER_COORD; i++)
            {
                if (currnode->children[i] != NULL)
                {
                    nodes.push(currnode->children[i]);
                }
            }
        }
    }
}

...and the Coord class...

class Coord : public Loc
{
    public:

    Coord(int xPos, int yPos);

    Coord* children[MAX_CHILDREN_PER_COORD];

    bool getValidMoves();

    bool operator==(Coord coord);
    bool operator==(Loc loc);

};

Coord::Coord(int xPos, int yPos) : Loc(xPos, yPos) {}

bool Coord::getValidMoves()
{
    //This line segfaults
    Coord test = *this;

    //Global boolean method. Checks found
    if (!foundTrue())
    {
        for (int i = 0; i < MAX_CHILDREN_PER_COORD; i++)
        {
            //If the above segfaulting line is commented out, this is the first place that segfaults
            int newX = x + knightPositions[i].x;
            int newY = y + knightPositions[i].y;

            if ( !(newX > GRID_X || newX < 0 || newY > GRID_Y || newY < 0) )
            {
                //knightPositions is a Loc array of length MAX_CHILDREN_PER_COORD
                children[i] = new Coord(x + knightPositions[i].x, y + knightPositions[i].y);
                //Global 2d array of ints. Gets checked by foundTrue()
                found[x + knightPositions[i].x][y + knightPositions[i].y] = true;
            }
        }

        return true;
    }

    else
    {
        return false;
    }

    //Otherwise, just leave it as a blank array
}

bool Coord::operator==(Coord coord)
{
    return coord.x == x && coord.y == y;
}

bool Coord::operator==(Loc loc)
{
    return loc.x == x && loc.y == y;
}

... and the Loc class, from which Coord inheirits...

class Loc
{
    public:
        int x, y;

        //Constructor
        Loc(int xPos, int yPos) : x(xPos), y(yPos) {}
};

The segfault occurs in Coord::getValidMoves() as indicated by the comments. If step through the code to that point, then make a watch for *this or x or this->x, I get a "Cannot access memory at 0xbaadf00d"

Why is this happening? Where have I messed up? I just don't understand how trying to access *this in a method could possibly result in a segfault.

Body:
If you make your constructor look like this:

Coord::Coord(int xPos, int yPos) : Loc(xPos, yPos)
{
    for (int i = 0; i < MAX_CHILDREN_PER_COORD; ++i) {
        children[i] = NULL;
    }
}

your problem will go away. You should initialize all your data members in the constructor.

The problem is that children will contain random data.  It won't be initialized to NULL, and so the test currnode->children[i] != NULL will not be true even for non-existent children.  You will then call member functions on these non-existent children and when those member functions run they will have an invalid this pointer.


问:
$(selector, element) Native JS alternative
Hi I'm trying to remove all jQuery from my platform one line at a time.

But I'm having some trouble finding a replacement for this

```<code>$('[data-attribute="value"]', GenericHTMLElement);
</code>```

I was hoping it would be something simple like

var div = document.createElement('div');
div.innerHTML = '

';
var b = div.childNodes;

var a = b.querySelector('[data-attribute="value"]');```

But that's not working either. Does have any suggestions for me?

答:
First you need to understand what the first code does. It searches for given selector, limiting it to HTMLElementObject scope. Understanding that we can try to do something similar.

From MSDN example, he is using body element:

```<code>var el = document.body.querySelector("style[type='text/css'], style:not([type])");
</code>```

They have this example with data-attributes, take a look please.

Body:
Hi I'm trying to remove all jQuery from my platform one line at a time.

But I'm having some trouble finding a replacement for this

$('[data-attribute="value"]', GenericHTMLElement);

I was hoping it would be something simple like

var div = document.createElement('div');
div.innerHTML = '

';
var b = div.childNodes;

var a = b.querySelector('[data-attribute="value"]');

But that's not working either. Does have any suggestions for me?

Body:
First you need to understand what the first code does. It searches for given selector, limiting it to HTMLElementObject scope. Understanding that we can try to do something similar.

From MSDN example, he is using body element:

var el = document.body.querySelector("style[type='text/css'], style:not([type])");

They have this example with data-attributes, take a look please.


问:
Duplicate column name error using UNION query on the world table
I am trying to do a full join on the Mysql built in World database's three tables by the country code. I want to count the number of row returned.

Here is what I wrote:

```<code>    SELECT * From city
 LEFT JOIN country
        ON city.CountryCode = country.Code
 LEFT JOIN countrylanguage
        ON country.Code = countrylanguage.CountryCode
     UNION
    SELECT * from city
RIGHT JOIN country
        ON city.CountryCode = country.Code
RIGHT JOIN countrylanguage
        ON country.Code = countrylanguage.CountryCode;
</code>```

This returned 30671 rows.
If I wrap the COUNT(*) clause outside,

```<code>    SELECT COUNT(*) FROM (
    SELECT * from city
 LEFT JOIN country
        ON city.CountryCode = country.Code
 LEFT JOIN countrylanguage
        ON country.Code = countrylanguage.CountryCode
     UNION
    SELECT * from city
RIGHT JOIN country
        ON city.CountryCode = country.Code
RIGHT JOIN countrylanguage
        ON country.Code = countrylanguage.CountryCode) AS B;
</code>```

it rises
Error Code: 1060. Duplicate column name 'Name'.

I try to do it the other way:

```<code>    SELECT COUNT(*) from (
    SELECT c1.* from city AS c1
 LEFT JOIN country AS co1
        ON c1.CountryCode = co1.Code
 LEFT JOIN countrylanguage AS cl1
        ON co1.Code = cl1.CountryCode
     UNION
    SELECT c2.* from city AS c2
RIGHT JOIN country AS co2
        ON c2.CountryCode = co2.Code
RIGHT JOIN countrylanguage AS cl2
        ON co2.Code = cl2.CountryCode) AS B;
</code>```

Only has 4080 rows.

I am not sure which one is the correct way?

Thank you

答:
Generally speaking, sub-queries cannot contain two columns with same name, otherwise you get error 1060.

The workaround is to replace * with the complete list of columns, aliasing when necessary:

```<code>SELECT COUNT(*) FROM (
        SELECT
               city.ID, city.Name, city.CountryCode, city.District, city.Population,
               country.Code, country.Name AS country_Name, country.Continent, country.Region, country.SurfaceArea, country.IndepYear, country.Population AS country_Population, country.LifeExpectancy, country.GNP, country.GNPOld, country.LocalName, country.GovernmentForm, country.HeadOfState, country.Capital, country.Code2,
               countrylanguage.CountryCode AS countrylanguage_CountryCode, countrylanguage.Language, countrylanguage.IsOfficial, countrylanguage.Percentage
          FROM city
     LEFT JOIN country
</code>```

However, you are not interested in all columns, just enough to get the number of distinct combinations. So  your query simplifies to:

```<code>SELECT COUNT(*) FROM (
        SELECT city.ID, country.Code, countrylanguage.CountryCode, countrylanguage.Language From city
     LEFT JOIN country
            ON city.CountryCode = country.Code
     LEFT JOIN countrylanguage
            ON country.Code = countrylanguage.CountryCode
         UNION
        SELECT city.ID, country.Code, countrylanguage.CountryCode, countrylanguage.Language From city
    RIGHT JOIN country
            ON city.CountryCode = country.Code
    RIGHT JOIN countrylanguage
            ON country.Code = countrylanguage.CountryCode
) AS B;

-- 30671
</code>```

Body:
I am trying to do a full join on the Mysql built in World database's three tables by the country code. I want to count the number of row returned.

Here is what I wrote:

    SELECT * From city
 LEFT JOIN country
        ON city.CountryCode = country.Code
 LEFT JOIN countrylanguage
        ON country.Code = countrylanguage.CountryCode
     UNION
    SELECT * from city
RIGHT JOIN country
        ON city.CountryCode = country.Code
RIGHT JOIN countrylanguage
        ON country.Code = countrylanguage.CountryCode;

This returned 30671 rows.
If I wrap the COUNT(*) clause outside,

    SELECT COUNT(*) FROM (
    SELECT * from city
 LEFT JOIN country
        ON city.CountryCode = country.Code
 LEFT JOIN countrylanguage
        ON country.Code = countrylanguage.CountryCode
     UNION
    SELECT * from city
RIGHT JOIN country
        ON city.CountryCode = country.Code
RIGHT JOIN countrylanguage
        ON country.Code = countrylanguage.CountryCode) AS B;

it rises
Error Code: 1060. Duplicate column name 'Name'.

I try to do it the other way:

    SELECT COUNT(*) from (
    SELECT c1.* from city AS c1
 LEFT JOIN country AS co1
        ON c1.CountryCode = co1.Code
 LEFT JOIN countrylanguage AS cl1
        ON co1.Code = cl1.CountryCode
     UNION
    SELECT c2.* from city AS c2
RIGHT JOIN country AS co2
        ON c2.CountryCode = co2.Code
RIGHT JOIN countrylanguage AS cl2
        ON co2.Code = cl2.CountryCode) AS B;

Only has 4080 rows.

I am not sure which one is the correct way?

Thank you

Body:
Generally speaking, sub-queries cannot contain two columns with same name, otherwise you get error 1060.

The workaround is to replace * with the complete list of columns, aliasing when necessary:

SELECT COUNT(*) FROM (
        SELECT
               city.ID, city.Name, city.CountryCode, city.District, city.Population,
               country.Code, country.Name AS country_Name, country.Continent, country.Region, country.SurfaceArea, country.IndepYear, country.Population AS country_Population, country.LifeExpectancy, country.GNP, country.GNPOld, country.LocalName, country.GovernmentForm, country.HeadOfState, country.Capital, country.Code2,
               countrylanguage.CountryCode AS countrylanguage_CountryCode, countrylanguage.Language, countrylanguage.IsOfficial, countrylanguage.Percentage
          FROM city
     LEFT JOIN country

However, you are not interested in all columns, just enough to get the number of distinct combinations. So  your query simplifies to:

SELECT COUNT(*) FROM (
        SELECT city.ID, country.Code, countrylanguage.CountryCode, countrylanguage.Language From city
     LEFT JOIN country
            ON city.CountryCode = country.Code
     LEFT JOIN countrylanguage
            ON country.Code = countrylanguage.CountryCode
         UNION
        SELECT city.ID, country.Code, countrylanguage.CountryCode, countrylanguage.Language From city
    RIGHT JOIN country
            ON city.CountryCode = country.Code
    RIGHT JOIN countrylanguage
            ON country.Code = countrylanguage.CountryCode
) AS B;

-- 30671


问:
Ruby 1.9.2 + heroku gem + rails 3 + windows
On my windows computer, I installed Ruby 1.9.2 and Rails 3.0.3 successfully. I then installed the the heroku gem (gem install heroku), version 1.17.10, and it installed fine. When I tried to run "heroku version", it gave me a message, "This application has failed to start because msvcrt-ruby18.dll was not found. Re-installing the application may fix this problem." </p>

<p>Can anybody tell me what to do now? I appreciate any help that I can get. </p>

答:
One of the gems that you have installed has been compiled for Ruby 1.8.x and not Ruby 1.9.x

The binary part (extension) link against the Ruby shared library (DLL) of that version, so msvcrt-ruby18.dll

For them to work on Ruby 1.9.x, they need to also include the binary extension that links against to the shared library of Ruby 1.9.x

There are two known gems that present this issue: JSON and win32-api.

This has been discussed on RubyInstaller group several times:

Issues with win32-api (and instructions)

In that link will find also instructions how to solve JSON gem too.

To install the RubyInstaller DevKit, please go to our downloads page and once you obtain the binary, follow the instructions in our wiki

Since you haven't provided exact output of the error, I'm doing my best to guess what is the issue.

Hope this helps.

Body:
On my windows computer, I installed Ruby 1.9.2 and Rails 3.0.3 successfully. I then installed the the heroku gem (gem install heroku), version 1.17.10, and it installed fine. When I tried to run "heroku version", it gave me a message, "This application has failed to start because msvcrt-ruby18.dll was not found. Re-installing the application may fix this problem."

Can anybody tell me what to do now? I appreciate any help that I can get.


问:
How to do an operation on a subpart of a pandas dataframe?
I have a short table such as :

```<code>In [36]: df = pd.DataFrame({k: pd.np.random.random(4) for k in "ms"}, index=["A", "AH", "B", "BH"])

In [37]: df
Out[37]:
           m         s
A   0.266581  0.386802
AH  0.626642  0.657029
B   0.643837  0.629465
BH  0.297297  0.766521
</code>```

In column m, and only m, I want to subtract the two first lines from A and the last two from B. Something like: A - A, A - AH, B - B, B - BH

For example I can do :

```<code>In [38]: df.loc[["A", "AH"]]["m"] - df.loc["A"]["m"]
Out[38]:
A     0.000000
AH    0.360061
Name: m, dtype: float64
</code>```

But if I try to do that on the table I did not succeed :

```<code>In [39]: df2 = df.copy()

In [44]: df2.loc[["A", "AH"]]["m"] = df.loc[["A", "AH"]]["m"] - df.loc["A"]["m"]

In [45]: df2
Out[45]:
           m         s
A   0.266581  0.386802
AH  0.626642  0.657029
B   0.643837  0.629465
BH  0.297297  0.766521
</code>```

I do not understand why nothing was done ?

答:
I think you need remove [] for DataFrame.loc instead Series.loc:

```<code>print (df.loc[["A", "AH"], "m"] - df.loc["A", "m"])
A     0.000000
AH   -0.696391
Name: m, dtype: float64

df.loc[["A", "AH"], "m"] = df.loc[["A", "AH"], "m"] - df.loc["A", "m"]
df.loc[["B", "BH"], "m"] = df.loc[["B", "BH"], "m"] - df.loc["B", "m"]
print (df)
           m         s
A   0.000000  0.992226
AH -0.696391  0.465135
B   0.000000  0.611135
BH  0.448778  0.569463
</code>```

Why your code does not work:

Reason is called chained indexing.

If want some simply rule from tutorial modern pandas in first intro by Tom Augspurger:

The rough rule is any time you see back-to-back square brackets, ][, you're in asking for trouble. Replace that with a .loc[..., ...] and you'll be set.

Body:
I have a short table such as :

In [36]: df = pd.DataFrame({k: pd.np.random.random(4) for k in "ms"}, index=["A", "AH", "B", "BH"])

In [37]: df
Out[37]:
           m         s
A   0.266581  0.386802
AH  0.626642  0.657029
B   0.643837  0.629465
BH  0.297297  0.766521

In column m, and only m, I want to subtract the two first lines from A and the last two from B. Something like: A - A, A - AH, B - B, B - BH

For example I can do :

In [38]: df.loc[["A", "AH"]]["m"] - df.loc["A"]["m"]
Out[38]:
A     0.000000
AH    0.360061
Name: m, dtype: float64

But if I try to do that on the table I did not succeed :

In [39]: df2 = df.copy()

In [44]: df2.loc[["A", "AH"]]["m"] = df.loc[["A", "AH"]]["m"] - df.loc["A"]["m"]

In [45]: df2
Out[45]:
           m         s
A   0.266581  0.386802
AH  0.626642  0.657029
B   0.643837  0.629465
BH  0.297297  0.766521

I do not understand why nothing was done ?

Body:
I think you need remove [] for DataFrame.loc instead Series.loc:

print (df.loc[["A", "AH"], "m"] - df.loc["A", "m"])
A     0.000000
AH   -0.696391
Name: m, dtype: float64

df.loc[["A", "AH"], "m"] = df.loc[["A", "AH"], "m"] - df.loc["A", "m"]
df.loc[["B", "BH"], "m"] = df.loc[["B", "BH"], "m"] - df.loc["B", "m"]
print (df)
           m         s
A   0.000000  0.992226
AH -0.696391  0.465135
B   0.000000  0.611135
BH  0.448778  0.569463

Why your code does not work:

Reason is called chained indexing.

If want some simply rule from tutorial modern pandas in first intro by Tom Augspurger:

The rough rule is any time you see back-to-back square brackets, ][, you're in asking for trouble. Replace that with a .loc[..., ...] and you'll be set.


问:
How do I always view a list of compiler warnings in IntelliJ IDEA?
I'm on IntelliJ IDEA 2017.2.6, wholly new to Java, so I apologize if this question is trivial or misguided.

From my days of Visual Studio, I'm expecting to see a clear list of errors and warnings (regardless whether the compilation succeeded or not), but instead what I see are "Information" messages, and only after manually opening the Messages pane. I do see warnings highlighted in code, which I can mouseover and expand, but I'm wondering why I don't see a consolidated list somewhere.

I searched around and covered all the basics I think—I found out that Alt+0 brings up the Messages pane, I verified that "Hide Warnings..." was untoggled, etc. I tried checking the "Build project automatically" setting as well.

Regardless, I just don't see an intuitive list of warnings. What am I missing? Perhaps I'm looking for something obsolete, and I should get with a new workflow?

Edit

Okay, I've found what I'm looking for by going to Analyze > Inspect Code...

Once inspected, I can reopen the Inspection Analysis from the Tool Windows menu.

I guess the refined question is: Is there a way to always inspect code along with building?

Any insight as to why it's not that way by default?

答:
You can use the Eclipse compiler for this:

File > Settings and go to Build, Execution, Deployment > Compiler > Java Compiler

where you can pick Eclipse from the Use compiler dropdown.

Also see IntelliJ Help on this.


问:
int max = ~0; What does it mean?
int max = ~0;

What does it mean?

答:
It is a bitwise negation of the bytes 0000....0000. It is the value of an integer where all bits are set to 1.

In an unsigned situation it would be the maximum possible value. In a signed situation it is -1.

Title: int max = ~0; What does it mean?

Body:
int max = ~0;

What does it mean?


问:
How to get AD properties in sharepoint using Javascript?
I need to get an user info from AD into a list that I am filling in using javascript. For some, I use SP services, but now I need to get an address  (street, city, postal code), telephone number and email of a currently signed in user. I can get phone number and email from SP service function SPGetCurrentUser but how about that address? Any suggestions? Thanks a lot!</p>

答:
Use Rest API and get the desired properties:</p>

```<code>$.ajax({

    url: _spPageContextInfo.webAbsoluteUrl + "/_api/SP.UserProfiles.PeopleManager/GetMyProperties",
    method: "GET",
    headers: { Accept: "application/json;odata=verbose" },
    success: function (data) {
        try {
            //Get properties from user profile Json response
            var properties = data.d.UserProfileProperties.results;
            accountName = GetPropertyVal(properties, "AccountName");
            Location = GetPropertyVal(properties, "SPS-Location");
            SIP = GetPropertyVal(properties, "SPS-sipAddress");

            $("[title='CurrentUser']").val(accountName);

        } catch (err2) {

        }
    },
    error: function (jQxhr, errorCode, errorThrown) {

    }
});

 function GetPropertyVal(properties, key) {
var value = "";
for (var i = 0; i < properties.length; i++) {
    if (properties[i].Key == key) {
        value = properties[i].Value;
        break;
    }
}
return value;
 }
</code>```

Body:
Use Rest API and get the desired properties:

$.ajax({

    url: _spPageContextInfo.webAbsoluteUrl + "/_api/SP.UserProfiles.PeopleManager/GetMyProperties",
    method: "GET",
    headers: { Accept: "application/json;odata=verbose" },
    success: function (data) {
        try {
            //Get properties from user profile Json response
            var properties = data.d.UserProfileProperties.results;
            accountName = GetPropertyVal(properties, "AccountName");
            Location = GetPropertyVal(properties, "SPS-Location");
            SIP = GetPropertyVal(properties, "SPS-sipAddress");

            $("[title='CurrentUser']").val(accountName);

        } catch (err2) {

        }
    },
    error: function (jQxhr, errorCode, errorThrown) {

    }
});

 function GetPropertyVal(properties, key) {
var value = "";
for (var i = 0; i < properties.length; i++) {
    if (properties[i].Key == key) {
        value = properties[i].Value;
        break;
    }
}
return value;
 }


问:
remove Editext views created dynamically
I have created my views programmatically using the below code

method to create edittext

```<code> private View newedittext() {
    final EditText editText = new EditText(getActivity());
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f);
    params.setMargins(0, 30, 0, 0);
    editText.setLayoutParams(params);

    editText.setId(count++);
    editText.setTextSize(14);
    editText.setTextColor(Color.rgb(0, 0, 0));
    editText.setMaxEms(2);
    editText.setInputType(InputType.TYPE_CLASS_TEXT);
    return editText;
}
</code>```

method to create an imageview

```<code>  public ImageView newImageview(Context context) {
    final ImageView imgView = new ImageView(context);
    imgView.setOnClickListener(this);
    imgView.setId(count);
    imgView.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_close_red));
    return imgView;
}
</code>```

inside my oncreateview fragment

```<code> Button btnad = (Button) child.findViewById(R.id.btnad);
                btnad.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        LinearLayout layout = new LinearLayout(getActivity());
                        layout.setOrientation(LinearLayout.HORIZONTAL);

                        layout.addView(newedittext());
                        layout.addView(newImageview(getActivity()));
                        lnrView.addView(layout);
                    }
                });
</code>```

on click of imageview here i want to remove the edittext view

```<code>@Override
public void onClick(View v) {
    Toast.makeText(getActivity(), "clicked" + v.getId(), Toast.LENGTH_SHORT).show();

}
</code>```

How to remove an edittext having a particular id on a  click can any one help me

答:
You can find this view in your activity and remove it form its parent.

```<code>private void removeViewWithId(int id) {
    View view = findViewById(id);
    if(view != null){
        ViewParent parent = view.getParent();
        if(parent instanceof ViewGroup){
            ((ViewGroup)parent).removeView(view);
        }
    }
}
</code>```

EDIT

After question edditing it look like you want to remove EditText and also ImageView (full row). You can achive it that way:

```<code>@Override
public void onClick(View view) {
    ViewParent parent = view.getParent();
    if (parent instanceof ViewGroup) {
        ((ViewGroup) parent).removeAllViews();
    }
}
</code>```

If you only want to remove EditText, pass id as ImageView tag:

```<code>Button btnad = (Button) child.findViewById(R.id.btnad);
            btnad.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        LinearLayout layout = new LinearLayout(getActivity());
        layout.setOrientation(LinearLayout.HORIZONTAL);

        EditText et = newedittext();
        layout.addView(et);
        ImageView iv = newImageview(getActivity())
        iv.setTag(et.getId());
        layout.addView(iv);
        lnrView.addView(layout);
    }
});
</code>```

And then remove it in onImageViewClick:

```<code> @Override
    public void onClick(View view) {
        Object editTextId = view.getTag();
        if(editTextId == null){
            return;
        }

        ViewParent parent = view.getParent();
        if (parent instanceof ViewGroup) {
            EditText et = ((ViewGroup) parent).findViewById((Integer) editTextId);
            ((ViewGroup) parent).removeView(et);
        }
    }
</code>```

Body:
I have created my views programmatically using the below code

method to create edittext

 private View newedittext() {
    final EditText editText = new EditText(getActivity());
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f);
    params.setMargins(0, 30, 0, 0);
    editText.setLayoutParams(params);

    editText.setId(count++);
    editText.setTextSize(14);
    editText.setTextColor(Color.rgb(0, 0, 0));
    editText.setMaxEms(2);
    editText.setInputType(InputType.TYPE_CLASS_TEXT);
    return editText;
}

method to create an imageview

  public ImageView newImageview(Context context) {
    final ImageView imgView = new ImageView(context);
    imgView.setOnClickListener(this);
    imgView.setId(count);
    imgView.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_close_red));
    return imgView;
}

inside my oncreateview fragment

 Button btnad = (Button) child.findViewById(R.id.btnad);
                btnad.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        LinearLayout layout = new LinearLayout(getActivity());
                        layout.setOrientation(LinearLayout.HORIZONTAL);

                        layout.addView(newedittext());
                        layout.addView(newImageview(getActivity()));
                        lnrView.addView(layout);
                    }
                });

on click of imageview here i want to remove the edittext view

@Override
public void onClick(View v) {
    Toast.makeText(getActivity(), "clicked" + v.getId(), Toast.LENGTH_SHORT).show();

}

How to remove an edittext having a particular id on a  click can any one help me

Body:
You can find this view in your activity and remove it form its parent.

private void removeViewWithId(int id) {
    View view = findViewById(id);
    if(view != null){
        ViewParent parent = view.getParent();
        if(parent instanceof ViewGroup){
            ((ViewGroup)parent).removeView(view);
        }
    }
}

EDIT

After question edditing it look like you want to remove EditText and also ImageView (full row). You can achive it that way:

@Override
public void onClick(View view) {
    ViewParent parent = view.getParent();
    if (parent instanceof ViewGroup) {
        ((ViewGroup) parent).removeAllViews();
    }
}

If you only want to remove EditText, pass id as ImageView tag:

Button btnad = (Button) child.findViewById(R.id.btnad);
            btnad.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        LinearLayout layout = new LinearLayout(getActivity());
        layout.setOrientation(LinearLayout.HORIZONTAL);

        EditText et = newedittext();
        layout.addView(et);
        ImageView iv = newImageview(getActivity())
        iv.setTag(et.getId());
        layout.addView(iv);
        lnrView.addView(layout);
    }
});

And then remove it in onImageViewClick:

 @Override
    public void onClick(View view) {
        Object editTextId = view.getTag();
        if(editTextId == null){
            return;
        }

        ViewParent parent = view.getParent();
        if (parent instanceof ViewGroup) {
            EditText et = ((ViewGroup) parent).findViewById((Integer) editTextId);
            ((ViewGroup) parent).removeView(et);
        }
    }


问:
Debugging SIGBUS on x86 Linux
What can cause SIGBUS (bus error) on a generic x86 userland application in Linux?  All of the discussion I've been able to find online is regarding memory alignment errors, which from what I understand doesn't really apply to x86.

(My code is running on a Geode, in case there are any relevant processor-specific quirks there.)

答:
This was briefly mentioned above as a "failed IO request", but I'll expand upon it a bit.

A frequent case is when you lazily grow a file using ftruncate, map it into memory, start writing data and then run out of space in your filesystem. Physical space for mapped file is allocated on page faults, if there's none left then process receives a SIGBUS.

If you need your application to correctly recover from this error, it makes sense to explicitly reserve space prior to mmap using fallocate. Handling ENOSPC  in errno after fallocate call is much simpler than dealing with signals, especially in a multi-threaded application.

Title: Debugging SIGBUS on x86 Linux


问:
Implementing Modal as confirmation before redirecting
I am currently trying to implement a table that, when a row is clicked on, will display a modal that acts as a confirmation page where the user can then submit the information. When the user clicks on the submit in the modal, it needs to add the row data to a sql database and redirect the user to another page. I am stuck on how to pass the information that the user clicks on to my python code where I can add it to sql and I can't get the page to redirect.

This is my table tag

```<code><tr class="room" data-id="{{ res.room_id }}" data-toggle="modal" data-target="#orderModal" >
</code>```

This is my modal

```<code><div id="orderModal" class="modal fade" role="dialog" aria-labelledby="orderModal" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h2>Order</h2>
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
      </div>
      <div id="orderDetails" class="modal-body"></div>
      <div id="orderItems" class="modal-body"></div>

      <div class="modal-footer">
           <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
            <a href="#" id="submit" type="submit" class="btn btn-success">Submit</a>
      </div>
    </div>
  </div>
</div>

</div>
</code>```

This is my javascript

```<code>$('#orderModal').modal({
        keyboarnd: true,
        backdrop: "static",
        show:false,

    }).on('show.bs.modal', function(){
          var getIdFromRow = $(this).data('orderid');
        //make your ajax call populate items or what even you need
        $(this).find('#orderDetails').html($('<b> Order Id selected: ' + getIdFromRow  + '</b>'))
    });

    $(".table-striped").find('tr[data-target]').on('click', function(){
        //or do your operations here instead of on show of modal to populate values to modal.
         $('#orderModal').data('orderid',$(this).data('id'));
    });
</code>```

This is my python pseudocode

```<code>@app.route("/table", methods=["GET", "POST"])
@login_required
def book():
     # """Confirm the room you have selected to book"""

     # User reached route via POST (as by submitting a form via POST) --> BUT ONLY BY CLICKING OK BUTTON, NOT CANCEL BUTTON
    if request.method == "POST":

         # Update bookings with user's booking
         # Redirect to history.html where it displays a table of only your history of bookings (date, start time, end time, room)

          return redirect("/")

    else:
        return render_template("history.html")
</code>```

Thank you for any help!

答:
I do not know much about python, but from what I understand from your question it seems like you want to get the table row that you clicked to the modal.

If so, you can use some javascript to do that. Add an onclick event to the table rows and pass the parameters you want in the modal: Eg onclick="setModalValues('1', 'John Doe')

```<code><tr class="room" data-id="{{ res.room_id }}" data-toggle="modal" data-target="#orderModal"  onclick="setModalValues('1', 'John Doe')>
</code>```

Write a javascript to set modal form input values on click.

```<code><script type="text/javascript">
 function setModalValues(id, name) {
    $("#modalID").val(id);
    $("#modalName").val(name);
 }
</script>
</code>```

In the modal you could have a form with the inputs fields like:

```<code><input type="hidden" class="form-control" id="modalID"  name="modalID">

<div class="form-group">
   <label for="name">Name:</label>
   <input type="text" class="form-control" id="modalName" name="modalName">
</div>
</code>```

Hope you can implement something similar in your case.

See a sample fiddle here

Body:
I am currently trying to implement a table that, when a row is clicked on, will display a modal that acts as a confirmation page where the user can then submit the information. When the user clicks on the submit in the modal, it needs to add the row data to a sql database and redirect the user to another page. I am stuck on how to pass the information that the user clicks on to my python code where I can add it to sql and I can't get the page to redirect.

This is my table tag

This is my modal

Order

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>

           <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
            Submit

This is my javascript

$('#orderModal').modal({
        keyboarnd: true,
        backdrop: "static",
        show:false,

    }).on('show.bs.modal', function(){
          var getIdFromRow = $(this).data('orderid');
        //make your ajax call populate items or what even you need
        $(this).find('#orderDetails').html($(' Order Id selected: ' + getIdFromRow  + ''))
    });

    $(".table-striped").find('tr[data-target]').on('click', function(){
        //or do your operations here instead of on show of modal to populate values to modal.
         $('#orderModal').data('orderid',$(this).data('id'));
    });

This is my python pseudocode

@app.route("/table", methods=["GET", "POST"])
@login_required
def book():
     # """Confirm the room you have selected to book"""

     # User reached route via POST (as by submitting a form via POST) --> BUT ONLY BY CLICKING OK BUTTON, NOT CANCEL BUTTON
    if request.method == "POST":

         # Update bookings with user's booking
         # Redirect to history.html where it displays a table of only your history of bookings (date, start time, end time, room)

          return redirect("/")

    else:
        return render_template("history.html")

Thank you for any help!

Body:
I do not know much about python, but from what I understand from your question it seems like you want to get the table row that you clicked to the modal.

If so, you can use some javascript to do that. Add an onclick event to the table rows and pass the parameters you want in the modal: Eg onclick="setModalValues('1', 'John Doe')

<tr class="room" data-id="{{ res.room_id }}" data-toggle="modal" data-target="#orderModal"  onclick="setModalValues('1', 'John Doe')>

Write a javascript to set modal form input values on click.

<script type="text/javascript">
 function setModalValues(id, name) {
    $("#modalID").val(id);
    $("#modalName").val(name);
 }
</script>

In the modal you could have a form with the inputs fields like:

<input type="hidden" class="form-control" id="modalID"  name="modalID">

<div class="form-group">
   <label for="name">Name:</label>
   <input type="text" class="form-control" id="modalName" name="modalName">
</div>

Hope you can implement something similar in your case.

See a sample fiddle here


问:
Espresso Testing: Accessing Variables
I'm writing data driven testing of my android app, and have begun writing a CSV to espresso testing framework which will allow me to quickly design and alter tests. Espresso can verify basic things about the UI such as successful clicks and text entry, but can it handle more advanced logic?

For example, I'm attempting to create a receipt based on some clicks that are made during the test. This will have been costed before runtime and entered into the CSV for automatic comparison of actual vs expected outcomes. In order to do this, I will need to access the receipt object to check its values? Or at least the textbox which displays it (easy, but not really what I'm after).

So, is there any way to get objects stored in memory from the main application into the espresso testing framework?

答:
Found the answer to my question.

In order to get to any objects/variables, you need to get to a class in which they exist. This is achieved in espresso with the @Rule tag:

```<code>@Rule
public ActivityTestRule<MainActivity> mainActivityTestRule = new ActivityTestRule<MainActivity>(MainActivity.class);
</code>```

From here you can do:

```<code>mainActivityTestRule.getActivity();
</code>```

and from there all objects can be accessed

EDIT:

Primitives seem to come through fine, but I'm still trying to confirm if objects are actually passed through. It seems that the objects that are in my Espresso class are default, as though the constructor has just been run. Will update with more info.

Edit 2:

This does NOT work for objects. Putting a break-point in the espresso class and one in the main application and comparing them shows different object IDs. Getting the object from the main application doesn't return the object in the same state.

Title: Espresso Testing: Accessing Variables

Body:
Found the answer to my question.

In order to get to any objects/variables, you need to get to a class in which they exist. This is achieved in espresso with the @Rule tag:

@Rule
public ActivityTestRule<MainActivity> mainActivityTestRule = new ActivityTestRule<MainActivity>(MainActivity.class);

From here you can do:

mainActivityTestRule.getActivity();

and from there all objects can be accessed

EDIT:

Primitives seem to come through fine, but I'm still trying to confirm if objects are actually passed through. It seems that the objects that are in my Espresso class are default, as though the constructor has just been run. Will update with more info.

Edit 2:

This does NOT work for objects. Putting a break-point in the espresso class and one in the main application and comparing them shows different object IDs. Getting the object from the main application doesn't return the object in the same state.


答:
This uses column C as a helper column, which is filled with a SumIF formula to sum up all values matching the Column A values, then delete column B and shift Column C into its place before removing duplicates to give you the desired outcome.

The following should do as you want:

```<code>Sub foo()
    LastRow = Sheet1.Cells(Rows.Count, "A").End(xlUp).Row 'find the last row with data
    Sheet1.Cells(1, 3).Value = "Heading 2" 'add heading to column C
        For i = 2 To LastRow
            Sheet1.Cells(i, 3).Value = "=SUMIF(C[-2],RC[-2],C[-1])" 'enter formula to sum values of column B into column C
        Next i
    Sheet1.Range("C:C").Copy 'Copy values of column C
    Sheet1.Range("C:C").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False 'paste as values on column C
    Range("B:B").Delete Shift:=xlToLeft 'Delete Column B and shift Column C to the left
    Application.CutCopyMode = False
    Sheet1.Range("$A$1:$B$" & LastRow).RemoveDuplicates Columns:=Array(1, 2), Header:=xlYes ' Remove duplicates
End Sub
</code>```

Title: Combine duplicate rows and sum up the next column vba

Body:
How do i find the duplicates in a cloumn and merge them as a single cell and
    add their adjacent columns and show them as a single cell value?
    In short how do i convert table 1 to table 2 format?
   Table 1

|---------------------|------------------|
|      Heading 1      |     Heading 2    |
|---------------------|------------------|
|          12         |         34       |
|---------------------|------------------|
|---------------------|------------------|
|          12         |         54       |
|---------------------|------------------|
|---------------------|------------------|
|          13         |         43       |
|---------------------|------------------|

Table 2

|---------------------|------------------|
|      Heading 1      |     Heading 2    |
|---------------------|------------------|
|          12         |         88       |
|---------------------|------------------|
|---------------------|------------------|
|          13         |         43       |
|---------------------|------------------|

Below is the code i have tried. It just marks the duplicate values as duplicate and i am unable to sum up the values and show them in the previous cell

Sub sbFindDuplicatesInColumn()
Dim lastRow As Long
Dim matchFoundIndex As Long
Dim iCntr As Long
lastRow = Range("A65000").End(xlUp).Row
For iCntr = 1 To lastRow
If Cells(iCntr, 1) <> "" Then
matchFoundIndex = WorksheetFunction.Match(Cells(iCntr, 1), Range("A1:A" &
lastRow), 0)
If iCntr <> matchFoundIndex Then
Cells(iCntr, 2) = "Duplicate"
End If
End If
Next
End Sub

Body:
This uses column C as a helper column, which is filled with a SumIF formula to sum up all values matching the Column A values, then delete column B and shift Column C into its place before removing duplicates to give you the desired outcome.

The following should do as you want:

Sub foo()
    LastRow = Sheet1.Cells(Rows.Count, "A").End(xlUp).Row 'find the last row with data
    Sheet1.Cells(1, 3).Value = "Heading 2" 'add heading to column C
        For i = 2 To LastRow
            Sheet1.Cells(i, 3).Value = "=SUMIF(C[-2],RC[-2],C[-1])" 'enter formula to sum values of column B into column C
        Next i
    Sheet1.Range("C:C").Copy 'Copy values of column C
    Sheet1.Range("C:C").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False 'paste as values on column C
    Range("B:B").Delete Shift:=xlToLeft 'Delete Column B and shift Column C to the left
    Application.CutCopyMode = False
    Sheet1.Range("$A$1:$B$" & LastRow).RemoveDuplicates Columns:=Array(1, 2), Header:=xlYes ' Remove duplicates
End Sub


问:
input as float or int
I would like to be able to display double the value of any number the user inputs.

```<code>spam = int(input('choose any number: '))
print('Your number doubled is: ' + str(spam*2))
</code>```

The problem is if the user inputs a decimal, ie 3.4. It comes up with an error since it becomes a float value.

```<code>Traceback (most recent call last):
  File "<pyshell#66>", line 1, in <module>
    spam = int(input('choose any number: '))
ValueError: invalid literal for int() with base 10: '3.4'
</code>```

Is there a simple way to let the user input any number (be it integer or float value)?

This is in python 3, so raw_input doesn't work.

答:
Do this:

```<code>spam = input('choose any number: ')

try:
        print('Your number doubled is: ' ,int(spam)*2)

except ValueError:
        print('Your number doubled is: ' ,float(spam)*2)
</code>```

The way this works is that it will try to convert into an integer, and if that doesn't work it will convert it into a float.

Title: input as float or int

Body:
I would like to be able to display double the value of any number the user inputs.

spam = int(input('choose any number: '))
print('Your number doubled is: ' + str(spam*2))

The problem is if the user inputs a decimal, ie 3.4. It comes up with an error since it becomes a float value.

Traceback (most recent call last):
  File "<pyshell#66>", line 1, in <module>
    spam = int(input('choose any number: '))
ValueError: invalid literal for int() with base 10: '3.4'

Is there a simple way to let the user input any number (be it integer or float value)?

This is in python 3, so raw_input doesn't work.

Body:
Do this:

spam = input('choose any number: ')

try:
        print('Your number doubled is: ' ,int(spam)*2)

except ValueError:
        print('Your number doubled is: ' ,float(spam)*2)

The way this works is that it will try to convert into an integer, and if that doesn't work it will convert it into a float.