问:
Git: Export MySQL database on commit?
Is there a way I can utilize git to export/download my MySQL development database that is utilized in my code on a commit or some other way through git so that whenever I clone my project, I always have a current copy of the database?

If not, I can always export the database, and add it to the source, I was just wondering if git had the capability of doing this almost like a hook.

答:
I ended up using the git hooks as I anticipated.  I created the pre-commit hook and added the following to it:

```#!/bin/bash
DBUSER="sysbackup"
DBPASS="password"
DB="database-name"
SCHEMAPATH="DBSchema"

mysqldump -u $DBUSER -p$DBPASS $DB > $SCHEMAPATH/$DB.sql
git add $SCHEMAPATH/$DB.sql
exit 0```

Title: Git: Export MySQL database on commit?

Body:
I ended up using the git hooks as I anticipated.  I created the pre-commit hook and added the following to it:

#!/bin/bash
DBUSER="sysbackup"
DBPASS="password"
DB="database-name"
SCHEMAPATH="DBSchema"

mysqldump -u $DBUSER -p$DBPASS $DB > $SCHEMAPATH/$DB.sql
git add $SCHEMAPATH/$DB.sql
exit 0


来源: stackexchange

问:
User groups, and dififerent views / functions for each group
Desired Output:
Employee and Client user types. If registering through the main website the user will automatically be a Client. Client type users get a different menu/dashboard/portal whatever you wanna call that. For examples. Clients can book an appointment. Then for employees that usertype is set manually in django admin. AFterwards when they log in, they get a different dashboard, say  one that displays their schedule and they can put available hours. This user doesnt even need to have a registration page it can all be done in admin.

From my limited understanding to bring this desired outcome to reality I must extend the userprofile? Or should I entirely create a custom userprofile using the AbstractUser abstraction?

Also where does django groups come in. And is all this User model extending even necessary? Can django groups be used entirely for this project?

```<code>class UserProfile(models.Model):
    user = models.ForeignKey(User)
    #define general fields

class Client(models.Model):
    profile = models.ForeignKey(UserProfile)
    #freelancer specific  fields

    class Meta:
        db_table = 'Client'

class Employee(models.Model):
    profile = models.ForeignKey(UserProfile)
    #Employee specific fields

   class Meta:
        db_table = 'Employee'
</code>```

Thanks in advance!!

答:
You can use default django groups

in your views.py:

from django.contrib.auth.models import User
from django.contrib.auth.models import Group

# for inscription register the right group
def inscription(request):
    g = Group.objects.get(name='client')
    user = User()
    "etc"
    user.groups.add(g)
    user.save()

#To login
def loggedPage(request):
    userGroup = Group.objects.get(user=request.user).name
    if userGroup == 'client':
         "do some stuff"
    elif userGroup == 'employee':
         "do some other stuff"
```
<p>WARNING: you have to register 2 groups with</p>
<blockquote>
<p>python manage.py shell</p>
</blockquote>
<p>one called <em>employee</em> and the other <em>client</em></p>
<p>You can also use management to initialize your db with the right groups:
create a file called <em>yourapp/management/commands/DB_init.py</em> (create folders if doesn't exists, and write this in it:</p>
<pre class="lang-py prettyprint-override"><code>import os
os.environ["DJANGO_SETTINGS_MODULE"] = "YOURAPP.settings"
from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import  Group

class Command(BaseCommand):
    def __init__(self, *args, **kwargs):
        super(Command, self).__init__(*args, **kwargs)
        group, created = Group.objects.get_or_create(name="client")
        if created:
            group.name = "client"
            group.save()

        group, created = Group.objects.get_or_create(name="employee")
        if created:
            group.name = "employee"
            group.save()
</code>```

If you have created folders, think to put an "__ init __.py" in them to transform them as python packages.

your files should look like this:

YOURAPP/
    __init__.py
    models.py
    management/
        __init__.py
        commands/
            __init__.py
            DB_init.py
    tests.py
    views.py
```

Run

python manage.py DB_init

and voila !

ContentLicense: CC BY-SA 3.0

Body:
Desired Output:
Employee and Client user types. If registering through the main website the user will automatically be a Client. Client type users get a different menu/dashboard/portal whatever you wanna call that. For examples. Clients can book an appointment. Then for employees that usertype is set manually in django admin. AFterwards when they log in, they get a different dashboard, say  one that displays their schedule and they can put available hours. This user doesnt even need to have a registration page it can all be done in admin.

From my limited understanding to bring this desired outcome to reality I must extend the userprofile? Or should I entirely create a custom userprofile using the AbstractUser abstraction?

Also where does django groups come in. And is all this User model extending even necessary? Can django groups be used entirely for this project?

class UserProfile(models.Model):
    user = models.ForeignKey(User)
    #define general fields

class Client(models.Model):
    profile = models.ForeignKey(UserProfile)
    #freelancer specific  fields

    class Meta:
        db_table = 'Client'

class Employee(models.Model):
    profile = models.ForeignKey(UserProfile)
    #Employee specific fields

   class Meta:
        db_table = 'Employee'

Thanks in advance!!

Body:
You can use default django groups

in your views.py:

from django.contrib.auth.models import User
from django.contrib.auth.models import Group

# for inscription register the right group
def inscription(request):
    g = Group.objects.get(name='client')
    user = User()
    "etc"
    user.groups.add(g)
    user.save()

#To login
def loggedPage(request):
    userGroup = Group.objects.get(user=request.user).name
    if userGroup == 'client':
         "do some stuff"
    elif userGroup == 'employee':
         "do some other stuff"

WARNING: you have to register 2 groups with

python manage.py shell

one called employee and the other client

You can also use management to initialize your db with the right groups:
create a file called yourapp/management/commands/DB_init.py (create folders if doesn't exists, and write this in it:

import os
os.environ["DJANGO_SETTINGS_MODULE"] = "YOURAPP.settings"
from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import  Group

class Command(BaseCommand):
    def __init__(self, *args, **kwargs):
        super(Command, self).__init__(*args, **kwargs)
        group, created = Group.objects.get_or_create(name="client")
        if created:
            group.name = "client"
            group.save()

        group, created = Group.objects.get_or_create(name="employee")
        if created:
            group.name = "employee"
            group.save()

If you have created folders, think to put an "__ init __.py" in them to transform them as python packages.

your files should look like this:

YOURAPP/
    __init__.py
    models.py
    management/
        __init__.py
        commands/
            __init__.py
            DB_init.py
    tests.py
    views.py

Run

python manage.py DB_init

and voila !


问:
Broken symmetry of operations between Boolean pandas.Series with unequal index
The implicit index-matching of pandas for operations between different DataFrame/Series is great and most of the times, it just works.

However, I've stumbled on an example that does not work as expected:

```<code>import pandas as pd # 0.21.0
import numpy as np # 1.13.3
x = pd.Series([True, False, True, True], index = range(4))
y = pd.Series([False, True, True, False], index = [2,4,3,5])

# logical AND: this works, symmetric as it should be
pd.concat([x, y, x & y, y & x], keys = ['x', 'y', 'x&y', 'y&x'], axis = 1)
#        x      y    x&y    y&x
# 0   True    NaN  False  False
# 1  False    NaN  False  False
# 2   True  False  False  False
# 3   True   True   True   True
# 4    NaN   True  False  False
# 5    NaN  False  False  False

# but logical OR is not symmetric anymore (same for XOR: x^y vs. y^x)
pd.concat([x, y, x | y, y | x], keys = ['x', 'y', 'x|y', 'y|x'], axis = 1)
#        x      y    x|y    y|x
# 0   True    NaN   True  False <-- INCONSISTENT!
# 1  False    NaN  False  False
# 2   True  False   True   True
# 3   True   True   True   True
# 4    NaN   True  False   True <-- INCONSISTENT!
# 5    NaN  False  False  False
</code>```

Researching a bit, I found two points that seem relevant:

bool(np.nan) equals True, cf. https://stackoverflow.com/a/15686477/2965879

| is resolved to np.bitwise_or, rather than np.logical_or, cf. https://stackoverflow.com/a/37132854/2965879

But ultimately, the kicker seems to be that pandas does casting from nan to False at some point. Looking at the above, it appears that this happens after calling  np.bitwise_or, while I think this should happen before?

In particular, using np.logical_or does not help because it misses the index alignment that pandas does, and also, I don't want np.nan or False to equal True. (In other words, the answer https://stackoverflow.com/a/37132854/2965879 does not help.)

I think that if this wonderful syntactic sugar is provided, it should be as consistent as possible*, and so | should be symmetric. It's really hard to debug (as happened to me) when something that's always symmetric suddenly isn't anymore.

So finally, the question: Is there any feasible workaround (e.g. overloading something) to salvage x|y == y|x, and ideally in such a way that (loosely speaking) nan | True == True == True | nan and nan | False == False == False | nan?

*even if De Morgan's law falls apart regardless - ~(x&y) can not fully match ~y|~x because the NaNs only come in at the index alignment (and so are not affected by a previous negation).

答:
After doing some exploring in pandas, I discovered that there is a function called pandas.core.ops._bool_method_SERIES which is one of several factory functions that wrap the boolean operators for Series objects.

```<code>>>> f = pandas.Series.__or__
>>> f #the actual function you call when you do x|y
<function _bool_method_SERIES.<locals>.wrapper at 0x107436bf8>
>>> f.__closure__[0].cell_contents
    #it holds a reference to the other function defined in this factory na_op
<function _bool_method_SERIES.<locals>.na_op at 0x107436b70>
>>> f.__closure__[0].cell_contents.__closure__[0].cell_contents
    #and na_op has a reference to the built-in function or_
<built-in function or_>
</code>```

This means we could theoretically define our own method that would perform a logical or with the correct logic, first let's see what it will actually do (remember an operator function is expected to raise a TypeError if the operation can't be performed)

```<code>def test_logical_or(a,b):
    print("**** calling logical_or with ****")
    print(type(a), a)
    print(type(b), b)
    print("******")
    raise TypeError("my_logical_or isn't implemented")

#make the wrapper method
wrapper = pd.core.ops._bool_method_SERIES(test_logical_or, None,None)
pd.Series.logical_or = wrapper #insert method

x = pd.Series([True, False, True, True], index = range(4))
y = pd.Series([False, True, True, False], index = [2,4,3,5])

z = x.logical_or(y) #lets try it out!

print(x,y,z, sep="\n")
</code>```

When this gets run (at least with pandas vs 0.19.1)

```<code>**** calling logical_or with ****
<class 'numpy.ndarray'> [True False True True nan nan]
<class 'numpy.ndarray'> [False False False  True  True False]
******
**** calling logical_or with ****
<class 'bool'> True
<class 'bool'> False
******
Traceback (most recent call last):
   ...
</code>```

So it looks like it tried to call our method with two numpy arrays, where for whatever reason the second one has the nan values already replaced with False but not the first one which is likely why our symmetry breaks.  and then when that failed it tried again I'd assume element-wise.

So as a bare minimum to get this working you can just explicitly check that both arguments are numpy arrays, try to convert all the nan entries of the first to False then return np.logical_or(a,b).  I'm going to assume if anything else is the case we will just raise an error.

```<code>def my_logical_or(a,b):
    if isinstance(a, np.ndarray) and isinstance(b, np.ndarray):
        a[np.isnan(a.astype(float))] = False
        b[np.isnan(b.astype(float))] = False
        return np.logical_or(a,b)
    else:
        raise TypeError("custom logical or is only implemented for numpy arrays")

wrapper = pd.core.ops._bool_method_SERIES(my_logical_or, None,None)
pd.Series.logical_or = wrapper

x = pd.Series([True, False, True, True], index = range(4))
y = pd.Series([False, True, True, False], index = [2,4,3,5])

z = pd.concat([x, y, x.logical_or(y), y.logical_or(x)], keys = ['x', 'y', 'x|y', 'y|x'], axis = 1)
print(z)
#        x      y    x|y    y|x
# 0   True    NaN   True   True
# 1  False    NaN  False  False <-- same!
# 2   True  False   True   True
# 3   True   True   True   True
# 4    NaN   True   True   True <-- same!
# 5    NaN  False  False  False
</code>```

So that could be your workaround, I would not recommend modifying Series.__or__ since we don't know who else would be using it and don't want to break any code that expects the default behaviour.

Alternatively,  we can modify the source code at pandas.core.ops line 943 to fill NaN values with False (or 0) for self in the same way it does with other, so we'd change the line:

```<code>    return filler(self._constructor(na_op(self.values, other.values),
                                    index=self.index, name=name))
</code>```

to use filler(self).values instead of self.values:

```<code>    return filler(self._constructor(na_op(filler(self).values, other.values),
                                    index=self.index, name=name))
</code>```

This also fixes the issue with or and xor not being symmetric, however, I would not recommend this since it may break other code, I personally don't have nearly enough experience with pandas to determine what this would change in different circumstances.

Body:
The implicit index-matching of pandas for operations between different DataFrame/Series is great and most of the times, it just works.

However, I've stumbled on an example that does not work as expected:

import pandas as pd # 0.21.0
import numpy as np # 1.13.3
x = pd.Series([True, False, True, True], index = range(4))
y = pd.Series([False, True, True, False], index = [2,4,3,5])

# logical AND: this works, symmetric as it should be
pd.concat([x, y, x & y, y & x], keys = ['x', 'y', 'x&y', 'y&x'], axis = 1)
#        x      y    x&y    y&x
# 0   True    NaN  False  False
# 1  False    NaN  False  False
# 2   True  False  False  False
# 3   True   True   True   True
# 4    NaN   True  False  False
# 5    NaN  False  False  False

# but logical OR is not symmetric anymore (same for XOR: x^y vs. y^x)
pd.concat([x, y, x | y, y | x], keys = ['x', 'y', 'x|y', 'y|x'], axis = 1)
#        x      y    x|y    y|x
# 0   True    NaN   True  False <-- INCONSISTENT!
# 1  False    NaN  False  False
# 2   True  False   True   True
# 3   True   True   True   True
# 4    NaN   True  False   True <-- INCONSISTENT!
# 5    NaN  False  False  False

Researching a bit, I found two points that seem relevant:

bool(np.nan) equals True, cf. https://stackoverflow.com/a/15686477/2965879

| is resolved to np.bitwise_or, rather than np.logical_or, cf. https://stackoverflow.com/a/37132854/2965879

But ultimately, the kicker seems to be that pandas does casting from nan to False at some point. Looking at the above, it appears that this happens after calling  np.bitwise_or, while I think this should happen before?

In particular, using np.logical_or does not help because it misses the index alignment that pandas does, and also, I don't want np.nan or False to equal True. (In other words, the answer https://stackoverflow.com/a/37132854/2965879 does not help.)

I think that if this wonderful syntactic sugar is provided, it should be as consistent as possible*, and so | should be symmetric. It's really hard to debug (as happened to me) when something that's always symmetric suddenly isn't anymore.

So finally, the question: Is there any feasible workaround (e.g. overloading something) to salvage x|y == y|x, and ideally in such a way that (loosely speaking) nan | True == True == True | nan and nan | False == False == False | nan?

*even if De Morgan's law falls apart regardless - ~(x&y) can not fully match ~y|~x because the NaNs only come in at the index alignment (and so are not affected by a previous negation).

Body:
After doing some exploring in pandas, I discovered that there is a function called pandas.core.ops._bool_method_SERIES which is one of several factory functions that wrap the boolean operators for Series objects.

>>> f = pandas.Series.__or__
>>> f #the actual function you call when you do x|y
<function _bool_method_SERIES.<locals>.wrapper at 0x107436bf8>
>>> f.__closure__[0].cell_contents
    #it holds a reference to the other function defined in this factory na_op
<function _bool_method_SERIES.<locals>.na_op at 0x107436b70>
>>> f.__closure__[0].cell_contents.__closure__[0].cell_contents
    #and na_op has a reference to the built-in function or_
<built-in function or_>

This means we could theoretically define our own method that would perform a logical or with the correct logic, first let's see what it will actually do (remember an operator function is expected to raise a TypeError if the operation can't be performed)

def test_logical_or(a,b):
    print("**** calling logical_or with ****")
    print(type(a), a)
    print(type(b), b)
    print("******")
    raise TypeError("my_logical_or isn't implemented")

#make the wrapper method
wrapper = pd.core.ops._bool_method_SERIES(test_logical_or, None,None)
pd.Series.logical_or = wrapper #insert method

x = pd.Series([True, False, True, True], index = range(4))
y = pd.Series([False, True, True, False], index = [2,4,3,5])

z = x.logical_or(y) #lets try it out!

print(x,y,z, sep="\n")

When this gets run (at least with pandas vs 0.19.1)

**** calling logical_or with ****
<class 'numpy.ndarray'> [True False True True nan nan]
<class 'numpy.ndarray'> [False False False  True  True False]
******
**** calling logical_or with ****
<class 'bool'> True
<class 'bool'> False
******
Traceback (most recent call last):
   ...

So it looks like it tried to call our method with two numpy arrays, where for whatever reason the second one has the nan values already replaced with False but not the first one which is likely why our symmetry breaks.  and then when that failed it tried again I'd assume element-wise.

So as a bare minimum to get this working you can just explicitly check that both arguments are numpy arrays, try to convert all the nan entries of the first to False then return np.logical_or(a,b).  I'm going to assume if anything else is the case we will just raise an error.

def my_logical_or(a,b):
    if isinstance(a, np.ndarray) and isinstance(b, np.ndarray):
        a[np.isnan(a.astype(float))] = False
        b[np.isnan(b.astype(float))] = False
        return np.logical_or(a,b)
    else:
        raise TypeError("custom logical or is only implemented for numpy arrays")

wrapper = pd.core.ops._bool_method_SERIES(my_logical_or, None,None)
pd.Series.logical_or = wrapper

x = pd.Series([True, False, True, True], index = range(4))
y = pd.Series([False, True, True, False], index = [2,4,3,5])

z = pd.concat([x, y, x.logical_or(y), y.logical_or(x)], keys = ['x', 'y', 'x|y', 'y|x'], axis = 1)
print(z)
#        x      y    x|y    y|x
# 0   True    NaN   True   True
# 1  False    NaN  False  False <-- same!
# 2   True  False   True   True
# 3   True   True   True   True
# 4    NaN   True   True   True <-- same!
# 5    NaN  False  False  False

So that could be your workaround, I would not recommend modifying Series.__or__ since we don't know who else would be using it and don't want to break any code that expects the default behaviour.

Alternatively,  we can modify the source code at pandas.core.ops line 943 to fill NaN values with False (or 0) for self in the same way it does with other, so we'd change the line:

    return filler(self._constructor(na_op(self.values, other.values),
                                    index=self.index, name=name))

to use filler(self).values instead of self.values:

    return filler(self._constructor(na_op(filler(self).values, other.values),
                                    index=self.index, name=name))

This also fixes the issue with or and xor not being symmetric, however, I would not recommend this since it may break other code, I personally don't have nearly enough experience with pandas to determine what this would change in different circumstances.


问:
How to add fixed text
This question is specific to aframe library.

I was wondering how you can make a text always fixed on the screen, no matter how users move/look around;

E.g. I am developing an aframe VR game and I want to show the scores on the top left of the screen. So no matter what angle the user looks at or wherever he moves to, he will be able to see the his score on the screen.

Hope my question is clear enough.

答:
You have to make the text a child of the camera:

```<code><a-camera>
 <a-text value="Hello, World!" position="0 0 -1"></a-text>
</a-camera>
</code>```

This will place the text 1m in front of the user.

Title: How to add fixed text

Body:
You have to make the text a child of the camera:

<a-camera>
 <a-text value="Hello, World!" position="0 0 -1"></a-text>
</a-camera>

This will place the text 1m in front of the user.


问:
Is it correct, that JUnit is not working with JSF on GlassFish v3, without instantiating an ejb container?
I'am developing a web-app for my thesis. Now I'm on that part, where I want to run automated tests on that web-app. The problem is, that I'm not able to run this tests. Stacjtrace says that he could not find classes which are needen from the class that I want to test.

I've debugged and looked in NetBeans which classes are loaded. And it seems that only the class, which I test was loaded. Someone told me, that I must run an embedded GlassFish.

Thanks in advance

```<code>Testcase: testGetInstance(org.iav.io.IOFacadeTest):        Caused an ERROR
null
java.lang.ExceptionInInitializerError
        at org.iav.io.IOFacade.<init>(IOFacade.java:32)
        at org.iav.io.IOFacade.getInstance(IOFacade.java:47)
        at org.iav.io.IOFacadeTest.testGetInstance(IOFacadeTest.java:50)
Caused by: java.lang.NullPointerException
        at org.iav.io.LicenseListFileBean.<clinit>(LicenseListFileBean.java:47)

Testcase: testGetPoolSize(org.iav.io.IOFacadeTest):        Caused an ERROR
Could not initialize class org.iav.io.LicenseListFileBean
java.lang.NoClassDefFoundError: Could not initialize class org.iav.io.LicenseListFileBean
        at org.iav.io.IOFacade.<init>(IOFacade.java:32)
        at org.iav.io.IOFacadeTest.testGetPoolSize(IOFacadeTest.java:63)
</code>```

The class IOFacade:

```<code>@ApplicationScoped
public class IOFacade extends Observable {

    private static IOFacade instance;
    private UserListFileBean userListFileBean;
    private LicenseListFileBean licenseListFileBean;
    private FileAccessorBean fileAccessorBean;

    /**
     * Constructor for this class. Initializing also dependent classes.
     * Encapsulates IO-Subsystem from beeing direct accessed.
     */
    public IOFacade() {
        licenseListFileBean = LicenseListFileBean.getInstance();
        userListFileBean = UserListFileBean.getInstance();
        fileAccessorBean = FileAccessorBean.getInstance();
        /** Registering this instance at fileAccessorBean to be notified if list
         * has changed.
         */
        addObserver(fileAccessorBean);
    }
</code>```

答:
Yes, a unit test involves only the class you are testing.  You have to mock out the container classes for your unit test.

If what you are after is an integration or systems test, which tests how your class interacts with it's environment, then you will need to run your application in an embedded environment.  Check out Arquillian, it provides a simple easy to use way to manage your embedded test environment.  Works with Glassfish 3.0.1, JBoss, and some other containers.

ContentLicense: CC BY-SA 2.5

Body:
I'am developing a web-app for my thesis. Now I'm on that part, where I want to run automated tests on that web-app. The problem is, that I'm not able to run this tests. Stacjtrace says that he could not find classes which are needen from the class that I want to test.

I've debugged and looked in NetBeans which classes are loaded. And it seems that only the class, which I test was loaded. Someone told me, that I must run an embedded GlassFish.

Thanks in advance

Testcase: testGetInstance(org.iav.io.IOFacadeTest):        Caused an ERROR
null
java.lang.ExceptionInInitializerError
        at org.iav.io.IOFacade.<init>(IOFacade.java:32)
        at org.iav.io.IOFacade.getInstance(IOFacade.java:47)
        at org.iav.io.IOFacadeTest.testGetInstance(IOFacadeTest.java:50)
Caused by: java.lang.NullPointerException
        at org.iav.io.LicenseListFileBean.<clinit>(LicenseListFileBean.java:47)

Testcase: testGetPoolSize(org.iav.io.IOFacadeTest):        Caused an ERROR
Could not initialize class org.iav.io.LicenseListFileBean
java.lang.NoClassDefFoundError: Could not initialize class org.iav.io.LicenseListFileBean
        at org.iav.io.IOFacade.<init>(IOFacade.java:32)
        at org.iav.io.IOFacadeTest.testGetPoolSize(IOFacadeTest.java:63)

The class IOFacade:

@ApplicationScoped
public class IOFacade extends Observable {

    private static IOFacade instance;
    private UserListFileBean userListFileBean;
    private LicenseListFileBean licenseListFileBean;
    private FileAccessorBean fileAccessorBean;

    /**
     * Constructor for this class. Initializing also dependent classes.
     * Encapsulates IO-Subsystem from beeing direct accessed.
     */
    public IOFacade() {
        licenseListFileBean = LicenseListFileBean.getInstance();
        userListFileBean = UserListFileBean.getInstance();
        fileAccessorBean = FileAccessorBean.getInstance();
        /** Registering this instance at fileAccessorBean to be notified if list
         * has changed.
         */
        addObserver(fileAccessorBean);
    }


问:
VBA: Disable button in Excel after first click
I am trying to disable a button placed on my sheet1 once the user click on it.
I went through few old Stackoverflow answers but dosent work as my expectation.

The code:

```<code>Sub Button2_Click()

    Call FindADate

    Dim myshape As Shape: Set myshape = ThisWorkbook.Worksheets("Sheet1").Shapes("Button 2")
    With myshape
        .ControlFormat.Enabled = False           '---> Disable the button
        .TextFrame.Characters.Font.ColorIndex = 15 '---> Grey out button label
    End With
End Sub
</code>```

It actually grayed out the button which give a feel that the button is disabled but User can click again and again and it run my code.

Kindly let me know a solution to get the button disabled after 1 click, the button will be active again only once I close and re open the excel. (I am using MS Office professional Plus 2013)

Thanks in advance.

答:
You need to record somehow not to process the click.  You could examine the button's text colour and if grey then ignore the click.  Alternatively, you could set a variable either a global, module or static local variable.  I chose the static local variable in the code below, called vDisable.

```<code>Option Explicit

Sub Button2_Click()
    Static vDisable As Variant
    If IsEmpty(vDisable) Then

        Call FindADate

        Dim myshape As Shape: Set myshape = ThisWorkbook.Worksheets("Sheet1").Shapes("Button 2")
        With myshape
            .ControlFormat.Enabled = False           '---> Disable the button
            .TextFrame.Characters.Font.ColorIndex = 15 '---> Grey out button label
        End With
        vDisable = True
    End If
End Sub
</code>```

Body:
I am trying to disable a button placed on my sheet1 once the user click on it.
I went through few old Stackoverflow answers but dosent work as my expectation.

The code:

Sub Button2_Click()

    Call FindADate

    Dim myshape As Shape: Set myshape = ThisWorkbook.Worksheets("Sheet1").Shapes("Button 2")
    With myshape
        .ControlFormat.Enabled = False           '---> Disable the button
        .TextFrame.Characters.Font.ColorIndex = 15 '---> Grey out button label
    End With
End Sub

It actually grayed out the button which give a feel that the button is disabled but User can click again and again and it run my code.

Kindly let me know a solution to get the button disabled after 1 click, the button will be active again only once I close and re open the excel. (I am using MS Office professional Plus 2013)

Thanks in advance.

Body:
You need to record somehow not to process the click.  You could examine the button's text colour and if grey then ignore the click.  Alternatively, you could set a variable either a global, module or static local variable.  I chose the static local variable in the code below, called vDisable.

Option Explicit

Sub Button2_Click()
    Static vDisable As Variant
    If IsEmpty(vDisable) Then

        Call FindADate

        Dim myshape As Shape: Set myshape = ThisWorkbook.Worksheets("Sheet1").Shapes("Button 2")
        With myshape
            .ControlFormat.Enabled = False           '---> Disable the button
            .TextFrame.Characters.Font.ColorIndex = 15 '---> Grey out button label
        End With
        vDisable = True
    End If
End Sub

ContentLicense: CC BY-SA 4.0


问:
Hive on Tez doesn't work in Spark 2
when working with HDP 2.5 with spark 1.6.2 we used Hive with Tez as its execution engine and it worked.

But when we moved to HDP 2.6 with spark 2.1.0, Hive didn't work with Tez as its execution engine, and the following exception was thrown when the DataFrame.saveAsTable API was called:

java.lang.NoClassDefFoundError: org/apache/tez/dag/api/SessionNotRunning
at org.apache.hadoop.hive.ql.session.SessionState.start(SessionState.java:529)
at org.apache.spark.sql.hive.client.HiveClientImpl.<init> HiveClientImpl.scala:188)

after looking at the answer to this question, we switched hive execution engine to MR (MapReduce) instead of Tez and it worked.

However, we'd like to work with Hive on Tez. what's required to solve the above exception in order for Hive on Tez to work?

答:
I had the same issue when the spark job was running in YARN CLUSTER mode and that was resolved when correct hive-site.xml was added to ( add to spark-default configuration) " spark.yarn.dist.files "

Basically there are two different hive-site.xml files,
one is for hive configuration :  /usr/hdp/current/hive-client/conf/hive-site.xml
The other one is lighter version for spark  ( had the details only for spark to work with hive) : /etc/spark//0/hive-site.xml ( please check the path once for your setup)

we need to use the second file for spark.yarn.dist.files.

Title: Hive on Tez doesn't work in Spark 2


问:
Merge MSER detected objetcs (OpenCV, Python)
I am working on this image as source:

Applying the next code...

```<code>import cv2
import numpy as np

mser = cv2.MSER_create()
img = cv2.imread('C:\\Users\\Link\\Desktop\\test2.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
vis = img.copy()
regions, _ = mser.detectRegions(gray)
hulls = [cv2.convexHull(p.reshape(-1, 1, 2)) for p in regions]
cv2.polylines(vis, hulls, 1, (0, 255, 0))

mask = np.zeros((img.shape[0], img.shape[1], 1), dtype=np.uint8)
for contour in hulls:
    cv2.drawContours(mask, [contour], -1, (255, 255, 255), -1)

    text_only = cv2.bitwise_and(img, img, mask=mask)

cv2.imshow('img', vis)
cv2.waitKey(0)
cv2.imshow('img', mask)
cv2.waitKey(0)
cv2.imshow('img', text_only)
cv2.waitKey(0)

cv2.imwrite('C:\\Users\\Link\\Desktop\\test_o\\1.png', text_only)
</code>```

...I am obtaining this as result (mask):

The question is this:

how to merge into a single object the number 5 in the number series (157661546) as long as it is divided in the mask image ?

Thanks

答:
Have a look here, it seems like the exact answer.

Here instead there is my version of the above code fine tuned for text extraction (with masking too).

Below there is the original code from the previous article, "ported" to python 3, opencv 3, added mser and bounding boxes. The main difference with my version is how the grouping distance is defined: mine is text-oriented while the one below is a free geometrical distance.

```<code>import sys
import cv2
import numpy as np

def find_if_close(cnt1,cnt2):
    row1,row2 = cnt1.shape[0],cnt2.shape[0]
    for i in range(row1):
        for j in range(row2):
            dist = np.linalg.norm(cnt1[i]-cnt2[j])
            if abs(dist) < 25:      # <-- threshold
                return True
            elif i==row1-1 and j==row2-1:
                return False

img = cv2.imread(sys.argv[1])
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

cv2.imshow('input', img)

ret,thresh = cv2.threshold(gray,127,255,0)

mser=False
if mser:
    mser = cv2.MSER_create()
    regions = mser.detectRegions(thresh)
    hulls = [cv2.convexHull(p.reshape(-1, 1, 2)) for p in regions[0]]
    contours = hulls
else:
    thresh = cv2.bitwise_not(thresh) # wants black bg
    im2,contours,hier = cv2.findContours(thresh,cv2.RETR_EXTERNAL,2)

cv2.drawContours(img, contours, -1, (0,0,255), 1)
cv2.imshow('base contours', img)

LENGTH = len(contours)
status = np.zeros((LENGTH,1))

print("Elements:", len(contours))
for i,cnt1 in enumerate(contours):
    x = i
    if i != LENGTH-1:
        for j,cnt2 in enumerate(contours[i+1:]):
            x = x+1
            dist = find_if_close(cnt1,cnt2)
            if dist == True:
                val = min(status[i],status[x])
                status[x] = status[i] = val
            else:
                if status[x]==status[i]:
                    status[x] = i+1

unified = []
maximum = int(status.max())+1
for i in range(maximum):
    pos = np.where(status==i)[0]
    if pos.size != 0:
        cont = np.vstack(contours[i] for i in pos)
        hull = cv2.convexHull(cont)
        unified.append(hull)

cv2.drawContours(img,contours,-1,(0,0,255),1)
cv2.drawContours(img,unified,-1,(0,255,0),2)
#cv2.drawContours(thresh,unified,-1,255,-1)

for c in unified:
    (x,y,w,h) = cv2.boundingRect(c)
    cv2.rectangle(img, (x,y), (x+w,y+h), (255, 0, 0), 2)

cv2.imshow('result', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code>```

Sample output (the yellow blob is below the binary threshold conversion so it's ignored). Red: original contours, green: unified ones, blue: bounding boxes.

Probably there is no need to use MSER as a simple findContours may work fine.

------------------------

Starting from here there is my old answer, before I found the above code. I'm leaving it anyway as it describe a couple of different approaches that may be easier/more appropriate for some scenarios.

A quick and dirty trick is to add a small gaussian blur and a high threshold before the MSER (or some dilute/erode if you prefer fancy things). In practice you just make the text bolder so that it fills small gaps. Obviously you can later discard this version and crop from the original one.

Otherwise, if your text is in lines, you may try to detect the average line center (make an histogram of Y coordinates and find the peaks for example). Then, for each line, look for fragments with a close average X. Quite fragile if text is noisy/complex.

If you do not need to split each letter, getting the bounding box for the whole word, may be easier: just split in groups based on a maximum horizontal distance between fragments (using the leftmost/rightmost points of the contour). Then use the leftmost and rightmost boxes within each group to find the whole bounding box. For multiline text first group by centroids Y coordinate.

Implementation notes:

Opencv allows you to create histograms but you probably can get away with something like this (worked for me on a similar task):

```<code>def histogram(vals, th=4, bins=400):
    hist = np.zeros(bins)
    for y_center in vals:
        bucket = int(round(y_center / 2.)) <-- change this "2."
        hist[bucket-1] += 1
    print("hist: ", hist)

    hist = np.where(hist > th, hist, 0)
    return hist
</code>```

Here my histogram is just an array with 400 buckets (my image was 800px high so each bucket catches two pixels, that is where the "2." comes from). Vals are the Y coordinates of the centroids of each fragment (you may want to ignore very small elements when you build this list). The th threshold is there just to remove some noise. You should get something like this:

```<code>0,0,0,5,22,0,0,0,0,43,7,0,0,0
</code>```

This list describes, moving top to bottom, how many fragments are at each location.

Now I ran another pass to merge the peaks into a single value (just scan the array and sum while it is non-zero and reset the count on first zero) getting something like this {y:count}:

```<code>{9:27, 20:50}
</code>```

Now I know I have two text rows at y=9 and y=20. Now, or before, you assign each fragment to on line (with again an 8px threshold in my case). Now you can process each line on its own, finding "words". BTW, I have your identical problem with broken letters that's why I came here looking for MSER :). Notice that if you find the whole bounding box for the word this problem happens only on the first/last letters: the other broken letters just falls inside the word box anyway.

Here is a reference for the erode/dilate thing, but gaussian blur/th worked for me.

UPDATE: I've noticed that there is something wrong in this line:

```<code>regions = mser.detectRegions(thresh)
</code>```

I pass in the already thresholded image(!?). This is not relevant for the aggregation part but keep in mind that the mser part is not being used as expected.

Body:
I am working on this image as source:

Applying the next code...

import cv2
import numpy as np

mser = cv2.MSER_create()
img = cv2.imread('C:\\Users\\Link\\Desktop\\test2.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
vis = img.copy()
regions, _ = mser.detectRegions(gray)
hulls = [cv2.convexHull(p.reshape(-1, 1, 2)) for p in regions]
cv2.polylines(vis, hulls, 1, (0, 255, 0))

mask = np.zeros((img.shape[0], img.shape[1], 1), dtype=np.uint8)
for contour in hulls:
    cv2.drawContours(mask, [contour], -1, (255, 255, 255), -1)

    text_only = cv2.bitwise_and(img, img, mask=mask)

cv2.imshow('img', vis)
cv2.waitKey(0)
cv2.imshow('img', mask)
cv2.waitKey(0)
cv2.imshow('img', text_only)
cv2.waitKey(0)

cv2.imwrite('C:\\Users\\Link\\Desktop\\test_o\\1.png', text_only)

...I am obtaining this as result (mask):

The question is this:

how to merge into a single object the number 5 in the number series (157661546) as long as it is divided in the mask image ?

Thanks

Body:
Have a look here, it seems like the exact answer.

Here instead there is my version of the above code fine tuned for text extraction (with masking too).

Below there is the original code from the previous article, "ported" to python 3, opencv 3, added mser and bounding boxes. The main difference with my version is how the grouping distance is defined: mine is text-oriented while the one below is a free geometrical distance.

import sys
import cv2
import numpy as np

def find_if_close(cnt1,cnt2):
    row1,row2 = cnt1.shape[0],cnt2.shape[0]
    for i in range(row1):
        for j in range(row2):
            dist = np.linalg.norm(cnt1[i]-cnt2[j])
            if abs(dist) < 25:      # <-- threshold
                return True
            elif i==row1-1 and j==row2-1:
                return False

img = cv2.imread(sys.argv[1])
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

cv2.imshow('input', img)

ret,thresh = cv2.threshold(gray,127,255,0)

mser=False
if mser:
    mser = cv2.MSER_create()
    regions = mser.detectRegions(thresh)
    hulls = [cv2.convexHull(p.reshape(-1, 1, 2)) for p in regions[0]]
    contours = hulls
else:
    thresh = cv2.bitwise_not(thresh) # wants black bg
    im2,contours,hier = cv2.findContours(thresh,cv2.RETR_EXTERNAL,2)

cv2.drawContours(img, contours, -1, (0,0,255), 1)
cv2.imshow('base contours', img)

LENGTH = len(contours)
status = np.zeros((LENGTH,1))

print("Elements:", len(contours))
for i,cnt1 in enumerate(contours):
    x = i
    if i != LENGTH-1:
        for j,cnt2 in enumerate(contours[i+1:]):
            x = x+1
            dist = find_if_close(cnt1,cnt2)
            if dist == True:
                val = min(status[i],status[x])
                status[x] = status[i] = val
            else:
                if status[x]==status[i]:
                    status[x] = i+1

unified = []
maximum = int(status.max())+1
for i in range(maximum):
    pos = np.where(status==i)[0]
    if pos.size != 0:
        cont = np.vstack(contours[i] for i in pos)
        hull = cv2.convexHull(cont)
        unified.append(hull)

cv2.drawContours(img,contours,-1,(0,0,255),1)
cv2.drawContours(img,unified,-1,(0,255,0),2)
#cv2.drawContours(thresh,unified,-1,255,-1)

for c in unified:
    (x,y,w,h) = cv2.boundingRect(c)
    cv2.rectangle(img, (x,y), (x+w,y+h), (255, 0, 0), 2)

cv2.imshow('result', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Sample output (the yellow blob is below the binary threshold conversion so it's ignored). Red: original contours, green: unified ones, blue: bounding boxes.

Probably there is no need to use MSER as a simple findContours may work fine.

------------------------

Starting from here there is my old answer, before I found the above code. I'm leaving it anyway as it describe a couple of different approaches that may be easier/more appropriate for some scenarios.

A quick and dirty trick is to add a small gaussian blur and a high threshold before the MSER (or some dilute/erode if you prefer fancy things). In practice you just make the text bolder so that it fills small gaps. Obviously you can later discard this version and crop from the original one.

Otherwise, if your text is in lines, you may try to detect the average line center (make an histogram of Y coordinates and find the peaks for example). Then, for each line, look for fragments with a close average X. Quite fragile if text is noisy/complex.

If you do not need to split each letter, getting the bounding box for the whole word, may be easier: just split in groups based on a maximum horizontal distance between fragments (using the leftmost/rightmost points of the contour). Then use the leftmost and rightmost boxes within each group to find the whole bounding box. For multiline text first group by centroids Y coordinate.

Implementation notes:

Opencv allows you to create histograms but you probably can get away with something like this (worked for me on a similar task):

def histogram(vals, th=4, bins=400):
    hist = np.zeros(bins)
    for y_center in vals:
        bucket = int(round(y_center / 2.)) <-- change this "2."
        hist[bucket-1] += 1
    print("hist: ", hist)

    hist = np.where(hist > th, hist, 0)
    return hist

Here my histogram is just an array with 400 buckets (my image was 800px high so each bucket catches two pixels, that is where the "2." comes from). Vals are the Y coordinates of the centroids of each fragment (you may want to ignore very small elements when you build this list). The th threshold is there just to remove some noise. You should get something like this:

0,0,0,5,22,0,0,0,0,43,7,0,0,0

This list describes, moving top to bottom, how many fragments are at each location.

Now I ran another pass to merge the peaks into a single value (just scan the array and sum while it is non-zero and reset the count on first zero) getting something like this {y:count}:

{9:27, 20:50}

Now I know I have two text rows at y=9 and y=20. Now, or before, you assign each fragment to on line (with again an 8px threshold in my case). Now you can process each line on its own, finding "words". BTW, I have your identical problem with broken letters that's why I came here looking for MSER :). Notice that if you find the whole bounding box for the word this problem happens only on the first/last letters: the other broken letters just falls inside the word box anyway.

Here is a reference for the erode/dilate thing, but gaussian blur/th worked for me.

UPDATE: I've noticed that there is something wrong in this line:

regions = mser.detectRegions(thresh)

I pass in the already thresholded image(!?). This is not relevant for the aggregation part but keep in mind that the mser part is not being used as expected.


问:
Easier way to to compare lots of values not using if else statements? Bad Design?
My problem is that I have lots of If-Else statements. A LOT. It gets hard to read it, and I sometimes get output I don't want.

I have to compare 5 animals names, weights, and ages. As well as outputting and checking if they are same animal and display which are younger, older, weigh less, and weigh more. It works, sort of, but it is bad code design

Code:

```<code> if(petOne.getName().equalsIgnoreCase(petTwo.getName()) && petThree.getName().equalsIgnoreCase(petFour.getName()) && petFour.getName().equalsIgnoreCase(petFive.getName()) )
    {
            System.out.println("All five dogs have the same name.");
    }
    else if(petOne.getWeight() == petTwo.getWeight() && petThree.getWeight() == petFour.getWeight() && petFour.getName() == petFive.getName())
    {
        System.out.println("All five dogs have the same weight");
    }
    else if(petOne.getAge() == petTwo.getAge() && petThree.getAge() == petFour.getAge() && petFour.getAge() == petFive.getAge())
    {
        System.out.println("All five dogs are the same age.");
    }
    //Below check if any pets are the same
    //1
     if(petOne.toString().equals(petTwo.toString()))
    {
        System.out.println(petOne.toString()+" and "+petTwo.toString()+" are the same");
    }
    else if(petOne.toString().equals(petThree.toString()))
    {
        System.out.println(petOne.toString()+" and "+petThree.toString()+" are the same");
    }
    else if(petOne.toString().equals(petFour.toString()))
    {
        System.out.println(petOne.toString()+" and "+petFour.toString()+ "are the same");
    }
    else if(petOne.toString().equals(petFive.toString()))
    {
        System.out.println(petOne.toString()+" and "+petFive.toString()+" are the same");
    }
    //2
        if(petTwo.toString().equals(petOne.toString()))
    {
        System.out.println(petTwo.toString()+" and "+petOne.toString()+" are the sae");
    }
    else if(petTwo.toString().equals(petThree.toString()))
    {
        System.out.println(petTwo.toString()+" and "+petThree.toString()+" are the same");
    }
    else if(petTwo.toString().equals(petFour.toString()))
    {
        System.out.println(petTwo.toString()+" and "+petFour.toString()+" are the same");
    }
    else if(petTwo.toString().equals(petFive.toString()))
    {
        System.out.println(petTwo.toString()+" and "+petFive.toString()+" are the same");
    }
    //3
        if(petThree.toString().equals(petOne.toString()))
    {
        System.out.println(petThree.toString()+" and "+petOne.toString()+" are the same");
    }
     else if(petThree.toString().equals(petTwo.toString()))
    {
        System.out.println(petThree.toString()+" and "+petTwo.toString()+" are the same");
    }
    else if(petThree.toString().equals(petFour.toString()))
    {
        System.out.println(petThree.toString()+" and "+petFour.toString()+" are the same");
    }
    else if(petThree.toString().equals(petFive.toString()))
    {
        System.out.println(petThree.toString()+" and "+petFive.toString()+" are the same");
    }
    //4
        if(petFour.toString().equals(petOne.toString()))
    {
        System.out.println(petFour.toString()+" and "+petOne.toString()+" are the same");
    }
    else if(petFour.toString().equals(petTwo.toString()))
    {
        System.out.println(petFour.toString()+" and "+petTwo.toString()+" are the same");
    }
    else if(petFour.toString().equals(petThree.toString()))
    {
        System.out.println(petFour.toString()+" and "+petThree.toString()+" are the same");
    }
    else if(petFour.toString().equals(petFive.toString()))
    {
        System.out.println(petFour.toString()+" and "+petFour.toString()+" are the same");
    }
    //5
        if(petFive.toString().equals(petOne.toString()))
    {
        System.out.println(petFive.toString()+" and "+petOne.toString()+" are the same");
    }
    else if(petFive.toString().equals(petTwo.toString()))
    {
        System.out.println(petFive.toString()+" and "+petTwo.toString()+" are the same");
    }
    else if(petFive.toString().equals(petThree.toString()))
    {
        System.out.println(petFive.toString()+" and "+petThree.toString()+" are the same");
    }
    else if(petFive.toString().equals(petFour.toString()))
    {
        System.out.println(petFive.toString()+" and "+petFour.toString()+" are the same");
    }
    //Below caculates which pet is the youngest

        if(petOne.getAge() < petTwo.getAge() && petOne.getAge() < petThree.getAge() && petOne.getAge() < petFour.getAge() && petOne.getAge() < petFive.getAge())
    {
        System.out.println(petOne.getName()+" is the youngest pet.");
    }
    else if(petTwo.getAge() < petOne.getAge() && petTwo.getAge() < petThree.getAge() && petTwo.getAge() < petFour.getAge() && petTwo.getAge() < petFive.getAge())
    {
        System.out.println(petTwo.getName()+" is the youngest pet.");
    }
    else if(petThree.getAge() < petOne.getAge() && petThree.getAge() < petTwo.getAge() && petThree.getAge() < petFour.getAge() && petThree.getAge() < petFive.getAge())
    {
        System.out.println(petThree.getName()+" is the youngest pet.");
    }
    else if(petFour.getAge() < petOne.getAge() && petFour.getAge() < petTwo.getAge() && petFour.getAge() < petThree.getAge() && petFour.getAge() < petFive.getAge())
    {
        System.out.println(petFour.getName()+" is the youngest pet.");
    }
    else if(petFive.getAge() < petOne.getAge() && petFive.getAge() < petTwo.getAge() && petFive.getAge() < petThree.getAge() && petFive.getAge() < petFour.getAge())
    {
        System.out.println(petFive.getName()+" is the youngest pet.");
    }
    //Below caculates which pet is the oldest
        if(petOne.getAge() > petTwo.getAge() && petOne.getAge() > petThree.getAge() && petOne.getAge() > petFour.getAge() && petOne.getAge() > petFive.getAge())
    {
        System.out.println(petOne.getName()+" is the oldest pet.");
    }
     else if(petTwo.getAge() > petOne.getAge() && petTwo.getAge() > petThree.getAge() && petTwo.getAge() > petFour.getAge() && petTwo.getAge() > petFive.getAge())
    {
        System.out.println(petTwo.getName()+" is the oldest pet.");
    }
     else if(petThree.getAge() > petOne.getAge() && petThree.getAge() > petTwo.getAge() && petThree.getAge() > petFour.getAge() && petThree.getAge() > petFive.getAge())
    {
        System.out.println(petThree.getName()+" is the oldest pet.");
    }
     else if(petFour.getAge() > petOne.getAge() && petFour.getAge() > petTwo.getAge() && petFour.getAge() > petThree.getAge() && petFour.getAge() > petFive.getAge())
    {
        System.out.println(petFour.getName()+" is the oldest pet.");
    }
     else if(petFive.getAge() > petOne.getAge() && petFive.getAge() > petTwo.getAge() && petFive.getAge() > petThree.getAge() && petFive.getAge() > petFour.getAge())
    {
        System.out.println(petFive.getName()+" is the oldest pet.");
    }
    //Below caculates which pet is the smallest
        if(petOne.getWeight() < petTwo.getWeight() && petOne.getWeight() < petThree.getWeight() && petOne.getWeight() < petFour.getWeight() && petOne.getWeight() < petFive.getWeight())
    {
        System.out.println(petOne.getName()+" is the smallest pet.");
    }
     else if(petTwo.getWeight() < petOne.getWeight() && petTwo.getWeight() < petThree.getWeight() && petTwo.getWeight() < petFour.getWeight() && petTwo.getWeight() < petFive.getWeight())
    {
        System.out.println(petTwo.getName()+" is the smallest pet.");
    }
     else if(petThree.getWeight() < petOne.getWeight() && petThree.getWeight() < petTwo.getWeight() && petThree.getWeight() < petFour.getWeight() && petThree.getAge() < petFive.getWeight())
    {
        System.out.println(petThree.getName()+" is the smallest pet.");
    }
     else if(petFour.getWeight() < petOne.getWeight() && petFour.getWeight() < petTwo.getWeight() && petFour.getWeight() < petThree.getWeight() && petFour.getWeight() < petFive.getWeight())
    {
        System.out.println(petFour.getName()+" is the smallest pet.");
    }
     else  if(petFive.getWeight() < petOne.getWeight() && petFive.getWeight() < petTwo.getWeight() && petFive.getWeight() < petThree.getWeight() && petFive.getWeight() < petFour.getWeight())
    {
        System.out.println(petFive.getName()+" is the smallest pet.");
    }
    //Below caculates to see which pet is the largest
        if(petOne.getWeight() > petTwo.getWeight() && petOne.getWeight() > petThree.getWeight() && petOne.getWeight() > petFour.getWeight() && petOne.getWeight() > petFive.getWeight())
    {
        System.out.println(petOne.getName()+" is the largest pet.");
    }
     else if(petTwo.getWeight() > petOne.getWeight() && petTwo.getWeight() > petThree.getWeight() && petTwo.getWeight() > petFour.getWeight() && petTwo.getWeight() > petFive.getWeight())
    {
        System.out.println(petTwo.getName()+" is the largest pet.");
    }
     else if(petThree.getWeight() > petOne.getWeight() && petThree.getWeight() > petTwo.getWeight() && petThree.getWeight() > petFour.getWeight() && petThree.getAge() > petFive.getWeight())
    {
        System.out.println(petThree.getName()+" is the largest pet.");
    }
    else if(petFour.getWeight() > petOne.getWeight() && petFour.getWeight() > petTwo.getWeight() && petFour.getWeight() > petThree.getWeight() && petFour.getWeight() > petFive.getWeight())
    {
        System.out.println(petFour.getName()+" is the largest pet.");
    }
    else if(petFive.getWeight() > petOne.getWeight() && petFive.getWeight() > petTwo.getWeight() && petFive.getWeight() > petThree.getWeight() && petFive.getWeight() > petFour.getWeight())
    {
        System.out.println(petFive.getName()+" is the largest pet.");
    }
</code>```

答:
Assuming the following data structure used to store pets:

```<code>List<Pet> pets = new ArrayList<>();
</code>```

and assuming sensible definitions for toString and equals, your queries can be handled through the use of streams and filters.

```<code>// Case 1:  Find all equivalent pets
List<Pet> equivalentPets = pets.stream()
                   .distinct()
                   .collect(Collectors.toList());

// Case 2:  Find the heaviest pet
Pet heaviestPet = pets.stream()
                      .max(Comparator.comparing(Pet::getWeight))
                      .get();
</code>```

The rest is left as an exercise for the reader.  The main objective is to iterate over the collection instead of repeating yourself.  You're more prone to errors the more you repeat yourself.

Body:
My problem is that I have lots of If-Else statements. A LOT. It gets hard to read it, and I sometimes get output I don't want.

I have to compare 5 animals names, weights, and ages. As well as outputting and checking if they are same animal and display which are younger, older, weigh less, and weigh more. It works, sort of, but it is bad code design

Code:

 if(petOne.getName().equalsIgnoreCase(petTwo.getName()) && petThree.getName().equalsIgnoreCase(petFour.getName()) && petFour.getName().equalsIgnoreCase(petFive.getName()) )
    {
            System.out.println("All five dogs have the same name.");
    }
    else if(petOne.getWeight() == petTwo.getWeight() && petThree.getWeight() == petFour.getWeight() && petFour.getName() == petFive.getName())
    {
        System.out.println("All five dogs have the same weight");
    }
    else if(petOne.getAge() == petTwo.getAge() && petThree.getAge() == petFour.getAge() && petFour.getAge() == petFive.getAge())
    {
        System.out.println("All five dogs are the same age.");
    }
    //Below check if any pets are the same
    //1
     if(petOne.toString().equals(petTwo.toString()))
    {
        System.out.println(petOne.toString()+" and "+petTwo.toString()+" are the same");
    }
    else if(petOne.toString().equals(petThree.toString()))
    {
        System.out.println(petOne.toString()+" and "+petThree.toString()+" are the same");
    }
    else if(petOne.toString().equals(petFour.toString()))
    {
        System.out.println(petOne.toString()+" and "+petFour.toString()+ "are the same");
    }
    else if(petOne.toString().equals(petFive.toString()))
    {
        System.out.println(petOne.toString()+" and "+petFive.toString()+" are the same");
    }
    //2
        if(petTwo.toString().equals(petOne.toString()))
    {
        System.out.println(petTwo.toString()+" and "+petOne.toString()+" are the sae");
    }
    else if(petTwo.toString().equals(petThree.toString()))
    {
        System.out.println(petTwo.toString()+" and "+petThree.toString()+" are the same");
    }
    else if(petTwo.toString().equals(petFour.toString()))
    {
        System.out.println(petTwo.toString()+" and "+petFour.toString()+" are the same");
    }
    else if(petTwo.toString().equals(petFive.toString()))
    {
        System.out.println(petTwo.toString()+" and "+petFive.toString()+" are the same");
    }
    //3
        if(petThree.toString().equals(petOne.toString()))
    {
        System.out.println(petThree.toString()+" and "+petOne.toString()+" are the same");
    }
     else if(petThree.toString().equals(petTwo.toString()))
    {
        System.out.println(petThree.toString()+" and "+petTwo.toString()+" are the same");
    }
    else if(petThree.toString().equals(petFour.toString()))
    {
        System.out.println(petThree.toString()+" and "+petFour.toString()+" are the same");
    }
    else if(petThree.toString().equals(petFive.toString()))
    {
        System.out.println(petThree.toString()+" and "+petFive.toString()+" are the same");
    }
    //4
        if(petFour.toString().equals(petOne.toString()))
    {
        System.out.println(petFour.toString()+" and "+petOne.toString()+" are the same");
    }
    else if(petFour.toString().equals(petTwo.toString()))
    {
        System.out.println(petFour.toString()+" and "+petTwo.toString()+" are the same");
    }
    else if(petFour.toString().equals(petThree.toString()))
    {
        System.out.println(petFour.toString()+" and "+petThree.toString()+" are the same");
    }
    else if(petFour.toString().equals(petFive.toString()))
    {
        System.out.println(petFour.toString()+" and "+petFour.toString()+" are the same");
    }
    //5
        if(petFive.toString().equals(petOne.toString()))
    {
        System.out.println(petFive.toString()+" and "+petOne.toString()+" are the same");
    }
    else if(petFive.toString().equals(petTwo.toString()))
    {
        System.out.println(petFive.toString()+" and "+petTwo.toString()+" are the same");
    }
    else if(petFive.toString().equals(petThree.toString()))
    {
        System.out.println(petFive.toString()+" and "+petThree.toString()+" are the same");
    }
    else if(petFive.toString().equals(petFour.toString()))
    {
        System.out.println(petFive.toString()+" and "+petFour.toString()+" are the same");
    }
    //Below caculates which pet is the youngest

        if(petOne.getAge() < petTwo.getAge() && petOne.getAge() < petThree.getAge() && petOne.getAge() < petFour.getAge() && petOne.getAge() < petFive.getAge())
    {
        System.out.println(petOne.getName()+" is the youngest pet.");
    }
    else if(petTwo.getAge() < petOne.getAge() && petTwo.getAge() < petThree.getAge() && petTwo.getAge() < petFour.getAge() && petTwo.getAge() < petFive.getAge())
    {
        System.out.println(petTwo.getName()+" is the youngest pet.");
    }
    else if(petThree.getAge() < petOne.getAge() && petThree.getAge() < petTwo.getAge() && petThree.getAge() < petFour.getAge() && petThree.getAge() < petFive.getAge())
    {
        System.out.println(petThree.getName()+" is the youngest pet.");
    }
    else if(petFour.getAge() < petOne.getAge() && petFour.getAge() < petTwo.getAge() && petFour.getAge() < petThree.getAge() && petFour.getAge() < petFive.getAge())
    {
        System.out.println(petFour.getName()+" is the youngest pet.");
    }
    else if(petFive.getAge() < petOne.getAge() && petFive.getAge() < petTwo.getAge() && petFive.getAge() < petThree.getAge() && petFive.getAge() < petFour.getAge())
    {
        System.out.println(petFive.getName()+" is the youngest pet.");
    }
    //Below caculates which pet is the oldest
        if(petOne.getAge() > petTwo.getAge() && petOne.getAge() > petThree.getAge() && petOne.getAge() > petFour.getAge() && petOne.getAge() > petFive.getAge())
    {
        System.out.println(petOne.getName()+" is the oldest pet.");
    }
     else if(petTwo.getAge() > petOne.getAge() && petTwo.getAge() > petThree.getAge() && petTwo.getAge() > petFour.getAge() && petTwo.getAge() > petFive.getAge())
    {
        System.out.println(petTwo.getName()+" is the oldest pet.");
    }
     else if(petThree.getAge() > petOne.getAge() && petThree.getAge() > petTwo.getAge() && petThree.getAge() > petFour.getAge() && petThree.getAge() > petFive.getAge())
    {
        System.out.println(petThree.getName()+" is the oldest pet.");
    }
     else if(petFour.getAge() > petOne.getAge() && petFour.getAge() > petTwo.getAge() && petFour.getAge() > petThree.getAge() && petFour.getAge() > petFive.getAge())
    {
        System.out.println(petFour.getName()+" is the oldest pet.");
    }
     else if(petFive.getAge() > petOne.getAge() && petFive.getAge() > petTwo.getAge() && petFive.getAge() > petThree.getAge() && petFive.getAge() > petFour.getAge())
    {
        System.out.println(petFive.getName()+" is the oldest pet.");
    }
    //Below caculates which pet is the smallest
        if(petOne.getWeight() < petTwo.getWeight() && petOne.getWeight() < petThree.getWeight() && petOne.getWeight() < petFour.getWeight() && petOne.getWeight() < petFive.getWeight())
    {
        System.out.println(petOne.getName()+" is the smallest pet.");
    }
     else if(petTwo.getWeight() < petOne.getWeight() && petTwo.getWeight() < petThree.getWeight() && petTwo.getWeight() < petFour.getWeight() && petTwo.getWeight() < petFive.getWeight())
    {
        System.out.println(petTwo.getName()+" is the smallest pet.");
    }
     else if(petThree.getWeight() < petOne.getWeight() && petThree.getWeight() < petTwo.getWeight() && petThree.getWeight() < petFour.getWeight() && petThree.getAge() < petFive.getWeight())
    {
        System.out.println(petThree.getName()+" is the smallest pet.");
    }
     else if(petFour.getWeight() < petOne.getWeight() && petFour.getWeight() < petTwo.getWeight() && petFour.getWeight() < petThree.getWeight() && petFour.getWeight() < petFive.getWeight())
    {
        System.out.println(petFour.getName()+" is the smallest pet.");
    }
     else  if(petFive.getWeight() < petOne.getWeight() && petFive.getWeight() < petTwo.getWeight() && petFive.getWeight() < petThree.getWeight() && petFive.getWeight() < petFour.getWeight())
    {
        System.out.println(petFive.getName()+" is the smallest pet.");
    }
    //Below caculates to see which pet is the largest
        if(petOne.getWeight() > petTwo.getWeight() && petOne.getWeight() > petThree.getWeight() && petOne.getWeight() > petFour.getWeight() && petOne.getWeight() > petFive.getWeight())
    {
        System.out.println(petOne.getName()+" is the largest pet.");
    }
     else if(petTwo.getWeight() > petOne.getWeight() && petTwo.getWeight() > petThree.getWeight() && petTwo.getWeight() > petFour.getWeight() && petTwo.getWeight() > petFive.getWeight())
    {
        System.out.println(petTwo.getName()+" is the largest pet.");
    }
     else if(petThree.getWeight() > petOne.getWeight() && petThree.getWeight() > petTwo.getWeight() && petThree.getWeight() > petFour.getWeight() && petThree.getAge() > petFive.getWeight())
    {
        System.out.println(petThree.getName()+" is the largest pet.");
    }
    else if(petFour.getWeight() > petOne.getWeight() && petFour.getWeight() > petTwo.getWeight() && petFour.getWeight() > petThree.getWeight() && petFour.getWeight() > petFive.getWeight())
    {
        System.out.println(petFour.getName()+" is the largest pet.");
    }
    else if(petFive.getWeight() > petOne.getWeight() && petFive.getWeight() > petTwo.getWeight() && petFive.getWeight() > petThree.getWeight() && petFive.getWeight() > petFour.getWeight())
    {
        System.out.println(petFive.getName()+" is the largest pet.");
    }

Body:
Assuming the following data structure used to store pets:

List<Pet> pets = new ArrayList<>();

and assuming sensible definitions for toString and equals, your queries can be handled through the use of streams and filters.

// Case 1:  Find all equivalent pets
List<Pet> equivalentPets = pets.stream()
                   .distinct()
                   .collect(Collectors.toList());

// Case 2:  Find the heaviest pet
Pet heaviestPet = pets.stream()
                      .max(Comparator.comparing(Pet::getWeight))
                      .get();

The rest is left as an exercise for the reader.  The main objective is to iterate over the collection instead of repeating yourself.  You're more prone to errors the more you repeat yourself.


问:
How to validate data inside a csv or excel file?
I currently have a mvc task to validate the data inside the csv or excel file before it uploads to sharepoint.
I need to validate the data such as phone number format and other types of data inside the uploaded csv or excel file.if the phone number format inside the file is not correct(ex: (985)-265-abcd) the file should not validate/upload and it has thorw validation error.

Is there any way to achieve that kind of functionality

答: You need to create an event receiver that fires when the item is being added to the library.  At that point, you need to get your file, run the validation logic, and if validation fails, cancel the event to prevent the file from uploading.</p>


问:
How to join 3 DataFrames in to one DataFrame?
I am trying to join three different DataFrames together in to one but I am having trouble in  joining all three. I have been able to join two.

How can I join three DataFrames correctly?

Pyspark: 1.6.0

Below is my working so far:

```<code># EXPECTED OUTPUT:

# -------file1.csv---------|---file2.csv--|---file3.csv------------|
# |col1|col2|col3|col4|col5|col1|col2|col3|col1|col2|col3|col4|col5|

# Loading in all the files
file1_rdd = sc.textFile("file1.csv").map(lambda line: line.split(","))
file2_rdd = sc.textFile("file2.csv").map(lambda line: line.split(","))
file3_rdd = sc.textFile("file3.csv").map(lambda line: line.split(","))

# Capturing the header
file1_header = file1_rdd.first()
file2_header = file2_rdd.first()
file3_header = file3_rdd.first()

# Removing the header from the table rows
df_file1 = file1_rdd.filter(lambda row : row != file1_header).toDF(file1_header)
df_file2 = file1_rdd.filter(lambda row : row != file2_header).toDF(file2_header)
df_file3 = file1_rdd.filter(lambda row : row != file3_header).toDF(file3_header)

# WORKS: df_file1.join(df_file2, df_file1.col1 == df_file2.col2)

# OUTPUT:
# -------file1.csv---------|---file2.csv--|
# |col1|col2|col3|col4|col5|col1|col2|col3|

# DOES NOT WORK: df_file1.join(df_file2, df_file1.col1 == df_file2.col2).join(df_file3, df_file2.col2 == df_file3.col2)

# OUTPUT:
# Caused by: java.lang.IllegalStateException: Input row doesn't have expected number of values required by the schema. 4 fields are required while 5 values are provided.
</code>```

Why is there an error that 4 fields are required when I can join the first two without that error even though the fields are not of the same length?

答:
The issue was that file3.csv contained data which was not properly sanitised. In order to fix it I simply enforced a maximum split like so:

file3_rdd = sc.textFile("file3.csv").map(lambda line: line.split(",", 3))

To anybody reading who may have faced a similar issue: check that you can first view the tables independently without errors. Doing df_file3.show() returned the same error and would have helped me see the issue much faster.

Body:
I am trying to join three different DataFrames together in to one but I am having trouble in  joining all three. I have been able to join two.

How can I join three DataFrames correctly?

Pyspark: 1.6.0

Below is my working so far:

# EXPECTED OUTPUT:

# -------file1.csv---------|---file2.csv--|---file3.csv------------|
# |col1|col2|col3|col4|col5|col1|col2|col3|col1|col2|col3|col4|col5|

# Loading in all the files
file1_rdd = sc.textFile("file1.csv").map(lambda line: line.split(","))
file2_rdd = sc.textFile("file2.csv").map(lambda line: line.split(","))
file3_rdd = sc.textFile("file3.csv").map(lambda line: line.split(","))

# Capturing the header
file1_header = file1_rdd.first()
file2_header = file2_rdd.first()
file3_header = file3_rdd.first()

# Removing the header from the table rows
df_file1 = file1_rdd.filter(lambda row : row != file1_header).toDF(file1_header)
df_file2 = file1_rdd.filter(lambda row : row != file2_header).toDF(file2_header)
df_file3 = file1_rdd.filter(lambda row : row != file3_header).toDF(file3_header)

# WORKS: df_file1.join(df_file2, df_file1.col1 == df_file2.col2)

# OUTPUT:
# -------file1.csv---------|---file2.csv--|
# |col1|col2|col3|col4|col5|col1|col2|col3|

# DOES NOT WORK: df_file1.join(df_file2, df_file1.col1 == df_file2.col2).join(df_file3, df_file2.col2 == df_file3.col2)

# OUTPUT:
# Caused by: java.lang.IllegalStateException: Input row doesn't have expected number of values required by the schema. 4 fields are required while 5 values are provided.

Why is there an error that 4 fields are required when I can join the first two without that error even though the fields are not of the same length?


问:
Outlook Add-in: questions about calling EWS
We have an Outlook office.js API add-in that customizes meetings using a task pane the user opens from an add-in command while editing a meeting. We need information from the meeting that is not exposed by the office.js API. We can use the Outlook REST API or the Microsoft Graph API for our Office 365 users, but for those users on Exchange 2013+ On-Premise I believe we need to use EWS (correct?).

This is new to me so if I may, I have some questions:

I read that "The server administrator must set OAuthAuthentication to true on The Client Access Server EWS directory to enable the makeEwsRequestAsync method to make EWS requests." This seems like a serious limitation. Is there anyway around this? We want the add-in to be completely user-installable.

All the examples I've seen make use of makeEwsRequestAsync. What is ewsUrl used for? Can someone point me to an example?

Can someone recommend some good links?

Thanks.

答:
Without OAuthAuthentication enabled, there would be no way authenticate the user. Keep in mind that your add-in is running on your web server. Outlook uses OAUTH to authenticate the user and allow your web app to make an EWS request on that user's behalf.

The most common use of the ewsUrl is to get attachments of an Outlook item from the server.


问:
How to get checked radio to also select other fields in group?
I have a very long form with groups of fields.  When a radio field is selected, I need it to also select several "hidden" fields in the same div and to pass those values on submission. If another radio is selected, than these hidden fields need to clear, and instead the other group's are selected.

Example 1 - Radio 1 is selected which selects all hidden fields in same div/fieldset:

Group A:

Radio 1 (checked)

Hidden Field 1a (checked)

Hidden Field 1b (checked)

Hidden field 1c (checked)

Group B:

Radio 2

Hidden Field 2a

Hidden Field 2b

Hidden field 2c

Example 2 - Radio 2 is selected which selects all hidden fields in same div/fieldset, all of Radio 1 fields are deselected.:

Group A:

Radio 1

Hidden Field 1a

Hidden Field 1b

Hidden field 1c

Group B:

Radio 2  (checked)

Hidden Field 2a (checked)

Hidden Field 2b (checked)

Hidden field 2c (checked)

Visual Example:

Example HTML:

```<code><div class="item">
    <h3>Item 1</h3>
    <div class="item-1-set options-set-a">
        <div class="checkbox-wrapper">
            <label for="item-1-a">Item 1, Options Set A Label</label>
            <input id="item-1-a" name="item-1" type="radio" value="Item 1 A">
        </div>
        <input name="item-1-a-entryid" type="checkbox" value="Item 1 A ID" class="hidden">
        <input name="item-1-a-title" type="checkbox" value="Item 1 A Title" class="hidden">
        <input name="item-1-a-image" type="checkbox" value="Item 1 Image URL" class="hidden">
    </div>
    <div class="item-1-set options-set-b">
        <div class="checkbox-wrapper">
            <label for="item-1-b">Item 1, Options Set B Label</label>
            <input id="item-1-b" name="item-1" type="radio" value="Item 1 B">
        </div>
        <input name="item-1-b-entryid" type="checkbox" value="Item 1 B ID" class="hidden">
        <input name="item-1-b-title" type="checkbox" value="Item 1 B Title" class="hidden">
        <input name="item-1-b-title" type="checkbox" value="Item 1 B Image URL" class="hidden">
    </div>
</div>

<div class="item">
    <h3>Item 2</h3>
    <div class="item-2-set options-set-a">
        <div class="checkbox-wrapper">
            <label for="item-2-a">Item 2, Options Set A Label</label>
            <input id="item-2-a" name="item-2" type="radio" value="Item 2 A">
        </div>
        <input name="item-2-a-entryid" type="checkbox" value="Item 2 A ID" class="hidden">
        <input name="item-2-a-title" type="checkbox" value="Item 2 A Title" class="hidden">
        <input name="item-2-a-image" type="checkbox" value="Item 2 Image URL" class="hidden">
    </div>
    <div class="item-2-set options-set-b">
        <div class="checkbox-wrapper">
            <label for="item-2-b">Item 2, Options Set B Label</label>
            <input id="item-2-b" name="item-2" type="radio" value="Item 2 B">
        </div>
        <input name="item-2-b-entryid" type="checkbox" value="Item 2 B ID" class="hidden">
        <input name="item-2-b-title" type="checkbox" value="Item 2 B Title" class="hidden">
        <input name="item-2-b-title" type="checkbox" value="Item 2 B Image URL" class="hidden">
    </div>
</div>
</code>```

I could also group these in a fieldset or other element, but I just need the selected radio to select the rest of the form fields in that same group. Also, the groups and fields are added dynamically, so I'm hoping for a "catch all" type of function...

How could I do this?

答:
Check the change event of the radio elements, and delegate the checks to the document so it will work with dynamic elements.

$(document).on('change', '.checkbox-wrapper input[type="radio"]', function() {
  $(this)
    .closest('.item')
    .find('.checkbox-wrapper')
    .each(function() {
      var checkboxes = $(this).siblings('input[type="checkbox"]'),
        radio = $('input[type="radio"]', this).get(0);

      checkboxes.prop('checked', radio.checked);
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="item">
  <h3>Item 1</h3>
  <div class="item-1-set options-set-a">
    <div class="checkbox-wrapper">
      <label for="item-1-a">Item 1, Options Set A Label</label>
      <input id="item-1-a" name="item-1" type="radio" value="Item 1 A">
    </div>
    <input name="item-1-a-entryid" type="checkbox" value="Item 1 A ID" class="hidden">
    <input name="item-1-a-title" type="checkbox" value="Item 1 A Title" class="hidden">
    <input name="item-1-a-image" type="checkbox" value="Item 1 Image URL" class="hidden">
  </div>
  <div class="item-1-set options-set-b">
    <div class="checkbox-wrapper">
      <label for="item-1-b">Item 1, Options Set B Label</label>
      <input id="item-1-b" name="item-1" type="radio" value="Item 1 B">
    </div>
    <input name="item-1-b-entryid" type="checkbox" value="Item 1 B ID" class="hidden">
    <input name="item-1-b-title" type="checkbox" value="Item 1 B Title" class="hidden">
    <input name="item-1-b-title" type="checkbox" value="Item 1 B Image URL" class="hidden">
  </div>
</div>

<div class="item">
  <h3>Item 2</h3>
  <div class="item-2-set options-set-a">
    <div class="checkbox-wrapper">
      <label for="item-2-a">Item 2, Options Set A Label</label>
      <input id="item-2-a" name="item-2" type="radio" value="Item 2 A">
    </div>
    <input name="item-2-a-entryid" type="checkbox" value="Item 2 A ID" class="hidden">
    <input name="item-2-a-title" type="checkbox" value="Item 2 A Title" class="hidden">
    <input name="item-2-a-image" type="checkbox" value="Item 2 Image URL" class="hidden">
  </div>
  <div class="item-2-set options-set-b">
    <div class="checkbox-wrapper">
      <label for="item-2-b">Item 2, Options Set B Label</label>
      <input id="item-2-b" name="item-2" type="radio" value="Item 2 B">
    </div>
    <input name="item-2-b-entryid" type="checkbox" value="Item 2 B ID" class="hidden">
    <input name="item-2-b-title" type="checkbox" value="Item 2 B Title" class="hidden">
    <input name="item-2-b-title" type="checkbox" value="Item 2 B Image URL" class="hidden">
  </div>
</div></code>```

Body:
I have a very long form with groups of fields.  When a radio field is selected, I need it to also select several "hidden" fields in the same div and to pass those values on submission. If another radio is selected, than these hidden fields need to clear, and instead the other group's are selected.

Example 1 - Radio 1 is selected which selects all hidden fields in same div/fieldset:

Group A:

Radio 1 (checked)

Hidden Field 1a (checked)

Hidden Field 1b (checked)

Hidden field 1c (checked)

Group B:

Radio 2

Hidden Field 2a

Hidden Field 2b

Hidden field 2c

Example 2 - Radio 2 is selected which selects all hidden fields in same div/fieldset, all of Radio 1 fields are deselected.:

Group A:

Radio 1

Hidden Field 1a

Hidden Field 1b

Hidden field 1c

Group B:

Radio 2  (checked)

Hidden Field 2a (checked)

Hidden Field 2b (checked)

Hidden field 2c (checked)

Visual Example:

Example HTML:

Item 1

            Item 1, Options Set A Label
            <input id="item-1-a" name="item-1" type="radio" value="Item 1 A">

        <input name="item-1-a-entryid" type="checkbox" value="Item 1 A ID" class="hidden">
        <input name="item-1-a-title" type="checkbox" value="Item 1 A Title" class="hidden">
        <input name="item-1-a-image" type="checkbox" value="Item 1 Image URL" class="hidden">

            Item 1, Options Set B Label
            <input id="item-1-b" name="item-1" type="radio" value="Item 1 B">

        <input name="item-1-b-entryid" type="checkbox" value="Item 1 B ID" class="hidden">
        <input name="item-1-b-title" type="checkbox" value="Item 1 B Title" class="hidden">
        <input name="item-1-b-title" type="checkbox" value="Item 1 B Image URL" class="hidden">

Item 2

            Item 2, Options Set A Label
            <input id="item-2-a" name="item-2" type="radio" value="Item 2 A">

        <input name="item-2-a-entryid" type="checkbox" value="Item 2 A ID" class="hidden">
        <input name="item-2-a-title" type="checkbox" value="Item 2 A Title" class="hidden">
        <input name="item-2-a-image" type="checkbox" value="Item 2 Image URL" class="hidden">

            Item 2, Options Set B Label
            <input id="item-2-b" name="item-2" type="radio" value="Item 2 B">

        <input name="item-2-b-entryid" type="checkbox" value="Item 2 B ID" class="hidden">
        <input name="item-2-b-title" type="checkbox" value="Item 2 B Title" class="hidden">
        <input name="item-2-b-title" type="checkbox" value="Item 2 B Image URL" class="hidden">

I could also group these in a fieldset or other element, but I just need the selected radio to select the rest of the form fields in that same group. Also, the groups and fields are added dynamically, so I'm hoping for a "catch all" type of function...

How could I do this?

Body:
Check the change event of the radio elements, and delegate the checks to the document so it will work with dynamic elements.

$(document).on('change', '.checkbox-wrapper input[type="radio"]', function() {
  $(this)
    .closest('.item')
    .find('.checkbox-wrapper')
    .each(function() {
      var checkboxes = $(this).siblings('input[type="checkbox"]'),
        radio = $('input[type="radio"]', this).get(0);

      checkboxes.prop('checked', radio.checked);
    });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="item">
  <h3>Item 1</h3>
  <div class="item-1-set options-set-a">
    <div class="checkbox-wrapper">
      <label for="item-1-a">Item 1, Options Set A Label</label>
      <input id="item-1-a" name="item-1" type="radio" value="Item 1 A">
    </div>
    <input name="item-1-a-entryid" type="checkbox" value="Item 1 A ID" class="hidden">
    <input name="item-1-a-title" type="checkbox" value="Item 1 A Title" class="hidden">
    <input name="item-1-a-image" type="checkbox" value="Item 1 Image URL" class="hidden">
  </div>
  <div class="item-1-set options-set-b">
    <div class="checkbox-wrapper">
      <label for="item-1-b">Item 1, Options Set B Label</label>
      <input id="item-1-b" name="item-1" type="radio" value="Item 1 B">
    </div>
    <input name="item-1-b-entryid" type="checkbox" value="Item 1 B ID" class="hidden">
    <input name="item-1-b-title" type="checkbox" value="Item 1 B Title" class="hidden">
    <input name="item-1-b-title" type="checkbox" value="Item 1 B Image URL" class="hidden">
  </div>
</div>

<div class="item">
  <h3>Item 2</h3>
  <div class="item-2-set options-set-a">
    <div class="checkbox-wrapper">
      <label for="item-2-a">Item 2, Options Set A Label</label>
      <input id="item-2-a" name="item-2" type="radio" value="Item 2 A">
    </div>
    <input name="item-2-a-entryid" type="checkbox" value="Item 2 A ID" class="hidden">
    <input name="item-2-a-title" type="checkbox" value="Item 2 A Title" class="hidden">
    <input name="item-2-a-image" type="checkbox" value="Item 2 Image URL" class="hidden">
  </div>
  <div class="item-2-set options-set-b">
    <div class="checkbox-wrapper">
      <label for="item-2-b">Item 2, Options Set B Label</label>
      <input id="item-2-b" name="item-2" type="radio" value="Item 2 B">
    </div>
    <input name="item-2-b-entryid" type="checkbox" value="Item 2 B ID" class="hidden">
    <input name="item-2-b-title" type="checkbox" value="Item 2 B Title" class="hidden">
    <input name="item-2-b-title" type="checkbox" value="Item 2 B Image URL" class="hidden">
  </div>
</div>


问:
How do I print data in a csv file that corresponds to another column?
I am attempting to print the every value under the attribute Title of a csv file that corresponds to the the value ('Image segmentation') under the attribute Field. I've tried numerous codes to figure this out but keep getting the wrong answer or no answer at all. My latest attempt is below. I'm not sure where to go from here so any help is appreciated.

```<code>import pandas as pd

data_file=pd.read_csv('7papers.csv')
data_file.columns=data_file.columns.str.strip()

field=data_file.Field

title=data_file.Title

for field in data_file:
    if field == ('Image segmentation'):
        print(title)
</code>```

答:
I'm not certain I'm following your question and as commented above seeing the csv file would help, but it sounds like you are wanting to do this:

```<code>print data_file.loc[ data_file.Field == 'Image segmentation', 'Title' ]
</code>```

This says "select the rows where Field has the value we want and then print the value of Title in those rows". Does that work?

Body:
I am attempting to print the every value under the attribute Title of a csv file that corresponds to the the value ('Image segmentation') under the attribute Field. I've tried numerous codes to figure this out but keep getting the wrong answer or no answer at all. My latest attempt is below. I'm not sure where to go from here so any help is appreciated.

import pandas as pd

data_file=pd.read_csv('7papers.csv')
data_file.columns=data_file.columns.str.strip()

field=data_file.Field

title=data_file.Title

for field in data_file:
    if field == ('Image segmentation'):
        print(title)

Body:
I'm not certain I'm following your question and as commented above seeing the csv file would help, but it sounds like you are wanting to do this:

print data_file.loc[ data_file.Field == 'Image segmentation', 'Title' ]

This says "select the rows where Field has the value we want and then print the value of Title in those rows". Does that work?


答:
after Dim line just write:

```<code>if myshape.TextFrame.Characters.Font.ColorIndex = 15 then exit sub
</code>```

that should be enough

Title: VBA: Disable button in Excel after first click

Body:
after Dim line just write:

if myshape.TextFrame.Characters.Font.ColorIndex = 15 then exit sub

that should be enough


问:
Bootstrap adding hidden Margins to Columns
For some reason bootstrap is adding a hidden margin to my column classes. When I inspect on an element which is currently 'col-lg-3' it does not show any margin CSS and even if I add margin:0 to the column it still adds a margin.

Please see image below.

I have been looking around for a while, and I am quite shocked I have not been able to find an answer to this. Does anyone have any insight in whats going wrong?

enter image description here

答: That happens because your element tries to occupy all the width that the father has, you can modify that by adding display: inline-flex or display: flex;</p>


问:
Too many values to unpack (expected 4)
I have this piece of basic code just trying to split a file into 4 lists. The .txt file is formatted as shown underneath the code, with spaces delimiting each number. The error appearing is 'ValueError: too many values to unpack (expected 4)'.

```<code>file = open("myfreefall.txt","r")
for line in file:
     if not line.startswith('#'):
         v,a,t,y= line.split(' ')

#v  a  t  y
-0.10 -9.81 0.01 5500.00
-0.20 -9.81 0.02 5500.00
-0.29 -9.81 0.03 5500.00
-0.39 -9.81 0.04 5499.99
-0.49 -9.81 0.05 5499.99
-0.59 -9.81 0.06 5499.99
-0.69 -9.81 0.07 5499.98
-0.78 -9.81 0.08 5499.97
...
</code>```

However I changed the code to be as shown below to test how many variables it was expecting, and the error changed to 'not enough values to unpack (expected 5, got 4)'. This doesn't make sense as now the code is unpacking the four variables I wanted! Any solutions/pointers would be much appreciated.

```<code>file = open("myfreefall.txt","r")
for line in file:
     if not line.startswith('#'):
         v,a,t,y,test= line.split(' ')
</code>```

答:
The second error is correct since you're unpacking 5 values as per this line:

```<code>v,a,t,y,test = line.split(' ')
#       ^^^^
</code>```

Since each line when split will return 4 elements, a 5th value is non-existent, hence the error. Note that using unpacking this way can be problematic in the long run, particularly with many elements. It may be worth examining doing an explicit check on the length of the split line.

For your original problem, try using line.split() since this automatically splits on whitespace - i.e. it's possible that the space may be a tab, or one of the blank unicode characters (see: http://jkorpela.fi/chars/spaces.html).

Or, one could use a regex on the line which could simplify parsing the text:

```<code>import re

regex = re.compile('([-+]?[0-9]*\.[0-9]+|[0-9]+)')  # regex for floating-point numbers
matches = regex.findall(line)  # `matches` will return a list
</code>```

Title: Too many values to unpack (expected 4)

Body:
I have this piece of basic code just trying to split a file into 4 lists. The .txt file is formatted as shown underneath the code, with spaces delimiting each number. The error appearing is 'ValueError: too many values to unpack (expected 4)'.

file = open("myfreefall.txt","r")
for line in file:
     if not line.startswith('#'):
         v,a,t,y= line.split(' ')

#v  a  t  y
-0.10 -9.81 0.01 5500.00
-0.20 -9.81 0.02 5500.00
-0.29 -9.81 0.03 5500.00
-0.39 -9.81 0.04 5499.99
-0.49 -9.81 0.05 5499.99
-0.59 -9.81 0.06 5499.99
-0.69 -9.81 0.07 5499.98
-0.78 -9.81 0.08 5499.97
...

However I changed the code to be as shown below to test how many variables it was expecting, and the error changed to 'not enough values to unpack (expected 5, got 4)'. This doesn't make sense as now the code is unpacking the four variables I wanted! Any solutions/pointers would be much appreciated.

file = open("myfreefall.txt","r")
for line in file:
     if not line.startswith('#'):
         v,a,t,y,test= line.split(' ')

Body:
The second error is correct since you're unpacking 5 values as per this line:

v,a,t,y,test = line.split(' ')
#       ^^^^

Since each line when split will return 4 elements, a 5th value is non-existent, hence the error. Note that using unpacking this way can be problematic in the long run, particularly with many elements. It may be worth examining doing an explicit check on the length of the split line.

For your original problem, try using line.split() since this automatically splits on whitespace - i.e. it's possible that the space may be a tab, or one of the blank unicode characters (see: http://jkorpela.fi/chars/spaces.html).

Or, one could use a regex on the line which could simplify parsing the text:

import re

regex = re.compile('([-+]?[0-9]*\.[0-9]+|[0-9]+)')  # regex for floating-point numbers
matches = regex.findall(line)  # `matches` will return a list