问:
Selenium Stale Element Reference Exception
Everytime got StaleElementReferenceException exception.

Here is a method, pls help.

```<code>private void selectAndClickRow(String elementName, boolean doubleClick) {
    try {
        String elementXpath = "//tr//td//div[contains(text(),'" + elementName + "')]";
        new WebDriverWait(Init.getWebDriver(), Init.getTimeOutInSeconds()).until(ExpectedConditions.visibilityOf(Init.getDriverExtensions().waitUntilElementAppearsInDom(By.xpath(elementXpath))));
        WebElement row = table.findElements(By.xpath(elementXpath)).get(0);
        row.click();
        if (doubleClick) {
            row.click();
        }
        Init.getDriverExtensions().waitUntilElementAppearsInDom(By.xpath("//tr//td[contains(@class,'selected')]//div[contains(text(),'" + elementName + "')]"));
    } catch (StaleElementReferenceException e) {
        freeze(1);
        selectAndClickRow(elementName, doubleClick);
    }
    waitToLoad();
}

public WebElement waitUntilElementAppearsInDom(By by) {
    Wait wait = new WebDriverWait(Init.getWebDriver(), (long)Init.getTimeOutInSeconds());
    wait.until(ExpectedConditions.presenceOfElementLocated(by));
    return Init.getWebDriver().findElement(by);
}
</code>```

I already added an element research and waiting for a second. It doesn't help.

答:
I guess, you are trying to double click on a element. You can use actions class as given below instead of clicking twice on a element.</p>

```<code>private void selectAndClickRow(String elementName, boolean doubleClick) {
    try {
        String elementXpath = "//tr//td//div[contains(text(),'" + elementName + "')]";
        new WebDriverWait(Init.getWebDriver(), Init.getTimeOutInSeconds()).until(ExpectedConditions.visibilityOf(Init.getDriverExtensions().waitUntilElementAppearsInDom(By.xpath(elementXpath))));
        WebElement row = table.findElements(By.xpath(elementXpath)).get(0);
        new Actions(driver).doubleClick(row).perform();
    } catch (StaleElementReferenceException e) {
        //freeze(1);
        //selectAndClickRow(elementName, doubleClick);
    }
    waitToLoad();
}
</code>```

Body:
Everytime got StaleElementReferenceException exception.

Here is a method, pls help.

private void selectAndClickRow(String elementName, boolean doubleClick) {
    try {
        String elementXpath = "//tr//td//div[contains(text(),'" + elementName + "')]";
        new WebDriverWait(Init.getWebDriver(), Init.getTimeOutInSeconds()).until(ExpectedConditions.visibilityOf(Init.getDriverExtensions().waitUntilElementAppearsInDom(By.xpath(elementXpath))));
        WebElement row = table.findElements(By.xpath(elementXpath)).get(0);
        row.click();
        if (doubleClick) {
            row.click();
        }
        Init.getDriverExtensions().waitUntilElementAppearsInDom(By.xpath("//tr//td[contains(@class,'selected')]//div[contains(text(),'" + elementName + "')]"));
    } catch (StaleElementReferenceException e) {
        freeze(1);
        selectAndClickRow(elementName, doubleClick);
    }
    waitToLoad();
}

public WebElement waitUntilElementAppearsInDom(By by) {
    Wait wait = new WebDriverWait(Init.getWebDriver(), (long)Init.getTimeOutInSeconds());
    wait.until(ExpectedConditions.presenceOfElementLocated(by));
    return Init.getWebDriver().findElement(by);
}

I already added an element research and waiting for a second. It doesn't help.

Body:
I guess, you are trying to double click on a element. You can use actions class as given below instead of clicking twice on a element.

private void selectAndClickRow(String elementName, boolean doubleClick) {
    try {
        String elementXpath = "//tr//td//div[contains(text(),'" + elementName + "')]";
        new WebDriverWait(Init.getWebDriver(), Init.getTimeOutInSeconds()).until(ExpectedConditions.visibilityOf(Init.getDriverExtensions().waitUntilElementAppearsInDom(By.xpath(elementXpath))));
        WebElement row = table.findElements(By.xpath(elementXpath)).get(0);
        new Actions(driver).doubleClick(row).perform();
    } catch (StaleElementReferenceException e) {
        //freeze(1);
        //selectAndClickRow(elementName, doubleClick);
    }
    waitToLoad();
}


来源: stackexchange

问:
Django: Parent categories doesn't shown in admin interface
Problem:
Dash signs display in 'Parent category' column before I open any menu item. I get 'Parent category' items when open menu item profile(see admin.py below)

Before and after opening of menu profile: picture1 and picture2 (pay attention on Parent Category column)

My models.py: (attention on parent_id)

```<code>class Menu(models.Model):

    cat_title = models.CharField(max_length=150, verbose_name='Category title')
    menu_title = models.CharField(max_length=150, verbose_name='Menu title')
    parent_id = models.IntegerField(blank=True, null=True, verbose_name='Parent category', choices=(('',''),))
    url = models.CharField(max_length=255, verbose_name='URL', blank=True)
    named_url = models.CharField(max_length=255, verbose_name='Named URL', blank=True)
    level = models.IntegerField(default=0, editable=False)
</code>```

My admin.py: ()

```<code>class MyMenu(admin.ModelAdmin):

    def get_choices(self):
        choices = (('',''),)
        categories = models.Menu.objects.all().values()
        for i in categories:
            choices += ((i['id'], i['cat_title']),)
        return choices

    def formfield_for_choice_field(self, db_field, request):
        if db_field.name == 'parent_id':
            db_field.choices = self.get_choices()

        return super().formfield_for_choice_field(db_field, request)
    list_display = ('cat_title', 'menu_title', 'parent_id', 'level')
    list_display_links = ('cat_title', 'menu_title')

    admin.site.register(models.Menu, MyMenu)
</code>```

Question: How could I rewrite my admin.py to show parent_id items without opening any menu item profile?

I've already tried Model.get_FOO_display() but it doesn't work in right way. Any help would be appreciated.

答:
Without changing your model, the simplest solution is probably to add a parent method in your admin and use it instead of "parent_id" in the list_display list:

```<code>class MyMenu(admin.ModelAdmin):
    # ....
    def parent(self, obj):
        if obj.parent_id:
            return Menu.objects.get(pk=obj.parent_id).cat_title
        return ""

    list_display = ('cat_title', 'menu_title', 'parent', 'level')

    # Unrelated but you may also want to rewrite `get_choices`
    # in a simpler and more performant way:
    def get_choices(self):
        choices = models.Menu.objects.values_list("id", "cat_title"))
        return (('',''),) + tuple(choices)
</code>```

Or to make parent a method or property on your Menu model:

```<code>class Menu(models.Model):
    # ...

    # you may want to use django's `cached_property` instead
    # but then you'll have to invalidate the cache when setting
    # (or unsetting) `.parent_id`
    @property
    def parent(self):
        if not self.parent_id:
            return None
        return Menu.objects.get(pk=self.parent_id)
</code>```

and add "parent" to your admin's list_display.

BUT since Menu.parent_id is actually a foreign key on Menu, the proper solution is to declare it as such in your model:

```<code>class Menu(models.Model):
    cat_title = models.CharField(max_length=150, verbose_name='Category title')
    menu_title = models.CharField(max_length=150, verbose_name='Menu title')
    parent = models.ForeignKey("self", blank=True, null=True, related_name="children")
    # etc
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Problem:
Dash signs display in 'Parent category' column before I open any menu item. I get 'Parent category' items when open menu item profile(see admin.py below)

Before and after opening of menu profile: picture1 and picture2 (pay attention on Parent Category column)

My models.py: (attention on parent_id)

class Menu(models.Model):

    cat_title = models.CharField(max_length=150, verbose_name='Category title')
    menu_title = models.CharField(max_length=150, verbose_name='Menu title')
    parent_id = models.IntegerField(blank=True, null=True, verbose_name='Parent category', choices=(('',''),))
    url = models.CharField(max_length=255, verbose_name='URL', blank=True)
    named_url = models.CharField(max_length=255, verbose_name='Named URL', blank=True)
    level = models.IntegerField(default=0, editable=False)

My admin.py: ()

class MyMenu(admin.ModelAdmin):

    def get_choices(self):
        choices = (('',''),)
        categories = models.Menu.objects.all().values()
        for i in categories:
            choices += ((i['id'], i['cat_title']),)
        return choices

    def formfield_for_choice_field(self, db_field, request):
        if db_field.name == 'parent_id':
            db_field.choices = self.get_choices()

        return super().formfield_for_choice_field(db_field, request)
    list_display = ('cat_title', 'menu_title', 'parent_id', 'level')
    list_display_links = ('cat_title', 'menu_title')

    admin.site.register(models.Menu, MyMenu)

Question: How could I rewrite my admin.py to show parent_id items without opening any menu item profile?

I've already tried Model.get_FOO_display() but it doesn't work in right way. Any help would be appreciated.

Body:
Without changing your model, the simplest solution is probably to add a parent method in your admin and use it instead of "parent_id" in the list_display list:

class MyMenu(admin.ModelAdmin):
    # ....
    def parent(self, obj):
        if obj.parent_id:
            return Menu.objects.get(pk=obj.parent_id).cat_title
        return ""

    list_display = ('cat_title', 'menu_title', 'parent', 'level')

    # Unrelated but you may also want to rewrite `get_choices`
    # in a simpler and more performant way:
    def get_choices(self):
        choices = models.Menu.objects.values_list("id", "cat_title"))
        return (('',''),) + tuple(choices)

Or to make parent a method or property on your Menu model:

class Menu(models.Model):
    # ...

    # you may want to use django's `cached_property` instead
    # but then you'll have to invalidate the cache when setting
    # (or unsetting) `.parent_id`
    @property
    def parent(self):
        if not self.parent_id:
            return None
        return Menu.objects.get(pk=self.parent_id)

and add "parent" to your admin's list_display.

BUT since Menu.parent_id is actually a foreign key on Menu, the proper solution is to declare it as such in your model:

class Menu(models.Model):
    cat_title = models.CharField(max_length=150, verbose_name='Category title')
    menu_title = models.CharField(max_length=150, verbose_name='Menu title')
    parent = models.ForeignKey("self", blank=True, null=True, related_name="children")
    # etc


问:
GIT keeps introducing uncomitted changes on checkout
I have created a new repository in BitBucket Server, and it is populated and in use. However, several of our users (myself included) are having a problem where unexpected changes are appearing on checkout. It does not appear on every checkout, only sporadically.

The changes appear to be a complete rewrite of the file(s) in question. git diff does not show, for example, that all line endings have changed. We are also using SVN Mirror to bring in changes from our older subversion repository on trunk -> master.
Everyone is using 2.14 version of git on Windows.

The following commands will fix it temporarily, but it inevitably comes back

```<code>git rm --cache -r
git reset --hard
</code>```

Example:

```<code>MINGW64 /c/code/git/repo (master)
$ git status
On branch master
Your branch is ahead of 'origin/master' by 1 commit.
  (use "git push" to publish your local commits)

nothing to commit, working tree clean

MINGW64 /c/code/git/repo (master)
$ git checkout -
Switched to branch 'dev/test_branch'

MINGW64 /c/code/git/repo (dev/test_branch)
$ git status
On branch dev/test_branch
nothing to commit, working tree clean

MINGW64 /c/code/git/repo (dev/test_branch)
$ git checkout -
Switched to branch 'master'
Your branch is ahead of 'origin/master' by 1 commit.
  (use "git push" to publish your local commits)

MINGW64 /c/code/git/repo (master)
$ git status
On branch master
Your branch is ahead of 'origin/master' by 1 commit.
  (use "git push" to publish your local commits)

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

        modified:   <snip-filename>.java
        modified:   <snip-filename2>.java
 ... etc ...
        modified:   <snip-lastfilename>.java

no changes added to commit (use "git add" and/or "git commit -a")
</code>```

Edit: Checking git diff -w to exclude whitespace changes shows no differences, so it definitely appears to be eol related.

答:
For this issue, it ended up being due to Subversion mirroring. When enabled, the line endings coming from Subversion were not corrected automatically, and so had their original eol. With the GIT repository set either through .gitattributes, or through a user's default settings, to automatically correct line endings, this would cause a mismatch where the original line ending was CRLF, and the updated version just LF.

This was identified by using

```<code>git diff --ignore-space-at-eol
</code>```

which showed no differences to the previous version.

The solution was to commit and push the line-ending adjusted files into GIT. This then mirrored to Subversion, and put them back into sync again.

For more information, I found a very useful guide here: https://help.github.com/articles/dealing-with-line-endings/

Body:
I have created a new repository in BitBucket Server, and it is populated and in use. However, several of our users (myself included) are having a problem where unexpected changes are appearing on checkout. It does not appear on every checkout, only sporadically.

The changes appear to be a complete rewrite of the file(s) in question. git diff does not show, for example, that all line endings have changed. We are also using SVN Mirror to bring in changes from our older subversion repository on trunk -> master.
Everyone is using 2.14 version of git on Windows.

The following commands will fix it temporarily, but it inevitably comes back

git rm --cache -r
git reset --hard

Example:

MINGW64 /c/code/git/repo (master)
$ git status
On branch master
Your branch is ahead of 'origin/master' by 1 commit.
  (use "git push" to publish your local commits)

nothing to commit, working tree clean

MINGW64 /c/code/git/repo (master)
$ git checkout -
Switched to branch 'dev/test_branch'

MINGW64 /c/code/git/repo (dev/test_branch)
$ git status
On branch dev/test_branch
nothing to commit, working tree clean

MINGW64 /c/code/git/repo (dev/test_branch)
$ git checkout -
Switched to branch 'master'
Your branch is ahead of 'origin/master' by 1 commit.
  (use "git push" to publish your local commits)

MINGW64 /c/code/git/repo (master)
$ git status
On branch master
Your branch is ahead of 'origin/master' by 1 commit.
  (use "git push" to publish your local commits)

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

        modified:   <snip-filename>.java
        modified:   <snip-filename2>.java
 ... etc ...
        modified:   <snip-lastfilename>.java

no changes added to commit (use "git add" and/or "git commit -a")

Edit: Checking git diff -w to exclude whitespace changes shows no differences, so it definitely appears to be eol related.

Body:
For this issue, it ended up being due to Subversion mirroring. When enabled, the line endings coming from Subversion were not corrected automatically, and so had their original eol. With the GIT repository set either through .gitattributes, or through a user's default settings, to automatically correct line endings, this would cause a mismatch where the original line ending was CRLF, and the updated version just LF.

This was identified by using

git diff --ignore-space-at-eol

which showed no differences to the previous version.

The solution was to commit and push the line-ending adjusted files into GIT. This then mirrored to Subversion, and put them back into sync again.

For more information, I found a very useful guide here: https://help.github.com/articles/dealing-with-line-endings/


问:
PyInstaller does NOT work when including Pysnmp
Just trying one of the official documentation site examples:

```<code>from pysnmp.hlapi import *

errorIndication, errorStatus, errorIndex, varBinds = next(
    getCmd(SnmpEngine(),
          CommunityData('public'),
          UdpTransportTarget(('192.168.1.14', 161)),
          ContextData(),
          ObjectType(ObjectIdentity('1.3.6.1.2.1.1.1.0')))
)

if errorIndication:
    print(errorIndication)
elif errorStatus:
    print('%s at %s' % (
           errorStatus.prettyPrint(),
           errorIndex and varBinds[int(errorIndex)-1][0] or '?'
       )
    )
else:
    for varBind in varBinds:
       print(' = '.join([ x.prettyPrint() for x in varBind ]))
</code>```

we can see it does work if its executed through the Python interpreter:

```<code> (Compiler)[user@machine testSNMP]$ python testSNMP.py
 SNMPv2-MIB::sysDescr."0" = 48-port 10/100/1000 Gigabit Switch
</code>```

However, if I try to "freeze" it with PyInstaller (PyInstaller --onefile) I get the following error once it is executed:

```<code>  (Compiler)[user@machine testSNMP]$ /lab/testSNMP/dist/testSNMP
Traceback (most recent call last):
  File "<string>", line 4, in <module>
  File "/lab/testSNMP/build/testSNMP/out00-PYZ.pyz/pysnmp.entity.engine", line 83, in __init__
  File "/lab/testSNMP/build/testSNMP/out00-PYZ.pyz/pysnmp.smi.builder", line 359, in importSymbols
pysnmp.smi.error.MibNotFoundError: No module __SNMP-FRAMEWORK-MIB loaded at <pysnmp.smi.builder.MibBuilder instance at 0x179f518>
</code>```

It seems that mandatory files in pysnmp/smi/mibs are not explicitly imported to be used. That's why I've split the build procedure in phases. Fist, create the spec file.

```<code>(Compiler)[user@machine testSNMP]$ pyi-makespec --onefile getInterfaces.py
wrote /lab/testSNMP/getInterfaces.spec
now run pyinstaller.py to build the executable
</code>```

Then, I've edited it to import required files following advices from this other stack post (Can't get pysnmp to work with pyinstaller):

```<code># -*- mode: python -*-
import PyInstaller.hooks.hookutils
hiddenimports = ['pysnmp.smi.exval','pysnmp.cache'] + PyInstaller.hooks.hookutils.collect_submodules('pysnmp.smi.mibs') + PyInstaller.hooks.hookutils.collect_submodules('pysnmp.smi.mibs.instances')
a = Analysis(['testSNMP.py'],
            pathex=['/lab/testSNMP'],
            hiddenimports=hiddenimports,
            hookspath=None,
            runtime_hooks=None)
x = Tree('/virtualenvs/Compiler/lib/python2.7/site-packages/pysnmp/smi/mibs',prefix='pysnmp/smi/mibs',excludes='.py')
pyz = PYZ(a.pure)
exe = EXE(pyz,
         a.scripts,
         a.binaries,
         a.zipfiles,
         a.datas,
         x,
         name='testSNMP',
         debug=False,
         strip=None,
         upx=True,
         console=True )
</code>```

But then, once it's built and executed, I'm getting this other error:

```<code>(Compiler)[user@machine testSNMP]$ /lab/testSNMP/dist/testSNMP
Traceback (most recent call last):
  File "<string>", line 15, in <module>
  File "/lab/testSNMP/build/testSNMP/out00-PYZ.pyz/pysnmp.hlapi.asyncore.sync.cmdgen", line 98, in getCmd
  File "/lab/testSNMP/build/testSNMP/out00-PYZ.pyz/pysnmp.hlapi.asyncore.cmdgen", line 135, in getCmd
  File "/lab/testSNMP/build/testSNMP/out00-PYZ.pyz/pysnmp.hlapi.varbinds", line 30, in makeVarBinds
  File "/lab/testSNMP/build/testSNMP/out00-PYZ.pyz/pysnmp.smi.rfc1902", line 689, in resolveWithMib
  File "/lab/testSNMP/build/testSNMP/out00-PYZ.pyz/pysnmp.smi.rfc1902", line 299, in resolveWithMib
  File "/lab/testSNMP/build/testSNMP/out00-PYZ.pyz/pysnmp.smi.compiler", line 44, in addMibCompiler
  File "/lab/testSNMP/build/testSNMP/out00-PYZ.pyz/pysmi.parser.smi", line 21, in __init__
  File "/lab/testSNMP/build/testSNMP/out00-PYZ.pyz/pysmi.lexer.smi", line 83, in __init__
  File "/lab/testSNMP/build/testSNMP/out00-PYZ.pyz/pysmi.lexer.smi", line 100, in reset
  File "/lab/testSNMP/build/testSNMP/out00-PYZ.pyz/ply.lex", line 915, in lex
  File "/lab/testSNMP/build/testSNMP/out00-PYZ.pyz/ply.lex", line 577, in validate_all
  File "/lab/testSNMP/build/testSNMP/out00-PYZ.pyz/ply.lex", line 819, in validate_rules
  File "/lab/testSNMP/build/testSNMP/out00-PYZ.pyz/ply.lex", line 830, in validate_module
  File "/lab/testSNMP/build/testSNMP/out00-PYZ.pyz/inspect", line 690, in getsourcelines
  File "/lab/testSNMP/build/testSNMP/out00-PYZ.pyz/inspect", line 538, in findsource
IOError: could not get source code
</code>```

What else can I do? Thanks in advance!

答:
To make Jeremy's answer portable, you can modify your specfile like this diff:

```<code>+ import os.path
+ import pysmi
+ import pysnmp.smi.mibs

+ def module_base(module):
+   return os.path.abspath(os.path.join(module.__file__, os.pardir))

  coll = COLLECT(
      exe,
      a.binaries,
      a.zipfiles,
      a.datas,
+     Tree(module_base(pysmi), prefix='pysmi'),
+     Tree(module_base(pysnmp.smi.mibs), prefix='pysnmp/smi/mibs'),
      ...
</code>```

EDIT:
turn out adding these to hiddenimports solved the problem for me:

```<code>'pysnmp.smi.mibs', 'pysnmp.smi.mibs.instances', 'pysnmp.smi.exval', 'pysnmp.cache'
</code>```

Body:
Just trying one of the official documentation site examples:

from pysnmp.hlapi import *

errorIndication, errorStatus, errorIndex, varBinds = next(
    getCmd(SnmpEngine(),
          CommunityData('public'),
          UdpTransportTarget(('192.168.1.14', 161)),
          ContextData(),
          ObjectType(ObjectIdentity('1.3.6.1.2.1.1.1.0')))
)

if errorIndication:
    print(errorIndication)
elif errorStatus:
    print('%s at %s' % (
           errorStatus.prettyPrint(),
           errorIndex and varBinds[int(errorIndex)-1][0] or '?'
       )
    )
else:
    for varBind in varBinds:
       print(' = '.join([ x.prettyPrint() for x in varBind ]))

we can see it does work if its executed through the Python interpreter:

 (Compiler)[user@machine testSNMP]$ python testSNMP.py
 SNMPv2-MIB::sysDescr."0" = 48-port 10/100/1000 Gigabit Switch

However, if I try to "freeze" it with PyInstaller (PyInstaller --onefile) I get the following error once it is executed:

  (Compiler)[user@machine testSNMP]$ /lab/testSNMP/dist/testSNMP
Traceback (most recent call last):
  File "<string>", line 4, in <module>
  File "/lab/testSNMP/build/testSNMP/out00-PYZ.pyz/pysnmp.entity.engine", line 83, in __init__
  File "/lab/testSNMP/build/testSNMP/out00-PYZ.pyz/pysnmp.smi.builder", line 359, in importSymbols
pysnmp.smi.error.MibNotFoundError: No module __SNMP-FRAMEWORK-MIB loaded at <pysnmp.smi.builder.MibBuilder instance at 0x179f518>

It seems that mandatory files in pysnmp/smi/mibs are not explicitly imported to be used. That's why I've split the build procedure in phases. Fist, create the spec file.

(Compiler)[user@machine testSNMP]$ pyi-makespec --onefile getInterfaces.py
wrote /lab/testSNMP/getInterfaces.spec
now run pyinstaller.py to build the executable

Then, I've edited it to import required files following advices from this other stack post (Can't get pysnmp to work with pyinstaller):

# -*- mode: python -*-
import PyInstaller.hooks.hookutils
hiddenimports = ['pysnmp.smi.exval','pysnmp.cache'] + PyInstaller.hooks.hookutils.collect_submodules('pysnmp.smi.mibs') + PyInstaller.hooks.hookutils.collect_submodules('pysnmp.smi.mibs.instances')
a = Analysis(['testSNMP.py'],
            pathex=['/lab/testSNMP'],
            hiddenimports=hiddenimports,
            hookspath=None,
            runtime_hooks=None)
x = Tree('/virtualenvs/Compiler/lib/python2.7/site-packages/pysnmp/smi/mibs',prefix='pysnmp/smi/mibs',excludes='.py')
pyz = PYZ(a.pure)
exe = EXE(pyz,
         a.scripts,
         a.binaries,
         a.zipfiles,
         a.datas,
         x,
         name='testSNMP',
         debug=False,
         strip=None,
         upx=True,
         console=True )

But then, once it's built and executed, I'm getting this other error:

(Compiler)[user@machine testSNMP]$ /lab/testSNMP/dist/testSNMP
Traceback (most recent call last):
  File "<string>", line 15, in <module>
  File "/lab/testSNMP/build/testSNMP/out00-PYZ.pyz/pysnmp.hlapi.asyncore.sync.cmdgen", line 98, in getCmd
  File "/lab/testSNMP/build/testSNMP/out00-PYZ.pyz/pysnmp.hlapi.asyncore.cmdgen", line 135, in getCmd
  File "/lab/testSNMP/build/testSNMP/out00-PYZ.pyz/pysnmp.hlapi.varbinds", line 30, in makeVarBinds
  File "/lab/testSNMP/build/testSNMP/out00-PYZ.pyz/pysnmp.smi.rfc1902", line 689, in resolveWithMib
  File "/lab/testSNMP/build/testSNMP/out00-PYZ.pyz/pysnmp.smi.rfc1902", line 299, in resolveWithMib
  File "/lab/testSNMP/build/testSNMP/out00-PYZ.pyz/pysnmp.smi.compiler", line 44, in addMibCompiler
  File "/lab/testSNMP/build/testSNMP/out00-PYZ.pyz/pysmi.parser.smi", line 21, in __init__
  File "/lab/testSNMP/build/testSNMP/out00-PYZ.pyz/pysmi.lexer.smi", line 83, in __init__
  File "/lab/testSNMP/build/testSNMP/out00-PYZ.pyz/pysmi.lexer.smi", line 100, in reset
  File "/lab/testSNMP/build/testSNMP/out00-PYZ.pyz/ply.lex", line 915, in lex
  File "/lab/testSNMP/build/testSNMP/out00-PYZ.pyz/ply.lex", line 577, in validate_all
  File "/lab/testSNMP/build/testSNMP/out00-PYZ.pyz/ply.lex", line 819, in validate_rules
  File "/lab/testSNMP/build/testSNMP/out00-PYZ.pyz/ply.lex", line 830, in validate_module
  File "/lab/testSNMP/build/testSNMP/out00-PYZ.pyz/inspect", line 690, in getsourcelines
  File "/lab/testSNMP/build/testSNMP/out00-PYZ.pyz/inspect", line 538, in findsource
IOError: could not get source code

What else can I do? Thanks in advance!

Body:
To make Jeremy's answer portable, you can modify your specfile like this diff:

+ import os.path
+ import pysmi
+ import pysnmp.smi.mibs

+ def module_base(module):
+   return os.path.abspath(os.path.join(module.__file__, os.pardir))

  coll = COLLECT(
      exe,
      a.binaries,
      a.zipfiles,
      a.datas,
+     Tree(module_base(pysmi), prefix='pysmi'),
+     Tree(module_base(pysnmp.smi.mibs), prefix='pysnmp/smi/mibs'),
      ...

EDIT:
turn out adding these to hiddenimports solved the problem for me:

'pysnmp.smi.mibs', 'pysnmp.smi.mibs.instances', 'pysnmp.smi.exval', 'pysnmp.cache'


问:
How can i improve this data like structure in python?
This is a data base like structure for students i created in python , i was wonder if you guys can take a look at this code and give me some suggestions on how to get better writing good code(meaning that looks good and that is easy to understand , i just started coding around 2-3 weeks ago) any thing you guys suggest i will take into consideration , im just trying to improve :)

```<code>#Our Gui TOOls
from tkinter import *
from tkinter import ttk

#Window
root = Tk()
#Not allowing the window to be resized
root.resizable(height = False , width = False)
#title of window when we get more things in the window
root.title(string = 'Ronald')
#The object /class
class Students:
    def __init__(self, root):
        self.root = root
        self.data = [{"Student Info": "Ronald Colyar", "Gpa": "4.0", "GradeLVL": "10", "NumOfClasses": "6" , 'Parents number': '773-567-2791'},
                 {"Student Info": "Beta", "Gpa": "1", "GradeLVL": "5", "NumOfClasses": "9", 'Parents number': '773-867-2791'},
                 {"Student Info": "Charlie", "Gpa": "2", "GradeLVL": "6", "NumOfClasses": "6", 'Parents number': '773-566-2791'}
            ]

#Container (very vaguly speaking )
        self.var = StringVar()
#track what is being put inside entry
        self.var.trace("w", self.callback)
#The entry across 2 columns in row 0
        self.entry = ttk.Entry(self.root, textvariable=self.var)
        self.entry.grid(row=0, column=0, columnspan=2)

#All of the labels that correspond the the information in self.data
        self.labels = [(ttk.Label(self.root, text="Student Info"),ttk.Label(self.root)),(ttk.Label(self.root, text="Gpa"),ttk.Label(self.root)),(ttk.Label(self.root, text="GradeLVL"),ttk.Label(self.root)),(ttk.Label(self.root, text="NumOfClasses"),ttk.Label(self.root)),(ttk.Label(self.root, text="Parents number"),ttk.Label(self.root))]
#spacing the labels out in the window by the amount of them

        for i in range(len(self.labels)):
            self.labels[i][0].grid(row = i+1, column=0)
            self.labels[i][1].grid(row = i+1, column=1)
#if the entry  matches the data , display the data.

    def callback(self, *args):
        for i in self.data:
            #if the data matches evaluates to true
            if i["Student Info"] == self.var.get():
                #execute if data matches
                for c in self.labels:
                    c[1].configure(text=i[c[0].cget("text")])
#Calling our object inside of root
Students(root)
#Constant loop of our window
root.mainloop()
</code>```

3rd week programming how do you guys think im learning , am i behind for 3 weeks , or am i kind of on track for becoming a good software developer , also im 16 so i have a few years to master these skills.

答:
This code is pretty well laid out (if I do say so myself) in terms of readability and Pythonic best practice.

There are a few subjective improvements which could be made.

The first of which is the use of enumerate() here:

```<code>for i in range(len(self.labels)):
    self.labels[i][0].grid(row = i+1, column=0)
    self.labels[i][1].grid(row = i+1, column=1)
</code>```

Instead of the above we can use something like the below:

```<code>for c, i in enumerate(self.labels, 1):
    i[0].grid(row = c+1, column=0)
    i[1].grid(row = c+1, column=1)
</code>```

enumerate() takes a list and returns a tuple with an index number associated with the value in the list, so in this case where we have declared that the first index value should be 1 we get a data structure returned like the below:

```<code>[(1, (ttk.Label(self.root, text="Student Info"),ttk.Label(self.root))),(2, (ttk.Label(self.root, text="Gpa"),ttk.Label(self.root))), . . . ]
</code>```

This means we can forego having to use a separate counting variable and the confusion that can result from that.

We can also implement a system where by we can have an "autocomplete" functionality with the searches, we can do this by modifying the below line:

```<code>if i["Student Info"] == self.var.get():
</code>```

To:

```<code>if i["Student Info"][:len(self.var.get())] == self.var.get() and ([x["Student Info"][:len(self.var.get())] for x in self.data].count(self.var.get()) == 1 or i["Student Info"] == self.var.get()):
</code>```

Which looks scary and like there's a lot going on but let's take a look at it closer.

We use string splicing to pull back the first part of the name string up to the length of the string in the Entry field and compare it against the value in the Entry to see whether we get a match, if we do then the program then has to evaluate whether there are any other records which would match this (for example if we had Ron and Ronald registered we don't want it to autocomplete until we're sure that the user wants Ron or Ronald). To do this we use an or clause on our if statement:

```<code>([x["Student Info"][:len(self.var.get())] for x in self.data].count(self.var.get()) == 1 or i["Student Info"] == self.var.get()):
</code>```

This means that if either of the two conditions return True we will proceed with the block of code underneath the statement. The first half of the or statement uses list comprehension to return a list of the name strings up to the length of the value in the Entry and then counts how many of those match the value in the Entry (for example, if we had Ron and Ronald and typed in "Ro" this would return 2) and then checks to see if that count is equal to 1. If it is then we return True because there can't possibly be any other matches in our data. The second half checks if the value in the Entry exactly matches anything in our data, if we didn't do this then Ron would never be returned where we had both Ron and Ronald because Ron will always return a count of 2 for the previous statement.

Lastly, if you wanted you could move over your data into another file, like a .json or .csv (this would be subjectively easier with a .json file than .csv) so that it didn't clutter up your program. You'd then need to import the data to be used within your program. This has been explained a lot on SO, so you should be able to find a question which helps you.

Body:
This is a data base like structure for students i created in python , i was wonder if you guys can take a look at this code and give me some suggestions on how to get better writing good code(meaning that looks good and that is easy to understand , i just started coding around 2-3 weeks ago) any thing you guys suggest i will take into consideration , im just trying to improve :)

#Our Gui TOOls
from tkinter import *
from tkinter import ttk

#Window
root = Tk()
#Not allowing the window to be resized
root.resizable(height = False , width = False)
#title of window when we get more things in the window
root.title(string = 'Ronald')
#The object /class
class Students:
    def __init__(self, root):
        self.root = root
        self.data = [{"Student Info": "Ronald Colyar", "Gpa": "4.0", "GradeLVL": "10", "NumOfClasses": "6" , 'Parents number': '773-567-2791'},
                 {"Student Info": "Beta", "Gpa": "1", "GradeLVL": "5", "NumOfClasses": "9", 'Parents number': '773-867-2791'},
                 {"Student Info": "Charlie", "Gpa": "2", "GradeLVL": "6", "NumOfClasses": "6", 'Parents number': '773-566-2791'}
            ]

#Container (very vaguly speaking )
        self.var = StringVar()
#track what is being put inside entry
        self.var.trace("w", self.callback)
#The entry across 2 columns in row 0
        self.entry = ttk.Entry(self.root, textvariable=self.var)
        self.entry.grid(row=0, column=0, columnspan=2)

#All of the labels that correspond the the information in self.data
        self.labels = [(ttk.Label(self.root, text="Student Info"),ttk.Label(self.root)),(ttk.Label(self.root, text="Gpa"),ttk.Label(self.root)),(ttk.Label(self.root, text="GradeLVL"),ttk.Label(self.root)),(ttk.Label(self.root, text="NumOfClasses"),ttk.Label(self.root)),(ttk.Label(self.root, text="Parents number"),ttk.Label(self.root))]
#spacing the labels out in the window by the amount of them

        for i in range(len(self.labels)):
            self.labels[i][0].grid(row = i+1, column=0)
            self.labels[i][1].grid(row = i+1, column=1)
#if the entry  matches the data , display the data.

    def callback(self, *args):
        for i in self.data:
            #if the data matches evaluates to true
            if i["Student Info"] == self.var.get():
                #execute if data matches
                for c in self.labels:
                    c[1].configure(text=i[c[0].cget("text")])
#Calling our object inside of root
Students(root)
#Constant loop of our window
root.mainloop()

3rd week programming how do you guys think im learning , am i behind for 3 weeks , or am i kind of on track for becoming a good software developer , also im 16 so i have a few years to master these skills.

Body:
This code is pretty well laid out (if I do say so myself) in terms of readability and Pythonic best practice.

There are a few subjective improvements which could be made.

The first of which is the use of enumerate() here:

for i in range(len(self.labels)):
    self.labels[i][0].grid(row = i+1, column=0)
    self.labels[i][1].grid(row = i+1, column=1)

Instead of the above we can use something like the below:

for c, i in enumerate(self.labels, 1):
    i[0].grid(row = c+1, column=0)
    i[1].grid(row = c+1, column=1)

enumerate() takes a list and returns a tuple with an index number associated with the value in the list, so in this case where we have declared that the first index value should be 1 we get a data structure returned like the below:

[(1, (ttk.Label(self.root, text="Student Info"),ttk.Label(self.root))),(2, (ttk.Label(self.root, text="Gpa"),ttk.Label(self.root))), . . . ]

This means we can forego having to use a separate counting variable and the confusion that can result from that.

We can also implement a system where by we can have an "autocomplete" functionality with the searches, we can do this by modifying the below line:

if i["Student Info"] == self.var.get():

To:

if i["Student Info"][:len(self.var.get())] == self.var.get() and ([x["Student Info"][:len(self.var.get())] for x in self.data].count(self.var.get()) == 1 or i["Student Info"] == self.var.get()):

Which looks scary and like there's a lot going on but let's take a look at it closer.

We use string splicing to pull back the first part of the name string up to the length of the string in the Entry field and compare it against the value in the Entry to see whether we get a match, if we do then the program then has to evaluate whether there are any other records which would match this (for example if we had Ron and Ronald registered we don't want it to autocomplete until we're sure that the user wants Ron or Ronald). To do this we use an or clause on our if statement:

([x["Student Info"][:len(self.var.get())] for x in self.data].count(self.var.get()) == 1 or i["Student Info"] == self.var.get()):

This means that if either of the two conditions return True we will proceed with the block of code underneath the statement. The first half of the or statement uses list comprehension to return a list of the name strings up to the length of the value in the Entry and then counts how many of those match the value in the Entry (for example, if we had Ron and Ronald and typed in "Ro" this would return 2) and then checks to see if that count is equal to 1. If it is then we return True because there can't possibly be any other matches in our data. The second half checks if the value in the Entry exactly matches anything in our data, if we didn't do this then Ron would never be returned where we had both Ron and Ronald because Ron will always return a count of 2 for the previous statement.

Lastly, if you wanted you could move over your data into another file, like a .json or .csv (this would be subjectively easier with a .json file than .csv) so that it didn't clutter up your program. You'd then need to import the data to be used within your program. This has been explained a lot on SO, so you should be able to find a question which helps you.


问:
How to use config server to serve resource bundles to micro services
We are using Spring Cloud config server in our project which has multiple micro services. With config server in place, we are now storing all properties for all the micro services in a central git repository. Each micro service is able to pull his own properties file based on application name and profiles.
We are trying to store our resource bundles in the central repository and have config-server serve these resource bundles to micro services. Our resource bundles include properties files like messages_en.properties, messages_es.properties, messages_cn.properties, etc. We are able to load an resource bundle to config server using profile but it is acting as properties file.
We are using resource bundle in velocity template for GUI. Like

```<code>    <div class="top-content">
                        <div class="intro-box">
                            <h1 class="font-light">#**springMessageText("welcome.text2","W**elcome to <br/><strong>Our Website!")</strong>
</h1>
</code>```

Could someone suggest how they have done it ? or any link to use config server for loading n using resource bundle?

答:
I had this same issue, I worked round it by deriving a new sub class of ReloadableResourceBundleMessageSource and overriding protected List<String> calculateFilenamesForLocale(String basename, Locale locale)

The overridden method adds the locale variants to the base URL so for the base url http://localhost:8888/app-default and Locale.ENGLISH we get

http://localhost:8888/app-default

http://localhost:8888/app_en-default

http://localhost:8888/app_en_GB-default

It assumes the last index of '-' in the basename is the start of the profile.

Body:
We are using Spring Cloud config server in our project which has multiple micro services. With config server in place, we are now storing all properties for all the micro services in a central git repository. Each micro service is able to pull his own properties file based on application name and profiles.
We are trying to store our resource bundles in the central repository and have config-server serve these resource bundles to micro services. Our resource bundles include properties files like messages_en.properties, messages_es.properties, messages_cn.properties, etc. We are able to load an resource bundle to config server using profile but it is acting as properties file.
We are using resource bundle in velocity template for GUI. Like

#**springMessageText("welcome.text2","W**elcome to
Our Website!")

Could someone suggest how they have done it ? or any link to use config server for loading n using resource bundle?


问:
Set minimal reasonable width for a QScrollArea
I am relatively new to Qt, which I access through PySide.

I have a longish list of content that I want to make vertically scrollable.
The horizontal size is not an issue. I tried using QScrollArea for that. Here is a minimal example:

```<code>import sys

import PySide.QtGui as gui

application = gui.QApplication(sys.argv)

window = gui.QScrollArea()
list = gui.QWidget()
layout = gui.QVBoxLayout(list)

for i in range(100):
    layout.addWidget(gui.QLabel(
        "A something longish, slightly convoluted example text."))

window.setWidget(list)

window.show()

sys.exit(application.exec_())
</code>```

What happens:

The scroll-area sets its horizontal size to the size needed for the labels

It notices that the vertical space is insufficient, so it adds a vertical scrollbar.

Due to the vertical scrollbar, the horizontal space is now insufficient as well, and so the horizontal scrollbar is also shown.

I can make the horizontal scrollbar go away with setHorizontalScrollBarPolicy, but the main problem persists: the vertical scrollbar obscures part of the labels.

How can I set the width of the scroll-area to the minimal value which does not need a horizontal scrollbar?

答:
Try to use sizeHint() in the widgets and use the result to set the minimum width of the QScrollArea.

Some extra info here: http://doc.qt.io/qt-5/layout.html

Body:
I am relatively new to Qt, which I access through PySide.

I have a longish list of content that I want to make vertically scrollable.
The horizontal size is not an issue. I tried using QScrollArea for that. Here is a minimal example:

import sys

import PySide.QtGui as gui

application = gui.QApplication(sys.argv)

window = gui.QScrollArea()
list = gui.QWidget()
layout = gui.QVBoxLayout(list)

for i in range(100):
    layout.addWidget(gui.QLabel(
        "A something longish, slightly convoluted example text."))

window.setWidget(list)

window.show()

sys.exit(application.exec_())

What happens:

The scroll-area sets its horizontal size to the size needed for the labels

It notices that the vertical space is insufficient, so it adds a vertical scrollbar.

Due to the vertical scrollbar, the horizontal space is now insufficient as well, and so the horizontal scrollbar is also shown.

I can make the horizontal scrollbar go away with setHorizontalScrollBarPolicy, but the main problem persists: the vertical scrollbar obscures part of the labels.

How can I set the width of the scroll-area to the minimal value which does not need a horizontal scrollbar?


问:
What does the "yield" keyword do in Python?
What is the use of the yield keyword in Python? What does it do?

For example, I'm trying to understand this code1:

```<code>def _get_child_candidates(self, distance, min_dist, max_dist):
    if self._leftchild and distance - max_dist < self._median:
        yield self._leftchild
    if self._rightchild and distance + max_dist >= self._median:
        yield self._rightchild
</code>```

And this is the caller:

```<code>result, candidates = [], [self]
while candidates:
    node = candidates.pop()
    distance = node._get_dist(obj)
    if distance <= max_dist and distance >= min_dist:
        result.extend(node._values)
    candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))
return result
</code>```

What happens when the method _get_child_candidates is called?
Is a list returned? A single element? Is it called again? When will subsequent calls stop?

1. This piece of code was written by Jochen Schulz (jrschulz), who made a great Python library for metric spaces. This is the link to the complete source: Module mspace.

答:
All great answers, however a bit difficult for newbies.

I assume you have learned the return statement.

As an analogy, return and yield are twins. return means 'return and stop' whereas 'yield` means 'return, but continue'

Try to get a num_list with return.

```<code>def num_list(n):
    for i in range(n):
        return i
</code>```

Run it:

```<code>In [5]: num_list(3)
Out[5]: 0
</code>```

See, you get only a single number rather than a list of them. return never allows you prevail happily, just implements once and quit.

There comes yield

Replace return with yield:

```<code>In [10]: def num_list(n):
    ...:     for i in range(n):
    ...:         yield i
    ...:

In [11]: num_list(3)
Out[11]: <generator object num_list at 0x10327c990>

In [12]: list(num_list(3))
Out[12]: [0, 1, 2]
</code>```

Now, you win to get all the numbers.

Comparing to return which runs once and stops, yield runs times you planed.
You can interpret return as return one of them, and yield as return all of them. This is called iterable.

One more step we can rewrite yield statement with return

```<code>In [15]: def num_list(n):
    ...:     result = []
    ...:     for i in range(n):
    ...:         result.append(i)
    ...:     return result

In [16]: num_list(3)
Out[16]: [0, 1, 2]
</code>```

It's the core about yield.

The difference between a list return outputs and the object yield output is:

You will always get [0, 1, 2] from a list object but only could retrieve them from 'the object yield output' once. So, it has a new name generator object as displayed in Out[11]: <generator object num_list at 0x10327c990>.

In conclusion, as a metaphor to grok it:

return and yield are twins

list and generator are twins

OwnerDisplayName: Alex. S.

ContentLicense: CC BY-SA 4.0

Body:
What is the use of the yield keyword in Python? What does it do?

For example, I'm trying to understand this code1:

def _get_child_candidates(self, distance, min_dist, max_dist):
    if self._leftchild and distance - max_dist < self._median:
        yield self._leftchild
    if self._rightchild and distance + max_dist >= self._median:
        yield self._rightchild

And this is the caller:

result, candidates = [], [self]
while candidates:
    node = candidates.pop()
    distance = node._get_dist(obj)
    if distance <= max_dist and distance >= min_dist:
        result.extend(node._values)
    candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))
return result

What happens when the method _get_child_candidates is called?
Is a list returned? A single element? Is it called again? When will subsequent calls stop?

1. This piece of code was written by Jochen Schulz (jrschulz), who made a great Python library for metric spaces. This is the link to the complete source: Module mspace.

LastEditorDisplayName: Scott Dorman

Body:
All great answers, however a bit difficult for newbies.

I assume you have learned the return statement.

As an analogy, return and yield are twins. return means 'return and stop' whereas 'yield` means 'return, but continue'

Try to get a num_list with return.

def num_list(n):
    for i in range(n):
        return i

Run it:

In [5]: num_list(3)
Out[5]: 0

See, you get only a single number rather than a list of them. return never allows you prevail happily, just implements once and quit.

There comes yield

Replace return with yield:

In [10]: def num_list(n):
    ...:     for i in range(n):
    ...:         yield i
    ...:

In [11]: num_list(3)
Out[11]: <generator object num_list at 0x10327c990>

In [12]: list(num_list(3))
Out[12]: [0, 1, 2]

Now, you win to get all the numbers.

Comparing to return which runs once and stops, yield runs times you planed.
You can interpret return as return one of them, and yield as return all of them. This is called iterable.

One more step we can rewrite yield statement with return

In [15]: def num_list(n):
    ...:     result = []
    ...:     for i in range(n):
    ...:         result.append(i)
    ...:     return result

In [16]: num_list(3)
Out[16]: [0, 1, 2]

It's the core about yield.

The difference between a list return outputs and the object yield output is:

You will always get [0, 1, 2] from a list object but only could retrieve them from 'the object yield output' once. So, it has a new name generator object as displayed in Out[11]: <generator object num_list at 0x10327c990>.

In conclusion, as a metaphor to grok it:

return and yield are twins

list and generator are twins


问:
How to connect to a docker container from outside the host (same network) [Windows]
I've created my first docker container, it's running a server using Go but I can't access it from outside the host computer. I've just started with docker so I'm a little lost here.

So I have a very simple Go code that starts a server, I have built the docker image which installs Go and builds the code in a Linux base image. I'm running the server on port 8080 so I expose that port to the host running the container like this:

```<code>docker run -p 8080:8080 dockertest
</code>```

That works and I get to access the server through docker's machine IP (the one that appears on the Docker Quickstart Terminal when initiated), the problem is I can't access the website I'm hosting from outside the host, so if I try to open the same IP address on my phone it just gives me an error: This webpage is not available (ERR_CONNECTION_TIMED_OUT).

I've also tried specifying the IP like this:

```<code>docker run -p 192.168.0.157:8080:8080 dockertest
</code>```

But when I do that I can access the website through neither the docker machine's IP nor the specified IP on the command line above.
I'm also not sure which IP I'm supposed to write in that command I used my computer's IP, I've also tried 127.0.0.1 (localhost) but that gave me the same result: couldn't access the website through any IP whatsoever.

I've googled this problem and found many StackOverflow questions but neither helped me solve my issue, most of them were oriented to Linux or Mac so the solution didn't apply to my situation.

Also, I can run the Go code on my computer and access the website from another device in the same network through my computer's IP. I don't understand why I can't access it when I'm running it in the docker machine, it occurred to me that it may have something to do with IP forwarding or something but I'm a complete noob in networking, I'm mostly a web developer and have almost no experience in native.

答:
After trying several things, this worked for me:

use the --publish=0.0.0.0:8080:8080 docker flag

set the virtualbox network mode to NAT, and don't use any port forwarding

With addresses other than 0.0.0.0 I had no success.

Body:
I've created my first docker container, it's running a server using Go but I can't access it from outside the host computer. I've just started with docker so I'm a little lost here.

So I have a very simple Go code that starts a server, I have built the docker image which installs Go and builds the code in a Linux base image. I'm running the server on port 8080 so I expose that port to the host running the container like this:

docker run -p 8080:8080 dockertest

That works and I get to access the server through docker's machine IP (the one that appears on the Docker Quickstart Terminal when initiated), the problem is I can't access the website I'm hosting from outside the host, so if I try to open the same IP address on my phone it just gives me an error: This webpage is not available (ERR_CONNECTION_TIMED_OUT).

I've also tried specifying the IP like this:

docker run -p 192.168.0.157:8080:8080 dockertest

But when I do that I can access the website through neither the docker machine's IP nor the specified IP on the command line above.
I'm also not sure which IP I'm supposed to write in that command I used my computer's IP, I've also tried 127.0.0.1 (localhost) but that gave me the same result: couldn't access the website through any IP whatsoever.

I've googled this problem and found many StackOverflow questions but neither helped me solve my issue, most of them were oriented to Linux or Mac so the solution didn't apply to my situation.

Also, I can run the Go code on my computer and access the website from another device in the same network through my computer's IP. I don't understand why I can't access it when I'm running it in the docker machine, it occurred to me that it may have something to do with IP forwarding or something but I'm a complete noob in networking, I'm mostly a web developer and have almost no experience in native.


问:
Formatting html email for Outlook
I have an html newsletter which works in most email clients, but the formatting is messed up in Outlook.

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style type="text/css">
  body {
    background-color: #98AFC7;
  }
</style>
<title></title>
</head>
<body>
<table border="1px solid" cellspacing="0" cellpadding="10px" width="600" style="margin-left: auto; margin-right: auto; height:auto; background-color: #ffffff; margin-top: 60px;">
    <tr>
        <td align="top" style="padding: 10px; font-family: arial; font-size: 12px;" ><center>Email not displaying correctly?<a href="#"><strong> View it in your browser</strong></a></center></td>
    </tr>
    <tr>
        <td style="border: 1px solid; height: 80px; text-align: center; padding: 10px;"><img src="http://demo.frostmiller.com/email/img/banner.jpg" alt="Banner will go here" align="middle" style="border: 1px solid;"></td>
    </tr>
    <tr>
        <td>
            <table style="border: 0; cellspacing: 0; cellpadding: 10px; height: auto;">
                <tr>
                    <td valign="baseline" style="padding: 10px; width:400px; border: 1px solid; halign: top;">
                    <h3>Top Stories</h3>
                        <ul>
                            <li>Topic 1</li>
                            <li>Topic 2</li>
                            <li>Topic 3</li>
                        </ul>
                            <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
                    </td>
                    <td valign="baseline" style="padding: 10px; border: 1px solid;">
                        <h3>Latest News</h3>
                        <p>
                        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting,
                        </p>
                    </td>
                </tr>
            </table>
        </td>
    </tr>
    <tr>
        <td cellpadding="10px" style="border: 1px solid; cellspacing: 0;  width: 100%; height: auto; text-align: center;">
            <strong>Copyright &copy 2011 Frost Miller Group </strong>
        </td>
    </tr>
    <tr>
        <td style="border: 1px solid; cellspacing: 0; cellpadding: 10px; width: 100%; height: auto">
            <center>
            <a href="#">Contact Us</a>

            <a href="#">Terms of Use</a>

            <a href="#">Trademarks</a>

            <a href="#">Privacy Statement</a>

            <a href="#">Site Feedback</a>
            </center>
        </td>
    </tr>
    </table>
</body>
</html>
</code>```

What changes do I need to make in order to get it to display correctly in Outlook?

答:
I used VML(Vector Markup Language) based formatting in my email template.
In VML Based you have write your code within comment

I took help from this site.

https://litmus.com/blog/a-guide-to-bulletproof-buttons-in-email-design#supporttable

Title: Formatting html email for Outlook

Body:
I have an html newsletter which works in most email clients, but the formatting is messed up in Outlook.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title></title>

        Email not displaying correctly? View it in your browser

Top Stories

Topic 1

Topic 2

Topic 3

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Latest News

                        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting,

            Copyright &copy 2011 Frost Miller Group

            Contact Us

            Terms of Use

            Trademarks

            Privacy Statement

            Site Feedback

What changes do I need to make in order to get it to display correctly in Outlook?


问:
Could not find com.opentok.android:opentok-android-sdk
Do you have an issue with your tokbox maven's ?
Because since this morning i can't compile my project, i have this error :

Could not find any matches for com.opentok.android:opentok-android-sdk:2.8.+

also after upgrade sdk version to 2.12.1 it's same

The maven links are in 404 :
https://bintray.com/tokbox/maven/opentok-android-sdk
http://tokbox.bintray.com/maven

Thanks

答:
To add an actual dependency, you're most likely using the wrong URL. Try this one instead:

```<code>compile 'com.opentok.android:opentok-android-sdk:2.12.0'
</code>```

In addition, you need to define the URL for the maven repo in the project-level build.gradle file:

```<code>allprojects {
   repositories {
       jcenter()
       maven {
           ...
           url 'https://tokbox.bintray.com/maven'
       }
   }
}
</code>```

Body:
To add an actual dependency, you're most likely using the wrong URL. Try this one instead:

compile 'com.opentok.android:opentok-android-sdk:2.12.0'

In addition, you need to define the URL for the maven repo in the project-level build.gradle file:

allprojects {
   repositories {
       jcenter()
       maven {
           ...
           url 'https://tokbox.bintray.com/maven'
       }
   }
}


问:
how to access derived class methods from another derived class
I'm using wxpython to generate a GUI. The structure of the program I'm doing is shown below. I have a class for each section of the GUI (class1 and class2). I'm using the Panel class to create these sections. class1 and class2 are derived from another class (the Group class). I want to access the methods of a derived class from the other derived class on the fly. So when I'm in classA.method1() I want to call classB.method3(). what is the best way to do that? </p>

```<code>class Panel(wx.Panel):

    def __init__(self, parent):
        class1 = ClassA()
        class2 = ClassB()

class Group(wx.Panel):

    def __init__(self, parent, name):
        .
        .
        .

class ClassA(Group):

    def method1(self):
        ....

    def method2(self):
        ....

class ClassB(Group):

    def method3(self):
        ....

    def method4(self):
        ....
</code>```

答:
I's assuming you want to call the class method, not the method of an instance of that class.

From ClassA.method1(), ClassB be should be a global, so all you have to do is:

```<code>class ClassA(Group):

    def method1(self):
        classB.method3(someclass)
</code>```

Now all you have to do is figure out what you want to put in for 'someclass'.  If method3 never uses 'self' then just pass it None.  If ClassA is compatible, then you can pass it 'self'.  Otherwise, you need to pass it an instance of ClassB.

ContentLicense: CC BY-SA 2.5

Body:
I'm using wxpython to generate a GUI. The structure of the program I'm doing is shown below. I have a class for each section of the GUI (class1 and class2). I'm using the Panel class to create these sections. class1 and class2 are derived from another class (the Group class). I want to access the methods of a derived class from the other derived class on the fly. So when I'm in classA.method1() I want to call classB.method3(). what is the best way to do that?

class Panel(wx.Panel):

    def __init__(self, parent):
        class1 = ClassA()
        class2 = ClassB()

class Group(wx.Panel):

    def __init__(self, parent, name):
        .
        .
        .

class ClassA(Group):

    def method1(self):
        ....

    def method2(self):
        ....

class ClassB(Group):

    def method3(self):
        ....

    def method4(self):
        ....

Body:
I's assuming you want to call the class method, not the method of an instance of that class.

From ClassA.method1(), ClassB be should be a global, so all you have to do is:

class ClassA(Group):

    def method1(self):
        classB.method3(someclass)

Now all you have to do is figure out what you want to put in for 'someclass'.  If method3 never uses 'self' then just pass it None.  If ClassA is compatible, then you can pass it 'self'.  Otherwise, you need to pass it an instance of ClassB.


问:
python manage.py collectstatic --noinput error when deploying Django project to Heroku
I've recently encountered a static files error when deploying my Django project again to Heroku. I've deployed the project to Heroku once already previously (without static files) and it worked. But recently, I altered the front-end and included some images and css files, and now I'm updating this project.

My Project files are as follows:

```<code>site1 - mynotes - settings.py
                - wsgi.py
      - mynotess - migrations
                 - static
                 - templates
      - users    - migrations
                 - templates
      - .gitignore.txt
      - manage.py
      - db.sqlite3
      - Procfile
      - requirements.txt
</code>```

Just to clarify, mynotes is the main project directory. 'users' and 'mynotess' (double s) are apps.

This is my settings.py:

```<code>import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'w2!3r+pgqz6yhwi_+aw_!-yra7#h69z-n3-ni$gs2v+!!k^2$b'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'bootstrap3',
    'mynotess',
    'users',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'mynotes.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [], #originally empty
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'mynotes.wsgi.application'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

STATIC_URL = '/static/'

LOGIN_URL = 'users/login'

BOOTSTRAP3 = {'include_jquery': True}

if os.getcwd() == '/app':
    import dj_database_url
    DATABASES = {
        'default': dj_database_url.config(default='postgres://localhost')
    }

    SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

    ALLOWED_HOSTS = ['*']

    BASE_DIR = os.path.dirname(os.path.abspath(__file__))
    STATIC_ROOT = 'staticfiles'
    STATICFILES_DIRS = (
        os.path.join(BASE_DIR, 'static'),
    )
</code>```

This is the error I got in Command Prompt:

```<code>C:\Users\Steven\site1>git push heroku master
Counting objects: 7, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (7/7), done.
Writing objects: 100% (7/7), 590 bytes | 0 bytes/s, done.
Total 7 (delta 5), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Python app detected
remote:      $ pip install -r requirements.txt
remote:
remote:      $ python manage.py collectstatic --noinput
remote:        Traceback (most recent call last):
remote:          File "manage.py", line 22, in <module>
remote:            execute_from_command_line(sys.argv)
remote:          File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
remote:            utility.execute()
remote:          File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/__init__.py", line 359, in execute
remote:            self.fetch_command(subcommand).run_from_argv(self.argv)
remote:          File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/base.py", line 294, in run_from_argv
remote:            self.execute(*args, **cmd_options)
remote:          File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/base.py", line 345, in execute
remote:            output = self.handle(*args, **options)
remote:          File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 193, in handle
remote:            collected = self.collect()
remote:          File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 124, in collect
remote:            handler(path, prefixed_path, storage)
remote:          File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 337, in copy_file
remote:            if not self.delete_file(path, prefixed_path, source_storage):
remote:          File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 255, in delete_file
remote:            if self.storage.exists(prefixed_path):
remote:          File "/app/.heroku/python/lib/python2.7/site-packages/django/core/files/storage.py", line 394, in exists
remote:            return os.path.exists(self.path(name))
remote:          File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/staticfiles/storage.py", line 49, in path
remote:            raise ImproperlyConfigured("You're using the staticfiles app "
remote:        django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path.
remote:
remote:  !     Error while running '$ python manage.py collectstatic --noinput'.
remote:        See traceback above for details.
remote:
remote:        You may need to update application code to resolve this error.
remote:        Or, you can disable collectstatic for this application:
remote:
remote:           $ heroku config:set DISABLE_COLLECTSTATIC=1
remote:
remote:        https://devcenter.heroku.com/articles/django-assets
remote:  !     Push rejected, failed to compile Python app.
remote:
remote:  !     Push failed
remote: Verifying deploy...
remote:
remote: !       Push rejected to my-compository.
remote:
To https://git.heroku.com/my-compository.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/my-compository.git'
</code>```

I feel like it has something to do with how my static files are configured in settings.py. Any kind of help/suggestions are greatly appreciated!

答: $ heroku config:set DISABLE_COLLECTSTATIC=1</p>

Body:
I've recently encountered a static files error when deploying my Django project again to Heroku. I've deployed the project to Heroku once already previously (without static files) and it worked. But recently, I altered the front-end and included some images and css files, and now I'm updating this project.

My Project files are as follows:

site1 - mynotes - settings.py
                - wsgi.py
      - mynotess - migrations
                 - static
                 - templates
      - users    - migrations
                 - templates
      - .gitignore.txt
      - manage.py
      - db.sqlite3
      - Procfile
      - requirements.txt

Just to clarify, mynotes is the main project directory. 'users' and 'mynotess' (double s) are apps.

This is my settings.py:

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'w2!3r+pgqz6yhwi_+aw_!-yra7#h69z-n3-ni$gs2v+!!k^2$b'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'bootstrap3',
    'mynotess',
    'users',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'mynotes.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [], #originally empty
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'mynotes.wsgi.application'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

STATIC_URL = '/static/'

LOGIN_URL = 'users/login'

BOOTSTRAP3 = {'include_jquery': True}

if os.getcwd() == '/app':
    import dj_database_url
    DATABASES = {
        'default': dj_database_url.config(default='postgres://localhost')
    }

    SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

    ALLOWED_HOSTS = ['*']

    BASE_DIR = os.path.dirname(os.path.abspath(__file__))
    STATIC_ROOT = 'staticfiles'
    STATICFILES_DIRS = (
        os.path.join(BASE_DIR, 'static'),
    )

This is the error I got in Command Prompt:

C:\Users\Steven\site1>git push heroku master
Counting objects: 7, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (7/7), done.
Writing objects: 100% (7/7), 590 bytes | 0 bytes/s, done.
Total 7 (delta 5), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Python app detected
remote:      $ pip install -r requirements.txt
remote:
remote:      $ python manage.py collectstatic --noinput
remote:        Traceback (most recent call last):
remote:          File "manage.py", line 22, in <module>
remote:            execute_from_command_line(sys.argv)
remote:          File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
remote:            utility.execute()
remote:          File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/__init__.py", line 359, in execute
remote:            self.fetch_command(subcommand).run_from_argv(self.argv)
remote:          File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/base.py", line 294, in run_from_argv
remote:            self.execute(*args, **cmd_options)
remote:          File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/base.py", line 345, in execute
remote:            output = self.handle(*args, **options)
remote:          File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 193, in handle
remote:            collected = self.collect()
remote:          File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 124, in collect
remote:            handler(path, prefixed_path, storage)
remote:          File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 337, in copy_file
remote:            if not self.delete_file(path, prefixed_path, source_storage):
remote:          File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 255, in delete_file
remote:            if self.storage.exists(prefixed_path):
remote:          File "/app/.heroku/python/lib/python2.7/site-packages/django/core/files/storage.py", line 394, in exists
remote:            return os.path.exists(self.path(name))
remote:          File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/staticfiles/storage.py", line 49, in path
remote:            raise ImproperlyConfigured("You're using the staticfiles app "
remote:        django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path.
remote:
remote:  !     Error while running '$ python manage.py collectstatic --noinput'.
remote:        See traceback above for details.
remote:
remote:        You may need to update application code to resolve this error.
remote:        Or, you can disable collectstatic for this application:
remote:
remote:           $ heroku config:set DISABLE_COLLECTSTATIC=1
remote:
remote:        https://devcenter.heroku.com/articles/django-assets
remote:  !     Push rejected, failed to compile Python app.
remote:
remote:  !     Push failed
remote: Verifying deploy...
remote:
remote: !       Push rejected to my-compository.
remote:
To https://git.heroku.com/my-compository.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/my-compository.git'

I feel like it has something to do with how my static files are configured in settings.py. Any kind of help/suggestions are greatly appreciated!


问:
convert incoming message to parquet format
I know I can read from nifi using spark and write to hdfs in parquet format, but is there a way directly from apache-nifi to write to HDFS in parquet format ?.Please advice

Thanks
Pradeep

答:
Yes. You can use the PutParquet processor in NiFi.
You will have to provide schema for the incoming flowfile in avro schema format and specify the HDFS directory the converted parquet file should be saved to. You can find detailed example here.</p>


问:
Calculate radius distance using cos/sin including if/then and inner join
What i need:

I need to write some kind of IF statement inside query to pick different coordinates, if table1.business_id is equal to 1.

For example:

Pick lng and lat fields from table1 if table1.business_id = 1, else, pick lng and lat fields from table2.

Query:

```<code>SELECT *,
(3959 * acos(
   cos(radians('.$cords['result']['latitude'].')) *
   cos(radians(lat)) * cos( radians(lng) -
   radians('.$cords['result']['longitude'].')) +
   sin(radians('.$cords['result']['latitude'].')) *
   sin(radians(lat))
)) AS distance
   FROM table1 INNER JOIN table2 ON table2.id = table1.business_id
   WHERE type <> "industry" AND '.$query.'
   HAVING distance < '.$radius.'
   ORDER BY distance LIMIT 100
</code>```

How i can get this working? How to write technically correct query?

Thanks for any answers.

答:
You can use either a CASE statement, or an IF statement to control the flow. The idea is to determine from which table to use the data so:

```<code>IF(`table1`.`business_id` = 1, `table1`.`lat`, `table2`.`lat`)
</code>```

Would get put in place of all existing uses of lat (and the same for long)

```<code>SELECT *,
(3959 * acos(
   cos(radians('.$cords['result']['latitude'].')) *
   cos(radians(IF(`table1`.`business_id` = 1, `table1`.`lat`, `table2`.`lat`))) *
   cos( radians(IF(`table1`.`business_id` = 1, `table1`.`lng`, `table2`.`lng`)) -
   radians('.$cords['result']['longitude'].')) +
   sin(radians('.$cords['result']['latitude'].')) *
   sin(radians(IF(`table1`.`business_id` = 1, `table1`.`lat`, `table2`.`lat`)))
)) AS distance
   FROM table1 INNER JOIN table2 ON table2.id = table1.business_id
   WHERE type <> "industry" AND '.$query.'
   HAVING distance < '.$radius.'
   ORDER BY distance LIMIT 100
</code>```

Unrelated, it looks like you're concatenating values into your query. Be very careful that you're not opening yourself up to SQL injection attacks!

Body:
What i need:

I need to write some kind of IF statement inside query to pick different coordinates, if table1.business_id is equal to 1.

For example:

Pick lng and lat fields from table1 if table1.business_id = 1, else, pick lng and lat fields from table2.

Query:

SELECT *,
(3959 * acos(
   cos(radians('.$cords['result']['latitude'].')) *
   cos(radians(lat)) * cos( radians(lng) -
   radians('.$cords['result']['longitude'].')) +
   sin(radians('.$cords['result']['latitude'].')) *
   sin(radians(lat))
)) AS distance
   FROM table1 INNER JOIN table2 ON table2.id = table1.business_id
   WHERE type <> "industry" AND '.$query.'
   HAVING distance < '.$radius.'
   ORDER BY distance LIMIT 100

How i can get this working? How to write technically correct query?

Thanks for any answers.

Body:
You can use either a CASE statement, or an IF statement to control the flow. The idea is to determine from which table to use the data so:

IF(`table1`.`business_id` = 1, `table1`.`lat`, `table2`.`lat`)

Would get put in place of all existing uses of lat (and the same for long)

SELECT *,
(3959 * acos(
   cos(radians('.$cords['result']['latitude'].')) *
   cos(radians(IF(`table1`.`business_id` = 1, `table1`.`lat`, `table2`.`lat`))) *
   cos( radians(IF(`table1`.`business_id` = 1, `table1`.`lng`, `table2`.`lng`)) -
   radians('.$cords['result']['longitude'].')) +
   sin(radians('.$cords['result']['latitude'].')) *
   sin(radians(IF(`table1`.`business_id` = 1, `table1`.`lat`, `table2`.`lat`)))
)) AS distance
   FROM table1 INNER JOIN table2 ON table2.id = table1.business_id
   WHERE type <> "industry" AND '.$query.'
   HAVING distance < '.$radius.'
   ORDER BY distance LIMIT 100

Unrelated, it looks like you're concatenating values into your query. Be very careful that you're not opening yourself up to SQL injection attacks!


问:
Javascript Confirm Before execute javascript in Chrome
The function hideWord() in function does not work when I run checkWord() function. promt() expects the function to finish.
What can I do.

I would like the function promt() to work after the function hideWord() before the function checkWord() works. Please compare Firefox and Chrome:

function checkWord() {
    hideWord();
    var answer = prompt("please you write word see?");
}

function hideWord() {
    document.getElementById('takistoskopContainer').innerHTML = "";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="takistoskopContainer">Must this text empty before promt!</div>
<br><br><button type="button" onclick="checkWord();">click me!</button></code>```

https://jsfiddle.net/dreamman/0o56etzk/

答:
i am solve this problem setTimeout():</p>

```<code>function checkWord() {
    hideWord();
    setTimeout(function() {
       var answer = prompt("please you write word see?");
    },0)
}
</code>```

Body:
The function hideWord() in function does not work when I run checkWord() function. promt() expects the function to finish.
What can I do.

I would like the function promt() to work after the function hideWord() before the function checkWord() works. Please compare Firefox and Chrome:

function checkWord() {
    hideWord();
    var answer = prompt("please you write word see?");
}

function hideWord() {
    document.getElementById('takistoskopContainer').innerHTML = "";
}

Must this text empty before promt!

<button type="button" onclick="checkWord();">click me!</button>

https://jsfiddle.net/dreamman/0o56etzk/

Body:
i am solve this problem setTimeout():

function checkWord() {
    hideWord();
    setTimeout(function() {
       var answer = prompt("please you write word see?");
    },0)
}


问:
How to upgrade minikube?
I had installed minikube a few months ago and wanted to upgrade as newer versions are available.

I am unable to find out how to upgrade minikube. I see a feature request for an upgrade command here - https://github.com/kubernetes/minikube/issues/1171

I tried to then uninstall minikube and hit another brickwall again. I don't see a command to uninstall minikube. The information that came closest to this was not very helpful - https://github.com/kubernetes/minikube/issues/1043

I guess we need ways to upgrade these (at least once every 6 months or so).

答:
Before reinstall minikube (OS X), check the following:

Make sure that you have brew updated:

```<code>brew update
</code>```

Make sure that you already have cask installed:

```<code>brew cask install minikube --verbose
</code>```

Finally, execute the following command in the same directory you've installed minikube previously (usually /usr/local/bin/):

```<code>brew cask reinstall minikube
</code>```

If you see an output similar to this:

Error: It seems there is already a Binary at '/usr/local/bin/minikube'; not linking.

Remove the existing binary:

```<code>rm /usr/local/bin/minikube
</code>```

Now, you should able to reinstall (upgrade) minikube. :)

Title: How to upgrade minikube?

Body:
Before reinstall minikube (OS X), check the following:

Make sure that you have brew updated:

brew update

Make sure that you already have cask installed:

brew cask install minikube --verbose

Finally, execute the following command in the same directory you've installed minikube previously (usually /usr/local/bin/):

brew cask reinstall minikube

If you see an output similar to this:

Error: It seems there is already a Binary at '/usr/local/bin/minikube'; not linking.

Remove the existing binary:

rm /usr/local/bin/minikube

Now, you should able to reinstall (upgrade) minikube. :)


问:
openssl / valgrind
I have an application that has to calculate the MD5 of file, I have
used the openssl library, valgrind complains about some blocks still
reachable.

Compile the following code:

```<code>#include <openssl/bio.h>

int main(int, char**)
{
   BIO * mem = BIO_new(BIO_s_mem());
   BIO_vfree(mem);
   return 0;
}
</code>```

the run it using valgrind this is what I'm obtaining:

```<code>==23597== 220 bytes in 6 blocks are still reachable in loss record 1 of 1
==23597==    at 0x4022D78: malloc (vg_replace_malloc.c:207)
==23597==    by 0x432FD0D: (within /usr/lib/i686/cmov/libcrypto.so.0.9.8)
==23597==    by 0x433036E: CRYPTO_malloc (in /usr/lib/i686/cmov/libcrypto.so.0.9.8)
==23597==    by 0x43989C9: lh_new (in /usr/lib/i686/cmov/libcrypto.so.0.9.8)
==23597==    by 0x4332025: (within /usr/lib/i686/cmov/libcrypto.so.0.9.8)
==23597==    by 0x433249B: (within /usr/lib/i686/cmov/libcrypto.so.0.9.8)
==23597==    by 0x4332B5D: CRYPTO_new_ex_data (in /usr/lib/i686/cmov/libcrypto.so.0.9.8)
==23597==    by 0x438E053: BIO_set (in /usr/lib/i686/cmov/libcrypto.so.0.9.8)
==23597==    by 0x438E0E9: BIO_new (in /usr/lib/i686/cmov/libcrypto.so.0.9.8)
==23597==    by 0x80485E1: main (in /home/kalman/cxx_test/md5test/a.out)
</code>```

anyone had same experience ?

答: OpenSSL has actions that confuse Valgrind when not compiled with -DPURIFY.  Is this the error you are seeing?</p>

OwnerDisplayName: kalman

Title: openssl / valgrind

Body:
I have an application that has to calculate the MD5 of file, I have
used the openssl library, valgrind complains about some blocks still
reachable.

Compile the following code:

#include <openssl/bio.h>

int main(int, char**)
{
   BIO * mem = BIO_new(BIO_s_mem());
   BIO_vfree(mem);
   return 0;
}

the run it using valgrind this is what I'm obtaining:

==23597== 220 bytes in 6 blocks are still reachable in loss record 1 of 1
==23597==    at 0x4022D78: malloc (vg_replace_malloc.c:207)
==23597==    by 0x432FD0D: (within /usr/lib/i686/cmov/libcrypto.so.0.9.8)
==23597==    by 0x433036E: CRYPTO_malloc (in /usr/lib/i686/cmov/libcrypto.so.0.9.8)
==23597==    by 0x43989C9: lh_new (in /usr/lib/i686/cmov/libcrypto.so.0.9.8)
==23597==    by 0x4332025: (within /usr/lib/i686/cmov/libcrypto.so.0.9.8)
==23597==    by 0x433249B: (within /usr/lib/i686/cmov/libcrypto.so.0.9.8)
==23597==    by 0x4332B5D: CRYPTO_new_ex_data (in /usr/lib/i686/cmov/libcrypto.so.0.9.8)
==23597==    by 0x438E053: BIO_set (in /usr/lib/i686/cmov/libcrypto.so.0.9.8)
==23597==    by 0x438E0E9: BIO_new (in /usr/lib/i686/cmov/libcrypto.so.0.9.8)
==23597==    by 0x80485E1: main (in /home/kalman/cxx_test/md5test/a.out)

anyone had same experience ?

OwnerDisplayName: HUAGHAGUAH


问:
Creating zend form element array with same name (ZF3)?
Since i've to position checkboxes in design I'm not using MultiCheckbox and using Checkbox instead in zend. I've seen some zf1 solutions but didnt found any zf2 or zf3 solutions.

My Php Code

```<code>$languages = new \Zend\Form\Element\Checkbox('languages[]');
$languages->setLabel('English');
$languages->setValue('1');
</code>```

This produce the following output

```<code><?php
    echo $this->formRow($form->get('languages[]'));
    //It produce the following
?>
<input type="checkbox" name="languages[]" value="1" checked="checked">
</code>```

How can I add more items with name "languages[]" without writing direct HTML code ?

答:
My solution (Method 2)

Method 1:
Give name as "language[1]" instead of "language[]". By using this I can call the elements in view seperately.

Creating form.

```<code>$language1 = new \Zend\Form\Element\Checkbox('language[1]');
$language2 = new \Zend\Form\Element\Checkbox('language[2]');

$form = new Form('Set');
$form->add($name)
        ->add($language1)
        ->add($language2)
        ->add($submit);
</code>```

In view file

```<code><div><?php echo $form->get('language[1]');?></div>
<div><?php echo $form->get('language[2]');?></div>
</code>```

Edit: Method 2
Using fieldset

```<code>//Create form
$languages = [
    ['id' => 1, 'language' => 'English'],
    ['id' => 2, 'language' => 'Malayalam'],
] ;
$fieldSet = new \Zend\Form\Fieldset('languages') ;
foreach( $languages as $one ) {
    $c = new \Zend\Form\Element\Checkbox($one['id']);
    $c->setLabel($one['language']) ;
    $fieldSet->add($c) ;
}
//Add collection of checkboxes to form
$form->add($fieldSet) ;
</code>```

In view file

```<code><?php
$language = $form->get('languages') ;
?>
<div class="form-group row">
    <label class="control-label col-sm-2" >Choose Languages</label>
    <div class="col-sm-10">
        <?php foreach($language as $one ) { ?>
        <?php echo $this->formCheckbox($one); ?> <span> <?php echo $this->formLabel( $one ) ; ?> </span>
        <?php echo $this->formElementErrors($one); ?>
        <?php } ?>
    </div>
</div>
</code>```

Body:
Since i've to position checkboxes in design I'm not using MultiCheckbox and using Checkbox instead in zend. I've seen some zf1 solutions but didnt found any zf2 or zf3 solutions.

My Php Code

$languages = new \Zend\Form\Element\Checkbox('languages[]');
$languages->setLabel('English');
$languages->setValue('1');

This produce the following output

<?php
    echo $this->formRow($form->get('languages[]'));
    //It produce the following
?>
<input type="checkbox" name="languages[]" value="1" checked="checked">

How can I add more items with name "languages[]" without writing direct HTML code ?

Body:
My solution (Method 2)

Method 1:
Give name as "language[1]" instead of "language[]". By using this I can call the elements in view seperately.

Creating form.

$language1 = new \Zend\Form\Element\Checkbox('language[1]');
$language2 = new \Zend\Form\Element\Checkbox('language[2]');

$form = new Form('Set');
$form->add($name)
        ->add($language1)
        ->add($language2)
        ->add($submit);

In view file

<div><?php echo $form->get('language[1]');?></div>
<div><?php echo $form->get('language[2]');?></div>

Edit: Method 2
Using fieldset

//Create form
$languages = [
    ['id' => 1, 'language' => 'English'],
    ['id' => 2, 'language' => 'Malayalam'],
] ;
$fieldSet = new \Zend\Form\Fieldset('languages') ;
foreach( $languages as $one ) {
    $c = new \Zend\Form\Element\Checkbox($one['id']);
    $c->setLabel($one['language']) ;
    $fieldSet->add($c) ;
}
//Add collection of checkboxes to form
$form->add($fieldSet) ;

In view file

<?php
$language = $form->get('languages') ;
?>
<div class="form-group row">
    <label class="control-label col-sm-2" >Choose Languages</label>
    <div class="col-sm-10">
        <?php foreach($language as $one ) { ?>
        <?php echo $this->formCheckbox($one); ?> <span> <?php echo $this->formLabel( $one ) ; ?> </span>
        <?php echo $this->formElementErrors($one); ?>
        <?php } ?>
    </div>
</div>