问:
Xerces XML parsing issue: 'No two Schemas should share the same targetNamespace'. How to fix it?
I am trying to get a web application to run on a weblogic server, but it throws an exception telling that there were more than one xml file using the same namespace. I've searched all XML's and I couldn't find any!

It throws the exception that follows:

```<code><01/09/2014 16h58min32s BRT> <Warning> <HTTP> <BEA-101162> <User defined listener org.jboss.weld.servlet.WeldListener failed: java.lang.IllegalStateException: Singleton not set for STATIC_INSTANCE => [].
java.lang.IllegalStateException: Singleton not set for STATIC_INSTANCE => []
at org.jboss.weld.bootstrap.api.helpers.RegistrySingletonProvider$RegistrySingleton.get(RegistrySingletonProvider.java:28)
at org.jboss.weld.Container.instance(Container.java:55)
at org.jboss.weld.SimpleCDI.<init>(SimpleCDI.java:77)
at org.jboss.weld.servlet.StaticWeldProvider$EnhancedCDI.<init>(StaticWeldProvider.java:27)
at org.jboss.weld.servlet.StaticWeldProvider$EnhancedCDI.<init>(StaticWeldProvider.java:27)
Truncated. see log file for complete stacktrace
>
<01/09/2014 16h58min33s BRT> <Warning> <HTTP> <BEA-101162> <User defined listener org.jboss.weld.environment.servlet.Listener failed: java.lang.IllegalArgumentException:  When using array of Objects as the value of SCHEMA_SOURCE property , no two Schemas should share the same targetNamespace. .
java.lang.IllegalArgumentException:  When using array of Objects as the value of SCHEMA_SOURCE property , no two Schemas should share the same targetNamespace.
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaLoader.processJAXPSchemaSource(XMLSchemaLoader.java:839)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaLoader.loadSchema(XMLSchemaLoader.java:605)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.findSchemaGrammar(XMLSchemaValidator.java:2453)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.handleStartElement(XMLSchemaValidator.java:1772)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.startElement(XMLSchemaValidator.java:746)
Truncated. see log file for complete stacktrace"
</code>```

答: That problem happened due to a weblogic 10 incompatibility with weld. To resolve it I would have to change things into weblogic jars, so It couldnt work with that version of weblogic at all. I changed to a later version and weblogic and it worked fine.</p>

Body:
I am trying to get a web application to run on a weblogic server, but it throws an exception telling that there were more than one xml file using the same namespace. I've searched all XML's and I couldn't find any!

It throws the exception that follows:

<01/09/2014 16h58min32s BRT> <Warning> <HTTP> <BEA-101162> <User defined listener org.jboss.weld.servlet.WeldListener failed: java.lang.IllegalStateException: Singleton not set for STATIC_INSTANCE => [].
java.lang.IllegalStateException: Singleton not set for STATIC_INSTANCE => []
at org.jboss.weld.bootstrap.api.helpers.RegistrySingletonProvider$RegistrySingleton.get(RegistrySingletonProvider.java:28)
at org.jboss.weld.Container.instance(Container.java:55)
at org.jboss.weld.SimpleCDI.<init>(SimpleCDI.java:77)
at org.jboss.weld.servlet.StaticWeldProvider$EnhancedCDI.<init>(StaticWeldProvider.java:27)
at org.jboss.weld.servlet.StaticWeldProvider$EnhancedCDI.<init>(StaticWeldProvider.java:27)
Truncated. see log file for complete stacktrace
>
<01/09/2014 16h58min33s BRT> <Warning> <HTTP> <BEA-101162> <User defined listener org.jboss.weld.environment.servlet.Listener failed: java.lang.IllegalArgumentException:  When using array of Objects as the value of SCHEMA_SOURCE property , no two Schemas should share the same targetNamespace. .
java.lang.IllegalArgumentException:  When using array of Objects as the value of SCHEMA_SOURCE property , no two Schemas should share the same targetNamespace.
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaLoader.processJAXPSchemaSource(XMLSchemaLoader.java:839)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaLoader.loadSchema(XMLSchemaLoader.java:605)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.findSchemaGrammar(XMLSchemaValidator.java:2453)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.handleStartElement(XMLSchemaValidator.java:1772)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.startElement(XMLSchemaValidator.java:746)
Truncated. see log file for complete stacktrace"


来源: stackexchange

问:
Buildbot parsing Python Unit test results
I have a test suite that outputs test results in the Python Unit Test format: http://docs.python.org/library/unittest.html

Is there an existing Buildbot module/plugin that can parse this form?

Example:

```<code>DigitalReadWrite_02                                         ... ok
DigitalReadWrite_03                                         ... ok
DigitalReadWrite_04                                         ... ok
PWMoutput_02  (PWM=128 50% LOW 49% HIGH)                    ... ok
PWMoutput_03  (PWM=128 50% LOW 49% HIGH)                    ... ok
PWMoutput_04  (PWM=128 50% LOW 49% HIGH)                    ... ok
--------------------------
Ran 6 tests in 1.652s

OK
</code>```

I've written a custom parser, but it's only got the basic cases. Is it worth the effort to make it comprehensive for all flavors of Python Unit test format.

答:
No, it makes no sense to develop a parser. You can obtain the equivalent information from classes in runner.py module.

Consider extending both classes TextTestRunner and TextTestResult with your custom logic (python 2.7). The output you have listed is produced by TextTestResult.

Alternatively you can extend only TextTestResult and alter the class attribute TextTestRunner.resultclass setting it to your new extension class name.

The data you can extract from TextTestResult and put into some list of dictionaries is greater or equivalent to the data your parser is able to extract.

The unittest framework allows such tricks due to its flexible design.
Hope this was helpful.

[EDIT]

I would find publishing your results so far (e.g. as an Open Source code on github) potentially very useful for people that find your question!

Having said that I doubt it would be easy to improve the actual parser beyond basic regexp parsing.

If you still would like to pursuit the text parsing approach - you might need to enumerate and describe "all flavors of Python Unit test format" that you want to cover/support. If you are lucky to put such a description in form of a context-free grammar, then maybe you would be able to develop a parser for it, that would cover "those" cases as a form of a language.

Please take my word of caution: if text parsing is not covered by simple regexp'ing and there is a chance that you are trying to parse some irregular (context-sensitive) language - most likely you would find it extremely difficult to accomplish.

ContentLicense: CC BY-SA 2.5

Body:
I have a test suite that outputs test results in the Python Unit Test format: http://docs.python.org/library/unittest.html

Is there an existing Buildbot module/plugin that can parse this form?

Example:

DigitalReadWrite_02                                         ... ok
DigitalReadWrite_03                                         ... ok
DigitalReadWrite_04                                         ... ok
PWMoutput_02  (PWM=128 50% LOW 49% HIGH)                    ... ok
PWMoutput_03  (PWM=128 50% LOW 49% HIGH)                    ... ok
PWMoutput_04  (PWM=128 50% LOW 49% HIGH)                    ... ok
--------------------------
Ran 6 tests in 1.652s

OK

I've written a custom parser, but it's only got the basic cases. Is it worth the effort to make it comprehensive for all flavors of Python Unit test format.

ContentLicense: CC BY-SA 3.0


问:
PHP7 fails to load memcached and redis on Alpine docker container
I'm trying to create a Docker image based on Alpine Linux which will run PHP 7.1 (apk add php7=7.1.9-r0) with some modules installed (memcached, mongodb, oauth, openssl and redis).

I install the modules through PECL like this:

RUN yes | pecl install \
  igbinary \
  redis-3.1.4 \
  oauth-2.0.2 \
  memcached-3.0.4 \
  mongodb-1.3.3
```

<p>Then add each of them to <code>php.ini</code>.</p>

<pre class="lang-bash prettyprint-override"><code>RUN for EXT in \
    igbinary \
    memcached \
    mongodb \
    oauth \
    openssl \
    redis; \
  do \
    echo "extension=${EXT}.so" >> /etc/php7/php.ini; \
  done
</code>```

Most modules install correctly, but memcached and redis don't want to play along:

# php -v
PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/lib/php7/modules/memcached.so' - Error relocating /usr/lib/php7/modules/memcached.so: php_session_create_id: symbol not found in Unknown on line 0
PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/lib/php7/modules/redis.so' - Error relocating /usr/lib/php7/modules/redis.so: php_session_register_module: symbol not found in Unknown on line 0
PHP Warning:  Module 'openssl' already loaded in Unknown on line 0
PHP Warning:  Cannot load module 'mongodb' because required module 'json' is not loaded in Unknown on line 0
PHP 7.1.9 (cli) (built: Oct  2 2017 20:51:54) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.1.0, Copyright (c) 1998-2017 Zend Technologies
```

<p>I've also tried from source:</p>

<pre class="lang-bash prettyprint-override"><code>RUN git clone https://github.com/php-memcached-dev/php-memcached
RUN cd php-memcached \
  && git checkout php7 \
  && git pull \
  && /usr/bin/phpize \
  && ./configure --with-php-config=/usr/bin/php-config \
  && make \
  && make install
</code>```

This however gives me the same result. I've done some searching and apparently there might be some related problem of glibc on Alpine (example thread) but I'm not quite sure this is the same issue as the error output is a bit confusing.

Is there anything I'm overlooking as to how these modules should be installed to work with PHP 7.1 on Alpine Linux?

答:
We were facing similar issues with the "official" PHP images build on Alpine. Ie. it was impossible for us to install a working ImageMagick version in PHP 7.1 which is based on Alpine 3.4

What we did is installing it from Alpine 3.6, while I actually won't recommend this it might be a workaround.

The other workaround is to wait for PHP 7.2 which is build on Alpine 3.6. Might be an option to look for a working PHP + Alpine combination, since you are building FROM alpine and not FROM php:alpine

Just saying: Issues like that made us go back to Debian images, since we've wasted tons of hours on that, including weird glibc issues like you mentioned.

Body:
I'm trying to create a Docker image based on Alpine Linux which will run PHP 7.1 (apk add php7=7.1.9-r0) with some modules installed (memcached, mongodb, oauth, openssl and redis).

I install the modules through PECL like this:

RUN yes | pecl install \
  igbinary \
  redis-3.1.4 \
  oauth-2.0.2 \
  memcached-3.0.4 \
  mongodb-1.3.3

Then add each of them to php.ini.

RUN for EXT in \
    igbinary \
    memcached \
    mongodb \
    oauth \
    openssl \
    redis; \
  do \
    echo "extension=${EXT}.so" >> /etc/php7/php.ini; \
  done

Most modules install correctly, but memcached and redis don't want to play along:

# php -v
PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/lib/php7/modules/memcached.so' - Error relocating /usr/lib/php7/modules/memcached.so: php_session_create_id: symbol not found in Unknown on line 0
PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/lib/php7/modules/redis.so' - Error relocating /usr/lib/php7/modules/redis.so: php_session_register_module: symbol not found in Unknown on line 0
PHP Warning:  Module 'openssl' already loaded in Unknown on line 0
PHP Warning:  Cannot load module 'mongodb' because required module 'json' is not loaded in Unknown on line 0
PHP 7.1.9 (cli) (built: Oct  2 2017 20:51:54) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.1.0, Copyright (c) 1998-2017 Zend Technologies

I've also tried from source:

RUN git clone https://github.com/php-memcached-dev/php-memcached
RUN cd php-memcached \
  && git checkout php7 \
  && git pull \
  && /usr/bin/phpize \
  && ./configure --with-php-config=/usr/bin/php-config \
  && make \
  && make install

This however gives me the same result. I've done some searching and apparently there might be some related problem of glibc on Alpine (example thread) but I'm not quite sure this is the same issue as the error output is a bit confusing.

Is there anything I'm overlooking as to how these modules should be installed to work with PHP 7.1 on Alpine Linux?


问:
Redirect error 404 Angular 5

I am trying to handle 404 error when urls are wrong, http://localhost:8100/#/login. This is my login url and if I write something like http:.../loginasdasd i would like to automatically open my own NotFoundPage.

```<code>const appRoutes3: Routes = [
  {
    path: '',
    children: [
      {
         path: 'login',
         component: LoginPage
      },
      { path: 'login**', redirectTo: '/notfound' }
   ]
 },
 { path: 'notfound', component: NotFoundPage }
];

RouterModule.forRoot(
  appRoutes3,
  { enableTracing: true } // <-- debugging purposes only
)
,
IonicModule.forRoot(MyApp, {}, {
  links: [
    { component: HomePage, name: "Home", segment: "" },
    { component: LoginPage, name: "Login", segment: "login", defaultHistory: [HomePage] },
    { component: SubscribePage, name: "Signup", segment: "signup", defaultHistory: [HomePage] },
    { component: SubscribeExtendPage, name: "Signup", segment: "signup-extend", defaultHistory: [HomePage] },
    { component: MainPage, name: "Main", segment: "main", defaultHistory: [HomePage] },
    { component: WelcomePage, name: "Welcome", segment: "welcome" },
    { component: NotFoundPage, name: "notFound", segment: "login/**", defaultHistory: [HomePage] },
  ]
}
)
],
</code>```

I am an angular noob and I don't how to properly do it, the best info i've found is https://vsavkin.com/angular-router-understanding-redirects-2826177761fc in some other angular redirection posts.

Please some help or any clue would be grateful.
Thanks.

答:
You need to use a wild character (**). The ** path should be last route. The router will select this route if the requested URL doesn't match any paths for routes defined in the configuration. This is useful for displaying a "404 - Not Found" page or redirecting to another route.

```<code>const appRoutes: Routes = [
  { path: 'crisis-center', component: CrisisListComponent },
  { path: 'hero/:id',      component: HeroDetailComponent },
  {
   path: 'heroes',
   component: HeroListComponent,
 data: { title: 'Heroes List' }
 },
 {  path: '',
 redirectTo: '/heroes',
 pathMatch: 'full'
 },
 { path: '**', component: PageNotFoundComponent }
];
</code>```

Hope this helps.

Title: Redirect error 404 Angular 5

Body:
I am trying to handle 404 error when urls are wrong, http://localhost:8100/#/login. This is my login url and if I write something like http:.../loginasdasd i would like to automatically open my own NotFoundPage.

const appRoutes3: Routes = [
  {
    path: '',
    children: [
      {
         path: 'login',
         component: LoginPage
      },
      { path: 'login**', redirectTo: '/notfound' }
   ]
 },
 { path: 'notfound', component: NotFoundPage }
];

RouterModule.forRoot(
  appRoutes3,
  { enableTracing: true } // <-- debugging purposes only
)
,
IonicModule.forRoot(MyApp, {}, {
  links: [
    { component: HomePage, name: "Home", segment: "" },
    { component: LoginPage, name: "Login", segment: "login", defaultHistory: [HomePage] },
    { component: SubscribePage, name: "Signup", segment: "signup", defaultHistory: [HomePage] },
    { component: SubscribeExtendPage, name: "Signup", segment: "signup-extend", defaultHistory: [HomePage] },
    { component: MainPage, name: "Main", segment: "main", defaultHistory: [HomePage] },
    { component: WelcomePage, name: "Welcome", segment: "welcome" },
    { component: NotFoundPage, name: "notFound", segment: "login/**", defaultHistory: [HomePage] },
  ]
}
)
],

I am an angular noob and I don't how to properly do it, the best info i've found is https://vsavkin.com/angular-router-understanding-redirects-2826177761fc in some other angular redirection posts.

Please some help or any clue would be grateful.
Thanks.

Body:
You need to use a wild character (**). The ** path should be last route. The router will select this route if the requested URL doesn't match any paths for routes defined in the configuration. This is useful for displaying a "404 - Not Found" page or redirecting to another route.

const appRoutes: Routes = [
  { path: 'crisis-center', component: CrisisListComponent },
  { path: 'hero/:id',      component: HeroDetailComponent },
  {
   path: 'heroes',
   component: HeroListComponent,
 data: { title: 'Heroes List' }
 },
 {  path: '',
 redirectTo: '/heroes',
 pathMatch: 'full'
 },
 { path: '**', component: PageNotFoundComponent }
];

Hope this helps.


问:
Intellij Plugin Development - Gradle does not find dependency of IntelliJ
I am currently developing a plugin for IntelliJ and trying to use another built-in IntelliJ Plugin as dependency (git4idea). As described in the IntelliJ Plugin Development documentation, I added the required JARs to my class Path in Project Structure:
Project Structure Dialog Screenshot

I also added <depends>Git4Idea</depends> to my plugin.xml file.

IntelliJ finds these jars now and Code Completion works well, no errors found...
But when I try to build the Plugin with gradle I get ClassNotFound errors or errors like this:

```<code>TkGitflowBaseImpl.java:15: error: package git4idea.commands does not exist
import git4idea.commands.Git;
                        ^
</code>```

Obviously, Gradle does not find these jars. Since they are part of the IntelliJ installation, I can't just add them to a lib folder and add them as local jars in the build.gradle file. As Gradle JVM, I chose the exact same JVM I chose as JVM behind the IDEA Platform SDK, so the jars should be available to Gradle.

Do you know how I can help Gradle find these jars or add them as "provided" dependencies without adding them to a lib folder?

I am using IntelliJ IDEA 2017.2.5 and Gradle 4.2.1

答:
After reading through the documentation of the IntelliJ Gradle Plugin (https://github.com/JetBrains/gradle-intellij-plugin), I saw that that a "=" was missing in the build.gradle file like:

```<code>intellij {
    version '2017.2.5'
    pluginName 'pluginname'
    plugins = ['Git4Idea']
}
</code>```

instead of

```<code>intellij {
    version '2017.2.5'
    pluginName 'pluginname'
    plugins ['Git4Idea']
}
</code>```

Body:
I am currently developing a plugin for IntelliJ and trying to use another built-in IntelliJ Plugin as dependency (git4idea). As described in the IntelliJ Plugin Development documentation, I added the required JARs to my class Path in Project Structure:
Project Structure Dialog Screenshot

I also added <depends>Git4Idea</depends> to my plugin.xml file.

IntelliJ finds these jars now and Code Completion works well, no errors found...
But when I try to build the Plugin with gradle I get ClassNotFound errors or errors like this:

TkGitflowBaseImpl.java:15: error: package git4idea.commands does not exist
import git4idea.commands.Git;
                        ^

Obviously, Gradle does not find these jars. Since they are part of the IntelliJ installation, I can't just add them to a lib folder and add them as local jars in the build.gradle file. As Gradle JVM, I chose the exact same JVM I chose as JVM behind the IDEA Platform SDK, so the jars should be available to Gradle.

Do you know how I can help Gradle find these jars or add them as "provided" dependencies without adding them to a lib folder?

I am using IntelliJ IDEA 2017.2.5 and Gradle 4.2.1

Body:
After reading through the documentation of the IntelliJ Gradle Plugin (https://github.com/JetBrains/gradle-intellij-plugin), I saw that that a "=" was missing in the build.gradle file like:

intellij {
    version '2017.2.5'
    pluginName 'pluginname'
    plugins = ['Git4Idea']
}

instead of

intellij {
    version '2017.2.5'
    pluginName 'pluginname'
    plugins ['Git4Idea']
}


问:
Prevent 100vw from creating horizontal scroll
If an element is set to width: 100vw; and there is a vertical scrollbar the width of the element will be equal to the viewport plus the width of the scrollbar.

Is it possible to prevent this?

Is it possible to prevent this without disabling horizontal scrolling on the entire page? Aside from changing my css/markup to make the element 100% of the body width I can't think of anything.

Tested in Chrome Version 43.0.2357.81 m & FF 36.0.1 & Opera 20.0.1387.91 on Windows 8.1

Here is the code as requested:

Example

html

```<code><div class="parent">
    <div class="box"></div>
</div>
<div class="tall"></div>
</code>```

css

```<code>body { margin: 0; }
html { box-sizing: border-box; }
*, *::before, *::after {
    box-sizing: inherit;
    position: relative;
}
.parent {
    background: rgba(0, 0, 0, .4);
    height: 100px;
    width: 5rem;
    margin-bottom: 25px;
}

.box {
    position: absolute;
    top: 0;
    left: 0;
    background: rgba(0, 0, 0, .4);
    height: 50px;
    width: 100vw;
}

.tall {
    height: 100rem;
}
</code>```

答:
I was also struggling with this, and I also thought of CSS variables as the solution. CSS variables aren't supported in IE11 though so I tried something else:

I fixed it by calculating the width of the scroll bar: subtracting the width of the body (not including scroll bar) from the width of the window (including the scroll bar). I use this to add it to the 100% of the body, see plusScrollBar variable.

JS:

```<code>    // calculate width of scrollbar and add it as inline-style to the body
var checkScrollBars = function() {
    var b = $('body');
    var normalw = 0;
    var scrollw = 0;
    normalw = window.innerWidth;
    scrollw = normalw - b.width();

    var plusScrollBar = 'calc(' + '100% + ' + scrollw + 'px)'
    document.querySelector('body').style.minWidth = plusScrollBar;
}();
</code>```

CSS:

```<code>html{
    overflow-x: hidden;
}
</code>```

Why I like this: it takes in consideration that not all scrollbars are the same width or considered as conserved space at all. :)

Body:
If an element is set to width: 100vw; and there is a vertical scrollbar the width of the element will be equal to the viewport plus the width of the scrollbar.

Is it possible to prevent this?

Is it possible to prevent this without disabling horizontal scrolling on the entire page? Aside from changing my css/markup to make the element 100% of the body width I can't think of anything.

Tested in Chrome Version 43.0.2357.81 m & FF 36.0.1 & Opera 20.0.1387.91 on Windows 8.1

Here is the code as requested:

Example

html

css

body { margin: 0; }
html { box-sizing: border-box; }
*, *::before, *::after {
    box-sizing: inherit;
    position: relative;
}
.parent {
    background: rgba(0, 0, 0, .4);
    height: 100px;
    width: 5rem;
    margin-bottom: 25px;
}

.box {
    position: absolute;
    top: 0;
    left: 0;
    background: rgba(0, 0, 0, .4);
    height: 50px;
    width: 100vw;
}

.tall {
    height: 100rem;
}

Body:
I was also struggling with this, and I also thought of CSS variables as the solution. CSS variables aren't supported in IE11 though so I tried something else:

I fixed it by calculating the width of the scroll bar: subtracting the width of the body (not including scroll bar) from the width of the window (including the scroll bar). I use this to add it to the 100% of the body, see plusScrollBar variable.

JS:

    // calculate width of scrollbar and add it as inline-style to the body
var checkScrollBars = function() {
    var b = $('body');
    var normalw = 0;
    var scrollw = 0;
    normalw = window.innerWidth;
    scrollw = normalw - b.width();

    var plusScrollBar = 'calc(' + '100% + ' + scrollw + 'px)'
    document.querySelector('body').style.minWidth = plusScrollBar;
}();

CSS:

html{
    overflow-x: hidden;
}

Why I like this: it takes in consideration that not all scrollbars are the same width or considered as conserved space at all. :)


问:
Using Try() mapping it into an Option with Some(errorMsg) in case of error
I wanted to replace the below code with something using either Either or Try(). With vanila scala, is there any straightforward way of making the below code more concise? What I seem to want is to have something like an hypotheticalTry(code).toOption.invert.

```<code>def calculateSomething(): Option[String] =
    try {
      // execute some side effects
      None
    } catch {
      case t:Throwable => Some("some error msg")
    }
</code>```

Thanks

答:
You could use the failed method of Try which is kind of like the invert method you're looking for :

```<code>val option = Try(code).failed.toOption
</code>```

The you can just map over it if you only want the error message:

```<code>option.map(_.getMessage)
</code>```

You can getMessage on the throwable or simply have a function that returns a constant (like _ => "my error message") if you want a custom message.

Body:
I wanted to replace the below code with something using either Either or Try(). With vanila scala, is there any straightforward way of making the below code more concise? What I seem to want is to have something like an hypotheticalTry(code).toOption.invert.

def calculateSomething(): Option[String] =
    try {
      // execute some side effects
      None
    } catch {
      case t:Throwable => Some("some error msg")
    }

Thanks

Body:
You could use the failed method of Try which is kind of like the invert method you're looking for :

val option = Try(code).failed.toOption

The you can just map over it if you only want the error message:

option.map(_.getMessage)

You can getMessage on the throwable or simply have a function that returns a constant (like _ => "my error message") if you want a custom message.


问:
NewConnectionError when trying to install Tensorflow on Windows 10 with python 3.5
I am currently trying to install tensorflow with Python 3.5 and I am running into a new connection error. I am trying to follow the install guide from tensorflow. Has anyone seen this issue before and figured out a solution? Thanks.</p>

```<code>c:\>pip3 install --upgrade tensorflow
Collecting tensorflow
Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x000002245E6C30F0>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it',)': /simple/tensorflow/
Retrying (Retry(total=3, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x000002245E6D0470>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it',)': /simple/tensorflow/
Retrying (Retry(total=2, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x000002245E6D05C0>: Failed to establish a new connection: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond',)': /simple/tensorflow/
Retrying (Retry(total=1, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x000002245E6D0710>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it',)': /simple/tensorflow/
Retrying (Retry(total=0, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x000002245E6D0860>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it',)': /simple/tensorflow/
Could not find a version that satisfies the requirement tensorflow (from versions: )
No matching distribution found for tensorflow
</code>```

答: In my case, the connection was blocked by Kaspersky. Temporary switching it off solved my issue.</p>

Body:
I am currently trying to install tensorflow with Python 3.5 and I am running into a new connection error. I am trying to follow the install guide from tensorflow. Has anyone seen this issue before and figured out a solution? Thanks.

c:\>pip3 install --upgrade tensorflow
Collecting tensorflow
Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x000002245E6C30F0>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it',)': /simple/tensorflow/
Retrying (Retry(total=3, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x000002245E6D0470>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it',)': /simple/tensorflow/
Retrying (Retry(total=2, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x000002245E6D05C0>: Failed to establish a new connection: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond',)': /simple/tensorflow/
Retrying (Retry(total=1, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x000002245E6D0710>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it',)': /simple/tensorflow/
Retrying (Retry(total=0, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x000002245E6D0860>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it',)': /simple/tensorflow/
Could not find a version that satisfies the requirement tensorflow (from versions: )
No matching distribution found for tensorflow


问:
How to Pass parameters to PowerShell script while building from VSTS
I am running the below PowerShell Script to deploy csv file data into Azure table storage. But The below parameters are different for different environment in the azure.Suppose the below script can be deployed to any environment but the below parameters will be varied as per the environment.So I want to pass the below parameters to the script while running from the PowerShell task in VSTS.How to accomplish task.Please help me out on this.So

```<code>**$subscriptionName = "Tech Enabled Solutions"
$resourceGroupName = "abc"
$storageAccountName = "defghi"
$location = "North Central US, South Central US"
$StorageAccountKey = "12345678"**
</code>```

PowerShell Script:

```<code>   function Add-Entity()
{
 [CmdletBinding()]

 param
 (
 $table,
 [string] $partitionKey,
 [string] $RowKey,
 [string] $Label_Usage,
 [string] $Label_Value,
 [string] $Usage_Location,
 [string] $subscriptionName,
 [string] $resourceGroupName,
 [string] $storageAccountName,
 [string] $location,
 [string] $StorageAccountKey
)

 $entity = New-Object -TypeName Microsoft.WindowsAzure.Storage.Table.DynamicTableEntity -ArgumentList $partitionKey, $rowKey
 $entity.Properties.Add("Label_Value",$Label_Value)
 $entity.Properties.Add("Label_Usage",$Label_Usage)
 $entity.Properties.Add("Usage_Location",$Usage_Location)
 $result = $table.CloudTable.Execute([Microsoft.WindowsAzure.Storage.Table.TableOperation]::InsertOrReplace($entity))
}
$tableName = "sampletable"

# Get a storage context
$ctx = New-AzureStorageContext $StorageAccountName $StorageAccountKey

# Get a reference to the table
$table = Get-AzureStorageTable -Name $tableName -Context $ctx -ErrorAction Ignore
$csv = Import-CSV "d:\a\1\s\DeploymentScripts\sampletable.csv"

ForEach ($line in $csv)
{
 Add-Entity -Table $table -partitionKey $line.partitionkey -rowKey $line.RowKey -Label_Usage $line.Label_Usage -Label_Value $line.Label_Value -Usage_Location $line.Usage_Location

}
</code>```

答:
Your script doesn't take any parameters. You have a function in your script that takes parameters. A param block at the top of your script, outside of any functions, will make your script take parameters.

Ex:

```<code>param($A)

function Foo {
param($B)
  Write-Output $B
}

Foo -B $A
</code>```

Body:
I am running the below PowerShell Script to deploy csv file data into Azure table storage. But The below parameters are different for different environment in the azure.Suppose the below script can be deployed to any environment but the below parameters will be varied as per the environment.So I want to pass the below parameters to the script while running from the PowerShell task in VSTS.How to accomplish task.Please help me out on this.So

**$subscriptionName = "Tech Enabled Solutions"
$resourceGroupName = "abc"
$storageAccountName = "defghi"
$location = "North Central US, South Central US"
$StorageAccountKey = "12345678"**

PowerShell Script:

   function Add-Entity()
{
 [CmdletBinding()]

 param
 (
 $table,
 [string] $partitionKey,
 [string] $RowKey,
 [string] $Label_Usage,
 [string] $Label_Value,
 [string] $Usage_Location,
 [string] $subscriptionName,
 [string] $resourceGroupName,
 [string] $storageAccountName,
 [string] $location,
 [string] $StorageAccountKey
)

 $entity = New-Object -TypeName Microsoft.WindowsAzure.Storage.Table.DynamicTableEntity -ArgumentList $partitionKey, $rowKey
 $entity.Properties.Add("Label_Value",$Label_Value)
 $entity.Properties.Add("Label_Usage",$Label_Usage)
 $entity.Properties.Add("Usage_Location",$Usage_Location)
 $result = $table.CloudTable.Execute([Microsoft.WindowsAzure.Storage.Table.TableOperation]::InsertOrReplace($entity))
}
$tableName = "sampletable"

# Get a storage context
$ctx = New-AzureStorageContext $StorageAccountName $StorageAccountKey

# Get a reference to the table
$table = Get-AzureStorageTable -Name $tableName -Context $ctx -ErrorAction Ignore
$csv = Import-CSV "d:\a\1\s\DeploymentScripts\sampletable.csv"

ForEach ($line in $csv)
{
 Add-Entity -Table $table -partitionKey $line.partitionkey -rowKey $line.RowKey -Label_Usage $line.Label_Usage -Label_Value $line.Label_Value -Usage_Location $line.Usage_Location

}

Body:
Your script doesn't take any parameters. You have a function in your script that takes parameters. A param block at the top of your script, outside of any functions, will make your script take parameters.

Ex:

param($A)

function Foo {
param($B)
  Write-Output $B
}

Foo -B $A


问:
Codeigniter display relational data directly in view from model
How can I display data from model mdl_request inside view using ajax

this is my model:

```<code>function get_unit_measurement_by_id($id){
     $this->db->from('items', 'item_unit');
     $this->db->join('item_unit', 'item_unit.item_unit_id = items.item_unit_id');
     $this->db->where('item_unit', $id);
     $query = $this->db->get();
     return $query->row();
}
</code>```

this is my view:

```<code><?php
     foreach($requests as $request):
         echo  $this->mdl_request->get_unit_measurement_by_id($request->item_unit);
     endforeach;
?>
</code>```

答: You can't....In order to display your data straight from that function it needs to be in a controller.</p>

Body:
How can I display data from model mdl_request inside view using ajax

this is my model:

function get_unit_measurement_by_id($id){
     $this->db->from('items', 'item_unit');
     $this->db->join('item_unit', 'item_unit.item_unit_id = items.item_unit_id');
     $this->db->where('item_unit', $id);
     $query = $this->db->get();
     return $query->row();
}

this is my view:

<?php
     foreach($requests as $request):
         echo  $this->mdl_request->get_unit_measurement_by_id($request->item_unit);
     endforeach;
?>


问:
Create table at runtime with Ecto
According to this issue – Dynamic Models in Phoenix Framework – it is possible to dynamically create a model in Elixir using Module.create.

Is it also possible to create a table in the database for this model during runtime, i.e. without using Ecto migration files?

答:
PostgreSQL and MySQL adapters for Ecto 2.0+ have an ability to execute raw SQL:

```<code>qry =
  """
  CREATE TABLE `users` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `name` varchar(255) DEFAULT NULL,
    PRIMARY KEY (`id`)
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  """

res = Ecto.Adapters.SQL.query!(Repo, qry, [])
</code>```

Ecto.Adapters.SQL.query/4.

Another (might be preferred) way would be to just delegate this to underlying mysql shell executable:

```<code>System.cmd("mysql", ["#{create_table_script}"])
</code>```

ContentLicense: CC BY-SA 4.0

Title: Create table at runtime with Ecto

Body:
PostgreSQL and MySQL adapters for Ecto 2.0+ have an ability to execute raw SQL:

qry =
  """
  CREATE TABLE `users` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `name` varchar(255) DEFAULT NULL,
    PRIMARY KEY (`id`)
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  """

res = Ecto.Adapters.SQL.query!(Repo, qry, [])

Ecto.Adapters.SQL.query/4.

Another (might be preferred) way would be to just delegate this to underlying mysql shell executable:

System.cmd("mysql", ["#{create_table_script}"])


问:
Dealing with NULL time values in excel
I have been tasked to make an employee schedule in excel, and I am relatively new to excel. I have figured out how to subtract the end time for a day for an employee from the start time to get the amount of time the employee is scheduled to work each day. These fields are of type time.

Essentially, I need to add the time the employee worked each day to a week time total column and display that. The problem I am having is if there is no start time and/or no end time filled in for a specific day. The blank or null value ruins the formula.

I want to avoid entering a default value to assure the formula doesn't get screwed up, and would rather leave the start time and end time fields blank if the employee is not working that day so that it is more clear to the employee that he or she is not working that day.

So how do I deal with the possibility of a null value and how do I get the total time into a proper decimal number? Thanks for any help.

答:
You can use COUNT function to count how many times there are, e.g. this formula will return a blank unless you have times in both A2 and B2

=IF(COUNT(A2,B2)=2,B2-A2,"")

format as h:mm

That gives the result as a time value like 7:30 - if you want a decimal number of hours like 7.5 then multiply by 24

=IF(COUNT(A2,B2)=2,(B2-A2)*24,"")

format as number

and if you might have shifts that cross midnight like 23:00 - 07:00 then you can add in a MOD function to accommodate that too

=IF(COUNT(A2,B2)=2,MOD(B2-A2,1)*24,"")

In all cases for weekly total use SUM function to sum the cells with the above formula so that any blanks are ignored, e.g. with daily hours in C2, F2 and I2 use this formula for the total

=SUM(C2,F2,I2)

Title: Dealing with NULL time values in excel


问:
EntityManager null in QuartzJob
i've this issue using EntityManager on QuartzJob instance:

java.lang.NullPointerException
    at weblogic.persistence.CICScopedEMProvider.getEMForCurrentCIC(CICScopedEMProvider.java:35)
      at weblogic.persistence.TransactionalEntityManagerProxyImpl.getPersistenceContext(TransactionalEntityManagerProxyImpl.java:122)
      at weblogic.persistence.BasePersistenceContextProxyImpl.invoke(BasePersistenceContextProxyImpl.java:94)
      at weblogic.persistence.TransactionalEntityManagerProxyImpl.invoke(TransactionalEntityManagerProxyImpl.java:164)
      at weblogic.persistence.BasePersistenceContextProxyImpl.invoke(BasePersistenceContextProxyImpl.java:86)
      at com.sun.proxy.$Proxy321.createQuery(Unknown Source)
      at com.myproject.repository.impl.PhotoRepositoryImpl.getShotsFromBackupOption(PhotoRepositoryImpl.java:44)
      at com.myproject.service.impl.PhotoServiceImpl.getPhoto(PhotoServiceImpl.java:90)
      at com.myproject.monitor.BackupJob.execute(BackupJob.java:46)
      at org.quartz.core.JobRunShell.run(JobRunShell.java:202)
      at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:573)

This is my job:

```<code>public class BackupJob implements Job{
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Inject private PhotoService photoService;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        try {
            String jobName = context.getJobDetail().getKey().getName();
            Long jobGroup = Long.parseLong(context.getJobDetail().getKey().getGroup());

            List<File> fileList = photoService.getPhoto(jobName, jobGroup);

            logger.info("Backup with deep {}", context.getJobDetail().getJobDataMap().get("deep"));
        } catch (Exception e) {
            logger.error("ERROR during backup job", e);
        }
    }
}
</code>```

(photoService is correctly injected, same thing for my photoRepository method called in photoService)

This is my repository:

```<code>@Stateless
public class PhotoRepositoryImpl implements PhotoRepository{

    @PersistenceContext(unitName=Constant.PU_NAME)
    private EntityManager em;

    @Override
    public List<Photo> getShotsFromBackupOption(String jobName, Long jobGroup) throws SQLException{

        Query query = em.createQuery("SELECT p "
                                    + "FROM Shot s "
                                    + "JOIN Photo p "
                                    + "WHERE s.dateShooting < "
                                        + "(SELECT b.previousThan "
                                        + "FROM BackupOption b "
                                        + "WHERE b.jobName = :jobName AND b.syncType.id = :jobGroup)"
                                    + "ORDER BY p.relativePath DESC");
        query.setParameter("jobName", jobName);
        query.setParameter("jobGroup", jobGroup);

        return (List<Photo>) query.getResultList();
    }
}
</code>```

This is my job factory

```<code>public class JobFactoryImpl implements JobFactory {

@Inject
private Instance<Job> jobs;

@Override
public Job newJob(TriggerFiredBundle triggerFiredBundle, Scheduler scheduler) throws SchedulerException {
    final JobDetail jobDetail = triggerFiredBundle.getJobDetail();
    final Class<? extends Job> jobClass = jobDetail.getJobClass();

    for (Job job : jobs) {
        if (job.getClass().isAssignableFrom(jobClass)) {
            return job;
        }
    }

    throw new RuntimeException("Cannot create a Job of type " + jobClass);
}}
</code>```

NullPointerException is thrown on em.createquery(---) method.
This query works nice when method is called out of my QuartzJob.
Do you have some nice workaround for this?

答:
I solved getting EntityManager in this way:</p>

```<code>@PersistenceUnit(unitName= Constant.PU_NAME)
private EntityManagerFactory emf;

private EntityManager em = emf.createEntityManager();
</code>```

Title: EntityManager null in QuartzJob

Body:
i've this issue using EntityManager on QuartzJob instance:

java.lang.NullPointerException
    at weblogic.persistence.CICScopedEMProvider.getEMForCurrentCIC(CICScopedEMProvider.java:35)
      at weblogic.persistence.TransactionalEntityManagerProxyImpl.getPersistenceContext(TransactionalEntityManagerProxyImpl.java:122)
      at weblogic.persistence.BasePersistenceContextProxyImpl.invoke(BasePersistenceContextProxyImpl.java:94)
      at weblogic.persistence.TransactionalEntityManagerProxyImpl.invoke(TransactionalEntityManagerProxyImpl.java:164)
      at weblogic.persistence.BasePersistenceContextProxyImpl.invoke(BasePersistenceContextProxyImpl.java:86)
      at com.sun.proxy.$Proxy321.createQuery(Unknown Source)
      at com.myproject.repository.impl.PhotoRepositoryImpl.getShotsFromBackupOption(PhotoRepositoryImpl.java:44)
      at com.myproject.service.impl.PhotoServiceImpl.getPhoto(PhotoServiceImpl.java:90)
      at com.myproject.monitor.BackupJob.execute(BackupJob.java:46)
      at org.quartz.core.JobRunShell.run(JobRunShell.java:202)
      at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:573)

This is my job:

public class BackupJob implements Job{
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Inject private PhotoService photoService;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        try {
            String jobName = context.getJobDetail().getKey().getName();
            Long jobGroup = Long.parseLong(context.getJobDetail().getKey().getGroup());

            List<File> fileList = photoService.getPhoto(jobName, jobGroup);

            logger.info("Backup with deep {}", context.getJobDetail().getJobDataMap().get("deep"));
        } catch (Exception e) {
            logger.error("ERROR during backup job", e);
        }
    }
}

(photoService is correctly injected, same thing for my photoRepository method called in photoService)

This is my repository:

@Stateless
public class PhotoRepositoryImpl implements PhotoRepository{

    @PersistenceContext(unitName=Constant.PU_NAME)
    private EntityManager em;

    @Override
    public List<Photo> getShotsFromBackupOption(String jobName, Long jobGroup) throws SQLException{

        Query query = em.createQuery("SELECT p "
                                    + "FROM Shot s "
                                    + "JOIN Photo p "
                                    + "WHERE s.dateShooting < "
                                        + "(SELECT b.previousThan "
                                        + "FROM BackupOption b "
                                        + "WHERE b.jobName = :jobName AND b.syncType.id = :jobGroup)"
                                    + "ORDER BY p.relativePath DESC");
        query.setParameter("jobName", jobName);
        query.setParameter("jobGroup", jobGroup);

        return (List<Photo>) query.getResultList();
    }
}

This is my job factory

public class JobFactoryImpl implements JobFactory {

@Inject
private Instance<Job> jobs;

@Override
public Job newJob(TriggerFiredBundle triggerFiredBundle, Scheduler scheduler) throws SchedulerException {
    final JobDetail jobDetail = triggerFiredBundle.getJobDetail();
    final Class<? extends Job> jobClass = jobDetail.getJobClass();

    for (Job job : jobs) {
        if (job.getClass().isAssignableFrom(jobClass)) {
            return job;
        }
    }

    throw new RuntimeException("Cannot create a Job of type " + jobClass);
}}

NullPointerException is thrown on em.createquery(---) method.
This query works nice when method is called out of my QuartzJob.
Do you have some nice workaround for this?

Body:
I solved getting EntityManager in this way:

@PersistenceUnit(unitName= Constant.PU_NAME)
private EntityManagerFactory emf;

private EntityManager em = emf.createEntityManager();


问:
VBA Calling a private function inside of a userform
I have a userform defined as "SingleListForm".
I have a private sub named "loadSingleListForm(ID As Double)"
I am attempting to pass a variable into the form and I was implementing it in the fashion that loadSingleListForm would set the form up based on ID, basically re-using one form to show variable data from variable sources in the listbox.

But calling a standard Intersect from  outside the form (Worksheet_SelectionChange) these two options compile but do not work.

```<code>Application.Run "SingleListForm.loadSingleListForm", ID 'ID already declared and assigned
</code>```

This doesn't work either

```<code>Call ActiveWorkbook.UserForm("SingleListForm").loadSingleListForm(ID)
</code>```

Where it says UserForm I have also tried SingleListForm.
Here the runtime error is:

I am trying hard not to use a Global Variable here to pass to the form.
Perhaps I should go to Initialize and try something there.
I am trying to pass the variable to the form and then of course set up the form based on this case and then show the form.  you can't pass with show so you have to find another way to set up.

I just realized I have not called a userform private function from outside of the form before, but I do it with modules all the time.  The first case works in that instance.

Cheers,
-WWC

答:
The better way to do this is to declare a property to the form. In the form's module enter

```<code>  Option Explicit
  Private myID as double

  Property Set ID(i as double)
     myID = i
  End Property
</code>```

Then your function

```<code>   Private Sub loadSingleListForm()
     can refer to myID with in it's code
</code>```

To Use this from outside modules you use

```<code>   Load SingleListForm
   SingleListForm.ID = ID 'ID variable already declared
</code>```

Body:
I have a userform defined as "SingleListForm".
I have a private sub named "loadSingleListForm(ID As Double)"
I am attempting to pass a variable into the form and I was implementing it in the fashion that loadSingleListForm would set the form up based on ID, basically re-using one form to show variable data from variable sources in the listbox.

But calling a standard Intersect from  outside the form (Worksheet_SelectionChange) these two options compile but do not work.

Application.Run "SingleListForm.loadSingleListForm", ID 'ID already declared and assigned

This doesn't work either

Call ActiveWorkbook.UserForm("SingleListForm").loadSingleListForm(ID)

Where it says UserForm I have also tried SingleListForm.
Here the runtime error is:

I am trying hard not to use a Global Variable here to pass to the form.
Perhaps I should go to Initialize and try something there.
I am trying to pass the variable to the form and then of course set up the form based on this case and then show the form.  you can't pass with show so you have to find another way to set up.

I just realized I have not called a userform private function from outside of the form before, but I do it with modules all the time.  The first case works in that instance.

Cheers,
-WWC

Body:
The better way to do this is to declare a property to the form. In the form's module enter

  Option Explicit
  Private myID as double

  Property Set ID(i as double)
     myID = i
  End Property

Then your function

   Private Sub loadSingleListForm()
     can refer to myID with in it's code

To Use this from outside modules you use

   Load SingleListForm
   SingleListForm.ID = ID 'ID variable already declared


问:
SQL Finding MAX number in a VARCHAR typed column
I have got SQL table where I have column DISTANCE (varchar50). It's number with dot.

```<code>+----+--------+--------+----------+
| ID | USERID | MONTH  | DISTANCE |
+----+--------+--------+----------+
| 1  |    1   | 201707 |   7.25   |
+----+--------+--------+----------+
| 2  |    2   | 201707 |   9.17   |
+----+--------+--------+----------+
| 3  |    2   | 201707 |  10.31   |
+----+--------+--------+----------+
| 4  |    1   | 201706 |  10.08   |
+----+--------+--------+----------+
</code>```

I would like to display MAX value od DISTANCE. If I ORDER BY distance DESC the result is:

```<code>SELECT * FROM mytable ORDER BY distance DESC
9.17
7.25
10.31
10.08
</code>```

I try to find the MAX but still is not correct

```<code>SELECT MAX(distance) AS mvzd FROM mytable
9.17
</code>```

How I can have correct max distance value which should be 10.31 with the provided sample data ?

答:
PROBLEM

SOLUTION

You can use the following query :

```<code>select max(cast(distance as decimal(10,2))) AS mvzd FROM mytable
</code>```

By your existing query, you are finding MAX on a VARCHAR typed column and you are getting correct result what you wrote! If you want to have your desired result, first you have to convert the type of that column like i did in the above query.

Body:
I have got SQL table where I have column DISTANCE (varchar50). It's number with dot.

+----+--------+--------+----------+
| ID | USERID | MONTH  | DISTANCE |
+----+--------+--------+----------+
| 1  |    1   | 201707 |   7.25   |
+----+--------+--------+----------+
| 2  |    2   | 201707 |   9.17   |
+----+--------+--------+----------+
| 3  |    2   | 201707 |  10.31   |
+----+--------+--------+----------+
| 4  |    1   | 201706 |  10.08   |
+----+--------+--------+----------+

I would like to display MAX value od DISTANCE. If I ORDER BY distance DESC the result is:

SELECT * FROM mytable ORDER BY distance DESC
9.17
7.25
10.31
10.08

I try to find the MAX but still is not correct

SELECT MAX(distance) AS mvzd FROM mytable
9.17

How I can have correct max distance value which should be 10.31 with the provided sample data ?

Body:
PROBLEM

SOLUTION

You can use the following query :

select max(cast(distance as decimal(10,2))) AS mvzd FROM mytable

By your existing query, you are finding MAX on a VARCHAR typed column and you are getting correct result what you wrote! If you want to have your desired result, first you have to convert the type of that column like i did in the above query.


问:
How can i make this media query work to see the menu vertically?
I created this small icon menu with the help of a tutorial and I am trying to make it responsive, but it is not working.

When the width is 400px I want the menu to be vertical.

body {
  margin: 0px;
}

.cuadro {
  width: 100%;
  background-color: pink;
  overflow: auto;
}

.cuadro a {
  float: left;
  text-align: center;
  width: 20%;
  padding: 12px 0;
  transition: all 0.3s ease;
  color: white;
  font-size: 36px;
}

.cuadro a:hover {
  background-color: green;
}

.active {
  background-color: purple !important;
}

@media only screen and (max-width: 414px) {
  body {
    margin: 0px;
  }
  .cuadro {
    position: fixed;
    width: 414px;
    text-align: center;
    color: white;
    font-size: 36px
  }
  .cuadro a {
    background-color: pink;
    display: block;
    padding: 16px;
    color: white;
  }
  .cuadro a:hover {
    transition: all 0.3s ease;
    background-color: green;
  }
  .active {
    background-color: purple !important;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <title>Title</title>
  <meta charset="utf-8">
  <meta content="viewport" content="width=device-width initial-scale=1">
  <script src="https://use.fontawesome.com/ea180863a6.js"></script>
</head>

<body>
  <div class="cuadro">
    <i class="fa fa-skype" aria-hidden="true"></i>
    <i class="fa fa-spotify" aria-hidden="true"></i>
    <i class="fa fa-snapchat-ghost" aria-hidden="true"></i>
    <i class="fa fa-whatsapp" aria-hidden="true"></i>
    <i class="fa fa-vk" aria-hidden="true"></i>
  </div>
</body>

</html></code>```

What am I doing wrong?

答:
You are almost good, simply make the menu item float:none and width:100% in the media query. You may also add box-sizing:border-box to avoid having overflow issue and you don't need to specify a width for .cuadro inside the media query :

body {
  margin: 0px;
}

.cuadro {
  width: 100%;
  background-color: pink;
  overflow: auto;
}

.cuadro a {
  float: left;
  text-align: center;
  width: 20%;
  padding: 12px 0;
  transition: all 0.3s ease;
  color: white;
  font-size: 36px;
  box-sizing:border-box;
}

.cuadro a:hover {
  background-color: green;
}

.active {
  background-color: purple !important;
}

@media all and (max-width: 414px) {
  .cuadro {
    position: fixed;
    width: 100%;
    text-align: center;
    color: white;
    font-size: 36px
  }
  .cuadro a {
    background-color: pink;
    display: block;
    width:100%;
    padding: 16px;
    color: white;
    float:none;
  }
  .cuadro a:hover {
    transition: all 0.3s ease;
    background-color: green;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>

  <title>Title</title>
  <meta charset="utf-8">
  <meta content="viewport" content="width=device-width initial-scale=1">
  <script src="https://use.fontawesome.com/ea180863a6.js"></script>
  <style>

  </style>
</head>

<body>

  <div class="cuadro">
    <i class="fa fa-skype" aria-hidden="true"></i>
    <i class="fa fa-spotify" aria-hidden="true"></i>
    <i class="fa fa-snapchat-ghost" aria-hidden="true"></i>
    <i class="fa fa-whatsapp" aria-hidden="true"></i>
    <i class="fa fa-vk" aria-hidden="true"></i>
  </div>

</body>

</html></code>```

Body:
I created this small icon menu with the help of a tutorial and I am trying to make it responsive, but it is not working.

When the width is 400px I want the menu to be vertical.

body {
  margin: 0px;
}

.cuadro {
  width: 100%;
  background-color: pink;
  overflow: auto;
}

.cuadro a {
  float: left;
  text-align: center;
  width: 20%;
  padding: 12px 0;
  transition: all 0.3s ease;
  color: white;
  font-size: 36px;
}

.cuadro a:hover {
  background-color: green;
}

.active {
  background-color: purple !important;
}

@media only screen and (max-width: 414px) {
  body {
    margin: 0px;
  }
  .cuadro {
    position: fixed;
    width: 414px;
    text-align: center;
    color: white;
    font-size: 36px
  }
  .cuadro a {
    background-color: pink;
    display: block;
    padding: 16px;
    color: white;
  }
  .cuadro a:hover {
    transition: all 0.3s ease;
    background-color: green;
  }
  .active {
    background-color: purple !important;
  }
}

<!DOCTYPE html>

  <title>Title</title>
  <meta charset="utf-8">
  <meta content="viewport" content="width=device-width initial-scale=1">

What am I doing wrong?

Body:
You are almost good, simply make the menu item float:none and width:100% in the media query. You may also add box-sizing:border-box to avoid having overflow issue and you don't need to specify a width for .cuadro inside the media query :

body {
  margin: 0px;
}

.cuadro {
  width: 100%;
  background-color: pink;
  overflow: auto;
}

.cuadro a {
  float: left;
  text-align: center;
  width: 20%;
  padding: 12px 0;
  transition: all 0.3s ease;
  color: white;
  font-size: 36px;
  box-sizing:border-box;
}

.cuadro a:hover {
  background-color: green;
}

.active {
  background-color: purple !important;
}

@media all and (max-width: 414px) {
  .cuadro {
    position: fixed;
    width: 100%;
    text-align: center;
    color: white;
    font-size: 36px
  }
  .cuadro a {
    background-color: pink;
    display: block;
    width:100%;
    padding: 16px;
    color: white;
    float:none;
  }
  .cuadro a:hover {
    transition: all 0.3s ease;
    background-color: green;
  }
}

<!DOCTYPE html>
<html>

<head>

  <title>Title</title>
  <meta charset="utf-8">
  <meta content="viewport" content="width=device-width initial-scale=1">
  <script src="https://use.fontawesome.com/ea180863a6.js"></script>
  <style>

  </style>
</head>

<body>

  <div class="cuadro">
    <a class="active" href="#"><i class="fa fa-skype" aria-hidden="true"></i></a>
    <a href="#"><i class="fa fa-spotify" aria-hidden="true"></i></a>
    <a href="#"><i class="fa fa-snapchat-ghost" aria-hidden="true"></i></a>
    <a href="#"><i class="fa fa-whatsapp" aria-hidden="true"></i></a>
    <a href="#"><i class="fa fa-vk" aria-hidden="true"></i></a>
  </div>

</body>

</html>


问:
Client must have ACCESS_FINE_LOCATION permission to request PRIORITY_HIGH_ACCURACY locations runtime error
There are plenty of similar questions asked but none seem to solve my problem.

I have applied run time permissions as mentioned on the documentation, still I am getting a run time error on the line

```<code>LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
</code>```

Here is my complete code.

```<code>public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener,LocationListener {

private static final String TAG ="hello" ;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;

public Location mLastLocation=null;

public final int MY_PERMISSIONS_REQUEST_COARSE_LOCATION=0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (mGoogleApiClient==null){
        mGoogleApiClient= new GoogleApiClient.Builder(this)

                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }

    mLocationRequest = LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
            .setInterval(10 * 100)        // 10 seconds, in milliseconds
            .setFastestInterval( 1* 100); // 1 second, in milliseconds

    }

@Override
public void onConnected(@Nullable Bundle bundle) {

    int permissionCheck = ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION);
    int permissionCheck1 = ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_COARSE_LOCATION);
    if (permissionCheck != PackageManager
            .PERMISSION_GRANTED && permissionCheck1 != PackageManager.PERMISSION_GRANTED) {

        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_FINE_LOCATION)) {

            // Show an explanation to the user *asynchronously* -- don't block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.

        } else {

            // No explanation needed, we can request the permission.

            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_COARSE_LOCATION);

        }
    }

    mLastLocation=LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    if (mLastLocation != null) {
        TextView mLatitudeText =(TextView)findViewById(R.id.textView);
        TextView mLongitudeText =(TextView)findViewById(R.id.textView2);

        mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
        mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));

        Log.i("Location Info", "Location achieved!");

    } else {

        Log.i("Location Info", "No location :(");

    }

    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);//error here!!

}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}

@Override
protected void onResume() {
    mGoogleApiClient.connect();
    super.onResume();

}

@Override
protected void onPause() {
    mGoogleApiClient.disconnect();
    super.onPause();
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode) {
        case  MY_PERMISSIONS_REQUEST_COARSE_LOCATION :{
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                Log.i("Message","Got full permission");

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }

}

@Override
public void onLocationChanged(Location location)
{
    Log.i("Location Info", "Location is changed Bitchh :(");
    handleNewLocation(location);
}

private void handleNewLocation(Location location) {
    Log.d(TAG, location.toString());
}
</code>```

}

Also I have given permission in the manifest file.

So, this is the error stack trace on run time

10-24 17:13:02.857 2224-2379/com.example.ashutosh.location E/AbstractTracker: Can't create handler inside thread that has not called Looper.prepare()
  0-24 17:13:03.184 2224-2224/com.example.ashutosh.location E/AndroidRuntime: FATAL EXCEPTION: main
                                                                               Process: com.example.ashutosh.location, PID: 2224
                                                                               java.lang.SecurityException: Client must have ACCESS_FINE_LOCATION permission to request PRIORITY_HIGH_ACCURACY locations.
                                                                                at android.os.Parcel.readException(Parcel.java:1620)
                                                                                at android.os.Parcel.readException(Parcel.java:1573)
                                                                                at com.google.android.gms.internal.zzed.zzb(Unknown Source)
                                                                                at com.google.android.gms.internal.zzcda.zza(Unknown Source)
                                                                                at com.google.android.gms.internal.zzcdd.zza(Unknown Source)
                                                                                at com.google.android.gms.internal.zzcdj.zza(Unknown Source)
                                                                                at com.google.android.gms.internal.zzccc.zza(Unknown Source)
                                                                                at com.google.android.gms.internal.zzbay.zzb(Unknown Source)
                                                                                at com.google.android.gms.internal.zzbca.zze(Unknown Source)
                                                                                at com.google.android.gms.internal.zzbcx.zze(Unknown Source)
                                                                                at com.google.android.gms.internal.zzbcp.zze(Unknown Source)
                                                                                at com.google.android.gms.internal.zzccb.requestLocationUpdates(Unknown Source)
                                                                                at com.example.ashutosh.location.MainActivity.onConnected(MainActivity.java:122)
                                                                                at com.google.android.gms.common.internal.zzac.zzn(Unknown Source)
                                                                                at com.google.android.gms.internal.zzbcp.zzm(Unknown Source)
                                                                                at com.google.android.gms.internal.zzbcd.zzpY(Unknown Source)
                                                                                at com.google.android.gms.internal.zzbcd.onConnected(Unknown Source)
                                                                                at com.google.android.gms.internal.zzbcx.onConnected(Unknown Source)
                                                                                at com.google.android.gms.internal.zzbbi.onConnected(Unknown Source)
                                                                                at com.google.android.gms.common.internal.zzaa.onConnected(Unknown Source)
                                                                                at com.google.android.gms.common.internal.zzn.zzrj(Unknown Source)
                                                                                at com.google.android.gms.common.internal.zze.zzs(Unknown Source)
                                                                                at com.google.android.gms.common.internal.zzi.zzrk(Unknown Source)
                                                                                at com.google.android.gms.common.internal.zzh.handleMessage(Unknown Source)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:152)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5497)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

答:
I hate the following solution but I did not find any better.
If you request location API from Google API's and you do: .addApi(LocationServices.API), you need to have location permitted before connecting GoogleAPI's.

Thus,

```<code>fun checkPermission(context:Context, permission:Name) : Boolean =
    ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED

fun isLocationPermissionGranted() = checkPermission(context, Manifest.permission.ACCESS_FINE_LOCATION)

if (isLocationPermissionGranted()) {
     googleApiBuilder.connect()
} else {
     MyPermissionChangeRegistrar().instance.register {
          if (isLocationPermissionGranted()) {
               googleApiBuilder.connect()
          }
     }
}
</code>```

When the Permission registrar is a class that calls a callback when a permission changed

```<code>class SomeActivity: Activity() {
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        MyPermissionChangeRegistrar.callCallbacks()
    }
}
</code>```

IMMHO, Google ought to protect against such cases internally. But they don't.

Body:
There are plenty of similar questions asked but none seem to solve my problem.

I have applied run time permissions as mentioned on the documentation, still I am getting a run time error on the line

LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);

Here is my complete code.

public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener,LocationListener {

private static final String TAG ="hello" ;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;

public Location mLastLocation=null;

public final int MY_PERMISSIONS_REQUEST_COARSE_LOCATION=0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (mGoogleApiClient==null){
        mGoogleApiClient= new GoogleApiClient.Builder(this)

                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }

    mLocationRequest = LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
            .setInterval(10 * 100)        // 10 seconds, in milliseconds
            .setFastestInterval( 1* 100); // 1 second, in milliseconds

    }

@Override
public void onConnected(@Nullable Bundle bundle) {

    int permissionCheck = ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION);
    int permissionCheck1 = ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_COARSE_LOCATION);
    if (permissionCheck != PackageManager
            .PERMISSION_GRANTED && permissionCheck1 != PackageManager.PERMISSION_GRANTED) {

        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_FINE_LOCATION)) {

            // Show an explanation to the user *asynchronously* -- don't block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.

        } else {

            // No explanation needed, we can request the permission.

            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_COARSE_LOCATION);

        }
    }

    mLastLocation=LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    if (mLastLocation != null) {
        TextView mLatitudeText =(TextView)findViewById(R.id.textView);
        TextView mLongitudeText =(TextView)findViewById(R.id.textView2);

        mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
        mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));

        Log.i("Location Info", "Location achieved!");

    } else {

        Log.i("Location Info", "No location :(");

    }

    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);//error here!!

}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}

@Override
protected void onResume() {
    mGoogleApiClient.connect();
    super.onResume();

}

@Override
protected void onPause() {
    mGoogleApiClient.disconnect();
    super.onPause();
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode) {
        case  MY_PERMISSIONS_REQUEST_COARSE_LOCATION :{
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                Log.i("Message","Got full permission");

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }

}

@Override
public void onLocationChanged(Location location)
{
    Log.i("Location Info", "Location is changed Bitchh :(");
    handleNewLocation(location);
}

private void handleNewLocation(Location location) {
    Log.d(TAG, location.toString());
}

}

Also I have given permission in the manifest file.

So, this is the error stack trace on run time

10-24 17:13:02.857 2224-2379/com.example.ashutosh.location E/AbstractTracker: Can't create handler inside thread that has not called Looper.prepare()
  0-24 17:13:03.184 2224-2224/com.example.ashutosh.location E/AndroidRuntime: FATAL EXCEPTION: main
                                                                               Process: com.example.ashutosh.location, PID: 2224
                                                                               java.lang.SecurityException: Client must have ACCESS_FINE_LOCATION permission to request PRIORITY_HIGH_ACCURACY locations.
                                                                                at android.os.Parcel.readException(Parcel.java:1620)
                                                                                at android.os.Parcel.readException(Parcel.java:1573)
                                                                                at com.google.android.gms.internal.zzed.zzb(Unknown Source)
                                                                                at com.google.android.gms.internal.zzcda.zza(Unknown Source)
                                                                                at com.google.android.gms.internal.zzcdd.zza(Unknown Source)
                                                                                at com.google.android.gms.internal.zzcdj.zza(Unknown Source)
                                                                                at com.google.android.gms.internal.zzccc.zza(Unknown Source)
                                                                                at com.google.android.gms.internal.zzbay.zzb(Unknown Source)
                                                                                at com.google.android.gms.internal.zzbca.zze(Unknown Source)
                                                                                at com.google.android.gms.internal.zzbcx.zze(Unknown Source)
                                                                                at com.google.android.gms.internal.zzbcp.zze(Unknown Source)
                                                                                at com.google.android.gms.internal.zzccb.requestLocationUpdates(Unknown Source)
                                                                                at com.example.ashutosh.location.MainActivity.onConnected(MainActivity.java:122)
                                                                                at com.google.android.gms.common.internal.zzac.zzn(Unknown Source)
                                                                                at com.google.android.gms.internal.zzbcp.zzm(Unknown Source)
                                                                                at com.google.android.gms.internal.zzbcd.zzpY(Unknown Source)
                                                                                at com.google.android.gms.internal.zzbcd.onConnected(Unknown Source)
                                                                                at com.google.android.gms.internal.zzbcx.onConnected(Unknown Source)
                                                                                at com.google.android.gms.internal.zzbbi.onConnected(Unknown Source)
                                                                                at com.google.android.gms.common.internal.zzaa.onConnected(Unknown Source)
                                                                                at com.google.android.gms.common.internal.zzn.zzrj(Unknown Source)
                                                                                at com.google.android.gms.common.internal.zze.zzs(Unknown Source)
                                                                                at com.google.android.gms.common.internal.zzi.zzrk(Unknown Source)
                                                                                at com.google.android.gms.common.internal.zzh.handleMessage(Unknown Source)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:152)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5497)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Body:
I hate the following solution but I did not find any better.
If you request location API from Google API's and you do: .addApi(LocationServices.API), you need to have location permitted before connecting GoogleAPI's.

Thus,

fun checkPermission(context:Context, permission:Name) : Boolean =
    ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED

fun isLocationPermissionGranted() = checkPermission(context, Manifest.permission.ACCESS_FINE_LOCATION)

if (isLocationPermissionGranted()) {
     googleApiBuilder.connect()
} else {
     MyPermissionChangeRegistrar().instance.register {
          if (isLocationPermissionGranted()) {
               googleApiBuilder.connect()
          }
     }
}

When the Permission registrar is a class that calls a callback when a permission changed

class SomeActivity: Activity() {
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        MyPermissionChangeRegistrar.callCallbacks()
    }
}

IMMHO, Google ought to protect against such cases internally. But they don't.


问:
Bootstrap4 hide show columns
I need to be able to hide/show columns based upon the screen size.

Example:

When the screen is eXtra Small <576px, I want 2 columns to show

When the screen is MeDium ≥768px, I want 4 columns to show

When the screen is eXtra Large ≥1200, I want 6 columns to show.

There are several hundred rows, so I don't want 3 tables, just the columns to show or hide based upon size.

JS Fiddle at:
https://jsfiddle.net/tkcynbjk/

```<code><div class="row">
    <div class="col-sm-12">
        <table class="table table-striped">
            <thead>
            <tr>
                <th class="d-none d-table-cell" scope="col">ALWAYS 1</th>
                <th class="d-none d-table-cell" scope="col">ALWAYS 2</th>
                <th class="d-none d-table-cell d-md-table-cell" scope="col">MED 1</th>
                <th class="d-none d-table-cell d-xl-table-cell" scope="col">XL ONLY 1</th>
                <th class="d-none d-table-cell d-md-table-cell" scope="col">MED 2</th>
                <th class="d-none d-table-cell d-xl-table-cell" scope="col">XL ONLY 2</th>
            </tr>
            </thead>
            <tbody>
                <tr>
                    <td>A</td>
                    <td>B</td>
                    <td>C</td>
                    <td>D</td>
                    <td>E</td>
                    <td>F</td>
                </tr>
            </tbody>
        </table>
    </div>
</div>
</code>```

答:
It should work when you remove the d-table-cell classes.

Run the snippet full-screen to see the media queries work, or check out your updated fiddle: https://jsfiddle.net/jkrielaars/tkcynbjk/1/

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>

                    ALWAYS 1
                    ALWAYS 2
                    MED 1
                    XL ONLY 1
                    MED 2
                    XL ONLY 2

                        A
                        B
                        C
                        D
                        E
                        F

```

Title: Bootstrap4 hide show columns

Body:
I need to be able to hide/show columns based upon the screen size.

Example:

When the screen is eXtra Small <576px, I want 2 columns to show

When the screen is MeDium ≥768px, I want 4 columns to show

When the screen is eXtra Large ≥1200, I want 6 columns to show.

There are several hundred rows, so I don't want 3 tables, just the columns to show or hide based upon size.

JS Fiddle at:
https://jsfiddle.net/tkcynbjk/

                ALWAYS 1
                ALWAYS 2
                MED 1
                XL ONLY 1
                MED 2
                XL ONLY 2

                    A
                    B
                    C
                    D
                    E
                    F

Body:
It should work when you remove the d-table-cell classes.

Run the snippet full-screen to see the media queries work, or check out your updated fiddle: https://jsfiddle.net/jkrielaars/tkcynbjk/1/

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>
    <div class="row">
        <div class="col-sm-12">
            <table class="table table-striped">
                <thead>
                <tr>
                    <th class="" scope="col">ALWAYS 1</th>
                    <th class="" scope="col">ALWAYS 2</th>
                    <th class="d-none d-md-table-cell" scope="col">MED 1</th>
                    <th class="d-none d-xl-table-cell" scope="col">XL ONLY 1</th>
                    <th class="d-none d-md-table-cell" scope="col">MED 2</th>
                    <th class="d-none d-xl-table-cell" scope="col">XL ONLY 2</th>
                </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>A</td>
                        <td>B</td>
                        <td  class="d-none d-md-table-cell">C</td>
                        <td class="d-none d-xl-table-cell">D</td>
                        <td class="d-none d-md-table-cell">E</td>
                        <td class="d-none d-xl-table-cell">F</td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>


问:
Hide and show text by click on div
I have a question concerning an event onclick. I found this code during my research. My question is : even before the click the text already appears, is it possible to hide the text until we click on the actual button. And is it possible to have numerous onclick event working seperately that is o say only open the text above it? Thank you

  <title>Show and hide div with JavaScript</title>

This div will be show and hide on button click

  <button id="button" onclick="showhide()">Click Me</button>

```

答:
make it by default as none in style on display property.</p>

```<code><div id="newpost" style="display:none">
    <p>This div will be show and hide on button click</p>
  </div>
</code>```

Title: Hide and show text by click on div

Body:
make it by default as none in style on display property.

<div id="newpost" style="display:none">
    <p>This div will be show and hide on button click</p>
  </div>


问:
How to use properly BigInteger methods in Java?
I'm trying to do the factorial of a number using this method:

```<code>public static BigInteger factorial (long n) {
    BigInteger result = BigInteger.ONE;
    for(BigInteger i = BigInteger.TWO; i.compareTo(BigInteger.valueOf(n)) >= 0; i = i.add(BigInteger.ONE)) {
        result = result.multiply(i);
    }
    return result;
}
</code>```

and I'm asking why te result stays always 1 (BigInteger.ONE) ?

答:
See the definition of compareTo(T o)

Returns: a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

You are using >= 0 meaning continue looping while i is greater than n.

You probably need <= 0.

Body:
I'm trying to do the factorial of a number using this method:

public static BigInteger factorial (long n) {
    BigInteger result = BigInteger.ONE;
    for(BigInteger i = BigInteger.TWO; i.compareTo(BigInteger.valueOf(n)) >= 0; i = i.add(BigInteger.ONE)) {
        result = result.multiply(i);
    }
    return result;
}

and I'm asking why te result stays always 1 (BigInteger.ONE) ?


问:
Any reason not to start using the HTML 5 doctype?

It is supposed to be backwards compatible with HTML4 and XHTML. John Resig posted about some of the benefits.

As long as we don't use any of the new and not supported yet features, would there be any downside to start building sites with this doctype?

答:
Take a look at this blog post! Not really a fan of HTML5
http://www.webscienceman.com/2009/01/24/html-xhtml-html5-future-html/</p>

OwnerDisplayName: Sonia Marras


问:
use 'perf trace command' to a special thread with TSX abort

I try to use 'perf trace' command to trace tsx abort in a special thread. But I get errors with arguments. All command I think may be right and tried is below.

```<code>perf trace --pid 24265 --event tx-abort

perf trace --pid 24265 --event {tx-abort}

perf trace --pid 24265 --event {'tx-abort'}

perf trace --pid {24265} --event tx-abort

perf trace --pid {24265} --event {tx-abort}

perf trace --pid {24265} --event {'tx-abort'}

perf trace --pid {'24265'} --event tx-abort

perf trace --pid {'24265'} --event {tx-abort}

perf trace --pid {'24265'} --event {'tx-abort'}
</code>```

All error hins is 'Problems parsing the target to trace,check your options'.

Is there any way to let perf trace run as expected?

答:
The issue is not the argument syntax, your first line should be just fine. First, check if tx-abort is listed by perf list, to see if it's generally supported on your system. Then the error may happen because the specified pid does not exist.

The TSX events are PMU events. As opposed to syscalls or tracepoints, not the individual event is instrumented in software, but there is a hardware counter within the Performance Monitoring Unit, that counts these events and triggers an interrupt after a certain amount of events. Taking a sample on each event is not typically feasible for PMU events. I suspect that is why it doesn't work for perf trace, which is originally intended for syscalls, even though the documentation a bit vague as to what type of events are supported.

Note I can reproduce that it doesn't work, but i get an "Invalid argument".  That PMU events are unsupported for perf trace is a a bit of speculation by me.

There is a broad documentation by Intel on analyzing TSX with perf, which gives examples and explanation on how to use the the tx events with perf record.

Body:
I try to use 'perf trace' command to trace tsx abort in a special thread. But I get errors with arguments. All command I think may be right and tried is below.

perf trace --pid 24265 --event tx-abort

perf trace --pid 24265 --event {tx-abort}

perf trace --pid 24265 --event {'tx-abort'}

perf trace --pid {24265} --event tx-abort

perf trace --pid {24265} --event {tx-abort}

perf trace --pid {24265} --event {'tx-abort'}

perf trace --pid {'24265'} --event tx-abort

perf trace --pid {'24265'} --event {tx-abort}

perf trace --pid {'24265'} --event {'tx-abort'}

All error hins is 'Problems parsing the target to trace,check your options'.

Is there any way to let perf trace run as expected?


问:
MongoDB sharded cluster using docker with persistent storage issue

I have been able to create a sharded cluster using docker which has 3 shards and each shard is a replica set, and each member of the replica set has persistent storage which I have tested and works.

The issue is, when I stop and delete the docker containers and then bring them up again to use the same persistent storage the shards do not attach to the cluster, after googling I believe this is because they have already been attached to a cluster previously.

Output of sh.status( { verbose : 1 } ) shows no shards

Output of sh.addShard("a/mongo-shard-a0:27017") shows:

```<code>"errmsg" : "E11000 duplicate key error collection: admin.system.version index: _id_ dup key: { : \"shardIdentity\" }"
</code>```

I naively presumed that when the docker containers came back and pointed towards the same data directory the cluster would be as it was before deleting the containers.

Any help with this one is much appreciated, thank you.

答: The issue was that I was setting up persistent storage to the /data/db directory for the configsvr's where in actual fact I need to mount the persistent storage within the docker file to the /data/configdb directory.</p>

Body:
I have been able to create a sharded cluster using docker which has 3 shards and each shard is a replica set, and each member of the replica set has persistent storage which I have tested and works.

The issue is, when I stop and delete the docker containers and then bring them up again to use the same persistent storage the shards do not attach to the cluster, after googling I believe this is because they have already been attached to a cluster previously.

Output of sh.status( { verbose : 1 } ) shows no shards

Output of sh.addShard("a/mongo-shard-a0:27017") shows:

"errmsg" : "E11000 duplicate key error collection: admin.system.version index: _id_ dup key: { : \"shardIdentity\" }"

I naively presumed that when the docker containers came back and pointed towards the same data directory the cluster would be as it was before deleting the containers.

Any help with this one is much appreciated, thank you.


问:
Checking if X-Y co-ordinate lies within bounds of a control saved in a dictionary
I am saving the extents of a control on a WinForm in a dictionary such as:

```<code>Dictionary<Tuple<int, int>, Control> dictionary =
    new Dictionary<Tuple<int, int>, Control>();
</code>```

And I am drawing controls on the WinForm programmatically. Whenever I draw each control I save the bounds of that control in this dictionary such as:

```<code>dictionary.Add(Tuple.Create(myControl.X, myControl.Y), myControl);
dictionary.Add(Tuple.Create(myControl.X + myControl.Length, myControl.Y), myControl);
dictionary.Add(Tuple.Create(myControl.X + myControl.Length, myControl.Y + myControl.Width), myControl);
dictionary.Add(Tuple.Create(myControl.X, myControl.Y + myControl.Width), myControl);
</code>```

Now, what I want to achieve is that whenever there is a mouse click on the WinForm for MouseEventArgs e, I want to check whether Point(e.X, e.Y) lies within the bounds of a control or not??

I am aware that I can iterate through the Key value pairs of the dictionary and calculate whether the Point(e.X,e.Y) lies within the bound or not. But I want to avoid iterating through the Keys of the dictionary and get the solution.

Any idea how I can achieve it without iterating through the dictionary and calculate for each point?

答:
Iteration should be super fast, especially if you are using the standard controls properties to determine it's position and size. For example this code will generate 5000 controls, gives them all random size and position, then loop through each one and tell you if a point sits within it's boundaries. This entire thing runs in less than 0.4 seconds on my machine:

```<code>var stopwatch = new Stopwatch();
stopwatch.Start();

Random rnd = new Random();

//Generate 500 controls with random positions
var controls = Enumerable.Range(0, 5000)
    .Select(index => new Control
    {
        Top = rnd.Next(0, 1000),
        Left = rnd.Next(0, 1000),
        Width = rnd.Next(0, 1000),
        Height = rnd.Next(0, 1000)
    })
    .ToList();

var controlsUnderMouse = controls
    .Where(c => c.Bounds.Contains(150, 150))
    .ToList();

Console.WriteLine($"Found {controlsUnderMouse.Count()} controls in {stopwatch.Elapsed}");
</code>```

Which will output something like this:

Found 106 controls in 00:00:00.3939616

If you are only looking for a single control, you could change the Where to First and that will return even quicker.

Body:
I am saving the extents of a control on a WinForm in a dictionary such as:

Dictionary<Tuple<int, int>, Control> dictionary =
    new Dictionary<Tuple<int, int>, Control>();

And I am drawing controls on the WinForm programmatically. Whenever I draw each control I save the bounds of that control in this dictionary such as:

dictionary.Add(Tuple.Create(myControl.X, myControl.Y), myControl);
dictionary.Add(Tuple.Create(myControl.X + myControl.Length, myControl.Y), myControl);
dictionary.Add(Tuple.Create(myControl.X + myControl.Length, myControl.Y + myControl.Width), myControl);
dictionary.Add(Tuple.Create(myControl.X, myControl.Y + myControl.Width), myControl);

Now, what I want to achieve is that whenever there is a mouse click on the WinForm for MouseEventArgs e, I want to check whether Point(e.X, e.Y) lies within the bounds of a control or not??

I am aware that I can iterate through the Key value pairs of the dictionary and calculate whether the Point(e.X,e.Y) lies within the bound or not. But I want to avoid iterating through the Keys of the dictionary and get the solution.

Any idea how I can achieve it without iterating through the dictionary and calculate for each point?

Body:
Iteration should be super fast, especially if you are using the standard controls properties to determine it's position and size. For example this code will generate 5000 controls, gives them all random size and position, then loop through each one and tell you if a point sits within it's boundaries. This entire thing runs in less than 0.4 seconds on my machine:

var stopwatch = new Stopwatch();
stopwatch.Start();

Random rnd = new Random();

//Generate 500 controls with random positions
var controls = Enumerable.Range(0, 5000)
    .Select(index => new Control
    {
        Top = rnd.Next(0, 1000),
        Left = rnd.Next(0, 1000),
        Width = rnd.Next(0, 1000),
        Height = rnd.Next(0, 1000)
    })
    .ToList();

var controlsUnderMouse = controls
    .Where(c => c.Bounds.Contains(150, 150))
    .ToList();

Console.WriteLine($"Found {controlsUnderMouse.Count()} controls in {stopwatch.Elapsed}");

Which will output something like this:

Found 106 controls in 00:00:00.3939616

If you are only looking for a single control, you could change the Where to First and that will return even quicker.