问:
Creating class instances
Could someone please explain to me how to create class instances from a list (or a string that might be fetched from excel). I always seem to run into this problem. I want to create many instances of classes and then save them in a shelve later.

This sample code doesn't work, but illustrates the approach I'm trying.

```<code>class test:
  def __init__(self):
      self.a='name'

if _name__=='__main__':
   list=['A','B']
   for item in list:
       item=test()
</code>```

答:
Few issues in your code includes naming of variables. It can confuse you.

```<code>class test:
    # I guess you want to provide the name to initialize the object attribute
    def __init__(self, name):
        # self.name is the attribute where the name is stored.
        # I prefer it to self.A
        self.name = name
</code>```

Now the issue here is that instance is also a element of your list, which I presume is a name.

```<code>if __name__=='__main__':
    # I presume these are list of names
    list_of_names = ['A','b','c']

    # You have to store your instance some where.
    instance_list = []

    # Here name is an element of the list that you are iterating
    # I change it to name instead of instance
    for name in list_of_names:
        # Here I am appending to the list, a test object that I create
        instance_list.append(test(name))
</code>```

[Edit:]

Now, I truly don't understand you, why this piece of code:

```<code>  for item in list:
       item=class()   # How can you reassign the item ?
</code>```

See what this item is .

```<code>>>> for item in ['A', 'B']:
...     print item
...
A
B
>>>
</code>```

You should not assign it item = .... but you should use it .... = ..(item) !!!

Title: Creating class instances

Body:
Could someone please explain to me how to create class instances from a list (or a string that might be fetched from excel). I always seem to run into this problem. I want to create many instances of classes and then save them in a shelve later.

This sample code doesn't work, but illustrates the approach I'm trying.

class test:
  def __init__(self):
      self.a='name'

if _name__=='__main__':
   list=['A','B']
   for item in list:
       item=test()

Body:
Few issues in your code includes naming of variables. It can confuse you.

class test:
    # I guess you want to provide the name to initialize the object attribute
    def __init__(self, name):
        # self.name is the attribute where the name is stored.
        # I prefer it to self.A
        self.name = name

Now the issue here is that instance is also a element of your list, which I presume is a name.

if __name__=='__main__':
    # I presume these are list of names
    list_of_names = ['A','b','c']

    # You have to store your instance some where.
    instance_list = []

    # Here name is an element of the list that you are iterating
    # I change it to name instead of instance
    for name in list_of_names:
        # Here I am appending to the list, a test object that I create
        instance_list.append(test(name))

[Edit:]

Now, I truly don't understand you, why this piece of code:

  for item in list:
       item=class()   # How can you reassign the item ?

See what this item is .

>>> for item in ['A', 'B']:
...     print item
...
A
B
>>>

You should not assign it item = .... but you should use it .... = ..(item) !!!


来源: stackexchange

问:
Resetting the navigation stack for the home screen (React Navigation and React Native)
I've got a problem with the navigation of React Navigation and React Native. It is about resetting navigation and returning to the home screen.

I've build a StackNavigator inside of a DrawerNavigator, and the navigation between home screen and other screens is working. But the problem is, that the navigation stack grows and grows. I'm not sure how to remove a screen from the stack.

For example when going from the home screen to the settings screen, then to the entry screen and lastly again to the home screen, the home screen is twice in the stack. With the back button I do not get out of the app, but again to the entry screen.

When selecting the home button again a reset of the stack would be great, but I don't know how to do this. Here someone tried to help an other person with a similar problem, but the solution didn't work for me.

```<code>const Stack = StackNavigator({
  Home: {
    screen: Home
  },
  Entry: {
    screen: Entry
  },
  Settings: {
    screen: Settings
  }
})

export const Drawer = DrawerNavigator({
  Home: {
    screen: Stack
  }},
  {
    contentComponent: HamburgerMenu
  }
)
</code>```

And this is a simple example of the drawer screen

```<code>export default class HamburgerMenu extends Component {
  render () {
    return <ScrollView>
      <Icon.Button
        name={'home'}
        borderRadius={0}
        size={25}
        onPress={() => { this.props.navigation.navigate('Home')}}>
        <Text>{I18n.t('home')}</Text>
      </Icon.Button>

      <Icon.Button
        name={'settings'}
        borderRadius={0}
        size={25}
        onPress={() => { this.props.navigation.navigate('Settings')}}>
        <Text>{I18n.t('settings')}</Text>
      </Icon.Button>

      <Icon.Button
        name={'entry'}
        borderRadius={0}
        size={25}
        onPress={() => { this.props.navigation.navigate('Entry')}}>
        <Text>{I18n.t('entry')}</Text>
      </Icon.Button>
    </ScrollView>
  }
}
</code>```

I hope you can help me. This is an essential part of the navigation and a solution would be great!

答:
In your StackNavigator and DrawerNavigator you have used Home as a key, and i think it has to be unique and that's why its creating the problem. Can you please try replacing Home with Stack inside your DrawerNavigator.

Hope this will help :)

ContentLicense: CC BY-SA 3.0

Body:
I've got a problem with the navigation of React Navigation and React Native. It is about resetting navigation and returning to the home screen.

I've build a StackNavigator inside of a DrawerNavigator, and the navigation between home screen and other screens is working. But the problem is, that the navigation stack grows and grows. I'm not sure how to remove a screen from the stack.

For example when going from the home screen to the settings screen, then to the entry screen and lastly again to the home screen, the home screen is twice in the stack. With the back button I do not get out of the app, but again to the entry screen.

When selecting the home button again a reset of the stack would be great, but I don't know how to do this. Here someone tried to help an other person with a similar problem, but the solution didn't work for me.

const Stack = StackNavigator({
  Home: {
    screen: Home
  },
  Entry: {
    screen: Entry
  },
  Settings: {
    screen: Settings
  }
})

export const Drawer = DrawerNavigator({
  Home: {
    screen: Stack
  }},
  {
    contentComponent: HamburgerMenu
  }
)

And this is a simple example of the drawer screen

export default class HamburgerMenu extends Component {
  render () {
    return <ScrollView>
      <Icon.Button
        name={'home'}
        borderRadius={0}
        size={25}
        onPress={() => { this.props.navigation.navigate('Home')}}>
        <Text>{I18n.t('home')}</Text>
      </Icon.Button>

      <Icon.Button
        name={'settings'}
        borderRadius={0}
        size={25}
        onPress={() => { this.props.navigation.navigate('Settings')}}>
        <Text>{I18n.t('settings')}</Text>
      </Icon.Button>

      <Icon.Button
        name={'entry'}
        borderRadius={0}
        size={25}
        onPress={() => { this.props.navigation.navigate('Entry')}}>
        <Text>{I18n.t('entry')}</Text>
      </Icon.Button>
    </ScrollView>
  }
}

I hope you can help me. This is an essential part of the navigation and a solution would be great!


问:
PHP HTML select option not working
I have a dropdown with 3 choices. Blank, Option A, and Option B. The code should be selecting the correct one, but it's making the wrong one selected.

Updated code with new parenthesis syntax

```<code>    <select name="memType">
        <option value="" selected="<?php if ( ($status !== 'Option A') && ($status !== 'Option B') ){echo 'selected';}?>">None</option>
        <option value="Option A" selected="<?php if (($status) == ('Option A')){echo 'selected';}?>">Option A</option>
        <option value="Option B" selected="<?php if (($status) == ('Option B')){echo 'selected';}?>">Option B</option>
    </select>
</code>```

答:
I hope this will work for you : </p>

```<code><select name="memType">
    <option value="" selected="<?php if ( ($status != 'Option A') && ($status != 'Option B') ){echo 'selected';}?>">None</option>
     <option value="Option A" selected="<?php if ($status == 'Option A'){echo 'selected';}?>">Option A</option>
    <option value="Option B" selected="<?php if ($status == 'Option B'){echo 'selected';}?>">Option B</option>
</select>
</code>```

Title: PHP HTML select option not working

Body:
I have a dropdown with 3 choices. Blank, Option A, and Option B. The code should be selecting the correct one, but it's making the wrong one selected.

Updated code with new parenthesis syntax

    <select name="memType">
        <option value="" selected="<?php if ( ($status !== 'Option A') && ($status !== 'Option B') ){echo 'selected';}?>">None</option>
        <option value="Option A" selected="<?php if (($status) == ('Option A')){echo 'selected';}?>">Option A</option>
        <option value="Option B" selected="<?php if (($status) == ('Option B')){echo 'selected';}?>">Option B</option>
    </select>

Body:
I hope this will work for you :

<select name="memType">
    <option value="" selected="<?php if ( ($status != 'Option A') && ($status != 'Option B') ){echo 'selected';}?>">None</option>
     <option value="Option A" selected="<?php if ($status == 'Option A'){echo 'selected';}?>">Option A</option>
    <option value="Option B" selected="<?php if ($status == 'Option B'){echo 'selected';}?>">Option B</option>
</select>


问:
copy a float texture with webgl2
I can no longer find any trace of copyTexImage2D in the specification of webgl2 : https://www.khronos.org/registry/webgl/specs/latest/2.0/

A few months ago I had asked the question of how to make a float-texture copy. With webgl version 1.0 this was not possible with copyTexImage2D (float type is not supported)
So I made a texture copy by building a simple shader.

I imagined that the restriction on the float32 type was lifted with webgl2. But I do not find any occurrence of the word "copyTexImage2D" in the specification of webgl 2.

How does it work? The specification of webgl2 gives only the novelties or new polymorphism functions since webgl1 ?

In short, with webgl2,  is a more efficient method to copy a texture ?

(In my slow, very slow, understanding of webgl2 I have not yet addressed the interesting novelty of feedback)

答:
Ok i find a solution: blitFramebuffer :

let texture1 be the texture which we want to copy in texture2. We have already two framebuffer copieFB and FBorig.
copieFB have a color attachment to texture2,
FBorig have a color attachment to texture1.

```<code>gl.bindFramebuffer ( gl.DRAW_FRAMEBUFFER, copieFB );
gl.bindFramebuffer ( gl.READ_FRAMEBUFFER, FBorig );
gl.readBuffer ( gl.COLOR_ATTACHMENT0 );
gl.blitFramebuffer(0, 0, PVS, PVS,0, 0, PVS, PVS,gl.COLOR_BUFFER_BIT, gl.NEAREST);
</code>```

old solution :

```<code>gl.bindFramebuffer( gl.FRAMEBUFFER , copieFB);
gl.viewport(0, 0, PVS, PVS);
gl.useProgram(copieShader);
gl.uniform1i(copieShader.FBorig,TEXTURE1);
gl.drawArrays(gl.POINTS , 0 , NBRE);
</code>```

the gain is some FPS.

Title: copy a float texture with webgl2

Body:
Ok i find a solution: blitFramebuffer :

let texture1 be the texture which we want to copy in texture2. We have already two framebuffer copieFB and FBorig.
copieFB have a color attachment to texture2,
FBorig have a color attachment to texture1.

gl.bindFramebuffer ( gl.DRAW_FRAMEBUFFER, copieFB );
gl.bindFramebuffer ( gl.READ_FRAMEBUFFER, FBorig );
gl.readBuffer ( gl.COLOR_ATTACHMENT0 );
gl.blitFramebuffer(0, 0, PVS, PVS,0, 0, PVS, PVS,gl.COLOR_BUFFER_BIT, gl.NEAREST);

old solution :

gl.bindFramebuffer( gl.FRAMEBUFFER , copieFB);
gl.viewport(0, 0, PVS, PVS);
gl.useProgram(copieShader);
gl.uniform1i(copieShader.FBorig,TEXTURE1);
gl.drawArrays(gl.POINTS , 0 , NBRE);

the gain is some FPS.


问:
How to connect MySQL Database in django 1.10.6
```<code>import MySQLDB as Database
</code>```

File "c:\pythonprojects\env\lib\site-packages\mysql_python-1.2.2-py3.6-win32.egg\mysqldb__init__py", line 22

```<code> raise ImportError, "This is MySQL Version %s, But _mysql is version %r"
</code>```

SyntaxError: invalid syntax

答:
Make sure you have pymysql installed. Then in settings.py do this</p>

```<code>try:
    import pymysql
    pymysql.install_as_MySQLdb()
except:
    pass

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'db-name',
        'USER': 'username',
        'PASSWORD': 'password',
        'HOST': 'localhost',   # Or an IP Address that your DB is hosted on
        'PORT': '3306',
    }
}
</code>```

Body:
import MySQLDB as Database

File "c:\pythonprojects\env\lib\site-packages\mysql_python-1.2.2-py3.6-win32.egg\mysqldb__init__py", line 22

 raise ImportError, "This is MySQL Version %s, But _mysql is version %r"

SyntaxError: invalid syntax

Body:
Make sure you have pymysql installed. Then in settings.py do this

try:
    import pymysql
    pymysql.install_as_MySQLdb()
except:
    pass

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'db-name',
        'USER': 'username',
        'PASSWORD': 'password',
        'HOST': 'localhost',   # Or an IP Address that your DB is hosted on
        'PORT': '3306',
    }
}


问:
Is this script only written in javascript and html?
I don't own this script but i'm curious to know if its written in anything besides javascript and html.

Is there certain place to write scripts like this? If so, could you recommend any websites? Thanks so much.

<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Chither.com The best Slither and Agar.io bots service</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="icon" type="image/png" href="/favicon.png" />
  <meta name="Description" content="free bots, best experience, without lags, Slither.io bots - Best Bots for Slither, agar.io bots - Best Bots for agar.io" />
  <meta name="Author" content="" />
  <meta name="Reply-To" content="" />
  <meta name="Robots" content="all" />
  <meta name="Rating" content="general" />
  <meta name="Keywords" content="Slither.io, chither, Slither bot, Slitherbots, Slither bots, Slitherio bots, Chither.com, hacks, cheats, free, bots, Slitheriobots, Slitherio bots, Slither.io bots, Bot, Worms, Worm, Bots, Worms, support, best, lagfree, Slither, agar.io, agar bot, agarbots, agar bots, agario bots, hacks, cheats, free, bots, agariobots, agario bots, agar.io bots, Bot, Minion, Bots, Minions, support, best, lagfree, agar, mass bot"
  />
  <link href="css/bootstrap.min.css" rel="stylesheet">
  <link href="font-awesome/css/font-awesome.css" rel="stylesheet">

  <link href="css/plugins/toastr/toastr.min.css" rel="stylesheet">

  <link href="js/plugins/gritter/jquery.gritter.css" rel="stylesheet">
  <link href="css/animate.css" rel="stylesheet">
  <link href="css/style.css" rel="stylesheet">

Login in

          <input type="text" name="username" id="loginusername" class="form-control" placeholder="Username" value="" />

          <input type="password" name="password" id="loginpassword" class="form-control" placeholder="Password" value="" />

          By logging in, you agree to our ToS

        <button class="btn btn-primary block full-width m-b" type="button" onclick="login()">Sign in</button>

Do not have an account?

        <button class="btn btn-sm btn-white btn-block" onClick="location.href='register.php'">Create an account</button>

 © All Rights Reserved Chither.com 2017

```

答:
Yes this "script" is written in only HTML and Javascript, but it uses multiple plugins and frameworks. This is defined by the link href and script tags. For example bootstrap is an front-end(how your page looks) framework and Jquery is an Javascript framework.

It does refer to other files for example PHP(e.g. index.php) and CSS styles(E.g. in link href="css/style.css" rel="stylesheet"). Without these CSS files your site will not have the same appearance and functionality.

The most simple way to write HTML is in notepad and safe them as .html. You can then open them with you preferred browser. For starting tutorials I would recommend W3Schools. For example a tutorial on Js is: https://www.w3schools.com/js/ or html: https://www.w3schools.com/html/

ContentLicense: CC BY-SA 4.0


问:
Merging columns and removing duplicates with Pandas
I need to merge similar columns and remove duplicates (entries with the same date). The data frame:

```<code>     Albumin  C-reactive protein    CRP  Ferritin  Haemoglobin     Hb  Iron  Nancy Index  Plasma  Platelets  Transferrin saturation %  Transferrin saturations  UCEIS (0 to 8)    WCC  White Cell Count           test_date
0        NaN                 NaN    NaN       NaN          NaN    NaN   NaN          NaN     NaN        NaN                       NaN                      NaN             NaN    NaN             12.35 2016-04-17 23:00:00
1        NaN                 NaN    NaN       NaN        133.0    NaN   NaN          NaN     NaN        NaN                       NaN                      NaN             NaN    NaN               NaN 2016-04-17 23:00:00
2        NaN                 NaN    NaN       NaN          NaN    NaN   NaN          NaN     NaN      406.0                       NaN                      NaN             NaN    NaN               NaN 2016-04-17 23:00:00
3        NaN                 NaN    NaN       NaN          NaN    NaN   NaN          NaN     NaN      406.0                       NaN                      NaN             NaN    NaN               NaN 2016-04-17 23:00:00
4        NaN                32.2    NaN       NaN          NaN    NaN   NaN          NaN     NaN        NaN                       NaN                      NaN             NaN    NaN               NaN 2016-04-17 23:00:00
5       36.0                 NaN    NaN       NaN          NaN    NaN   NaN          NaN     NaN        NaN                       NaN                      NaN             NaN    NaN               NaN 2016-04-17 23:00:00
6        NaN                 NaN    NaN      99.7          NaN    NaN   NaN          NaN     NaN        NaN                       NaN                      NaN             NaN    NaN               NaN 2016-04-17 23:00:00
7        NaN                 NaN    NaN       NaN          NaN    NaN   NaN          NaN     NaN        NaN                      25.0                      NaN             NaN    NaN               NaN 2016-04-17 23:00:00
12      36.0                 NaN   32.2      99.7          NaN  133.0   NaN          NaN     NaN      406.0                       NaN                     25.0             NaN  12.35               NaN 2016-04-17 23:00:00
14       NaN                 NaN    NaN       NaN          NaN    NaN   NaN          NaN     NaN        NaN                       NaN                      NaN             7.0    NaN               NaN 2016-04-25 23:00:00
79      34.0                 NaN    5.4      55.9          NaN  133.0   NaN          NaN     NaN      372.0                       NaN                     28.0             NaN   7.99               NaN 2016-06-12 23:00:00
</code>```

I need to get:

```<code>     Albumin    CRP  Ferritin     Hb  Nancy Index  Plasma  Platelets  Transferrin saturations  UCEIS (0 to 8)    WCC           test_date
12      36.0   32.2      99.7  133.0          NaN     NaN      406.0                     25.0             NaN  12.35 2016-04-17 23:00:00
14       NaN    NaN       NaN    NaN          NaN     NaN        NaN                      NaN             7.0    NaN 2016-04-25 23:00:00
79      34.0    5.4      55.9  133.0          NaN     NaN      372.0                     28.0             NaN   7.99 2016-06-12 23:00:00
</code>```

So, columns 'C-reactive protein' should be merged with 'CRP', 'Hemoglobin' with 'Hb', 'Transferrin saturation %' with 'Transferrin saturation'.

I can easily remove duplicates with .drop_duplicates(), but the trick is remove not only row with the same date, but also to make sure, that the values in the same column are duplicated. For example, 'C-reactive protein' at row '4' has the same values as 'CRP' in row '12', in addition, they both have the same entry date. Given all that, I need to have only 'CRP' column with values 32.2 and the date '2016-04-17' (plus other unique columns).

EDIT

Some entries are really duplicates (absolutely identical, due to system glitches), for example (last three rows, on 2016-06-20, indices '803' and '122'). Is the solution below capable of removing such identical rows?

P.S. Thanks for the amazing and general solution for duplicate, but not identical entries.

```<code>     Albumin  C-reactive protein  CRP  Ferritin  Haemoglobin     Hb  Iron  Nancy Index  Plasma  Platelets  Transferrin saturation %  Transferrin saturations  UCEIS (0 to 8)   WCC  White Cell Count          setName           test_date
735     39.0                 NaN  0.4      52.0          NaN  144.0   NaN          NaN     NaN      197.0                       NaN                     25.0             NaN  4.88               NaN           Bloods 2016-05-31 23:00:00
803     40.0                 NaN  0.2      81.0          NaN  147.0   NaN          NaN     NaN      234.0                       NaN                     35.0             NaN  8.47               NaN           Bloods 2016-06-20 23:00:00
347      NaN                 NaN  NaN       NaN          NaN    NaN   NaN          NaN     1.0        NaN                       NaN                      NaN             NaN   NaN               NaN  Research Bloods 2016-06-20 23:00:00
122     40.0                 NaN  0.2      81.9          NaN  147.0   NaN          NaN     NaN      234.0                       NaN                     35.0             NaN  8.47               NaN           Bloods 2016-06-20 23:00:00
</code>```

答:
I  think you need groupby with rename columns by dict:

```<code>d = {'C-reactive protein':'CRP', 'Hemoglobin':'Hb',
     'Transferrin saturation %':'Transferrin saturations'}
df = df.groupby('test_date').max().rename(columns=d).groupby(axis=1, level=0).max()
print (df)
                     Albumin   CRP  Ferritin  Haemoglobin     Hb  Iron  \
test_date
2016-04-17 23:00:00     36.0  32.2      99.7        133.0  133.0   NaN
2016-04-25 23:00:00      NaN   NaN       NaN          NaN    NaN   NaN
2016-06-12 23:00:00     34.0   5.4      55.9          NaN  133.0   NaN

                     Nancy Index  Plasma  Platelets  Transferrin saturations  \
test_date
2016-04-17 23:00:00          NaN     NaN      406.0                     25.0
2016-04-25 23:00:00          NaN     NaN        NaN                      NaN
2016-06-12 23:00:00          NaN     NaN      372.0                     28.0

                     UCEIS (0 to 8)    WCC  White Cell Count
test_date
2016-04-17 23:00:00             NaN  12.35             12.35
2016-04-25 23:00:00             7.0    NaN               NaN
2016-06-12 23:00:00             NaN   7.99               NaN
</code>```

More general solution is reshape by melt, remove duplicates and then create DataFrame back:

```<code>d = {'C-reactive protein':'CRP', 'Hemoglobin':'Hb',
'Transferrin saturation %':'Transferrin saturations'}
df = df.rename(columns=d).groupby(axis=1, level=0).max()

df = pd.melt(df, id_vars='test_date').dropna(subset=['value']).drop_duplicates()

df = df.groupby(['test_date','variable'])['value'] \
       .apply(lambda x: pd.Series(x.values)) \
       .unstack(1) \
       .reset_index(level=1, drop=True) \
       .reset_index() \
       .rename_axis(None,axis=1)
print (df)

             test_date  Albumin   CRP  Ferritin      Hb  Platelets  \
0  2016-04-17 23:00:00   1000.0  32.2      99.7  1000.0      406.0
1  2016-04-17 23:00:00     36.0   NaN       NaN   133.0        NaN
2  2016-04-25 23:00:00      NaN   NaN       NaN     NaN        NaN
3  2016-06-12 23:00:00     34.0   5.4      55.9   133.0      372.0

   Transferrin saturations  UCEIS (0 to 8)    WCC  White Cell Count
0                     25.0             NaN  12.35             12.35
1                      NaN             NaN    NaN               NaN
2                      NaN             7.0    NaN               NaN
3                     28.0             NaN   7.99               NaN
</code>```

Body:
I need to merge similar columns and remove duplicates (entries with the same date). The data frame:

     Albumin  C-reactive protein    CRP  Ferritin  Haemoglobin     Hb  Iron  Nancy Index  Plasma  Platelets  Transferrin saturation %  Transferrin saturations  UCEIS (0 to 8)    WCC  White Cell Count           test_date
0        NaN                 NaN    NaN       NaN          NaN    NaN   NaN          NaN     NaN        NaN                       NaN                      NaN             NaN    NaN             12.35 2016-04-17 23:00:00
1        NaN                 NaN    NaN       NaN        133.0    NaN   NaN          NaN     NaN        NaN                       NaN                      NaN             NaN    NaN               NaN 2016-04-17 23:00:00
2        NaN                 NaN    NaN       NaN          NaN    NaN   NaN          NaN     NaN      406.0                       NaN                      NaN             NaN    NaN               NaN 2016-04-17 23:00:00
3        NaN                 NaN    NaN       NaN          NaN    NaN   NaN          NaN     NaN      406.0                       NaN                      NaN             NaN    NaN               NaN 2016-04-17 23:00:00
4        NaN                32.2    NaN       NaN          NaN    NaN   NaN          NaN     NaN        NaN                       NaN                      NaN             NaN    NaN               NaN 2016-04-17 23:00:00
5       36.0                 NaN    NaN       NaN          NaN    NaN   NaN          NaN     NaN        NaN                       NaN                      NaN             NaN    NaN               NaN 2016-04-17 23:00:00
6        NaN                 NaN    NaN      99.7          NaN    NaN   NaN          NaN     NaN        NaN                       NaN                      NaN             NaN    NaN               NaN 2016-04-17 23:00:00
7        NaN                 NaN    NaN       NaN          NaN    NaN   NaN          NaN     NaN        NaN                      25.0                      NaN             NaN    NaN               NaN 2016-04-17 23:00:00
12      36.0                 NaN   32.2      99.7          NaN  133.0   NaN          NaN     NaN      406.0                       NaN                     25.0             NaN  12.35               NaN 2016-04-17 23:00:00
14       NaN                 NaN    NaN       NaN          NaN    NaN   NaN          NaN     NaN        NaN                       NaN                      NaN             7.0    NaN               NaN 2016-04-25 23:00:00
79      34.0                 NaN    5.4      55.9          NaN  133.0   NaN          NaN     NaN      372.0                       NaN                     28.0             NaN   7.99               NaN 2016-06-12 23:00:00

I need to get:

     Albumin    CRP  Ferritin     Hb  Nancy Index  Plasma  Platelets  Transferrin saturations  UCEIS (0 to 8)    WCC           test_date
12      36.0   32.2      99.7  133.0          NaN     NaN      406.0                     25.0             NaN  12.35 2016-04-17 23:00:00
14       NaN    NaN       NaN    NaN          NaN     NaN        NaN                      NaN             7.0    NaN 2016-04-25 23:00:00
79      34.0    5.4      55.9  133.0          NaN     NaN      372.0                     28.0             NaN   7.99 2016-06-12 23:00:00

So, columns 'C-reactive protein' should be merged with 'CRP', 'Hemoglobin' with 'Hb', 'Transferrin saturation %' with 'Transferrin saturation'.

I can easily remove duplicates with .drop_duplicates(), but the trick is remove not only row with the same date, but also to make sure, that the values in the same column are duplicated. For example, 'C-reactive protein' at row '4' has the same values as 'CRP' in row '12', in addition, they both have the same entry date. Given all that, I need to have only 'CRP' column with values 32.2 and the date '2016-04-17' (plus other unique columns).

EDIT

Some entries are really duplicates (absolutely identical, due to system glitches), for example (last three rows, on 2016-06-20, indices '803' and '122'). Is the solution below capable of removing such identical rows?

P.S. Thanks for the amazing and general solution for duplicate, but not identical entries.

     Albumin  C-reactive protein  CRP  Ferritin  Haemoglobin     Hb  Iron  Nancy Index  Plasma  Platelets  Transferrin saturation %  Transferrin saturations  UCEIS (0 to 8)   WCC  White Cell Count          setName           test_date
735     39.0                 NaN  0.4      52.0          NaN  144.0   NaN          NaN     NaN      197.0                       NaN                     25.0             NaN  4.88               NaN           Bloods 2016-05-31 23:00:00
803     40.0                 NaN  0.2      81.0          NaN  147.0   NaN          NaN     NaN      234.0                       NaN                     35.0             NaN  8.47               NaN           Bloods 2016-06-20 23:00:00
347      NaN                 NaN  NaN       NaN          NaN    NaN   NaN          NaN     1.0        NaN                       NaN                      NaN             NaN   NaN               NaN  Research Bloods 2016-06-20 23:00:00
122     40.0                 NaN  0.2      81.9          NaN  147.0   NaN          NaN     NaN      234.0                       NaN                     35.0             NaN  8.47               NaN           Bloods 2016-06-20 23:00:00

Body:
I  think you need groupby with rename columns by dict:

d = {'C-reactive protein':'CRP', 'Hemoglobin':'Hb',
     'Transferrin saturation %':'Transferrin saturations'}
df = df.groupby('test_date').max().rename(columns=d).groupby(axis=1, level=0).max()
print (df)
                     Albumin   CRP  Ferritin  Haemoglobin     Hb  Iron  \
test_date
2016-04-17 23:00:00     36.0  32.2      99.7        133.0  133.0   NaN
2016-04-25 23:00:00      NaN   NaN       NaN          NaN    NaN   NaN
2016-06-12 23:00:00     34.0   5.4      55.9          NaN  133.0   NaN

                     Nancy Index  Plasma  Platelets  Transferrin saturations  \
test_date
2016-04-17 23:00:00          NaN     NaN      406.0                     25.0
2016-04-25 23:00:00          NaN     NaN        NaN                      NaN
2016-06-12 23:00:00          NaN     NaN      372.0                     28.0

                     UCEIS (0 to 8)    WCC  White Cell Count
test_date
2016-04-17 23:00:00             NaN  12.35             12.35
2016-04-25 23:00:00             7.0    NaN               NaN
2016-06-12 23:00:00             NaN   7.99               NaN

More general solution is reshape by melt, remove duplicates and then create DataFrame back:

d = {'C-reactive protein':'CRP', 'Hemoglobin':'Hb',
'Transferrin saturation %':'Transferrin saturations'}
df = df.rename(columns=d).groupby(axis=1, level=0).max()

df = pd.melt(df, id_vars='test_date').dropna(subset=['value']).drop_duplicates()

df = df.groupby(['test_date','variable'])['value'] \
       .apply(lambda x: pd.Series(x.values)) \
       .unstack(1) \
       .reset_index(level=1, drop=True) \
       .reset_index() \
       .rename_axis(None,axis=1)
print (df)

             test_date  Albumin   CRP  Ferritin      Hb  Platelets  \
0  2016-04-17 23:00:00   1000.0  32.2      99.7  1000.0      406.0
1  2016-04-17 23:00:00     36.0   NaN       NaN   133.0        NaN
2  2016-04-25 23:00:00      NaN   NaN       NaN     NaN        NaN
3  2016-06-12 23:00:00     34.0   5.4      55.9   133.0      372.0

   Transferrin saturations  UCEIS (0 to 8)    WCC  White Cell Count
0                     25.0             NaN  12.35             12.35
1                      NaN             NaN    NaN               NaN
2                      NaN             7.0    NaN               NaN
3                     28.0             NaN   7.99               NaN


问:
How can I best lay out these components in Swing?
What would be the best approach / LayoutManager for a JPanel that needed to display the components shown in the image?
(Note that the fields should resize horizontally when the size of the window is changed, but not the labels).

I'm currently trying (and struggling) to do it with a GridBagLayout.  Is this the correct approach or is there a better way?  Should I be trying to divide + conquer the seperate sections maybe?

Any thoughts or advice would be gratefully appreciated.  :-)

http://img261.imageshack.us/img261/2091/layouthb6.png

PS If you read this and there's no image, please bear with me whilst I fix it!

答: I used to really hate doing swing layouts until Netbeans came out with their gui builder. You can see a demo here. http://rghosting.co.cc</p>

OwnerDisplayName: cagcowboy

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: John Topley


问:
Android layout bypass image with text
I want to achieve android layout for text and image to be as shown on the left pic, however with ImageSpan and in-lining image into text at start gives me only what's on the right pic.

Are there any solutions to beautifully bypass large image with text?

```<code>|-------------| texttexttexttexttext   |-------------|
|             | texttexttexttexttext   |             |
|   image     | texttexttexttexttext   |   image     |
|             | texttexttexttexttext   |             |
|-------------| texttexttexttexttext   |-------------| texttexttexttexttext
texttexttexttexttexttexttexttexttext    texttexttexttexttexttexttexttexttext
texttexttexttexttexttexttexttexttext    texttexttexttexttexttexttexttexttext
texttexttexttexttexttexttexttexttext    texttexttexttexttexttexttexttexttext
|
</code>```

答: Possible by using an WebView and writing HTML-code. Might also be doable by inserting the HTML into an TextView with Html.fromHtml(String, Html.ImageGetter, Html.TagHandler). See an example of using ImageGetter here.</p>

Title: Android layout bypass image with text

Body:
I want to achieve android layout for text and image to be as shown on the left pic, however with ImageSpan and in-lining image into text at start gives me only what's on the right pic.

Are there any solutions to beautifully bypass large image with text?

|-------------| texttexttexttexttext   |-------------|
|             | texttexttexttexttext   |             |
|   image     | texttexttexttexttext   |   image     |
|             | texttexttexttexttext   |             |
|-------------| texttexttexttexttext   |-------------| texttexttexttexttext
texttexttexttexttexttexttexttexttext    texttexttexttexttexttexttexttexttext
texttexttexttexttexttexttexttexttext    texttexttexttexttexttexttexttexttext
texttexttexttexttexttexttexttexttext    texttexttexttexttexttexttexttexttext
|


问:
How to get contract wage from worked days in odoo8
contract.wage is returning the wage of contract mentioned in payslip. But what if i have multiple worked days input and other inputs with different contracts of same person. We have a contract field for each input.

I want to get wage of each contract mentioned/selected in worked days inputs and other inputs.

Note: I want to access wage of contract in salary rules.

Any idea??

答:
You can can access the wage on Worked Days inputs from salary rules using the relation:

```<code>worked_days.WORK100.contract_id.wage
</code>```

where WORK100 is the code of the Worked Days input. In Odoo 10, this code can be named anything. For example, in my own case, I have input codes NORMAL and SPECIAL for normal and special work respectively.

Body:
You can can access the wage on Worked Days inputs from salary rules using the relation:

worked_days.WORK100.contract_id.wage

where WORK100 is the code of the Worked Days input. In Odoo 10, this code can be named anything. For example, in my own case, I have input codes NORMAL and SPECIAL for normal and special work respectively.


问:
Angular 2 and Spring Kerberos
Is it possible to use Kerberos in an Angular 2 application? We are using Spring which hosts our REST service and also protects the Angular 2 resources with Kerberos. We want to add roles and define what funtionality in the Angular2 application is available for certain roles. There seems to be little information around on how to do this since most of the people seem to have gone to use JWT or OAuth.

Would it be possible to use Kerberos for the initial authentication and then generate a JWT which is sent back to the browser?

At the moment I am thinking about setting up a REST endpoint /user which returns all the information about the currently logged-in user including his/her permissions. In Angular I can then read those permissions and manipulate the UI and the routes accordingly. The data coming from the server would already be protected by Kerberos and Spring. So if the user can still alter their local Angular to visit some of the protected routes, they would not see any data.

答:
This would be a perfect use case for JWT tokens. Once you are authenticated at server end backend service can create a JWT token with the roles of a particular user and return back the same to Angular2 app. Angular app can configure UI depending on the roles of the user. On every consecutive server calls the angular app can sends back this token, so that this token is used to find the roles of the user. Spring security allows to add the custom filter before Authentication which can be used to validate the token.

```<code>@Configuration
public class WebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.addFilterAfter(new TokenFilter(), BasicAuthenticationFilter.class);
    }
}
</code>```

Inside TokenFilter the JWT token can be parsed for finding the user roles and allowing the access for a particular protected resource. If anybody tries to modify the token or request a forbidden protect resource the JWT token validation would fail.

```<code>public class TokenFilter extends GenericFilterBean {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {
        // Validate Token her for the requested url
       if(validateToken(request.getHeader("auth")){
            chain.doFilter(request, response);
       }else{
            // return 403 response
    }
}
</code>```

Title: Angular 2 and Spring Kerberos

Body:
This would be a perfect use case for JWT tokens. Once you are authenticated at server end backend service can create a JWT token with the roles of a particular user and return back the same to Angular2 app. Angular app can configure UI depending on the roles of the user. On every consecutive server calls the angular app can sends back this token, so that this token is used to find the roles of the user. Spring security allows to add the custom filter before Authentication which can be used to validate the token.

@Configuration
public class WebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.addFilterAfter(new TokenFilter(), BasicAuthenticationFilter.class);
    }
}

Inside TokenFilter the JWT token can be parsed for finding the user roles and allowing the access for a particular protected resource. If anybody tries to modify the token or request a forbidden protect resource the JWT token validation would fail.

public class TokenFilter extends GenericFilterBean {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {
        // Validate Token her for the requested url
       if(validateToken(request.getHeader("auth")){
            chain.doFilter(request, response);
       }else{
            // return 403 response
    }
}


问:
A bug because of the accuracy of double type in C++
I have wrote a class to calculate the amount of money for me. Below is the code in brief.

```<code>class RMB
{
private:
    int yuan;
    int jiao;
    int fen;
    bool mark;
public:
RMB(int yu, int ji, int fe, bool mar = true)
    {
        yuan = yu;
        jiao = ji;
        fen = fe;
        mark = mar;
    }
    RMB(double money)
    {
        int money1 = int(money * 100);
        yuan = money1 / 100;
        fen = money1 % 10;
        jiao = (money1 - yuan * 100 - fen)/10;
        if (money < 0) mark = 0;
        else mark = 1;
    }
    operator double()
    {
        double money = yuan + double(jiao) / 10 + double(fen) / 100;
        if (mark == false) return -money;
        return money;
    }
};
int main()
{
    RMB a(1,2,3);RMB b(2,3,4);
cout << "a + c = " << RMB(a + c) << endl;//assume I have override "<<" and ">>"

cout << "a - b = " << RMB(a - b) << endl;
}
</code>```

But when I test my code,it happened that:

```<code>a + c = 2 yuan 4 jiao 5 fen

a - b = -1 yuan -1 jiao 0 fen
</code>```

I test it in VS2015,I have debugged it, and I see exact value of double(a-b） is -1.199999998. So how can I fix this bug and what can I do to avoid bug like this kind?

答:
The easiest thing to do by a country mile is to use an integral type for money values and work in cents. Using binary floating point types for exact decimal values is never going to end well.

If your compiler has them, then use std::uint64_t as the type, or std::int64_t if you need the concept of a negative amount. That's more than large enough for world GDP expressed in Zimbabwean Dollars. You could even wrap this in a class for future proofing.

C++ intentionally does not provide a decimal type "out of the box".

Body:
I have wrote a class to calculate the amount of money for me. Below is the code in brief.

class RMB
{
private:
    int yuan;
    int jiao;
    int fen;
    bool mark;
public:
RMB(int yu, int ji, int fe, bool mar = true)
    {
        yuan = yu;
        jiao = ji;
        fen = fe;
        mark = mar;
    }
    RMB(double money)
    {
        int money1 = int(money * 100);
        yuan = money1 / 100;
        fen = money1 % 10;
        jiao = (money1 - yuan * 100 - fen)/10;
        if (money < 0) mark = 0;
        else mark = 1;
    }
    operator double()
    {
        double money = yuan + double(jiao) / 10 + double(fen) / 100;
        if (mark == false) return -money;
        return money;
    }
};
int main()
{
    RMB a(1,2,3);RMB b(2,3,4);
cout << "a + c = " << RMB(a + c) << endl;//assume I have override "<<" and ">>"

cout << "a - b = " << RMB(a - b) << endl;
}

But when I test my code,it happened that:

a + c = 2 yuan 4 jiao 5 fen

a - b = -1 yuan -1 jiao 0 fen

I test it in VS2015,I have debugged it, and I see exact value of double(a-b） is -1.199999998. So how can I fix this bug and what can I do to avoid bug like this kind?


问:
Margin-right broken on width 100%
I have a DIV containing an image and a second DIV. The parent DIV is set to position: absolute; the child DIV is set to position: relative. The idea is that I display my photo caption on top of my image.

The child DIV should have 100% width of the parent, minus 10px on the left, right and bottom, plus a black background.

.article-container {
  position: relative;
}

.photo-caption {
  width: 100%;
  background-color: black;
  position: absolute;
  bottom: 0px;
  margin-right: 10px;
  margin-left: 10px;
  margin-bottom: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="span15 article-container">
  <img src="images/example-image-1.png" />
  <div class="photo-caption">This is the subtitle text on top.</div>
</div></code>```

The left margin bumps .photo-caption outside the bounds of .article-container. The right margin doesn't seem to have any effect.

I've also tried fixing this with box-sizing. It seems to get the width of .photo-caption down to the parent width but there's still the overhang.

答:
The problem is that you're setting your width to 100% which gives no room for margins. Instead adjust your width to a percentage less than 100% and then specify your margin as half the percentage of the remaining space.

For Example:

```<code>style="width:98%; margin-left: 1%;"
</code>```

Title: Margin-right broken on width 100%

Body:
I have a DIV containing an image and a second DIV. The parent DIV is set to position: absolute; the child DIV is set to position: relative. The idea is that I display my photo caption on top of my image.

The child DIV should have 100% width of the parent, minus 10px on the left, right and bottom, plus a black background.

.article-container {
  position: relative;
}

.photo-caption {
  width: 100%;
  background-color: black;
  position: absolute;
  bottom: 0px;
  margin-right: 10px;
  margin-left: 10px;
  margin-bottom: 10px;
}

This is the subtitle text on top.

The left margin bumps .photo-caption outside the bounds of .article-container. The right margin doesn't seem to have any effect.

I've also tried fixing this with box-sizing. It seems to get the width of .photo-caption down to the parent width but there's still the overhang.

Body:
The problem is that you're setting your width to 100% which gives no room for margins. Instead adjust your width to a percentage less than 100% and then specify your margin as half the percentage of the remaining space.

For Example:

style="width:98%; margin-left: 1%;"


问:
jquery mouseenter on child div with bigger dimensions than parent div
I have a parent div with height=100px which is smaller than child div which has height=200px.

When I attach jquery mouseenter on parent div then the event triggers even if I hover the pointer over child ( hover over the portion of child which extends the height of parent ).

Can anyone explain this?

$(document).ready(function() {
  $(".parent").mouseover(function(e) {
   console.log(e.target);
  });
  $(".child").mouseover(function(e) {
   console.log(e.target);
  });
  $(".grandchild").mouseover(function(e) {
   console.log(e.target);
  });
 });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.parent {
   background-color: green;
   height: 50px;
  }
  .child {
   background-color: red;
   height: 100px;
  }
  .grandchild {
   background-color: blue;
   height: 200px;
  }</code>```

    Test

```

--UPDATE--
At first it unclear to me what was exactly the problem. Now I think I understand (I updated the code).

Say we have a parent div with width=100px and height=100px.

Then we have a child div with width=200px and height=200px (bigger area than parent).

When I hover the mouse over the child (but not over the parent yet) the browser calculates that the pointer is over the parent too, although it does not.

So if I have a handler both on child and on parent, they will fire both by the time I enter the child div only.

Thank you.

答:
try this:

```<code>    $(".child").mouseover(function(e) {
    e.stopImmediatePropagation();
    console.log(e.isPropagationStopped());
    console.log(e.currentTarget);
});
</code>```

e.isPropagationStopped() tells you if the method e.stopImmediatePropagation(); is called. I tried and this works for me. And you have to select child instead of parent

Body:
I have a parent div with height=100px which is smaller than child div which has height=200px.

When I attach jquery mouseenter on parent div then the event triggers even if I hover the pointer over child ( hover over the portion of child which extends the height of parent ).

Can anyone explain this?

$(document).ready(function() {
  $(".parent").mouseover(function(e) {
   console.log(e.target);
  });
  $(".child").mouseover(function(e) {
   console.log(e.target);
  });
  $(".grandchild").mouseover(function(e) {
   console.log(e.target);
  });
 });

.parent {
   background-color: green;
   height: 50px;
  }
  .child {
   background-color: red;
   height: 100px;
  }
  .grandchild {
   background-color: blue;
   height: 200px;
  }

    Test

--UPDATE--
At first it unclear to me what was exactly the problem. Now I think I understand (I updated the code).

Say we have a parent div with width=100px and height=100px.

Then we have a child div with width=200px and height=200px (bigger area than parent).

When I hover the mouse over the child (but not over the parent yet) the browser calculates that the pointer is over the parent too, although it does not.

So if I have a handler both on child and on parent, they will fire both by the time I enter the child div only.

Thank you.

Body:
try this:

    $(".child").mouseover(function(e) {
    e.stopImmediatePropagation();
    console.log(e.isPropagationStopped());
    console.log(e.currentTarget);
});

e.isPropagationStopped() tells you if the method e.stopImmediatePropagation(); is called. I tried and this works for me. And you have to select child instead of parent


问:
Easiest way to get Zip Code from City Name
I wanted to mess around with an assignment of mine and search for weather by city name rather than by zip code(how i have it set up now). What would be the easiest way to use a city name input string and get a zip code out of it? Help is much appreciated! Thanks!</p>

答:
```<code>var res; // store response in res variable
var add_array  = res[0].address_components; //add_array = {
               "long_name" : "Clarkston",
               "short_name" : "Clarkston",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Oakland",
               "short_name" : "Oakland",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "Michigan",
               "short_name" : "MI",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "United States",
               "short_name" : "US",
               "types" : [ "country", "political" ]
            },
            {
               "long_name" : "48346",
               "short_name" : "48346",
               "types" : [ "postal_code" ]
            }
    var add_array = add_array[add_array.length-1]; //add_array = {
                   "long_name" : "48346",
                   "short_name" : "48346",
                   "types" : [ "postal_code" ]
                }
    var zip = add_array.long_name;  //zip = 48346
</code>```


问:
mysql query - accessing field without affecting output
I have 2 tables in mysql: tableA and tableB

```<code>tableA: idA
tableB: idB, name
</code>```

Now i want to fire following query:

```<code>SELECT * FROM tableA WHERE idA in (1, 2, 3, 4);
</code>```

idA and idB are exactly same. I want to access "name" field of tableB in the above query.

How do i do this???

Thanks alot for help
Regards

答:
Use a MySQL JOIN</p>

```<code>    SELECT tableB.name
      FROM tableA
INNER JOIN tableB ON tableA.idA=tableB.idB
     WHERE idA in (1, 2, 3, 4);
</code>```

Body:
I have 2 tables in mysql: tableA and tableB

tableA: idA
tableB: idB, name

Now i want to fire following query:

SELECT * FROM tableA WHERE idA in (1, 2, 3, 4);

idA and idB are exactly same. I want to access "name" field of tableB in the above query.

How do i do this???

Thanks alot for help
Regards

Body:
Use a MySQL JOIN

    SELECT tableB.name
      FROM tableA
INNER JOIN tableB ON tableA.idA=tableB.idB
     WHERE idA in (1, 2, 3, 4);


问:
Accessing the QPushButton in the callback function
I want to enable a pushbutton in a callback function. I have tried to do the following but I have got:

```<code>Runtime received SIGSEGV (address: 0x28 reason: address not mapped to object)
</code>```

```<code>class MyWindow: public QDialog
{
    Q_OBJECT
public:
   QPushButton *Btn;
   void Scan();
....
};
extern void StartScan(pfcallback);
void MyWindow::Scan()
{
 Btn->setEnabled(false);
 StartScan(Scanfinished);
}
void static Scanfinished()
{
  Btn->setEnabled(true);
}
</code>```

How to access the button in the callback function Scanfinished() ?

答:
You're attempting to manually manage memory. As you can see, it's very easy to use a dangling pointer or commit other blunders. Instead, let the compiler do it for you.

You use static incorrectly.

If I were to do it, I'd do as follows. The destructor is generated by the compiler and will correctly release all resources and reset m_instance to a null value.

```<code>class MyWindow : public QDialog
{
   Q_OBJECT
   static QPointer<MyWindow> m_instance;
   QVBoxLayout m_layout{this};
   QPushButton m_button{"Scan"};
public:
   MyWindow(QWidget * parent = nullptr) : QDialog(parent) {
      Q_ASSERT(! m_instance);
      m_instance = this;
      m_layout.addWidget(&m_button);
   }
   void Scan();
   static void ScanFinished();
};

QPointer<MyWindow> MyWindow::m_instance;

void StartScan(void(*callback)());

void MyWindow::Scan()
{
   m_button.setEnabled(false);
   StartScan(ScanFinished);
}

void MyWindow::ScanFinished()
{
   m_instance->m_button.setEnabled(true);
}
</code>```

At this point it's rather obvious that the API of StartScan is horribly broken, and this brokenness forces the use of a singleton MyWindow. When doing any kind of callbacks, you never use a sole C function pointer. You must accept both a function pointer that takes a void* and a void* that will be used to carry the data the function needs to work. This is an idiom. If you use C-style callbacks, you cannot not use the idiom without severely crippling the usability of your API.

Thus, this is a complete example and works in both Qt 4 and Qt 5. You should have posted something like it - a self-contained test case - in your question. It compiles and it works and you can even get the complete Qt Creator project from github. It will compile and run on all platforms supported by current Qt. It's not supposed to be hard: that's why you're using Qt, after all. Getting in the habit of creating such concise test cases to demonstrate your issues will make you a better developer, and make your questions much easier to answer.

```<code>// https://github.com/KubaO/stackoverflown/tree/master/questions/simple-callback-43094825
#include <QtGui>
#if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
#include <QtWidgets>
#include <QtConcurrent>
#endif

class MyWindow: public QDialog
{
   Q_OBJECT
   QVBoxLayout m_layout{this};
   QPushButton m_button{"Scan"};
   Q_SIGNAL void ScanFinished();
public:
   MyWindow(QWidget * parent = nullptr) : QDialog(parent) {
      m_layout.addWidget(&m_button);
      connect(&m_button, SIGNAL(clicked(bool)), this, SLOT(Scan()));
      connect(this, SIGNAL(ScanFinished()), this, SLOT(OnScanFinished()));
   }
   Q_SLOT void Scan();
   static void ScanFinishedCallback(void* w);
   Q_SLOT void OnScanFinished();
};

void StartScan(void(*callback)(void*), void* data) {
   // Mockup of the scanning process: invoke the callback after a delay from
   // a worker thread.
   QtConcurrent::run([=]{
      struct Helper : QThread { using QThread::sleep; };
      Helper::sleep(2);
      callback(data);
   });
}

void MyWindow::Scan()
{
   m_button.setEnabled(false);
   StartScan(ScanFinishedCallback, static_cast<void*>(this));
}

void MyWindow::ScanFinishedCallback(void* data)
{
   emit static_cast<MyWindow*>(data)->ScanFinished();
}

void MyWindow::OnScanFinished()
{
   m_button.setEnabled(true);
}

int main(int argc, char ** argv) {
   QApplication app(argc, argv);
   MyWindow w;
   w.show();
   return app.exec();
}
#include "main.moc"
</code>```

Of course StartScan cannot do the work in the thread it was called from: it'd block the GUI thread and make your application unresponsive. That's the prime source of bad user experience. Instead, it should spawn a concurrent job that will notify the caller when the scanning is done.

Since the callback will be called from that concurrent thread, it's not safe to use MyWindow's non-thread-safe methods. The only thread-safe methods are signals - thus we can emit a signal that Qt will the safely forward to MyWindow's thread and invoke OnScanFinished from the right thread.

Body:
I want to enable a pushbutton in a callback function. I have tried to do the following but I have got:

Runtime received SIGSEGV (address: 0x28 reason: address not mapped to object)

class MyWindow: public QDialog
{
    Q_OBJECT
public:
   QPushButton *Btn;
   void Scan();
....
};
extern void StartScan(pfcallback);
void MyWindow::Scan()
{
 Btn->setEnabled(false);
 StartScan(Scanfinished);
}
void static Scanfinished()
{
  Btn->setEnabled(true);
}

How to access the button in the callback function Scanfinished() ?

Body:
You're attempting to manually manage memory. As you can see, it's very easy to use a dangling pointer or commit other blunders. Instead, let the compiler do it for you.

You use static incorrectly.

If I were to do it, I'd do as follows. The destructor is generated by the compiler and will correctly release all resources and reset m_instance to a null value.

class MyWindow : public QDialog
{
   Q_OBJECT
   static QPointer<MyWindow> m_instance;
   QVBoxLayout m_layout{this};
   QPushButton m_button{"Scan"};
public:
   MyWindow(QWidget * parent = nullptr) : QDialog(parent) {
      Q_ASSERT(! m_instance);
      m_instance = this;
      m_layout.addWidget(&m_button);
   }
   void Scan();
   static void ScanFinished();
};

QPointer<MyWindow> MyWindow::m_instance;

void StartScan(void(*callback)());

void MyWindow::Scan()
{
   m_button.setEnabled(false);
   StartScan(ScanFinished);
}

void MyWindow::ScanFinished()
{
   m_instance->m_button.setEnabled(true);
}

At this point it's rather obvious that the API of StartScan is horribly broken, and this brokenness forces the use of a singleton MyWindow. When doing any kind of callbacks, you never use a sole C function pointer. You must accept both a function pointer that takes a void* and a void* that will be used to carry the data the function needs to work. This is an idiom. If you use C-style callbacks, you cannot not use the idiom without severely crippling the usability of your API.

Thus, this is a complete example and works in both Qt 4 and Qt 5. You should have posted something like it - a self-contained test case - in your question. It compiles and it works and you can even get the complete Qt Creator project from github. It will compile and run on all platforms supported by current Qt. It's not supposed to be hard: that's why you're using Qt, after all. Getting in the habit of creating such concise test cases to demonstrate your issues will make you a better developer, and make your questions much easier to answer.

// https://github.com/KubaO/stackoverflown/tree/master/questions/simple-callback-43094825
#include <QtGui>
#if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
#include <QtWidgets>
#include <QtConcurrent>
#endif

class MyWindow: public QDialog
{
   Q_OBJECT
   QVBoxLayout m_layout{this};
   QPushButton m_button{"Scan"};
   Q_SIGNAL void ScanFinished();
public:
   MyWindow(QWidget * parent = nullptr) : QDialog(parent) {
      m_layout.addWidget(&m_button);
      connect(&m_button, SIGNAL(clicked(bool)), this, SLOT(Scan()));
      connect(this, SIGNAL(ScanFinished()), this, SLOT(OnScanFinished()));
   }
   Q_SLOT void Scan();
   static void ScanFinishedCallback(void* w);
   Q_SLOT void OnScanFinished();
};

void StartScan(void(*callback)(void*), void* data) {
   // Mockup of the scanning process: invoke the callback after a delay from
   // a worker thread.
   QtConcurrent::run([=]{
      struct Helper : QThread { using QThread::sleep; };
      Helper::sleep(2);
      callback(data);
   });
}

void MyWindow::Scan()
{
   m_button.setEnabled(false);
   StartScan(ScanFinishedCallback, static_cast<void*>(this));
}

void MyWindow::ScanFinishedCallback(void* data)
{
   emit static_cast<MyWindow*>(data)->ScanFinished();
}

void MyWindow::OnScanFinished()
{
   m_button.setEnabled(true);
}

int main(int argc, char ** argv) {
   QApplication app(argc, argv);
   MyWindow w;
   w.show();
   return app.exec();
}
#include "main.moc"

Of course StartScan cannot do the work in the thread it was called from: it'd block the GUI thread and make your application unresponsive. That's the prime source of bad user experience. Instead, it should spawn a concurrent job that will notify the caller when the scanning is done.

Since the callback will be called from that concurrent thread, it's not safe to use MyWindow's non-thread-safe methods. The only thread-safe methods are signals - thus we can emit a signal that Qt will the safely forward to MyWindow's thread and invoke OnScanFinished from the right thread.


问:
Default error popup with TextInputLayout
Having a problem setting a different error message to EditText inside TextInputLayout.

What I get:

What I want:

Is there anyway to achieve it while maintaining TextInputLayout?

答:
Turns out i have allready solved it, i have wrote before in code:

```<code>((TextInputLayout) item_).setError(valid.getEventResult().getViewErrors()[i].getMessage().get_Message());
</code>```

All i had to do was change it so i set the error on EditText instead of TextInputLayout.

Body:
Turns out i have allready solved it, i have wrote before in code:

((TextInputLayout) item_).setError(valid.getEventResult().getViewErrors()[i].getMessage().get_Message());

All i had to do was change it so i set the error on EditText instead of TextInputLayout.


问:
Jenkins API - find all jobs using specific GIT repo
Any idea how I can query jenkins to get list of all jobs running specific GIT repo? Or list of all jobs and the GIT source code they are using?

Thanks,

答:
This is how you get specific build # configuration using python:
import json
import urllib

url = 'http://jenkins_user:jenkins_password@my_jenkins_repo.com:8080/job/job_folder/job/job_name/build_number/api/json?pretty=true'

response = urllib.urlopen(url)
data = json.loads(response.read())

print data

with this you can first find all jobs under folder/repo, take last job for each and find the git repo for each job.